repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
bogdanu/sweeper | src/main/java/gg/pistol/sweeper/core/Analyzer.java | 22646 | /*
* Sweeper - Duplicate file cleaner
* Copyright (C) 2012 Bogdan Ciprian Pistol
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package gg.pistol.sweeper.core;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import gg.pistol.lumberjack.JackLogger;
import gg.pistol.lumberjack.JackLoggerFactory;
import gg.pistol.sweeper.core.Target.Type;
import gg.pistol.sweeper.core.resource.Resource;
import gg.pistol.sweeper.core.resource.ResourceDirectory;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.NavigableSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Analyzes a set of targets to find duplicates.
*
* <p>The {@link #analyze} and {@link #delete} methods are not thread safe and must be called from the same thread or
* using synchronization techniques. The {@link #abortAnalysis} and {@link #abortDeletion} methods are thread safe
* and can be called from any thread.
*
* @author Bogdan Pistol
*/
// package private
class Analyzer {
private final JackLogger log;
private final HashFunction hashFunction;
private boolean analyzing;
private boolean deleting;
private final AtomicBoolean abortAnalysis;
private final AtomicBoolean abortDeletion;
@Nullable private SweeperCountImpl count;
@Nullable private TargetImpl rootTarget;
Analyzer() throws SweeperException {
try {
hashFunction = new HashFunction();
} catch (NoSuchAlgorithmException e) {
throw new SweeperException(e);
}
abortAnalysis = new AtomicBoolean();
abortDeletion = new AtomicBoolean();
log = JackLoggerFactory.getLogger(LoggerFactory.getLogger(Analyzer.class));
}
/**
* Compute the analysis.
*
* @return the set of all {@link DuplicateGroup}s sorted decreasingly by size.
*/
NavigableSet<DuplicateGroup> analyze(Collection<? extends Resource> targetResources, SweeperOperationListener listener)
throws SweeperAbortException {
Preconditions.checkNotNull(targetResources);
Preconditions.checkNotNull(listener);
Preconditions.checkArgument(!targetResources.isEmpty());
log.trace("Computing the analysis for the resources {}.", targetResources);
analyzing = true;
deleting = false;
abortAnalysis.set(false);
OperationTrackingListener trackingListener = new OperationTrackingListener(listener);
// The number of total targets (including the ROOT target) calculated at the beginning (before sizing the targets)
// by traverseResources().
MutableInteger totalTargets = new MutableInteger(0);
rootTarget = traverseResources(targetResources, totalTargets, trackingListener);
Collection<TargetImpl> sized = computeSize(rootTarget, totalTargets.intValue(), trackingListener);
Multimap<Long, TargetImpl> sizeDups = filterDuplicateSize(sized);
computeHash(sizeDups.values(), trackingListener);
Multimap<String, TargetImpl> hashDups = filterDuplicateHash(sizeDups.values());
count = computeCount(rootTarget, hashDups);
NavigableSet<DuplicateGroup> duplicates = createDuplicateGroups(hashDups);
analyzing = false;
return duplicates;
}
/**
* Traverse the resources and expand them.
*
* @return a root target that wraps the {@code targetResources}</code>
*/
private TargetImpl traverseResources(Collection<? extends Resource> targetResources, MutableInteger totalTargets,
OperationTrackingListener listener) throws SweeperAbortException {
log.trace("Traversing the resources.");
listener.updateOperation(SweeperOperation.RESOURCE_TRAVERSING);
TargetImpl root = new TargetImpl(new LinkedHashSet<Resource>(targetResources));
totalTargets.setValue(1);
int expandedTargets = expand(root.getChildren(), listener);
totalTargets.add(expandedTargets);
listener.operationCompleted();
return root;
}
/**
* Expand recursively.
*
* <p>This method has side effects: if there is an expanded target equal to any of the {@code rootChildren} then that root
* child will be removed from the {@code rootChildren} collection. This is done to prevent a target from having
* multiple parents.
*
* <p>Example of multiple parent situation: supposing that {@link #analyze} is called with the resource arguments
* "res1" and "res2", it could be the case that res2 is a descendant of res1:
*
* <pre><code>
* root---res1---dir---res2
* \
* --res2
* </code></pre>
*
* In this case res2 has two parents: root and dir, to prevent this from happening the "root---res2" child is
* removed.
*
* @return the number of traversed children targets
*/
private int expand(Collection<TargetImpl> rootChildren, OperationTrackingListener listener) throws SweeperAbortException {
Set<TargetImpl> rootChildrenSet = new HashSet<TargetImpl>(rootChildren);
Deque<TargetImpl> stack = new LinkedList<TargetImpl>();
stack.addAll(rootChildren);
int targetCount = 0;
while (!stack.isEmpty()) {
TargetImpl target = stack.pop();
target.expand(listener);
targetCount++;
for (TargetImpl t : target.getChildren()) {
if (t.getType() != Type.FILE) {
stack.push(t);
} else {
targetCount++;
}
// resolve the multiple parent situations
if (rootChildrenSet.contains(t)) {
rootChildrenSet.remove(t);
rootChildren.remove(t);
}
}
checkAbortFlag();
}
return targetCount;
}
// package private for testing
void checkAbortFlag() throws SweeperAbortException {
if (analyzing && abortAnalysis.get()) {
log.info("Aborting the analysis.");
throw new SweeperAbortException();
}
if (deleting && abortDeletion.get()) {
log.info("Aborting the deletion.");
throw new SweeperAbortException();
}
}
/**
* Compute the size recursively with progress indication (the maximum progress is specified by
* the {@code totalTargets} parameter).
*
* @return the collection of all the targets with computed size traversed from the {@code root}
*/
private Collection<TargetImpl> computeSize(TargetImpl root, int totalTargets,
final OperationTrackingListener listener) throws SweeperAbortException {
log.trace("Computing the size for {} that has <{}> total sub-targets.", root, totalTargets);
final Collection<TargetImpl> ret = new ArrayList<TargetImpl>();
listener.updateOperation(SweeperOperation.SIZE_COMPUTATION);
listener.setOperationMaxProgress(totalTargets);
traverseBottomUp(Collections.singleton(root), new TargetVisitorMethod() {
public void visit(TargetImpl target, int targetIndex) {
target.computeSize(listener);
if (target.isSized()) {
ret.add(target);
}
listener.incrementOperationProgress(targetIndex);
}
});
listener.operationCompleted();
return ret;
}
/*
* Bottom-up traversal of the tree of targets.
*
* For example the following tree has the bottom-up traversal: A, B, C, D, E, F, root.
*
* --E
* /
* root---F---D
* \
* --C---B
* \
* --A
*/
private void traverseBottomUp(Collection<TargetImpl> roots, TargetVisitorMethod visitor) throws SweeperAbortException {
Deque<TargetImpl> stack = new LinkedList<TargetImpl>(); // DFS style stack
Set<TargetImpl> childrenPushed = new HashSet<TargetImpl>(); // targets with the children pushed on the stack
stack.addAll(roots);
int targetIndex = 1; // counter for the n-th visited target
while (!stack.isEmpty()) {
TargetImpl target = stack.peek();
if (!childrenPushed.contains(target)) {
childrenPushed.add(target);
for (TargetImpl child : target.getChildren()) {
stack.push(child);
}
} else {
visitor.visit(target, targetIndex);
targetIndex++;
stack.pop();
}
checkAbortFlag();
}
}
/**
* Select all the targets for which there is at least another target with the same size.
*
* <p>The {@link Target.Type#ROOT} target is excluded.
*
* @return a multimap with sizes as keys and the targets with that same size as values for the key
*/
private Multimap<Long, TargetImpl> filterDuplicateSize(Collection<TargetImpl> list) throws SweeperAbortException {
log.trace("Deduplicating the size.");
Multimap<Long, TargetImpl> sizeDups = filterDuplicates(list, new Function<TargetImpl, Long>() {
@Nullable
public Long apply(TargetImpl input) {
// all the null return values will be ignored
return input.getType() != Target.Type.ROOT ? input.getSize() : null;
}
});
return sizeDups;
}
/**
* Select all the duplicates from the targets based on a criteria function.
* If the function returns the same value for two input targets then those targets are considered duplicates (in
* the context of the criteria function).
*
* @return a multimap with function values as keys and the targets that are considered duplicates as values for
* the key
*/
private <T> Multimap<T, TargetImpl> filterDuplicates(Collection<TargetImpl> targets,
Function<TargetImpl, T> indexFunction) throws SweeperAbortException {
// Dumping all the targets into the multimap (Multimaps.index() doesn't work because it does not support
// skipping null function values and also because of checking the abort flag).
Multimap<T, TargetImpl> map = ArrayListMultimap.create();
for (TargetImpl target : targets) {
T key = indexFunction.apply(target);
if (key != null) { // ignore null values
map.put(key, target);
}
checkAbortFlag();
}
// Filtering the targets (Multimaps.filterKeys() and/or Multimaps.filterValues() don't work because of checking
// the abort flag).
Multimap<T, TargetImpl> ret = ArrayListMultimap.create();
for (T key : map.keySet()) {
checkAbortFlag();
Collection<TargetImpl> collection = map.get(key);
// Ignore all the targets that are not duplicates.
if (collection.size() == 1) {
continue;
}
// Ignore all the targets that are a single child of a directory. In this case the directory will represent
// the child's content.
Collection<TargetImpl> values = new ArrayList<TargetImpl>();
for (TargetImpl target : collection) {
if (target.getParent() == null || target.getParent().getChildren().size() > 1) {
values.add(target);
}
}
if (values.size() > 1) {
ret.putAll(key, values);
}
}
return ret;
}
/**
* Compute the hash recursively for the specified targets.
*/
private void computeHash(Collection<TargetImpl> targets, final OperationTrackingListener listener)
throws SweeperAbortException {
log.trace("Computing the hash for {} targets.", targets.size());
listener.updateOperation(SweeperOperation.HASH_COMPUTATION);
// Filter the targets that are not the children of other targets. All the children targets will have the hash
// computed recursively from the parent target.
targets = filterUpperTargets(targets);
// Compute the total size of the targets to hash for progress tracking purposes.
long totalHashSize = 0;
for (TargetImpl target : targets) {
totalHashSize += target.getSize();
checkAbortFlag();
}
listener.setOperationMaxProgress(totalHashSize);
traverseBottomUp(targets, getHashVisitorMethod(listener));
listener.operationCompleted();
}
/**
* Filter the targets that are not the children of other targets.
*
* @return the collection of filtered targets
*/
private Collection<TargetImpl> filterUpperTargets(Collection<TargetImpl> targets) throws SweeperAbortException {
Set<TargetImpl> set = new HashSet<TargetImpl>();
Collection<TargetImpl> ret = new ArrayList<TargetImpl>();
for (TargetImpl target : targets) {
set.add(target);
checkAbortFlag();
}
for (TargetImpl target : targets) {
TargetImpl parent = target;
boolean isUpper = true;
while ((parent = parent.getParent()) != null) {
if (set.contains(parent)) {
isUpper = false;
break;
}
}
if (isUpper) {
ret.add(target);
}
checkAbortFlag();
}
return ret;
}
private TargetVisitorMethod getHashVisitorMethod(final OperationTrackingListener listener) {
return new TargetVisitorMethod() {
long currentSize = 0;
public void visit(TargetImpl target, int targetIndex) throws SweeperAbortException {
target.computeHash(hashFunction, listener, abortAnalysis);
// Keep track of file sizes only as directories only re-hash the hash of their children which should be
// fast compared to reading I/O operations and hashing of potentially very large files.
if (target.getType() == Type.FILE) {
currentSize += target.getSize();
listener.incrementOperationProgress(currentSize);
}
}
};
}
/**
* Select duplicate targets (having the same hash).
*
* @return a multimap with hashes as keys and duplicate targets as values for the key
*/
private Multimap<String, TargetImpl> filterDuplicateHash(Collection<TargetImpl> targets) throws SweeperAbortException {
log.trace("Deduplicating the hash for {} targets.", targets.size());
Multimap<String, TargetImpl> hashDups = filterDuplicates(targets,
new Function<TargetImpl, String>() {
@Nullable
public String apply(TargetImpl input) {
// all the null return values will be ignored
return input.isHashed() ? input.getHash() : null;
}
});
return hashDups;
}
private SweeperCountImpl computeCount(TargetImpl root, Multimap<String, TargetImpl> hashDups) throws SweeperAbortException {
log.trace("Counting {} hash duplicates.", hashDups.size());
int totalTargets = root.getTotalTargets();
int totalTargetFiles = root.getTotalTargetFiles();
long totalSize = root.getSize();
int duplicateTargets = 0;
int duplicateTargetFiles = 0;
long duplicateSize = 0;
// Filter the upper targets in order to have correct aggregate counting of duplicates. The hashDups can contain
// targets that are children of other targets.
Collection<TargetImpl> hashDupUpperTargets = filterUpperTargets(hashDups.values());
// Group the duplicate targets by hash.
Multimap<String, TargetImpl> dups = filterDuplicateHash(hashDupUpperTargets);
for (String key : dups.keySet()) {
Iterator<TargetImpl> iterator = dups.get(key).iterator();
// Jump over the first value from a duplicate group because deleting all the others will make this one
// a non-duplicate.
iterator.next();
while (iterator.hasNext()) {
TargetImpl target = iterator.next();
duplicateTargets += target.getTotalTargets();
duplicateTargetFiles += target.getTotalTargetFiles();
duplicateSize += target.getSize();
checkAbortFlag();
}
}
SweeperCountImpl count = new SweeperCountImpl(totalTargets, totalTargetFiles, totalSize, duplicateTargets,
duplicateTargetFiles, duplicateSize);
return count;
}
private NavigableSet<DuplicateGroup> createDuplicateGroups(Multimap<String, TargetImpl> hashDups) {
log.trace("Duplicate grouping.");
NavigableSet<DuplicateGroup> ret = new TreeSet<DuplicateGroup>();
for (String key : hashDups.keySet()) {
Collection<TargetImpl> values = hashDups.get(key);
DuplicateGroup dup = new DuplicateGroup(values);
ret.add(dup);
}
return ret;
}
void delete(Collection<? extends Target> targets, SweeperOperationListener listener) throws SweeperAbortException {
Preconditions.checkNotNull(targets);
Preconditions.checkNotNull(listener);
Preconditions.checkArgument(!targets.isEmpty());
log.trace("Deleting targets.");
analyzing = false;
deleting = true;
abortDeletion.set(false);
OperationTrackingListener trackingListener = new OperationTrackingListener(listener);
trackingListener.updateOperation(SweeperOperation.RESOURCE_DELETION);
// Remove the possible multiple instances of the same target and get the children of any ROOT target (deleting
// a ROOT target means to delete its children).
Set<TargetImpl> targetSet = new LinkedHashSet<TargetImpl>();
for (Target target : targets) {
if (target.getType() == Type.ROOT) {
targetSet.addAll(((TargetImpl) target).getChildren());
} else {
targetSet.add((TargetImpl) target);
}
checkAbortFlag();
}
// Use only the upper targets (deleting an upper target will also delete all of its descendants).
Collection<TargetImpl> upperTargets = filterUpperTargets(targetSet);
int totalProgress = 0; // total individual targets to delete
for (TargetImpl target : upperTargets) {
// In case of recursive deletion then a more granular progress tracking is possible, otherwise if
// a directory (with all of its contents) can be deleted in one step then the progress will be more coarse.
if (target.getType() == Type.DIRECTORY && ((ResourceDirectory) target.getResource()).deleteOnlyEmpty()) {
totalProgress += target.getTotalTargets();
} else {
totalProgress++;
}
checkAbortFlag();
}
trackingListener.setOperationMaxProgress(totalProgress);
MutableInteger progress = new MutableInteger(0);
// The visitor pattern is used for recursive deletion (bottom-up).
TargetVisitorMethod deleteMethod = getDeleteVisitorMethod(progress, trackingListener);
for (TargetImpl target : upperTargets) {
if (target.getType() == Type.DIRECTORY && ((ResourceDirectory) target.getResource()).deleteOnlyEmpty()) {
traverseBottomUp(Collections.singleton(target), deleteMethod);
} else {
// Deletion of a file or a directory that can be deleted in one single step.
target.delete(trackingListener);
progress.increment();
trackingListener.incrementOperationProgress(progress.intValue());
}
}
trackingListener.operationCompleted();
deleting = false;
}
private TargetVisitorMethod getDeleteVisitorMethod(final MutableInteger progress, final OperationTrackingListener listener) {
return new TargetVisitorMethod() {
public void visit(TargetImpl target, int targetIndex) {
target.delete(listener);
progress.increment();
listener.incrementOperationProgress(progress.intValue());
}
};
}
/**
* Abort the analyze operation.
*
* <p>This method is thread safe.
*/
void abortAnalysis() {
log.trace("Turning on the analysis abort flag.");
abortAnalysis.set(true);
}
/**
* Abort the delete operation.
*
* <p>This method is thread safe.
*/
void abortDeletion() {
log.trace("Turning on the deletion abort flag.");
abortDeletion.set(true);
}
@Nullable
SweeperCountImpl getCount() {
return count;
}
@Nullable
TargetImpl getRootTarget() {
return rootTarget;
}
/**
* Visitor pattern interface for hierarchies of targets.
*/
private static interface TargetVisitorMethod {
void visit(TargetImpl target, int targetIndex) throws SweeperAbortException;
}
}
| gpl-3.0 |
joansmith/graylog2-server | graylog2-server/src/main/java/org/graylog2/shared/rest/resources/system/MetricsResource.java | 6184 | /**
* This file is part of Graylog.
*
* Graylog is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>.
*/
package org.graylog2.shared.rest.resources.system;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.annotation.Timed;
import com.google.common.collect.Lists;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.graylog2.rest.models.system.metrics.requests.MetricsReadRequest;
import org.graylog2.rest.models.system.metrics.responses.MetricNamesResponse;
import org.graylog2.rest.models.system.metrics.responses.MetricsSummaryResponse;
import org.graylog2.shared.metrics.MetricUtils;
import org.graylog2.shared.rest.resources.RestResource;
import org.graylog2.shared.security.RestPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
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 java.util.List;
import java.util.Map;
@RequiresAuthentication
@Api(value = "System/Metrics", description = "Internal Graylog metrics")
@Path("/system/metrics")
public class MetricsResource extends RestResource {
private static final Logger LOG = LoggerFactory.getLogger(MetricsResource.class);
private final MetricRegistry metricRegistry;
@Inject
public MetricsResource(MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
}
@GET
@Timed
@RequiresPermissions(RestPermissions.METRICS_READALL)
@ApiOperation(value = "Get all metrics",
notes = "Note that this might return a huge result set.")
@Produces(MediaType.APPLICATION_JSON)
public MetricRegistry metrics() {
return metricRegistry;
}
@GET
@Timed
@Path("/names")
@ApiOperation(value = "Get all metrics keys/names")
@RequiresPermissions(RestPermissions.METRICS_ALLKEYS)
@Produces(MediaType.APPLICATION_JSON)
public MetricNamesResponse metricNames() {
return MetricNamesResponse.create(metricRegistry.getNames());
}
@GET
@Timed
@Path("/{metricName}")
@ApiOperation(value = "Get a single metric")
@ApiResponses(value = {
@ApiResponse(code = 404, message = "No such metric")
})
@Produces(MediaType.APPLICATION_JSON)
public Metric singleMetric(@ApiParam(name = "metricName", required = true)
@PathParam("metricName") String metricName) {
checkPermission(RestPermissions.METRICS_READ, metricName);
final Metric metric = metricRegistry.getMetrics().get(metricName);
if (metric == null) {
final String msg = "I do not have a metric called [" + metricName + "].";
LOG.debug(msg);
throw new NotFoundException(msg);
}
return metric;
}
@POST
@Timed
@Path("/multiple")
@ApiOperation("Get the values of multiple metrics at once")
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Malformed body")
})
public MetricsSummaryResponse multipleMetrics(@ApiParam(name = "Requested metrics", required = true)
@Valid @NotNull MetricsReadRequest request) {
final Map<String, Metric> metrics = metricRegistry.getMetrics();
final List<Map<String, Object>> metricsList = Lists.newArrayList();
for (String name : request.metrics()) {
if (!isPermitted(RestPermissions.METRICS_READ, name)) {
continue;
}
final Metric metric = metrics.get(name);
if (metric != null) {
metricsList.add(MetricUtils.map(name, metric));
}
}
return MetricsSummaryResponse.create(metricsList);
}
@GET
@Timed
@Path("/namespace/{namespace}")
@ApiOperation(value = "Get all metrics of a namespace")
@ApiResponses(value = {
@ApiResponse(code = 404, message = "No such metric namespace")
})
@Produces(MediaType.APPLICATION_JSON)
public MetricsSummaryResponse byNamespace(@ApiParam(name = "namespace", required = true)
@PathParam("namespace") String namespace) {
final List<Map<String, Object>> metrics = Lists.newArrayList();
for (Map.Entry<String, Metric> e : metricRegistry.getMetrics().entrySet()) {
final String metricName = e.getKey();
if (metricName.startsWith(namespace) && isPermitted(RestPermissions.METRICS_READ, metricName)) {
try {
final Metric metric = e.getValue();
metrics.add(MetricUtils.map(metricName, metric));
} catch (Exception ex) {
LOG.warn("Could not read metric in namespace list.", ex);
}
}
}
if (metrics.isEmpty()) {
final String msg = "No metrics with namespace [" + namespace + "] found.";
LOG.debug(msg);
throw new NotFoundException(msg);
}
return MetricsSummaryResponse.create(metrics);
}
}
| gpl-3.0 |
obulpathi/java | deitel/ch07/fig07_09_11/DeckOfCardsTest.java | 1772 | // Fig. 7.11: DeckOfCardsTest.java
// Card shuffling and dealing.
public class DeckOfCardsTest
{
// execute application
public static void main( String[] args )
{
DeckOfCards myDeckOfCards = new DeckOfCards();
myDeckOfCards.shuffle(); // place Cards in random order
// print all 52 Cards in the order in which they are dealt
for ( int i = 1; i <= 52; i++ )
{
// deal and display a Card
System.out.printf( "%-19s", myDeckOfCards.dealCard() );
if ( i % 4 == 0 ) // output a newline after every fourth card
System.out.println();
} // end for
} // end main
} // end class DeckOfCardsTest
/**************************************************************************
* (C) Copyright 1992-2012 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/
| gpl-3.0 |
hartwigmedical/hmftools | purple/src/main/java/com/hartwig/hmftools/purple/germline/GermlineVariants.java | 4458 | package com.hartwig.hmftools.purple.germline;
import static com.hartwig.hmftools.common.purple.PurpleCommon.PURPLE_GERMLINE_VCF_SUFFIX;
import static com.hartwig.hmftools.common.variant.impact.VariantTranscriptImpact.VAR_TRANS_IMPACT_ANNOATATION;
import static com.hartwig.hmftools.purple.PurpleCommon.PPL_LOGGER;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import com.hartwig.hmftools.common.purple.PurityAdjuster;
import com.hartwig.hmftools.common.purple.copynumber.PurpleCopyNumber;
import com.hartwig.hmftools.common.variant.VariantHeader;
import com.hartwig.hmftools.purple.config.PurpleConfig;
import com.hartwig.hmftools.purple.config.ReferenceData;
import org.apache.commons.compress.utils.Lists;
import org.jetbrains.annotations.NotNull;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.variantcontext.writer.VariantContextWriter;
import htsjdk.variant.variantcontext.writer.VariantContextWriterBuilder;
import htsjdk.variant.vcf.VCFFileReader;
public class GermlineVariants
{
private final PurpleConfig mConfig;
private final ReferenceData mReferenceData;
private final String mVersion;
private final List<VariantContext> mReportableVariants;
public GermlineVariants(final PurpleConfig config, final ReferenceData referenceData, final String version)
{
mReferenceData = referenceData;
mConfig = config;
mVersion = version;
mReportableVariants = Lists.newArrayList();
}
@NotNull
public List<VariantContext> reportableVariants()
{
return mReportableVariants;
}
public void loadReportableVariants(final String germlineVcf)
{
if(germlineVcf.isEmpty())
return;
PPL_LOGGER.info("Loading germline variants from {}", germlineVcf);
try
{
VCFFileReader vcfReader = new VCFFileReader(new File(germlineVcf), false);
for(VariantContext context : vcfReader)
{
if(context.getAttributeAsBoolean(VariantHeader.REPORTED_FLAG, false))
mReportableVariants.add(context);
}
}
catch(Exception e)
{
PPL_LOGGER.error("failed to read germline VCF from file({}): {}", germlineVcf, e.toString());
}
}
public void processAndWrite(
final String referenceId, final String tumorSample, final String germlineVcf, final PurityAdjuster purityAdjuster,
final List<PurpleCopyNumber> copyNumbers, final Set<String> somaticReportedGenes)
{
mReportableVariants.clear();
if(germlineVcf.isEmpty())
return;
final String outputVCF = mConfig.OutputDir + File.separator + tumorSample + PURPLE_GERMLINE_VCF_SUFFIX;
PPL_LOGGER.info("Loading germline variants from {}", germlineVcf);
PPL_LOGGER.info("Enriching germline variants");
try
{
VCFFileReader vcfReader = new VCFFileReader(new File(germlineVcf), false);
boolean isPaveAnnotated = vcfReader.getFileHeader().hasInfoLine(VAR_TRANS_IMPACT_ANNOATATION);
VariantContextWriter writer = new VariantContextWriterBuilder().setOutputFile(outputVCF)
.setOption(htsjdk.variant.variantcontext.writer.Options.ALLOW_MISSING_FIELDS_IN_HEADER)
.build();
final Consumer<VariantContext> consumer = context ->
{
if(context.getAttributeAsBoolean(VariantHeader.REPORTED_FLAG, false))
{
mReportableVariants.add(context);
}
writer.add(context);
};
final GermlineVariantEnrichment enrichment = new GermlineVariantEnrichment(
mVersion, referenceId, tumorSample, mReferenceData, purityAdjuster, copyNumbers,
mReferenceData.GermlineHotspots, somaticReportedGenes, !isPaveAnnotated, consumer);
writer.writeHeader(enrichment.enrichHeader(vcfReader.getFileHeader()));
for(VariantContext context : vcfReader)
{
enrichment.accept(context);
}
enrichment.flush();
writer.close();
}
catch(Exception e)
{
PPL_LOGGER.error(" failed to enrich germline variants: {}", e.toString());
}
}
}
| gpl-3.0 |
Roujo/Emily-Basic | src/roujo/emily/plugins/basic/reactions/HatsCommand.java | 515 | package roujo.emily.plugins.basic.reactions;
import roujo.emily.core.contexts.CommandContext;
import roujo.emily.core.contexts.MessageContext;
import roujo.emily.core.extensibility.util.Command;
import roujo.emily.core.extensibility.util.Reaction;
public class HatsCommand extends Reaction {
public HatsCommand() {
super("hats", ".*(?i)hats(?-i).*", "Who knows?");
}
@Override
public boolean react(MessageContext context) {
sendMessageBack(context, "no u");
return true;
}
}
| gpl-3.0 |
YixingHuang/CONRAD | src/edu/stanford/rsl/conrad/geometry/transforms/ScaleRotate.java | 1967 | package edu.stanford.rsl.conrad.geometry.transforms;
import edu.stanford.rsl.conrad.geometry.shapes.simple.PointND;
import edu.stanford.rsl.conrad.numerics.SimpleMatrix;
import edu.stanford.rsl.conrad.numerics.SimpleOperators;
import edu.stanford.rsl.conrad.numerics.SimpleVector;
/**
* This is a decorator class for a scale-rotation matrix. it performs a scale-rotate transformation on point and direction vectors.
* @author Rotimi X Ojo
*
*/
public class ScaleRotate extends Transform{
private static final long serialVersionUID = 4514828466172949672L;
private SimpleMatrix scaleRotate = null;
/**
* Initialize a scale-rotation transform using a rotation matrix
* @param t is a scale-rotation matrix
*/
public ScaleRotate(SimpleMatrix t){
scaleRotate = t;
}
/**
* Applies scale-rotate transformation on a given point
* @param point is point to be scale rotated
* @return point y = Ax, where A is the scale-rotate matrix wrapped by this class and x is the point to be rotated.
*/
@Override
public PointND transform(PointND point) {
return new PointND(SimpleOperators.multiply(scaleRotate, point.getAbstractVector()));
}
/**
* Applies scale-rotate transformation on a given direction
* @param dir is direction to be scale rotated.
* @return vector y = Ax, where A is the scale-rotate matrix wrapped by this class and x is the vector to be rotated.
*/
@Override
public SimpleVector transform(SimpleVector dir) {
return SimpleOperators.multiply(scaleRotate, dir);
}
@Override
public Transform inverse() {
return new ScaleRotate(scaleRotate.inverse(SimpleMatrix.InversionType.INVERT_QR));
}
@Override
public Transform clone() {
return new ScaleRotate(scaleRotate.clone());
}
@Override
public SimpleMatrix getData() {
return scaleRotate;
}
}
/*
* Copyright (C) 2010-2014 Andreas Maier, Rotimi X Ojo
* CONRAD is developed as an Open Source project under the GNU General Public License (GPL).
*/ | gpl-3.0 |
sufficientlysecure/ad-away | app/src/main/java/org/adaway/model/source/SourceBatchUpdater.java | 1438 | package org.adaway.model.source;
import org.adaway.db.dao.HostListItemDao;
import org.adaway.db.entity.HostListItem;
import org.adaway.db.entity.HostsSource;
import java.util.Collection;
/**
* This class is a tool to do batch update into the database.<br>
* It allows faster insertion by using only one transaction for a batch insert.
*
* @author Bruce BUJON (bruce.bujon(at)gmail(dot)com)
*/
class SourceBatchUpdater {
private static final int BATCH_SIZE = 100;
private final HostListItemDao hostListItemDao;
SourceBatchUpdater(HostListItemDao hostListItemDao) {
this.hostListItemDao = hostListItemDao;
}
void updateSource(HostsSource source, Collection<HostListItem> items) {
// Clear current hosts
int sourceId = source.getId();
this.hostListItemDao.clearSourceHosts(sourceId);
// Create batch
HostListItem[] batch = new HostListItem[BATCH_SIZE];
int cacheSize = 0;
// Insert parsed items
for (HostListItem item : items) {
batch[cacheSize++] = item;
if (cacheSize >= batch.length) {
this.hostListItemDao.insert(batch);
cacheSize = 0;
}
}
// Flush current batch
HostListItem[] remaining = new HostListItem[cacheSize];
System.arraycopy(batch, 0, remaining, 0, remaining.length);
this.hostListItemDao.insert(remaining);
}
}
| gpl-3.0 |
zbx/device | APDPlat_Core/src/main/java/org/apdplat/platform/generator/ActionGenerator.java | 14543 | /**
*
* APDPlat - Application Product Development Platform
* Copyright (c) 2013, 张炳祥, zbx13@163.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.apdplat.platform.generator;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apdplat.module.module.model.Command;
import org.apdplat.module.module.model.Module;
import org.apdplat.module.module.service.ModuleParser;
import org.apdplat.module.module.service.ModuleService;
import org.apdplat.module.system.service.PropertyHolder;
import org.apdplat.platform.generator.ModelGenerator.ModelInfo;
import org.apdplat.platform.model.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author 张炳祥
*/
public class ActionGenerator extends Generator{
private static Configuration freemarkerConfiguration = null;
static {
factory.setTemplateLoaderPath(PropertyHolder.getProperty("action.generator.freemarker.template"));
try {
freemarkerConfiguration = factory.createConfiguration();
} catch (IOException | TemplateException e) {
LOG.error("初始化模板错误",e);
}
}
/**
* 此方法专门给model的main方法使用
* @param clazz
*/
public static void generate(Class clazz) {
String workspaceModuleBasePath=ActionGenerator.class.getResource("/").getFile().replace("target/classes/", "")+"src/main/java/";
generateFromModel(clazz,workspaceModuleBasePath);
}
/**
* 生成批量模型对应的Action
* @param modelInfos 批量模型
* @param workspaceModuleBasePath 模块所在项目物理根路径
*/
public static void generate(List<ModelInfo> modelInfos,String workspaceModuleBasePath){
modelInfos.forEach(modelInfo -> {
String modelClzz=modelInfo.getModelPackage()+"."+modelInfo.getModelEnglish();
Class clazz;
try {
clazz = Class.forName(modelClzz);
generateFromModel(clazz,workspaceModuleBasePath+"/src/main/java/");
} catch (ClassNotFoundException ex) {
System.out.println("没有找到模型类: "+modelClzz);
}
});
generateFromModule(modelInfos,workspaceModuleBasePath);
}
/**
* 根据模块生成Action
* @param workspaceModuleBasePath1 开发时模块的根路径
*/
private static void generateFromModule(List<ModelInfo> modelInfos,String workspaceModuleBasePath1) {
List<String> models=new ArrayList<>();
String workspaceModuleBasePath=workspaceModuleBasePath1+"/src/main/java/";
for(ModelInfo info : modelInfos){
models.add(info.getModelEnglish());
}
try {
String moduleFile=workspaceModuleBasePath.replace("/src/main/java/", "/src/main/resources/META-INF/services/module.xml");
//获取所有叶子模块
Module rootModule = ModuleParser.getRootModule(new FileInputStream(moduleFile));
List<Module> modules=ModuleService.getLeafModule(rootModule);
//计算基本包名
StringBuilder actionPackageBase = new StringBuilder(findPackageName(workspaceModuleBasePath));
int index=actionPackageBase.indexOf("/src/main/java/");
String newActionPackageBase=actionPackageBase.substring(index).replace("/src/main/java/", "").replace("/", ".");
actionPackageBase.setLength(0);
actionPackageBase.append(newActionPackageBase);
modules.forEach(module -> {
List<Command> specialCommands=ModuleService.getSpecialCommand(module);
String action=Character.toUpperCase(module.getEnglish().charAt(0))+module.getEnglish().substring(1);
String actionName=action+"Action";
String actionNamespace=ModuleService.getModulePath(module.getParentModule());
String actionPackage=actionPackageBase+"."+actionNamespace.replace("/", ".").replace("\\", ".")+"action";
actionNamespace=actionNamespace.substring(0, actionNamespace.length()-1);
String actionPath=actionPackage.replace(".", "/");
//判断此模块是否已被指定操作特定的模型
Model model=actionToModel.get(module.getEnglish());
System.out.println("actionToModel action: "+module.getEnglish());
if(model!=null){
System.out.println("actionToModel model: "+model.getClass().getName());
System.out.println("模块 "+module.getChinese()+" 已被指定操作特定的模型 "+model.getMetaData());
//模块有指定的Model
String modelPackage=model.getClass().getName().replace("."+model.getClass().getSimpleName(), "");
generateAction(actionPackage,actionNamespace,actionName,modelPackage,model.getClass().getSimpleName(),workspaceModuleBasePath,specialCommands);
return;
}
System.out.println("模块 "+module.getChinese()+" 没有对应的模型 ");
if(models.contains(action)){
System.out.println(module.getEnglish()+" 有对应的模型,忽略generateFromModule");
return;
}
System.out.println("generateFromModule actionPackage:"+actionPackage);
System.out.println("generateFromModule namespace:"+actionNamespace);
System.out.println("generateFromModule actionPath:"+actionPath);
System.out.println("generateFromModule action:"+actionName);
generateFromModule(specialCommands,actionPackage,actionNamespace,actionName,workspaceModuleBasePath,actionPath);
});
} catch (FileNotFoundException e) {
LOG.error("生成ACTION错误",e);
}
}
private static void generateFromModule(List<Command> specialCommands, String actionPackage, String actionNamespace, String actionName, String workspaceModuleBasePath, String actionPath) {
String templateName="action_special.ftl";
LOG.info("开始生成Action");
LOG.info("workspaceModuleBasePath:" + workspaceModuleBasePath);
//准备数据
Map<String, Object> context = new HashMap<>();
context.put("actionPackage", actionPackage);
context.put("actionNamespace", actionNamespace);
context.put("actionName", actionName);
context.put("specialCommands", specialCommands);
boolean result=false;
try {
Template template = freemarkerConfiguration.getTemplate(templateName, ENCODING);
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, context);
result=saveFile(workspaceModuleBasePath, actionPath, actionName, content);
} catch (IOException | TemplateException e) {
LOG.error("生成ACTION错误",e);
}
if(result){
LOG.info("Action生成成功");
}else{
LOG.info("忽略生成Action");
}
}
private static String findPackageName(String workspaceModuleBasePath){
File base=new File(workspaceModuleBasePath);
File model=findModel(base);
if(model!=null){
return model.getParentFile().getParent();
}
return null;
}
/**
* 找到model文件夹
* @param file
* @return
*/
private static File findModel(File file){
//查看当前文件夹是否为 model 文件夹
if(file.getName().equals("model")){
return file;
}else{
File[] subFiles=file.listFiles(new FilenameFilter(){
@Override
public boolean accept(File dir, String name) {
if(name.startsWith(".")){
return false;
}
return true;
}
});
if(subFiles==null){
return null;
}
//对当前文件夹的子文件夹进行判断
for(File child : subFiles){
if(child.getName().equals("model")){
return child;
}
}
//当前文件夹的子文件夹没有model文件夹
for(File child : subFiles){
File result=findModel(child);
if(result!=null){
return result;
}
}
}
return null;
}
/**
* 根据模型生成Action
* @param clazz 模型
* @param workspaceModuleBasePath 开发时模块的根路径
*/
private static void generateFromModel(Class clazz,String workspaceModuleBasePath) {
String packageName=clazz.getPackage().getName();
String p=packageName.replace(".model","");
int index=p.lastIndexOf(".");
String _package=p.substring(0,index);
//最低层命名空间
String actionNamespace=p.substring(index+1);
String model=clazz.getSimpleName();
String actionName=model+"Action";
String actionPackage=_package+"."+actionNamespace+".action";
String modelPackage=_package+"."+actionNamespace+".model";
//完整命名空间
//获取namespace
int indexOf = packageName.indexOf(".module.");
actionNamespace = packageName.substring(indexOf).replace(".module.", "").replace(".model", "").replace(".", "/");
//普通情况下一个模型对应一个Action,如果某些模型不需要Action(即没有在module.xml中进行声明),则忽略生成此模型对应的Action
//从module.xml中查找该model是否配置在模块文件中
String shortModel=Character.toLowerCase(model.charAt(0))+model.substring(1);
Module m=ModuleService.getModuleFromXml(shortModel);
if(m==null){
LOG.info(shortModel+" 没有在module.xml中进行声明,忽略生成Action");
return ;
}
//添加自定义的方法
List<Command> specialCommands=ModuleService.getSpecialCommand(m);
System.out.println("generateFromModel actionPackage:"+actionPackage);
System.out.println("generateFromModel actionNamespace:"+actionNamespace);
System.out.println("generateFromModel model:"+model);
generateAction(actionPackage,actionNamespace,actionName,modelPackage,model,workspaceModuleBasePath,specialCommands);
}
/**
* 根据模型生成Action
* @param workspaceModuleBasePath 开发时模块的根路径
*/
private static void generateAction(String actionPackage, String actionNamespace, String actionName, String modelPackage,String model, String workspaceModuleBasePath, List<Command> specialCommands) {
//检查参数,防止空指针
if(specialCommands==null){
specialCommands=new ArrayList<>();
}
System.out.println("generateAction actionPackage:"+actionPackage);
System.out.println("generateAction actionNamespace:"+actionNamespace);
System.out.println("generateAction actionName:"+actionName);
System.out.println("generateAction model:"+model);
System.out.println("generateAction workspaceModuleBasePath:" + workspaceModuleBasePath);
String templateName="action.ftl";
System.out.println("开始生成Action");
//准备数据
String actionPath=actionPackage.replace(".", "/");
Map<String, Object> context = new HashMap<>();
context.put("actionPackage", actionPackage);
context.put("actionNamespace", actionNamespace);
context.put("modelPackage", modelPackage);
context.put("model", model);
context.put("actionName", actionName);
context.put("specialCommands", specialCommands);
boolean result=false;
try {
Template template = freemarkerConfiguration.getTemplate(templateName, ENCODING);
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, context);
result=saveFile(workspaceModuleBasePath, actionPath, actionName, content);
} catch (IOException | TemplateException e) {
LOG.error("生成ACTION错误",e);
}
if(result){
System.out.println("Action生成成功");
}else{
System.out.println("忽略生成Action");
}
}
/**
*
* @param workspaceModuleBasePath
* @param actionPath
* @param actionName
* @param content
* @return
*/
private static boolean saveFile(String workspaceModuleBasePath, String actionPath, String actionName, String content) {
if(workspaceModuleBasePath==null){
return false;
}
File file = new File(workspaceModuleBasePath);
file = new File(file, actionPath);
if (!file.exists()) {
file.mkdirs();
}
file = new File(file, actionName+".java");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
LOG.error("生成ACTION错误",e);
}
}else{
LOG.info("源文件已经存在,请删除 "+file.getAbsolutePath()+" 后在执行命令");
return false;
}
saveFile(file,content);
return true;
}
} | gpl-3.0 |
potty-dzmeia/db4o | src/db4oj.tests/src/com/db4o/db4ounit/util/test/AllTests.java | 1012 | /* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/. */
package com.db4o.db4ounit.util.test;
import db4ounit.extensions.*;
public class AllTests extends Db4oTestSuite {
public static void main(String[] args) {
new AllTests().runSolo();
}
protected Class[] testCases() {
return new Class[] {
JavaServicesTestCase.class,
PermutingTestConfigTestCase.class,
};
}
}
| gpl-3.0 |
craftercms/social | server/src/main/java/org/craftercms/social/services/ugc/pipeline/ModerationPipe.java | 1496 | /*
* Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.craftercms.social.services.ugc.pipeline;
import java.util.Map;
import org.craftercms.social.domain.UGC;
import org.craftercms.social.domain.social.SocialUgc;
import org.craftercms.social.exceptions.SocialException;
import org.craftercms.social.moderation.ModerationDecision;
import org.craftercms.social.services.ugc.UgcPipe;
/**
*
*/
public class ModerationPipe implements UgcPipe{
private ModerationDecision moderationDecision;
@Override
public <T extends UGC> void process(final T ugc,Map<String,Object> params) throws SocialException {
if(ugc instanceof SocialUgc)
moderationDecision.needModeration((SocialUgc)ugc);
}
public void setModerationDecision(final ModerationDecision moderationDecision) {
this.moderationDecision = moderationDecision;
}
}
| gpl-3.0 |
LexMinecraft/Launcher | src/main/java/com/atlauncher/data/ExtractTo.java | 825 | /*
* ATLauncher - https://github.com/ATLauncher/ATLauncher
* Copyright (C) 2013 ATLauncher
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.atlauncher.data;
public enum ExtractTo {
root, mods, coremods
}
| gpl-3.0 |
wellingtondellamura/compilers-codes-samples | parsers/tools/antlr/translation/MiniGrammar_v2Parser.java | 5402 | // Generated from /home/wellington/projects/aulas/compilers-codes-samples/antlr/translation/MiniGrammar_v2.g4 by ANTLR 4.1
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.misc.*;
import org.antlr.v4.runtime.tree.*;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class MiniGrammar_v2Parser extends Parser {
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
NUM=1, PLUS=2, MINUS=3;
public static final String[] tokenNames = {
"<INVALID>", "NUM", "'+'", "'-'"
};
public static final int
RULE_init = 0, RULE_expr = 1;
public static final String[] ruleNames = {
"init", "expr"
};
@Override
public String getGrammarFileName() { return "MiniGrammar_v2.g4"; }
@Override
public String[] getTokenNames() { return tokenNames; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public ATN getATN() { return _ATN; }
public MiniGrammar_v2Parser(TokenStream input) {
super(input);
_interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
public static class InitContext extends ParserRuleContext {
public ExprContext expr;
public ExprContext expr() {
return getRuleContext(ExprContext.class,0);
}
public InitContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_init; }
}
public final InitContext init() throws RecognitionException {
InitContext _localctx = new InitContext(_ctx, getState());
enterRule(_localctx, 0, RULE_init);
try {
enterOuterAlt(_localctx, 1);
{
setState(4); ((InitContext)_localctx).expr = expr();
System.out.println(((InitContext)_localctx).expr.value);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ExprContext extends ParserRuleContext {
public Integer value;
public Token NUM;
public Token n1;
public Token n2;
public List<TerminalNode> NUM() { return getTokens(MiniGrammar_v2Parser.NUM); }
public TerminalNode NUM(int i) {
return getToken(MiniGrammar_v2Parser.NUM, i);
}
public ExprContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_expr; }
}
public final ExprContext expr() throws RecognitionException {
ExprContext _localctx = new ExprContext(_ctx, getState());
enterRule(_localctx, 2, RULE_expr);
int _la;
try {
setState(22);
switch ( getInterpreter().adaptivePredict(_input,2,_ctx) ) {
case 1:
enterOuterAlt(_localctx, 1);
{
setState(7); ((ExprContext)_localctx).NUM = match(NUM);
((ExprContext)_localctx).value = Integer.valueOf((((ExprContext)_localctx).NUM!=null?((ExprContext)_localctx).NUM.getText():null));
}
break;
case 2:
enterOuterAlt(_localctx, 2);
{
setState(9); ((ExprContext)_localctx).n1 = match(NUM);
((ExprContext)_localctx).value = Integer.valueOf((((ExprContext)_localctx).n1!=null?((ExprContext)_localctx).n1.getText():null));
setState(19);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==PLUS || _la==MINUS) {
{
setState(17);
switch (_input.LA(1)) {
case PLUS:
{
setState(11); match(PLUS);
setState(12); ((ExprContext)_localctx).n2 = match(NUM);
_localctx.value += Integer.valueOf((((ExprContext)_localctx).n2!=null?((ExprContext)_localctx).n2.getText():null));
}
break;
case MINUS:
{
setState(14); match(MINUS);
setState(15); ((ExprContext)_localctx).n2 = match(NUM);
_localctx.value -= Integer.valueOf((((ExprContext)_localctx).n2!=null?((ExprContext)_localctx).n2.getText():null));
}
break;
default:
throw new NoViableAltException(this);
}
}
setState(21);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
break;
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static final String _serializedATN =
"\3\uacf5\uee8c\u4f5d\u8b0d\u4a45\u78bd\u1b2f\u3378\3\5\33\4\2\t\2\4\3"+
"\t\3\3\2\3\2\3\2\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\7\3\24\n\3\f"+
"\3\16\3\27\13\3\5\3\31\n\3\3\3\2\4\2\4\2\2\33\2\6\3\2\2\2\4\30\3\2\2\2"+
"\6\7\5\4\3\2\7\b\b\2\1\2\b\3\3\2\2\2\t\n\7\3\2\2\n\31\b\3\1\2\13\f\7\3"+
"\2\2\f\25\b\3\1\2\r\16\7\4\2\2\16\17\7\3\2\2\17\24\b\3\1\2\20\21\7\5\2"+
"\2\21\22\7\3\2\2\22\24\b\3\1\2\23\r\3\2\2\2\23\20\3\2\2\2\24\27\3\2\2"+
"\2\25\23\3\2\2\2\25\26\3\2\2\2\26\31\3\2\2\2\27\25\3\2\2\2\30\t\3\2\2"+
"\2\30\13\3\2\2\2\31\5\3\2\2\2\5\23\25\30";
public static final ATN _ATN =
ATNSimulator.deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
} | gpl-3.0 |
sinaa/train-simulator | src/main/java/ft/sim/world/connectables/Section.java | 887 | package ft.sim.world.connectables;
import ft.sim.world.placeables.Placeable;
import ft.sim.world.train.TrainTrail;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by Sina on 21/02/2017.
*/
public class Section {
// By default, each section is 1 metres
private static final transient int DEFAULT_LENGTH = 1;
private static final transient int length = Section.DEFAULT_LENGTH;
Set<Placeable> placeables = new HashSet<>();
public int getLength() {
return length;
}
public void addPlaceable(Placeable p) {
placeables.add(p);
if (p instanceof TrainTrail) {
((TrainTrail) p).nowOnSection(this);
}
}
public List<Placeable> getPlaceables() {
return new ArrayList<>(placeables);
}
public void removePlacebale(Placeable placeable) {
placeables.remove(placeable);
}
}
| gpl-3.0 |
amihaylov/code-me-fast | desktop/CodeMeFaster/src/com/boyko/codemefast/Gui.java | 3634 | package com.boyko.codemefast;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import com.sun.glass.events.KeyEvent;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class Gui extends JFrame {
public Gui() {
setSize(new Dimension(1020, 700));
setTitle("CodeMeFast");
createFrame();
}
public void createFrame() {
try {
UIManager.setLookAndFeel(new NimbusLookAndFeel());
} catch (Exception e) {
e.printStackTrace();
}
JButton login = Utility.createButton("login", KeyEvent.VK_ENTER);
AuthenteficationPanel authenteficationPanel = new AuthenteficationPanel();
authenteficationPanel.setPreferredSize(new Dimension(200, 200));
getContentPane().add(authenteficationPanel);
login.setBounds(300, 330, 70, 25);
authenteficationPanel.add(login);
login.setCursor(new Cursor(Cursor.HAND_CURSOR));
login.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String username = authenteficationPanel.getUsernameText().getText();
String password = authenteficationPanel.getPasswordText().getText();
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("username", username));
urlParameters.add(new BasicNameValuePair("password", password));
String serverResponse = null;
try {
serverResponse = ServerConnectionUtils.postRequest("api/login/", urlParameters);
} catch (IOException e1) {
e1.printStackTrace();
}
if (serverResponse.equals("ok")) {
UserData.setCurrentUser(username);
remove(authenteficationPanel);
getContentPane().add(new BottomPanel());
revalidate();
} else
if(serverResponse.equals("no")){
authenteficationPanel.getPasswordText().setText("");
JOptionPane.showMessageDialog(null, "Invalid password");
}
else
if(serverResponse.equals("nouser")){
authenteficationPanel.getUsernameText().setText("");
authenteficationPanel.getPasswordText().setText("");
JOptionPane.showMessageDialog(null, "No such user.");
}
}
});
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
}
| gpl-3.0 |
pkiraly/metadata-qa-marc | src/main/java/de/gwdg/metadataqa/marc/analysis/ThompsonTraillScores.java | 1608 | package de.gwdg.metadataqa.marc.analysis;
import de.gwdg.metadataqa.marc.Utils;
import java.util.*;
public class ThompsonTraillScores {
private Map<ThompsonTraillFields, Integer> scores;
public ThompsonTraillScores() {
scores = new LinkedHashMap<>();
for (ThompsonTraillFields field : ThompsonTraillFields.values()) {
if (!field.equals(ThompsonTraillFields.ID)) {
scores.put(field, 0);
}
}
}
public void count(ThompsonTraillFields key) {
Utils.count(key, scores);
}
/**
* Get the value of a key. If key is not found it returns null.
* @param key
*/
public Integer get(ThompsonTraillFields key) {
return scores.getOrDefault(key, null);
}
public void set(ThompsonTraillFields key, int value) {
scores.put(key, value);
}
public void calculateTotal() {
var total = 0;
for (Map.Entry<ThompsonTraillFields, Integer> entry : scores.entrySet()) {
ThompsonTraillFields field = entry.getKey();
if (!field.equals(ThompsonTraillFields.TOTAL)) {
if (field.isClassification())
total += Math.min(entry.getValue(), 10);
else
total += entry.getValue();
}
}
set(ThompsonTraillFields.TOTAL, total);
}
public List<Integer> asList() {
List<Integer> list = new ArrayList<>();
for (Map.Entry<ThompsonTraillFields, Integer> entry : scores.entrySet()) {
ThompsonTraillFields field = entry.getKey();
if (field.isClassification())
list.add(Math.min(entry.getValue(), 10));
else
list.add(entry.getValue());
}
return list;
}
}
| gpl-3.0 |
AlexNPavel/APCompSciStuff | APCompSciStuffSince Oct13/src/Scp.java | 762 |
public class Scp
{
int sides;
int dims;
int len;
int cnt;
public Scp(int v1, int v2)
{
sides = v1;
dims = v1+v2;
len = dims * dims;
}
public void tskA(int v1, int v2)
{
int sides = 0;
int dims = 0;
len = this.len - 19;
sides = v1 * v2;
dims = this.dims;
this.sides += v1;
cnt += dims + this.dims;
cnt = cnt + sides * this.sides / len;
System.out.println("TskA sides "+sides);
System.out.println("TskA dims "+dims);
}
public static void main(String arg[])
{
Scp w = new Scp(2, 5);
w.tskA(3, 7);
System.out.println("\nobj var sides = "+ w.sides);
System.out.println("obj var len = " + w.len);
System.out.println("obj var dims = " + w.dims);
System.out.println("obj var cnt = " + w.cnt);
}
}//end class Scp | gpl-3.0 |
valven/devfest | src/com/valven/devfest/adapter/SpeakerAdapter.java | 1788 | package com.valven.devfest.adapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.valven.devfest.R;
import com.valven.devfest.model.Speaker;
import com.valven.devfest.util.ImageLoader;
public class SpeakerAdapter extends BaseAdapter{
private List<Speaker> mData;
private Context mContext;
private LayoutInflater mInflater;
private static class ViewHolder {
private TextView name;
private TextView info;
private ImageView image;
}
public SpeakerAdapter(Context context, List<Speaker> data) {
mContext = context;
mData = data;
mInflater = LayoutInflater.from(mContext);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Speaker getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
View view = convertView;
if (view == null){
view = mInflater.inflate(R.layout.speaker_row, null);
holder = new ViewHolder();
holder.image = (ImageView)view.findViewById(R.id.image);
holder.info = (TextView)view.findViewById(R.id.info);
holder.name = (TextView)view.findViewById(R.id.name);
view.setTag(holder);
} else {
holder = (ViewHolder)view.getTag();
holder.image.setImageDrawable(null);
}
Speaker data = getItem(position);
holder.name.setText(data.getName());
holder.info.setText(data.getInfo());
ImageLoader.getInstance().displayImage(data.getImage(), holder.image);
return view;
}
}
| gpl-3.0 |
danielhams/mad-java | 3UTIL/util-audio/src/uk/co/modularaudio/util/audio/fft/HannFftWindow.java | 1159 | /**
*
* Copyright (C) 2015 - Daniel Hams, Modular Audio Limited
* daniel.hams@gmail.com
*
* Mad is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Mad 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 Mad. If not, see <http://www.gnu.org/licenses/>.
*
*/
package uk.co.modularaudio.util.audio.fft;
import uk.co.modularaudio.util.math.MathDefines;
public class HannFftWindow extends FftWindow
{
public HannFftWindow( final int length )
{
super( length );
}
@Override
protected final void fillAmps( final int length )
{
for( int i = 0 ; i < length ; i++ )
{
amps[i] = (float)(0.5 * ( 1.0 - Math.cos( (MathDefines.TWO_PI_D * i) / (length-1) ) ) );
}
}
}
| gpl-3.0 |
yl199610/KuGou | news/src/com/yc/news/service/impl/UserServiceImpl.java | 1845 | package com.yc.news.service.impl;
import java.util.List;
import com.yc.news.dao.UserDao;
import com.yc.news.dao.impl.UserDaoImpl;
import com.yc.news.entity.News;
import com.yc.news.entity.NewsBean;
import com.yc.news.entity.User;
import com.yc.news.entity.UserBean;
import com.yc.news.service.UserService;
public class UserServiceImpl implements UserService {
private UserDao userDao;
public UserServiceImpl() {
userDao = new UserDaoImpl();
}
@Override
public boolean login(String username, String password) {
return userDao.findUserbyNP(username, password) != null;
}
@Override
public boolean addUser(User user) {
return userDao.insertUser(user)>0;
}
@Override
public List<User> getAllUser() {
return userDao.findUser();
}
@Override
public User getUser(String id) {
return userDao.getUserById(id, User.class);
}
@Override
public boolean modifyUser(User n) {
return userDao.updateUser(n)>0;
}
@Override
public boolean ArchiveNews(String id) {
return userDao.ArchiveNews(id)>0;
}
@Override
public UserBean getPartUser(String size, String page) {
int currPage = 1; //默认当前页为第一页
int pageSize = 30; //默认页数数据条数为30条
if(size != null){
pageSize = Integer.parseInt(size); //取到每页的数据条数
}
int totalPage = getTotalPage(pageSize); //计算数据总页数
//取到当前页
if (page != null) {
currPage = Integer.parseInt(page);
if (currPage > totalPage) {
currPage = totalPage;
} else if (currPage < 1) {
currPage = 1;
}
}
List<User> newses = userDao.getPartNews(pageSize, currPage);
return new UserBean(currPage, totalPage, newses,pageSize*totalPage);
}
private int getTotalPage(int pageSize) {
return userDao.getTotalPage(pageSize);
}
}
| gpl-3.0 |
lightstar/jobj4-clinic-web | src/test/java/ru/lightstar/clinic/persistence/hibernate/HibernateRoleServiceTest.java | 6154 | package ru.lightstar.clinic.persistence.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.junit.Before;
import org.junit.Test;
import org.springframework.orm.hibernate5.HibernateTemplate;
import ru.lightstar.clinic.SessionFactoryMocker;
import ru.lightstar.clinic.exception.ServiceException;
import ru.lightstar.clinic.model.Role;
import ru.lightstar.clinic.persistence.RoleServiceTest;
import java.sql.SQLException;
import java.util.Collections;
/**
* <code>HibernateRoleService</code> class tests.
*
* @author LightStar
* @since 0.0.1
*/
public class HibernateRoleServiceTest extends RoleServiceTest {
/**
* Helper object used to mock hibernate session factory.
*/
private SessionFactoryMocker hibernateMocker;
/**
* Initialize test.
*/
@Before
public void initTest() {
this.hibernateMocker = new SessionFactoryMocker();
final SessionFactory sessionFactory = this.hibernateMocker.getSessionFactory();
final HibernateTemplate hibernateTemplate = new HibernateTemplate();
hibernateTemplate.setSessionFactory(sessionFactory);
this.roleService = new HibernateRoleService(hibernateTemplate);
}
/**
* {@inheritDoc}
*/
@Test
@Override
public void whenGetAllRolesThenResult() throws ServiceException {
super.whenGetAllRolesThenResult();
}
/**
* Test correctness of <code>getAllRoles</code> method when exception is thrown.
*/
@Test(expected = RuntimeException.class)
public void whenGetAllRolesWithExceptionThenException() throws ServiceException {
doThrow(HibernateException.class).when(this.hibernateMocker.getAllRolesQuery()).list();
super.whenGetAllRolesThenResult();
}
/**
* {@inheritDoc}
*/
@Test
@Override
public void whenGetRoleByNameThenResult() throws ServiceException, SQLException {
super.whenGetRoleByNameThenResult();
}
/**
* Check correctness of <code>getRoleByName</code> method when role can't be found.
*/
@Test(expected = ServiceException.class)
public void whenGetRoleByNameNotFoundThenException() throws ServiceException, SQLException {
when(this.hibernateMocker.getRoleByNameQuery().list()).thenReturn(Collections.emptyList());
super.whenGetRoleByNameThenResult();
}
/**
* Check correctness of <code>getRoleByName</code> method when exception is thrown.
*/
@Test(expected = RuntimeException.class)
public void whenGetRoleByNameWithExceptionThenException() throws ServiceException, SQLException {
doThrow(HibernateException.class).when(this.hibernateMocker.getRoleByNameQuery()).list();
super.whenGetRoleByNameThenResult();
}
/**
* Test correctness of <code>addRole</code> method.
*/
@Test
public void whenAddRoleThenItAdds() throws ServiceException, SQLException {
when(this.hibernateMocker.getRoleByNameQuery().list()).thenReturn(Collections.emptyList());
this.roleService.addRole("manager");
verify(this.hibernateMocker.getSession(), times(1))
.save(any(Role.class));
}
/**
* Test correctness of <code>addRole</code> method when role already exists.
*/
@Test(expected = ServiceException.class)
public void whenAddExistingRoleThenException() throws ServiceException, SQLException {
this.roleService.addRole("manager");
}
/**
* Test correctness of <code>addRole</code> method when name is empty.
*/
@Test(expected = ServiceException.class)
public void whenAddRoleWithEmptyNameThenException() throws ServiceException, SQLException {
when(this.hibernateMocker.getRoleByNameQuery().list()).thenReturn(Collections.emptyList());
this.roleService.addRole("");
}
/**
* Test correctness of <code>addRole</code> method when exception is thrown.
*/
@Test(expected = RuntimeException.class)
public void whenAddRoleWithExceptionThenException() throws ServiceException, SQLException {
when(this.hibernateMocker.getRoleByNameQuery().list()).thenReturn(Collections.emptyList());
doThrow(HibernateException.class).when(this.hibernateMocker.getSession()).save(any(Role.class));
this.roleService.addRole("manager");
}
/**
* Test correctness of <code>deleteRole</code> method.
*/
@Test
public void whenDeleteRoleThenItDeletes() throws ServiceException, SQLException {
when(this.hibernateMocker.getIsRoleBusyQuery().list()).thenReturn(Collections.emptyList());
this.roleService.deleteRole("client");
verify(this.hibernateMocker.getDeleteRoleQuery(), times(1))
.setParameter("name", "client");
verify(this.hibernateMocker.getDeleteRoleQuery(), times(1))
.executeUpdate();
}
/**
* Test correctness of <code>deleteRole</code> method when role is taken by some client.
*/
@Test(expected = ServiceException.class)
public void whenDeleteBusyRoleThenException() throws ServiceException, SQLException {
this.roleService.deleteRole("client");
}
/**
* Test correctness of <code>deleteRole</code> method when exception is thrown.
*/
@Test(expected = RuntimeException.class)
public void whenDeleteRoleWithExceptionThenException() throws ServiceException, SQLException {
when(this.hibernateMocker.getIsRoleBusyQuery().list()).thenReturn(Collections.emptyList());
doThrow(HibernateException.class).when(this.hibernateMocker.getDeleteRoleQuery()).executeUpdate();
this.roleService.deleteRole("client");
}
/**
* Test correctness of <code>deleteRole</code> method when exception in method <code>IsRoleBusy</code> is thrown.
*/
@Test(expected = RuntimeException.class)
public void whenDeleteRoleWithExceptionInIsRoleBusyThenException() throws ServiceException, SQLException {
doThrow(HibernateException.class).when(this.hibernateMocker.getIsRoleBusyQuery()).list();
this.roleService.deleteRole("client");
}
} | gpl-3.0 |
salema/PodCatcher-Deluxe-Android | src/net/alliknow/podcatcher/SettingsActivity.java | 4484 | /** Copyright 2012-2014 Kevin Hausmann
*
* This file is part of PodCatcher Deluxe.
*
* PodCatcher Deluxe is free software: you can redistribute it
* and/or modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* PodCatcher Deluxe 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 PodCatcher Deluxe. If not, see <http://www.gnu.org/licenses/>.
*/
package net.alliknow.podcatcher;
import android.content.Intent;
import android.os.Bundle;
import net.alliknow.podcatcher.preferences.DownloadFolderPreference;
import net.alliknow.podcatcher.view.fragments.SettingsFragment;
import java.io.File;
import java.io.IOException;
/**
* Update settings activity.
*/
public class SettingsActivity extends BaseActivity {
/** The flag for the first run dialog */
public static final String KEY_FIRST_RUN = "first_run";
/** The select all podcast on start-up preference key */
public static final String KEY_SELECT_ALL_ON_START = "select_all_on_startup";
/** The key for the sync preference */
public static final String KEY_SYNC = "synchronization";
/** The theme color preference key */
public static final String KEY_THEME_COLOR = "theme_color";
/** The episode list width preference key */
public static final String KEY_WIDE_EPISODE_LIST = "wide_episode_list";
/** The preference key for the auto download flag */
public static final String KEY_AUTO_DOWNLOAD = "auto_download";
/** The preference key for the auto delete flag */
public static final String KEY_AUTO_DELETE = "auto_delete";
/** The key for the download folder preference */
public static final String KEY_DOWNLOAD_FOLDER = "download_folder";
/** Setting key for the sync receive field */
public static final String KEY_SYNC_RECEIVE = "receive_controller";
/** Setting key for the sync field */
public static final String KEY_SYNC_ACTIVE = "enabled_sync_controllers";
/** Setting key for the last sync field */
public static final String KEY_LAST_SYNC = "last_full_sync";
/** Tag to find the add suggestion dialog fragment under */
private static final String SETTINGS_DIALOG_TAG = "settings_dialog";
/** The settings fragment we display */
private SettingsFragment settingsFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.preferences);
// Create and show suggestion fragment
if (savedInstanceState == null) {
// Create the fragment to show
this.settingsFragment = new SettingsFragment();
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, settingsFragment, SETTINGS_DIALOG_TAG)
.commit();
} else
this.settingsFragment = (SettingsFragment)
getFragmentManager().findFragmentByTag(SETTINGS_DIALOG_TAG);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent result) {
// This is used to fetch the result from the select folder dialog. The
// result is forwarded to the preference object via the fragment.
if (resultCode == RESULT_OK && requestCode == DownloadFolderPreference.REQUEST_CODE)
try {
final File downloadFolder = new File(result.getData().getPath());
final DownloadFolderPreference folderPreference = (DownloadFolderPreference)
settingsFragment.findPreference(KEY_DOWNLOAD_FOLDER);
// Make sure we can actually write to this folder
File.createTempFile("test", "tmp", downloadFolder).delete();
// Update the preference
folderPreference.update(downloadFolder);
} catch (IOException e) {
showToast(getString(R.string.file_select_access_denied));
} catch (NullPointerException npe) {
// pass, this should not happen
}
}
}
| gpl-3.0 |
kpytang/estrellita | app/src/main/java/edu/uci/ics/star/estrellita/updateservice/OnBootReceiver.java | 2852 | /***
Copyright (c) 2009-10 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
* Copyright (C) 2012 Karen P. Tang, Sen Hirano
*
* This file is part of the Estrellita project.
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or 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. If not, see
*
* http://www.gnu.org/licenses/
*
*/
/**
* @author Karen P. Tang
* @author Sen Hirano
*
*/
package edu.uci.ics.star.estrellita.updateservice;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
public class OnBootReceiver extends BroadcastReceiver {
private static final int PERIOD=1800000; // 30 mins
private static boolean isAlarmSet = false;
@Override
public void onReceive(Context context, Intent intent) {
// do a test to see if we want to start the add the alarm
// e.g. if setting is set to do this
if(!isAlarmSet) {
startAlarm(context);
}
}
/**
* @param context
*/
public static void startAlarm(Context context){
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0,
i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
//SystemClock.elapsedRealtime()+60000,
SystemClock.elapsedRealtime()+1000,
PERIOD,
pi);
isAlarmSet = true;
}
/**
* @param context
*/
public static void cancelAlarm(Context context){
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0,
i, 0);
mgr.cancel(pi);
isAlarmSet = false;
}
}
| gpl-3.0 |
zlisinski/zunits | zUnits/src/main/java/com/zlisinski/zunits/massUnits/AbstractMassUnit.java | 2228 | package com.zlisinski.zunits.massUnits;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
/**
* Created by zlisinski on 10/18/13.
*/
public abstract class AbstractMassUnit {
protected BigDecimal value;
protected MathContext mc = new MathContext(10, RoundingMode.HALF_UP);
public AbstractMassUnit(String strValue) {
this.value = new BigDecimal(strValue);
}
public BigDecimal getValue() {
return this.value;
}
public void setValue(String value) {
this.value = new BigDecimal(value);
}
public BigDecimal toMilligram() {
return this.toGram().multiply(new BigDecimal("1000"));
}
public abstract BigDecimal toGram();
public BigDecimal toKilogram() {
return this.toGram().divide(new BigDecimal("1000"), mc);
}
public BigDecimal toOunce() {
return this.toPound().multiply(new BigDecimal("16"));
}
public abstract BigDecimal toPound();
public BigDecimal toShortTon() {
return this.toPound().divide(new BigDecimal("2000"), mc);
}
public BigDecimal toLongTon() {
return this.toPound().divide(new BigDecimal("2240"), mc);
}
public BigDecimal toMetricTon() {
return this.toGram().divide(new BigDecimal("1000000"));
}
public BigDecimal toCarat() {
return this.toGram().multiply(new BigDecimal("5"));
}
public BigDecimal toGrain() {
return this.toPound().multiply(new BigDecimal("7000"));
}
public BigDecimal toDram() {
return this.toPound().multiply(new BigDecimal("256"));
}
public BigDecimal toPennyweight() {
BigDecimal b = new BigDecimal((double)7000/(double)24, mc);
return this.toPound().multiply(b);
}
public BigDecimal toStone() {
return this.toPound().divide(new BigDecimal("14"), mc);
}
public static BigDecimal gramToPound(BigDecimal gram) {
return gram.multiply(new BigDecimal("0.00220462"));
}
public static BigDecimal poundToGram(BigDecimal pound) {
return pound.multiply(new BigDecimal("453.592"));
}
}
| gpl-3.0 |
ByteSyze/CIS-18B | Assignments/6 - Tic Tac Toe/src/tic/tac/toe/listeners/PlayerMoveListener.java | 168 | package tic.tac.toe.listeners;
import tic.tac.toe.event.player.PlayerMoveEvent;
public interface PlayerMoveListener
{
public void onPlayerMove(PlayerMoveEvent e);
}
| gpl-3.0 |
pantelis60/L2Scripts_Underground | gameserver/src/main/java/l2s/gameserver/geodata/PathFind.java | 11992 | package l2s.gameserver.geodata;
import static l2s.gameserver.geodata.GeoEngine.EAST;
import static l2s.gameserver.geodata.GeoEngine.NORTH;
import static l2s.gameserver.geodata.GeoEngine.NSWE_ALL;
import static l2s.gameserver.geodata.GeoEngine.NSWE_NONE;
import static l2s.gameserver.geodata.GeoEngine.SOUTH;
import static l2s.gameserver.geodata.GeoEngine.WEST;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import l2s.gameserver.Config;
import l2s.gameserver.geodata.PathFindBuffers.GeoNode;
import l2s.gameserver.geodata.PathFindBuffers.PathFindBuffer;
import l2s.gameserver.utils.Location;
public class PathFind
{
public final static int BOOST_NONE = 0;
public final static int BOOST_START = 1;
public final static int BOOST_BOTH = 2;
public static List<Location> findPath(int x, int y, int z, Location target, boolean isPlayable, int geoIndex)
{
return findPath(x, y, z, target.x, target.y, target.z, isPlayable, geoIndex);
}
public static final List<Location> findPath(int x, int y, int z, int destX, int destY, int destZ, boolean isPlayable, int geoIndex)
{
if(Math.abs(z - destZ) > 256) //FIXME [G1ta0] достойно конфига
return null;
z = GeoEngine.getHeight(x, y, z, geoIndex);
destZ = GeoEngine.getHeight(destX, destY, destZ, geoIndex);
Location startPoint = Config.PATHFIND_BOOST == BOOST_NONE ? new Location(x, y, z) : GeoEngine.moveCheckWithCollision(x, y, z, destX, destY, true, geoIndex);
Location endPoint = Config.PATHFIND_BOOST != BOOST_BOTH || Math.abs(destZ - z) > 200 ? new Location(destX, destY, destZ) : GeoEngine.moveCheckBackwardWithCollision(destX, destY, destZ, startPoint.x, startPoint.y, true, geoIndex);
startPoint.world2geo();
endPoint.world2geo();
//startPoint.z = GeoEngine.NgetHeight(startPoint.x, startPoint.y, startPoint.z, geoIndex);
//endPoint.z = GeoEngine.NgetHeight(endPoint.x, endPoint.y, endPoint.z, geoIndex);
int xdiff = Math.abs(endPoint.x - startPoint.x);
int ydiff = Math.abs(endPoint.y - startPoint.y);
if(xdiff == 0 && ydiff == 0)
{
if(Math.abs(endPoint.z - startPoint.z) < Config.PATHFIND_MAX_Z_DIFF)
{
List<Location> path = new ArrayList<Location>(2);
path.add(new Location(x, y, z));
path.add(new Location(destX, destY, destZ));
return path;
}
return null;
}
List<Location> path = null;
int mapSize = Config.PATHFIND_MAP_MUL * Math.max(xdiff, ydiff);
PathFindBuffer buff;
if((buff = PathFindBuffers.alloc(mapSize)) != null)
{
buff.offsetX = startPoint.x - buff.mapSize / 2;
buff.offsetY = startPoint.y - buff.mapSize / 2;
//статистика
buff.totalUses++;
if(isPlayable)
buff.playableUses++;
PathFind n = new PathFind(startPoint, endPoint, buff, geoIndex);
path = n.findPath();
buff.free();
PathFindBuffers.recycle(buff);
}
if(path == null || path.isEmpty())
return null;
List<Location> targetRecorder = new ArrayList<Location>(path.size() + 2);
// добавляем первую точку в список (начальная позиция чара)
targetRecorder.add(new Location(x, y, z));
for(Location p : path)
targetRecorder.add(p.geo2world());
// добавляем последнюю точку в список (цель)
targetRecorder.add(new Location(destX, destY, destZ));
if(Config.PATH_CLEAN)
pathClean(targetRecorder, geoIndex);
return targetRecorder;
}
/**
* Очищает путь от ненужных точек.
* @param path путь который следует очистить
*/
private static void pathClean(List<Location> path, int geoIndex)
{
int size = path.size();
if(size > 2)
for(int i = 2; i < size; i++)
{
Location p3 = path.get(i); // точка конца движения
Location p2 = path.get(i - 1); // точка в середине, кандидат на вышибание
Location p1 = path.get(i - 2); // точка начала движения
if(p1.equals(p2) || p3.equals(p2) || IsPointInLine(p1, p2, p3)) // если вторая точка совпадает с первой/третьей или на одной линии с ними - она не нужна
{
path.remove(i - 1); // удаляем ее
size--; // отмечаем это в размере массива
i = Math.max(2, i - 2); // сдвигаемся назад, FIXME: может я тут не совсем прав
}
}
int current = 0;
int sub;
while(current < path.size() - 2)
{
Location one = path.get(current);
sub = current + 2;
while(sub < path.size())
{
Location two = path.get(sub);
if(one.equals(two) || GeoEngine.canMoveWithCollision(one.x, one.y, one.z, two.x, two.y, two.z, geoIndex)) //canMoveWithCollision / canMoveToCoord
while(current + 1 < sub)
{
path.remove(current + 1);
sub--;
}
sub++;
}
current++;
}
}
private static boolean IsPointInLine(Location p1, Location p2, Location p3)
{
// Все 3 точки на одной из осей X или Y.
if(p1.x == p3.x && p3.x == p2.x || p1.y == p3.y && p3.y == p2.y)
return true;
// Условие ниже выполнится если все 3 точки выстроены по диагонали.
// Это работает потому, что сравниваем мы соседние точки (расстояния между ними равны, важен только знак).
// Для случая с произвольными точками работать не будет.
if((p1.x - p2.x) * (p1.y - p2.y) == (p2.x - p3.x) * (p2.y - p3.y))
return true;
return false;
}
private final int geoIndex;
private final PathFindBuffer buff;
private final short[] hNSWE = new short[2];
private final Location startPoint, endPoint;
private GeoNode startNode, endNode, currentNode;
public PathFind(Location startPoint, Location endPoint, PathFindBuffer buff, int geoIndex)
{
this.geoIndex = geoIndex;
this.startPoint = startPoint;
this.endPoint = endPoint;
this.buff = buff;
}
private List<Location> findPath()
{
startNode = buff.nodes[startPoint.x - buff.offsetX][startPoint.y - buff.offsetY].set(startPoint.x, startPoint.y, (short) startPoint.z);
GeoEngine.NgetHeightAndNSWE(startPoint.x, startPoint.y, (short) startPoint.z, hNSWE, geoIndex);
startNode.z = hNSWE[0];
startNode.nswe = hNSWE[1];
startNode.costFromStart = 0f;
startNode.state = GeoNode.OPENED;
startNode.parent = null;
endNode = buff.nodes[endPoint.x - buff.offsetX][endPoint.y - buff.offsetY].set(endPoint.x, endPoint.y, (short) endPoint.z);
startNode.costToEnd = pathCostEstimate(startNode);
startNode.totalCost = startNode.costFromStart + startNode.costToEnd;
buff.open.add(startNode);
long nanos = System.nanoTime();
long searhTime = 0;
int itr = 0;
List<Location> path = null;
while((searhTime = System.nanoTime() - nanos) < Config.PATHFIND_MAX_TIME && (currentNode = buff.open.poll()) != null)
{
itr++;
if(currentNode.x == endPoint.x && currentNode.y == endPoint.y && Math.abs(currentNode.z - endPoint.z) < Config.MAX_Z_DIFF)
{
path = tracePath(currentNode);
break;
}
handleNode(currentNode);
currentNode.state = GeoNode.CLOSED;
}
buff.totalTime += searhTime;
buff.totalItr += itr;
if(path != null)
buff.successUses++;
else if(searhTime > Config.PATHFIND_MAX_TIME)
buff.overtimeUses++;
return path;
}
private List<Location> tracePath(GeoNode f)
{
LinkedList<Location> locations = new LinkedList<Location>();
do
{
locations.addFirst(f.getLoc());
f = f.parent;
} while(f.parent != null);
return locations;
}
private void handleNode(GeoNode node)
{
int clX = node.x;
int clY = node.y;
short clZ = node.z;
getHeightAndNSWE(clX, clY, clZ);
short NSWE = hNSWE[1];
if(Config.PATHFIND_DIAGONAL)
{
// Юго-восток
if((NSWE & SOUTH) == SOUTH && (NSWE & EAST) == EAST)
{
getHeightAndNSWE(clX + 1, clY, clZ);
if((hNSWE[1] & SOUTH) == SOUTH)
{
getHeightAndNSWE(clX, clY + 1, clZ);
if((hNSWE[1] & EAST) == EAST)
{
handleNeighbour(clX + 1, clY + 1, node, true);
}
}
}
// Юго-запад
if((NSWE & SOUTH) == SOUTH && (NSWE & WEST) == WEST)
{
getHeightAndNSWE(clX - 1, clY, clZ);
if((hNSWE[1] & SOUTH) == SOUTH)
{
getHeightAndNSWE(clX, clY + 1, clZ);
if((hNSWE[1] & WEST) == WEST)
{
handleNeighbour(clX - 1, clY + 1, node, true);
}
}
}
// Северо-восток
if((NSWE & NORTH) == NORTH && (NSWE & EAST) == EAST)
{
getHeightAndNSWE(clX + 1, clY, clZ);
if((hNSWE[1] & NORTH) == NORTH)
{
getHeightAndNSWE(clX, clY - 1, clZ);
if((hNSWE[1] & EAST) == EAST)
{
handleNeighbour(clX + 1, clY - 1, node, true);
}
}
}
// Северо-запад
if((NSWE & NORTH) == NORTH && (NSWE & WEST) == WEST)
{
getHeightAndNSWE(clX - 1, clY, clZ);
if((hNSWE[1] & NORTH) == NORTH)
{
getHeightAndNSWE(clX, clY - 1, clZ);
if((hNSWE[1] & WEST) == WEST)
{
handleNeighbour(clX - 1, clY - 1, node, true);
}
}
}
}
// Восток
if((NSWE & EAST) == EAST)
{
handleNeighbour(clX + 1, clY, node, false);
}
// Запад
if((NSWE & WEST) == WEST)
{
handleNeighbour(clX - 1, clY, node, false);
}
// Юг
if((NSWE & SOUTH) == SOUTH)
{
handleNeighbour(clX, clY + 1, node, false);
}
// Север
if((NSWE & NORTH) == NORTH)
{
handleNeighbour(clX, clY - 1, node, false);
}
}
private float pathCostEstimate(GeoNode n)
{
int diffx = endNode.x - n.x;
int diffy = endNode.y - n.y;
int diffz = endNode.z - n.z;
return (float) Math.sqrt(diffx * diffx + diffy * diffy + diffz * diffz / 256);
}
private float traverseCost(GeoNode from, GeoNode n, boolean d)
{
if(n.nswe != NSWE_ALL || Math.abs(n.z - from.z) > 16)
return 3f;
else
{
getHeightAndNSWE(n.x + 1, n.y, n.z);
if(hNSWE[1] != NSWE_ALL || Math.abs(n.z - hNSWE[0]) > 16){ return 2f; }
getHeightAndNSWE(n.x - 1, n.y, n.z);
if(hNSWE[1] != NSWE_ALL || Math.abs(n.z - hNSWE[0]) > 16){ return 2f; }
getHeightAndNSWE(n.x, n.y + 1, n.z);
if(hNSWE[1] != NSWE_ALL || Math.abs(n.z - hNSWE[0]) > 16){ return 2f; }
getHeightAndNSWE(n.x, n.y - 1, n.z);
if(hNSWE[1] != NSWE_ALL || Math.abs(n.z - hNSWE[0]) > 16){ return 2f; }
}
return d ? 1.414f : 1f;
}
private void handleNeighbour(int x, int y, GeoNode from, boolean d)
{
int nX = x - buff.offsetX, nY = y - buff.offsetY;
if(nX >= buff.mapSize || nX < 0 || nY >= buff.mapSize || nY < 0)
return;
GeoNode n = buff.nodes[nX][nY];
float newCost;
if(!n.isSet())
{
n = n.set(x, y, from.z);
GeoEngine.NgetHeightAndNSWE(x, y, from.z, hNSWE, geoIndex);
n.z = hNSWE[0];
n.nswe = hNSWE[1];
}
int height = Math.abs(n.z - from.z);
if(height > Config.PATHFIND_MAX_Z_DIFF || n.nswe == NSWE_NONE)
return;
newCost = from.costFromStart + traverseCost(from, n, d);
if(n.state == GeoNode.OPENED || n.state == GeoNode.CLOSED)
{
if(n.costFromStart <= newCost)
return;
}
if(n.state == GeoNode.NONE)
n.costToEnd = pathCostEstimate(n);
n.parent = from;
n.costFromStart = newCost;
n.totalCost = n.costFromStart + n.costToEnd;
if(n.state == GeoNode.OPENED)
return;
n.state = GeoNode.OPENED;
buff.open.add(n);
}
private void getHeightAndNSWE(int x, int y, short z)
{
int nX = x - buff.offsetX, nY = y - buff.offsetY;
if(nX >= buff.mapSize || nX < 0 || nY >= buff.mapSize || nY < 0)
{
hNSWE[1] = NSWE_NONE; // Затычка
return;
}
GeoNode n = buff.nodes[nX][nY];
if(!n.isSet())
{
n = n.set(x, y, z);
GeoEngine.NgetHeightAndNSWE(x, y, z, hNSWE, geoIndex);
n.z = hNSWE[0];
n.nswe = hNSWE[1];
}
else
{
hNSWE[0] = n.z;
hNSWE[1] = n.nswe;
}
}
} | gpl-3.0 |
ramsodev/DitaManagement | dita/dita.concept/src/net/ramso/dita/concept/GroupseqClass.java | 15448 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.08.02 at 08:05:16 PM CEST
//
package net.ramso.dita.concept;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for groupseq.class complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="groupseq.class">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <group ref="{}groupseq.content"/>
* </sequence>
* <attGroup ref="{}groupseq.attributes"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "groupseq.class", propOrder = {
"title",
"repsep",
"groupseqOrGroupchoiceOrGroupcomp"
})
@XmlSeeAlso({
Groupseq.class
})
public class GroupseqClass {
protected Title title;
protected Repsep repsep;
@XmlElements({
@XmlElement(name = "groupseq", type = Groupseq.class),
@XmlElement(name = "groupchoice", type = Groupchoice.class),
@XmlElement(name = "groupcomp", type = Groupcomp.class),
@XmlElement(name = "fragref", type = Fragref.class),
@XmlElement(name = "synnote", type = Synnote.class),
@XmlElement(name = "synnoteref", type = Synnoteref.class),
@XmlElement(name = "kwd", type = Kwd.class),
@XmlElement(name = "var", type = Var.class),
@XmlElement(name = "delim", type = Delim.class),
@XmlElement(name = "oper", type = Oper.class),
@XmlElement(name = "sep", type = Sep.class)
})
protected List<java.lang.Object> groupseqOrGroupchoiceOrGroupcomp;
@XmlAttribute(name = "outputclass")
protected String outputclass;
@XmlAttribute(name = "importance")
protected ImportanceAttProgdomClass importance;
@XmlAttribute(name = "xtrc")
protected String xtrc;
@XmlAttribute(name = "xtrf")
protected String xtrf;
@XmlAttribute(name = "base")
protected String base;
@XmlAttribute(name = "rev")
protected String rev;
@XmlAttribute(name = "status")
protected StatusAttsClass status;
@XmlAttribute(name = "props")
protected String props;
@XmlAttribute(name = "platform")
protected String platform;
@XmlAttribute(name = "product")
protected String product;
@XmlAttribute(name = "audience")
protected String audienceMod;
@XmlAttribute(name = "otherprops")
protected String otherprops;
@XmlAttribute(name = "translate")
protected YesnoAttClass translate;
@XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace")
protected String lang;
@XmlAttribute(name = "dir")
protected DirAttsClass dir;
@XmlAttribute(name = "id")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "NMTOKEN")
protected String id;
@XmlAttribute(name = "conref")
protected String conref;
@XmlAttribute(name = "conrefend")
protected String conrefend;
@XmlAttribute(name = "conaction")
protected ConactionAttClass conaction;
@XmlAttribute(name = "conkeyref")
protected String conkeyref;
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link Title }
*
*/
public Title getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link Title }
*
*/
public void setTitle(Title value) {
this.title = value;
}
/**
* Gets the value of the repsep property.
*
* @return
* possible object is
* {@link Repsep }
*
*/
public Repsep getRepsep() {
return repsep;
}
/**
* Sets the value of the repsep property.
*
* @param value
* allowed object is
* {@link Repsep }
*
*/
public void setRepsep(Repsep value) {
this.repsep = value;
}
/**
* Gets the value of the groupseqOrGroupchoiceOrGroupcomp property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the groupseqOrGroupchoiceOrGroupcomp property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getGroupseqOrGroupchoiceOrGroupcomp().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Groupseq }
* {@link Groupchoice }
* {@link Groupcomp }
* {@link Fragref }
* {@link Synnote }
* {@link Synnoteref }
* {@link Kwd }
* {@link Var }
* {@link Delim }
* {@link Oper }
* {@link Sep }
*
*
*/
public List<java.lang.Object> getGroupseqOrGroupchoiceOrGroupcomp() {
if (groupseqOrGroupchoiceOrGroupcomp == null) {
groupseqOrGroupchoiceOrGroupcomp = new ArrayList<java.lang.Object>();
}
return this.groupseqOrGroupchoiceOrGroupcomp;
}
/**
* Gets the value of the outputclass property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOutputclass() {
return outputclass;
}
/**
* Sets the value of the outputclass property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOutputclass(String value) {
this.outputclass = value;
}
/**
* Gets the value of the importance property.
*
* @return
* possible object is
* {@link ImportanceAttProgdomClass }
*
*/
public ImportanceAttProgdomClass getImportance() {
return importance;
}
/**
* Sets the value of the importance property.
*
* @param value
* allowed object is
* {@link ImportanceAttProgdomClass }
*
*/
public void setImportance(ImportanceAttProgdomClass value) {
this.importance = value;
}
/**
* Gets the value of the xtrc property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXtrc() {
return xtrc;
}
/**
* Sets the value of the xtrc property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXtrc(String value) {
this.xtrc = value;
}
/**
* Gets the value of the xtrf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXtrf() {
return xtrf;
}
/**
* Sets the value of the xtrf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXtrf(String value) {
this.xtrf = value;
}
/**
* Gets the value of the base property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBase() {
return base;
}
/**
* Sets the value of the base property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBase(String value) {
this.base = value;
}
/**
* Gets the value of the rev property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRev() {
return rev;
}
/**
* Sets the value of the rev property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRev(String value) {
this.rev = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link StatusAttsClass }
*
*/
public StatusAttsClass getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link StatusAttsClass }
*
*/
public void setStatus(StatusAttsClass value) {
this.status = value;
}
/**
* Gets the value of the props property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProps() {
return props;
}
/**
* Sets the value of the props property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProps(String value) {
this.props = value;
}
/**
* Gets the value of the platform property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPlatform() {
return platform;
}
/**
* Sets the value of the platform property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPlatform(String value) {
this.platform = value;
}
/**
* Gets the value of the product property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProduct() {
return product;
}
/**
* Sets the value of the product property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProduct(String value) {
this.product = value;
}
/**
* Gets the value of the audienceMod property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAudienceMod() {
return audienceMod;
}
/**
* Sets the value of the audienceMod property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAudienceMod(String value) {
this.audienceMod = value;
}
/**
* Gets the value of the otherprops property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOtherprops() {
return otherprops;
}
/**
* Sets the value of the otherprops property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOtherprops(String value) {
this.otherprops = value;
}
/**
* Gets the value of the translate property.
*
* @return
* possible object is
* {@link YesnoAttClass }
*
*/
public YesnoAttClass getTranslate() {
return translate;
}
/**
* Sets the value of the translate property.
*
* @param value
* allowed object is
* {@link YesnoAttClass }
*
*/
public void setTranslate(YesnoAttClass value) {
this.translate = value;
}
/**
* Gets the value of the lang property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLang() {
return lang;
}
/**
* Sets the value of the lang property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLang(String value) {
this.lang = value;
}
/**
* Gets the value of the dir property.
*
* @return
* possible object is
* {@link DirAttsClass }
*
*/
public DirAttsClass getDir() {
return dir;
}
/**
* Sets the value of the dir property.
*
* @param value
* allowed object is
* {@link DirAttsClass }
*
*/
public void setDir(DirAttsClass value) {
this.dir = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the conref property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConref() {
return conref;
}
/**
* Sets the value of the conref property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConref(String value) {
this.conref = value;
}
/**
* Gets the value of the conrefend property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConrefend() {
return conrefend;
}
/**
* Sets the value of the conrefend property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConrefend(String value) {
this.conrefend = value;
}
/**
* Gets the value of the conaction property.
*
* @return
* possible object is
* {@link ConactionAttClass }
*
*/
public ConactionAttClass getConaction() {
return conaction;
}
/**
* Sets the value of the conaction property.
*
* @param value
* allowed object is
* {@link ConactionAttClass }
*
*/
public void setConaction(ConactionAttClass value) {
this.conaction = value;
}
/**
* Gets the value of the conkeyref property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConkeyref() {
return conkeyref;
}
/**
* Sets the value of the conkeyref property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConkeyref(String value) {
this.conkeyref = value;
}
}
| gpl-3.0 |
cockroachzl/WebService | jws_ur_ch4/src/TumblrClient.java | 4891 | import java.net.URL;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.io.IOException;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMResult;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import java.io.ByteArrayInputStream;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
class TumblrClient {
public static void main(String[ ] args) {
if (args.length < 2) {
System.err.println("Usage: TumblrClient <email> <passwd>");
return;
}
new TumblrClient().tumble(args[0], args[1]);
}
private void tumble(String email, String password) {
try {
HttpURLConnection conn = null;
// GET request.
String url = "http://mgk-cdm.tumblr.com/api/read";
conn = get_connection(url, "GET");
conn.setRequestProperty("accept", "text/xml");
conn.connect();
String xml = get_response(conn);
if (xml.length() > 0) {
System.out.println("Raw XML:\n" + xml);
parse(xml, "\nSki photo captions:", "//photo-caption");
}
// POST request
url = "http://www.tumblr.com/api/write";
conn = get_connection(url, "POST");
String title = "Summer thoughts up north";
String body = "Craigieburn Ski Area, NZ";
String payload =
URLEncoder.encode("email", "UTF-8") + "=" +
URLEncoder.encode(email, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" +
URLEncoder.encode(password, "UTF-8") + "&" +
URLEncoder.encode("type", "UTF-8") + "=" +
URLEncoder.encode("regular", "UTF-8") + "&" +
URLEncoder.encode("title", "UTF-8") + "=" +
URLEncoder.encode(title, "UTF-8") + "&" +
URLEncoder.encode("body", "UTF-8") + "=" +
URLEncoder.encode(body, "UTF-8");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(payload);
out.flush();
String response = get_response(conn);
System.out.println("Confirmation code: " + response);
}
catch(IOException e) { System.err.println(e); }
catch(NullPointerException e) { System.err.println(e); }
}
private HttpURLConnection get_connection(String url_s, String verb) {
HttpURLConnection conn = null;
try {
URL url = new URL(url_s);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(verb);
conn.setDoInput(true);
conn.setDoOutput(true);
}
catch(MalformedURLException e) { System.err.println(e); }
catch(IOException e) { System.err.println(e); }
return conn;
}
private String get_response(HttpURLConnection conn) {
String xml = "";
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String next = null;
while ((next = reader.readLine()) != null) xml += next;
}
catch(IOException e) { System.err.println(e); }
return xml;
}
private void parse(String xml, String msg, String pattern) {
StreamSource source =
new StreamSource(new ByteArrayInputStream(xml.getBytes()));
DOMResult dom_result = new DOMResult();
System.out.println(msg);
try {
Transformer trans = TransformerFactory.newInstance().newTransformer();
trans.transform(source, dom_result);
XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
NodeList list = (NodeList)
xp.evaluate(pattern, dom_result.getNode(), XPathConstants.NODESET);
int len = list.getLength();
for (int i = 0; i < len; i++) {
Node node = list.item(i);
if (node != null)
System.out.println(node.getFirstChild().getNodeValue());
}
}
catch(TransformerConfigurationException e) { System.err.println(e); }
catch(TransformerException e) { System.err.println(e); }
catch(XPathExpressionException e) { System.err.println(e); }
}
}
| gpl-3.0 |
pkiraly/metadata-qa-marc | src/main/java/de/gwdg/metadataqa/marc/definition/controlpositions/tag007/Tag007nonprojected03.java | 1251 | package de.gwdg.metadataqa.marc.definition.controlpositions.tag007;
import de.gwdg.metadataqa.marc.Utils;
import de.gwdg.metadataqa.marc.definition.structure.ControlfieldPositionDefinition;
import static de.gwdg.metadataqa.marc.definition.FRBRFunction.*;
import java.util.Arrays;
/**
* Color
* https://www.loc.gov/marc/bibliographic/bd007k.html
*/
public class Tag007nonprojected03 extends ControlfieldPositionDefinition {
private static Tag007nonprojected03 uniqueInstance;
private Tag007nonprojected03() {
initialize();
extractValidCodes();
}
public static Tag007nonprojected03 getInstance() {
if (uniqueInstance == null)
uniqueInstance = new Tag007nonprojected03();
return uniqueInstance;
}
private void initialize() {
label = "Color";
id = "007nonprojected03";
mqTag = "color";
positionStart = 3;
positionEnd = 4;
descriptionUrl = "https://www.loc.gov/marc/bibliographic/bd007k.html";
codes = Utils.generateCodes(
"a", "One color",
"b", "Black-and-white",
"c", "Multicolored",
"h", "Hand colored",
"m", "Mixed",
"u", "Unknown",
"z", "Other",
"|", "No attempt to code"
);
functions = Arrays.asList(DiscoverySelect);
}
} | gpl-3.0 |
Olivia-Squirrel/Test-Mod | src/main/java/com/Bobbybim/LetsModReboot/item/itemMapleLeaf.java | 190 | package com.Bobbybim.LetsModReboot.item;
public class itemMapleLeaf extends itemLMRB
{
public itemMapleLeaf()
{
super();
this.setUnlocalizedName("Fabric");
}
}
| gpl-3.0 |
CopperheadOS/platform_packages_apps_F-Droid | app/src/main/java/org/fdroid/fdroid/views/categories/AppPreviewAdapter.java | 1121 | package org.fdroid.fdroid.views.categories;
import android.app.Activity;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import org.fdroid.fdroid.R;
import org.fdroid.fdroid.data.App;
class AppPreviewAdapter extends RecyclerView.Adapter<AppCardController> {
private Cursor cursor;
private final Activity activity;
AppPreviewAdapter(Activity activity) {
this.activity = activity;
}
@Override
public AppCardController onCreateViewHolder(ViewGroup parent, int viewType) {
return new AppCardController(activity, activity.getLayoutInflater()
.inflate(R.layout.app_card_normal, parent, false));
}
@Override
public void onBindViewHolder(AppCardController holder, int position) {
cursor.moveToPosition(position);
holder.bindApp(new App(cursor));
}
@Override
public int getItemCount() {
return cursor == null ? 0 : cursor.getCount();
}
public void setAppCursor(Cursor cursor) {
this.cursor = cursor;
notifyDataSetChanged();
}
}
| gpl-3.0 |
mars7105/JKLubTV | src/de/turnierverwaltung/view/export/HTMLToClipBoardDialogView.java | 3268 | package de.turnierverwaltung.view.export;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dialog;
import java.util.ArrayList;
import java.util.ListIterator;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import de.turnierverwaltung.view.ButtonPanelView;
import de.turnierverwaltung.view.Messages;
import de.turnierverwaltung.view.TitleLabelView;
public class HTMLToClipBoardDialogView extends JDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
private ButtonPanelView buttonPanel;
private ArrayList<HTMLToClipBoardView> htmlToClipBoard;
private TitleLabelView statusLabel;
public HTMLToClipBoardDialogView() {
super();
buttonPanel = new ButtonPanelView();
htmlToClipBoard = new ArrayList<HTMLToClipBoardView>();
statusLabel = new TitleLabelView("Clipboard:");
statusLabel.setFlowLayoutLeft();
}
public HTMLToClipBoardDialogView(ButtonPanelView buttonPanel, ArrayList<HTMLToClipBoardView> htmlToClipBoard) {
super();
this.buttonPanel = buttonPanel;
this.htmlToClipBoard = htmlToClipBoard;
statusLabel = new TitleLabelView("Clipboard:");
makeDialog(htmlToClipBoard);
}
public ButtonPanelView getButtonPanel() {
return buttonPanel;
}
public ArrayList<HTMLToClipBoardView> getHtmlToClipBoard() {
return htmlToClipBoard;
}
public TitleLabelView getStatusLabel() {
return statusLabel;
}
public void makeDialog(ArrayList<HTMLToClipBoardView> htmlToClipBoard) {
TitleLabelView titleview = new TitleLabelView(Messages.getString("HTMLToClipBoardView.1"));
titleview.setFlowLayoutLeft();
setTitle(Messages.getString("HTMLToClipBoardView.2"));
setLayout(new BorderLayout());
JPanel main = new JPanel();
main.setLayout(new BoxLayout(main, BoxLayout.PAGE_AXIS));
ListIterator<HTMLToClipBoardView> list = htmlToClipBoard.listIterator();
while (list.hasNext()) {
JSeparator separator = new JSeparator();
separator.setBorder(BorderFactory.createLineBorder(Color.black, 1));
main.add(list.next());
main.add(separator);
}
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
add(titleview, BorderLayout.NORTH);
mainPanel.add(main, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(mainPanel);
add(scrollPane, BorderLayout.CENTER);
buttonPanel.makeOKButton();
JPanel southPanel = new JPanel();
southPanel.setLayout(new BoxLayout(southPanel, BoxLayout.PAGE_AXIS));
southPanel.add(new JSeparator());
southPanel.add(statusLabel);
southPanel.add(buttonPanel);
add(southPanel, BorderLayout.SOUTH);
statusLabel.setFlowLayoutLeft();
}
public void showDialog() {
pack();
setLocationRelativeTo(null);
setEnabled(true);
setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
setVisible(true);
}
public void setButtonPanel(ButtonPanelView buttonPanel) {
this.buttonPanel = buttonPanel;
}
public void setHtmlToClipBoard(ArrayList<HTMLToClipBoardView> htmlToClipBoard) {
this.htmlToClipBoard = htmlToClipBoard;
}
public void setStatusLabel(TitleLabelView statusLabel) {
this.statusLabel = statusLabel;
}
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | frameworks/base/packages/SystemUI/src/com/android/systemui/qs/tiles/AirplaneModeTile.java | 4096 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.qs.tiles;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.provider.Settings.Global;
import com.android.systemui.R;
import com.android.systemui.qs.GlobalSetting;
import com.android.systemui.qs.QSTile;
/** Quick settings tile: Airplane mode **/
public class AirplaneModeTile extends QSTile<QSTile.BooleanState> {
private final AnimationIcon mEnable =
new AnimationIcon(R.drawable.ic_signal_airplane_enable_animation);
private final AnimationIcon mDisable =
new AnimationIcon(R.drawable.ic_signal_airplane_disable_animation);
private final GlobalSetting mSetting;
private boolean mListening;
public AirplaneModeTile(Host host) {
super(host);
mSetting = new GlobalSetting(mContext, mHandler, Global.AIRPLANE_MODE_ON) {
@Override
protected void handleValueChanged(int value) {
handleRefreshState(value);
}
};
}
@Override
protected BooleanState newTileState() {
return new BooleanState();
}
@Override
public void handleClick() {
setEnabled(!mState.value);
mEnable.setAllowAnimation(true);
mDisable.setAllowAnimation(true);
}
private void setEnabled(boolean enabled) {
final ConnectivityManager mgr =
(ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
mgr.setAirplaneMode(enabled);
}
@Override
protected void handleUpdateState(BooleanState state, Object arg) {
final int value = arg instanceof Integer ? (Integer)arg : mSetting.getValue();
final boolean airplaneMode = value != 0;
state.value = airplaneMode;
state.visible = true;
state.label = mContext.getString(R.string.quick_settings_airplane_mode_label);
if (airplaneMode) {
state.icon = mEnable;
state.contentDescription = mContext.getString(
R.string.accessibility_quick_settings_airplane_on);
} else {
state.icon = mDisable;
state.contentDescription = mContext.getString(
R.string.accessibility_quick_settings_airplane_off);
}
}
@Override
protected String composeChangeAnnouncement() {
if (mState.value) {
return mContext.getString(R.string.accessibility_quick_settings_airplane_changed_on);
} else {
return mContext.getString(R.string.accessibility_quick_settings_airplane_changed_off);
}
}
public void setListening(boolean listening) {
if (mListening == listening) return;
mListening = listening;
if (listening) {
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
mContext.registerReceiver(mReceiver, filter);
} else {
mContext.unregisterReceiver(mReceiver);
}
mSetting.setListening(listening);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(intent.getAction())) {
refreshState();
}
}
};
}
| gpl-3.0 |
Bombe/rhynodge | src/main/java/net/pterodactylus/rhynodge/package-info.java | 1056 | /**
* Rhynodge main definitions.
* <p>
* A {@link net.pterodactylus.rhynodge.Reaction} consists of three different
* elements: a {@link net.pterodactylus.rhynodge.Query}, a
* {@link net.pterodactylus.rhynodge.Trigger}, and an
* {@link net.pterodactylus.rhynodge.Action}.
* <p>
* A {@code Query} retrieves the current state of a system; this can simply be
* the current state of a local file, or it can be the last tweet of a certain
* Twitter account, or it can be anything inbetween, or something completely
* different.
* <p>
* After a {@code Query} retrieved the current
* {@link net.pterodactylus.rhynodge.State} of a system, this state and the
* previously retrieved state are handed in to a {@code Trigger}. The trigger
* then decides whether the state of the system can be considered a change.
* <p>
* If a system has been found to trigger, an {@code Action} is executed. It
* performs arbitrary actions and can use both the current state and the
* previous state to define that action.
*/
package net.pterodactylus.rhynodge;
| gpl-3.0 |
TheGreatAndPowerfulWeegee/wipunknown | build/tmp/recompileMc/sources/net/minecraft/entity/EntityFlying.java | 2794 | package net.minecraft.entity;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
public abstract class EntityFlying extends EntityLiving
{
public EntityFlying(World worldIn)
{
super(worldIn);
}
public void fall(float distance, float damageMultiplier)
{
}
protected void updateFallState(double y, boolean onGroundIn, IBlockState state, BlockPos pos)
{
}
public void travel(float p_191986_1_, float p_191986_2_, float p_191986_3_)
{
if (this.isInWater())
{
this.moveRelative(p_191986_1_, p_191986_2_, p_191986_3_, 0.02F);
this.move(MoverType.SELF, this.motionX, this.motionY, this.motionZ);
this.motionX *= 0.800000011920929D;
this.motionY *= 0.800000011920929D;
this.motionZ *= 0.800000011920929D;
}
else if (this.isInLava())
{
this.moveRelative(p_191986_1_, p_191986_2_, p_191986_3_, 0.02F);
this.move(MoverType.SELF, this.motionX, this.motionY, this.motionZ);
this.motionX *= 0.5D;
this.motionY *= 0.5D;
this.motionZ *= 0.5D;
}
else
{
float f = 0.91F;
if (this.onGround)
{
f = this.world.getBlockState(new BlockPos(MathHelper.floor(this.posX), MathHelper.floor(this.getEntityBoundingBox().minY) - 1, MathHelper.floor(this.posZ))).getBlock().slipperiness * 0.91F;
}
float f1 = 0.16277136F / (f * f * f);
this.moveRelative(p_191986_1_, p_191986_2_, p_191986_3_, this.onGround ? 0.1F * f1 : 0.02F);
f = 0.91F;
if (this.onGround)
{
f = this.world.getBlockState(new BlockPos(MathHelper.floor(this.posX), MathHelper.floor(this.getEntityBoundingBox().minY) - 1, MathHelper.floor(this.posZ))).getBlock().slipperiness * 0.91F;
}
this.move(MoverType.SELF, this.motionX, this.motionY, this.motionZ);
this.motionX *= (double)f;
this.motionY *= (double)f;
this.motionZ *= (double)f;
}
this.prevLimbSwingAmount = this.limbSwingAmount;
double d1 = this.posX - this.prevPosX;
double d0 = this.posZ - this.prevPosZ;
float f2 = MathHelper.sqrt(d1 * d1 + d0 * d0) * 4.0F;
if (f2 > 1.0F)
{
f2 = 1.0F;
}
this.limbSwingAmount += (f2 - this.limbSwingAmount) * 0.4F;
this.limbSwing += this.limbSwingAmount;
}
/**
* returns true if this entity is by a ladder, false otherwise
*/
public boolean isOnLadder()
{
return false;
}
} | gpl-3.0 |
Transkribus/TranskribusCore | src/test/java/eu/transkribus/core/io/formats/IngestHTRIntoAbbyyXML.java | 42501 | package eu.transkribus.core.io.formats;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.persistence.tools.file.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.google.common.io.Files;
import com.itextpdf.text.Image;
import eu.transkribus.core.io.LocalDocReader;
import eu.transkribus.core.model.beans.pagecontent.PcGtsType;
import eu.transkribus.core.util.JaxbUtils;
import eu.transkribus.core.util.PageXmlUtils;
import eu.transkribus.core.util.XmlUtils;
import eu.transkribus.interfaces.types.util.ImageUtils;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import javax.imageio.ImageIO;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
public class IngestHTRIntoAbbyyXML {
private static final Logger logger = LoggerFactory.getLogger(IngestHTRIntoAbbyyXML.class);
private static boolean createFinalPageXml = false;
public static void main(String[] args) throws IOException {
if (createFinalPageXml){
String imgDir = args[2];
File imgFileDir = new File(imgDir);
File convertedFileDir = new File(imgDir +"/convertedAbbyy/" );
if(!convertedFileDir.exists()){
logger.error("'convertedAbbyy' directoriy does not exist: " + args[2]);
return;
}
File[] ocrFiles = convertedFileDir.listFiles();
File[] imgFiles = imgFileDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile();
}
});
String resultDir = imgFileDir.getAbsolutePath()+"/convertedPage/";
new File(resultDir).mkdirs();
for (File abbyyXml : ocrFiles){
if (abbyyXml != null){
BufferedImage img = null;
String imgFn = abbyyXml != null ? imgDir + File.separator + StringUtils.substringBefore(abbyyXml.getName(),".xml") + ".jpg" : "";
logger.debug("imgFn " + imgFn);
File imgFile = new File(imgFn);
if (imgFile.exists()){
try
{
img = ImageIO.read(imgFile.getAbsoluteFile());
File pageOutFile = new File(resultDir+abbyyXml.getName());
if (pageOutFile.exists()){
continue;
}
createPageXml(pageOutFile, true, abbyyXml, true, true, false, imgFile.getName(), new Dimension(img.getWidth(), img.getHeight()));
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
else{
//Y:\HTR\Wiener_Adressbuch\done\htr_in Y:\HTR\Wiener_Adressbuch\done\ocr
if(args.length != 2){
usage();
return;
}
final String htrDir, ocrDir;
htrDir = args[0];
ocrDir = args[1];
File htrMainDir = new File(htrDir);
File ocrMainDir = new File(ocrDir);
ingestHtrIntoAbbyyForAllFolders(ocrMainDir, htrMainDir);
}
}
private static void ingestHtrIntoAbbyyForAllFolders(File ocrDir, File htrAndImgDir) throws IOException {
if(!ocrDir.exists() || !htrAndImgDir.exists()){
logger.error("One of the start directories does not exist: " + ocrDir + " or " + htrAndImgDir);
usage();
return;
}
if (htrAndImgDir.listFiles().length != ocrDir.listFiles().length){
logger.error("Directories must contain the same number of folders!");
usage();
return;
}
int countAllConverted = 0;
for (File imgFileDir : htrAndImgDir.listFiles()){
File ocrFileDir = new File(ocrDir.getAbsolutePath() + File.separator + imgFileDir.getName() + "/ocr");
logger.debug("ocr folder: " + ocrFileDir.getAbsolutePath());
File[] ocrFiles = ocrFileDir.listFiles();
File htrFileDir = new File(imgFileDir.getAbsolutePath() + "/page");
logger.debug("htr folder: " + htrFileDir.getAbsolutePath());
File[] htrFiles = htrFileDir.listFiles();
logger.debug("img folder: " + imgFileDir.getAbsolutePath());
File[] imgFiles = imgFileDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile();
}
});
File resultDir = new File(htrAndImgDir.getParentFile().getAbsolutePath() + "/converted" + File.separator + imgFileDir.getName() + File.separator + "ocr");
// if (resultDir.exists()){
// logger.debug(resultDir.getAbsolutePath() + " Result dir exists already - try next one");
// continue;
// }
resultDir.mkdirs();
logger.debug("resultDir folder: " + resultDir.getAbsolutePath());
File sampleDir = new File(htrAndImgDir.getParentFile().getAbsolutePath() + "/samples" + File.separator);
sampleDir.mkdirs();
logger.debug("sampleDir folder: " + sampleDir.getAbsolutePath());
if (htrFiles.length != ocrFiles.length){
logger.error("Directories must contain the same number of files!");
usage();
return;
}
Arrays.sort(htrFiles, (a, b) -> a.getName().compareToIgnoreCase(b.getName()));
Arrays.sort(ocrFiles, (a, b) -> a.getName().compareToIgnoreCase(b.getName()));
Arrays.sort(imgFiles, (a, b) -> a.getName().compareToIgnoreCase(b.getName()));
//
// displayFiles(htrFiles);
// displayFiles(ocrFiles);
// displayFiles(imgFiles);
int nr = 0;
for (File htr : htrFiles){
// String ocrName = findOcrFilename(htr);
// String ocrFn = ocrName != null ? ocrFileDir + File.separator + ocrName + ".xml" : "";
String ocrFn = ocrFileDir + File.separator + FilenameUtils.getBaseName(htr.getName())+ ".xml";
logger.debug("ocrFn " + ocrFn);
File ocrFile = new File(ocrFn);
if (ocrFile.exists()){
// logger.debug("htr file: " + htr.getName());
// logger.debug("ocr file: " + ocrFile.getName());
//
// System.in.read();
File convertedFile = new File(resultDir.getAbsolutePath()+File.separator+htr.getName());
if (convertedFile.exists()){
logger.debug("Already converted (" + countAllConverted++ + ")");
nr++;
continue;
}
//ingestHTRIntoOCR(htr, ocrFiles[nr++]);
File abbyyXml = combineHTRAndOCR(htr, ocrFile, convertedFile);
//take test sample for every 500th page
if (abbyyXml != null && nr % 500 == 400){
String resultPageDir = sampleDir.getAbsolutePath()+"/page/";
new File(resultPageDir).mkdirs();
File pageOutFile = new File(resultPageDir+htr.getName());
BufferedImage img = null;
try
{
img = ImageIO.read(imgFiles[nr].getAbsoluteFile());
FileUtils.copyFileToDirectory(imgFiles[nr], sampleDir);
createPageXml(pageOutFile, true, abbyyXml, true, true, false, imgFiles[nr].getName(), new Dimension(img.getWidth(), img.getHeight()));
}
catch (IOException e)
{
e.printStackTrace();
}
}
nr++;
}
else{
logger.error("No ocr File found :(");
}
}
}
}
private static void startSimpleTestWithFilenames(){
// read from files
String htrFilename= "C:/01_Projekte/READ/Projekte/Lehmann/Konvertierung/page/00000101.xml";
String ocrFilename = "C:/01_Projekte/READ/Projekte/Lehmann/Konvertierung/ocr/3697706.xml";
ingestHTRIntoOCR(new File(htrFilename), new File(ocrFilename));
}
private static String findOcrFilename(File htrFile){
try {
FileInputStream fileIsHTR = new FileInputStream(htrFile);
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document htrDocument = builder.parse(fileIsHTR);
XPath xPath = XPathFactory.newInstance().newXPath();
String expressionMd = "//TranskribusMetadata";
NodeList nodeListHTR = (NodeList) xPath.compile(expressionMd).evaluate(htrDocument, XPathConstants.NODESET);
System.out.println("nodeList length " + nodeListHTR.getLength());
for (int i = 0; i < nodeListHTR.getLength(); i++){
NamedNodeMap htrLineString = nodeListHTR.item(i).getAttributes();
Node pageId = nodeListHTR.item(i).getAttributes().getNamedItem("pageId");
if (pageId != null){
return pageId.getTextContent();
}
}
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private static void ingestHTRIntoOCR(File htrFile, File ocrFile) {
try {
FileInputStream fileIsHTR = new FileInputStream(htrFile);
FileInputStream fileIsOCR = new FileInputStream(ocrFile);
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document htrDocument = builder.parse(fileIsHTR);
Document ocrDocument = builder.parse(fileIsOCR);
XPath xPath = XPathFactory.newInstance().newXPath();
String expressionHTR = "//TextLine/TextEquiv/Unicode";
String expressionOCR = "//line";
//xPath: get all charParams for current node
String expAllCharParamsOfLine = ".//charParams";
NodeList nodeListOCR = (NodeList) xPath.compile(expressionOCR).evaluate(ocrDocument, XPathConstants.NODESET);
NodeList nodeListHTR = (NodeList) xPath.compile(expressionHTR).evaluate(htrDocument, XPathConstants.NODESET);
int countEqualLines = 0;
int countUnequalLines = 0;
int countEqualLineLengths = 0;
int countUnequalLinesLenths = 0;
// String test = "test";
// for (char c : test.toCharArray()){
// System.out.println(c);
//
// }
//System.out.println("result is " + result);
// // and iterate on links
System.out.println("nodeList length " + nodeListHTR.getLength());
for (int i = 0; i < nodeListHTR.getLength(); i++){
String htrLineString = nodeListHTR.item(i).getTextContent();
// NodeList formatting = nodeListOCR.item(i).getChildNodes();
// for (int j = 0; j<formatting.getLength(); j++){
// //NodeList charParams = formatting.item(j).getChildNodes();
//
// logger.debug("node " + formatting.item(j));
Node ocrLine = (Node) nodeListOCR.item(i);
Node formatting = ocrLine.getLastChild();
//logger.debug(ocrLine.getLastChild().getNodeName());
String left = "", right = "", top = "", bottom = "";
NamedNodeMap ocrLineAttributes = ocrLine.getAttributes();
for (int l = 0; l<ocrLineAttributes.getLength(); l++){
Node currAttr = ocrLineAttributes.item(l);
//logger.debug("node map name " + currAttr.getNodeName());
switch (currAttr.getNodeName()){
case "l": left=currAttr.getNodeValue();
case "r": right=currAttr.getNodeValue();
case "t": top=currAttr.getNodeValue();
case "b": bottom=currAttr.getNodeValue();
default: break;
}
}
int lineLeft = Integer.valueOf(left);
int lineRight = Integer.valueOf(right);
int lineTop = Integer.valueOf(top);
int lineBottom = Integer.valueOf(bottom);
NodeList nlCharParams = (NodeList) xPath.compile(expAllCharParamsOfLine).evaluate((Node) nodeListOCR.item(i), XPathConstants.NODESET);
// logger.debug("ocr length: " + nlCharParams.getLength());
// logger.debug("htr length: " + htrLineString.length());
boolean differentLength = nlCharParams.getLength() != htrLineString.length();
float newCharWidth = ( (Integer.valueOf(right)-Integer.valueOf(left))/htrLineString.length());
String ocrLineString = "";
for (int k = 0; k<nlCharParams.getLength(); k++){
ocrLineString += nlCharParams.item(k).getTextContent();
}
// logger.debug("htr line text: " + htrLineString);
// logger.debug("ocr line text: " + ocrLineString);
if (htrLineString.length() == ocrLineString.length()){
countEqualLineLengths++;
}
else{
countUnequalLinesLenths++;
}
if (htrLineString.equals(ocrLineString)){
// logger.debug("ocr and htr are the same - keep charparams as they are!!");
countEqualLines++;
continue;
}
else{
countUnequalLines++;
//logger.debug("go on");
}
// if (ocrLineString.length() > htrLineString.length()){
// System.in.read();
// }
for (int k = 0; k<nlCharParams.getLength(); k++){
Node charParamInOCR = nlCharParams.item(k);
Character ocrChar = nlCharParams.item(k).getTextContent().charAt(0);
Character htrChar = k<htrLineString.length()? htrLineString.charAt(k) : null;
// NamedNodeMap nodeMap = charParamInOCR.getAttributes();
// for (int l = 0; l<nodeMap.getLength(); l++){
// logger.debug("node map name " + nodeMap.item(l).getNodeName());
// logger.debug("node map " + nodeMap.item(l).getNodeValue());
// }
/*
* cases to be considered
* (1) ocr line shorter than htr -> add charparams for all additional chars
* (2) htr line shorter than ocr -> delete needless chars
* (3) equal size -> only replace text content for unequal chars
* (4) empty char in htr text but not in ocr
*/
//case 2: pointless ocr charParams need to be deleted
if(htrChar == null){
// logger.debug("remove child: " + charParamInOCR.getTextContent());
//text node of this element needs to be removed as well - otherwise you get empty lines in xml
Node prevElem = charParamInOCR.getPreviousSibling();
if (prevElem != null &&
prevElem .getNodeType() == Node.TEXT_NODE &&
prevElem .getNodeValue().trim().length() == 0) {
charParamInOCR.getParentNode().removeChild(prevElem);
}
//System.in.read();
charParamInOCR.getParentNode().removeChild(charParamInOCR);
continue;
}
//if chars differ: replace ocr with htr (includes case 3, valid for case 1 and 2 too)
if (ocrChar != htrChar){
//if we deal with different length of htr and ocr we newly calculate the coordinates of the bounding box of each character
if (differentLength){
int l = (int) (lineLeft+newCharWidth*k);
int r = (int) (lineLeft+newCharWidth*(k+1));
Node leftCoord = charParamInOCR.getAttributes().getNamedItem("l");
leftCoord.setNodeValue(Integer.toString(l));
Node rightCoord = charParamInOCR.getAttributes().getNamedItem("r");
rightCoord.setNodeValue(Integer.toString(r));
}
//empty space - insert and add wordStart = 1;
if (Character.isSpaceChar(htrChar)){//.equals("\u0020")){
if (charParamInOCR.getNextSibling() != null && charParamInOCR.getNextSibling().getNextSibling() != null){
Node wordStart = charParamInOCR.getNextSibling().getNextSibling().getAttributes().getNamedItem("wordStart");
if (wordStart != null){
wordStart.setNodeValue("1");
}
}
}
//set wordStart=0
else if (Character.isSpaceChar(ocrChar)){
if (charParamInOCR.getNextSibling() != null && charParamInOCR.getNextSibling().getNextSibling() != null){
logger.debug(charParamInOCR.getNextSibling().getNextSibling().getNodeName());
Node wordStart = charParamInOCR.getNextSibling().getNextSibling().getAttributes().getNamedItem("wordStart");
if (wordStart != null){
wordStart.setNodeValue("0");
}
}
}
deleteAllObsoleteAtttributes(charParamInOCR);
//Element additionalCharParam = ocrDocument.createElement("charParams");
//test if this is sufficient
charParamInOCR.setTextContent(htrChar.toString());
//charParamInOCR.getParentNode().replaceChild(charParamInOCR, charParamInOCR);
}
//nlCharParams.item(k).getParentNode().replaceChild(newChild, oldChild)
// logger.debug("node name: " + nlCharParams.item(k).getNodeName());
// if (nlCharParams.item(k).getNodeName().equals("charParams"))
// logger.debug("charParams: " + nlCharParams.item(k).getTextContent());
// if (k<htrLineString.length())
// logger.debug("vs. HTR char " + htrLineString.charAt(k));
}
//case 1:
int remaining = htrLineString.length()-ocrLineString.length();
if (remaining > 0){
//logger.debug("append node to line " + ocrLine.getTextContent());
for (int j = ocrLineString.length(); j<htrLineString.length(); j++){
/*
* calculate the left and right coordinates from lineWidth/numberOfHTRChars
* top and bottom are taken from line
*/
int l = (int) (lineLeft+newCharWidth*j);
int r = (int) (lineLeft+newCharWidth*(j+1));
Character htrChar = htrLineString.charAt(j);
Element additionalCharParam = ocrDocument.createElement("charParams");
additionalCharParam.setAttribute("l", Integer.toString(l));
additionalCharParam.setAttribute("t", top);
additionalCharParam.setAttribute("r", Integer.toString(r));
additionalCharParam.setAttribute("b", bottom);
additionalCharParam.appendChild(ocrDocument.createTextNode(htrChar.toString()));
Node node = formatting.appendChild(additionalCharParam);
// logger.debug("node added " + node.getTextContent());
//System.in.read();
}
}
//}
// for (char c : currLineString.toCharArray()){
//
// }
//logger.debug("ocr line length: " + nodeListOCR.item(i).getTextContent());
//logger.debug("child nodes of line: " + nodeListOCR.item(i).getFirstChild().getTextContent());
//logger.debug("ocr line length: " + nodeListOCR.item(i).getTextContent().length());
}
TransformerFactory tff = TransformerFactory.newInstance();
Transformer transformer = tff.newTransformer();
DOMSource xmlSource = new DOMSource(ocrDocument);
StreamResult outputTarget = new StreamResult(new File(ocrFile.getParentFile().getAbsolutePath() + File.separatorChar + htrFile.getName()));
transformer.transform(xmlSource, outputTarget);
logger.debug("Statistics of file " + htrFile.getAbsolutePath());
logger.debug("countEqualLines: "+countEqualLines);
logger.debug("countUnequalLines: " +countUnequalLines);
logger.debug("countEqualLineLengths: " +countEqualLineLengths);
logger.debug("countUnequalLinesLenths: " + countUnequalLinesLenths);
// System.out.println("nodeListOCR length " + nodeListOCR.getLength());
// for (int i = 0; i < nodeListOCR.getLength(); i++){
// logger.debug("node value: " + nodeListOCR.item(i).getTextContent().length());
// }
// Document doc1 = expandedData1.getOwnerDocument();
// // insert the nodes
// Node expandedData2 = (Node) xpath.evaluate("//expandedData", ocr, NODE);
// expandedData1.getParentNode()
// .replaceChild(doc1.adoptNode(expandedData2), expandedData1);
// // print results
// TransformerFactory.newInstance()
// .newTransformer()
// .transform(new DOMSource(doc1), new StreamResult(System.out));
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* experiment: combine OCR and HTR: the longest string wins
* seems to bring best results
* TODO: calculate error rates and compare!
*/
private static File combineHTRAndOCR(File htrFile, File ocrFile, File convertedFile) {
try {
FileInputStream fileIsHTR = new FileInputStream(htrFile);
FileInputStream fileIsOCR = new FileInputStream(ocrFile);
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document htrDocument = builder.parse(fileIsHTR);
Document ocrDocument = builder.parse(fileIsOCR);
XPath xPath = XPathFactory.newInstance().newXPath();
String expressionHTR = "//TextLine/TextEquiv/Unicode";
String expressionOCR = "//block[@blockType='Text']//line";
String expressionOCRTables = "//block[@blockType='Table']//line";
//xPath: get all charParams for current node
String expAllCharParamsOfLine = ".//charParams";
NodeList nodeListOCR = (NodeList) xPath.compile(expressionOCR).evaluate(ocrDocument, XPathConstants.NODESET);
NodeList nodeListOCRTables = (NodeList) xPath.compile(expressionOCRTables).evaluate(ocrDocument, XPathConstants.NODESET);
NodeList nodeListHTR = (NodeList) xPath.compile(expressionHTR).evaluate(htrDocument, XPathConstants.NODESET);
int countEqualLines = 0;
int countUnequalLines = 0;
int countEqualLineLengths = 0;
int countUnequalLinesLenths = 0;
// String test = "test";
// for (char c : test.toCharArray()){
// System.out.println(c);
//
// }
int tableNr = 0;
//System.out.println("result is " + result);
// // and iterate on links
//System.out.println("nodeList length " + nodeListHTR.getLength());
for (int i = 0; i < nodeListHTR.getLength(); i++){
String htrLineString = nodeListHTR.item(i).getTextContent();
// NodeList formatting = nodeListOCR.item(i).getChildNodes();
// for (int j = 0; j<formatting.getLength(); j++){
// //NodeList charParams = formatting.item(j).getChildNodes();
//
// logger.debug("node " + formatting.item(j));
Node ocrLine = (Node) nodeListOCR.item(i);
Node formatting = null;
if (ocrLine != null){
//logger.debug("ocr line not null");
formatting = ocrLine.getLastChild();
}
else{
logger.debug("ocr line is null - try table lines");
ocrLine = (Node) nodeListOCRTables.item(tableNr++);
}
if (ocrLine == null){
logger.debug("ocr line is null");
logger.debug("htr file name: " + htrFile.getName());
logger.debug("ocr file name: " + ocrFile.getName());
}
//logger.debug(ocrLine.getLastChild().getNodeName());
String left = "", right = "", top = "", bottom = "";
NamedNodeMap ocrLineAttributes = ocrLine.getAttributes();
for (int l = 0; l<ocrLineAttributes.getLength(); l++){
Node currAttr = ocrLineAttributes.item(l);
//logger.debug("node map name " + currAttr.getNodeName());
switch (currAttr.getNodeName()){
case "l": left=currAttr.getNodeValue();break;
case "r": right=currAttr.getNodeValue();break;
case "t": top=currAttr.getNodeValue();break;
case "b": bottom=currAttr.getNodeValue();break;
default: break;
}
}
int lineLeft = Integer.valueOf(left);
int lineRight = Integer.valueOf(right);
int lineTop = Integer.valueOf(top);
int lineBottom = Integer.valueOf(bottom);
NodeList nlCharParams = (NodeList) xPath.compile(expAllCharParamsOfLine).evaluate(ocrLine, XPathConstants.NODESET);
// logger.debug("ocr length: " + nlCharParams.getLength());
// logger.debug("htr length: " + htrLineString.length());
String ocrLineString = "";
String penaltyString = "";
boolean ocrIsWorse = false;
for (int k = 0; k<nlCharParams.getLength(); k++){
ocrLineString += nlCharParams.item(k).getTextContent();
// Node penalty = nlCharParams.item(k).getAttributes().getNamedItem("wordPenalty");
// Node charConf = nlCharParams.item(k).getAttributes().getNamedItem("charConfidence");
//
// if (penalty != null){
// penaltyString = penalty.getTextContent();
// }
//
// if (penalty != null && Integer.valueOf(penalty.getTextContent())>20){
// logger.debug("word Penalty: " + penalty.getTextContent());
//
// ocrIsWorse = true;
// }
// if (charConf != null && charConf.getTextContent().equals("-1")){
// logger.debug("char Confidence: " + charConf.getTextContent());
// ocrIsWorse = true;
// }
}
// logger.debug("htr line text: " + htrLineString);
// logger.debug("ocr line text: " + ocrLineString);
if (htrLineString.length() == ocrLineString.length()){
countEqualLineLengths++;
}
else{
countUnequalLinesLenths++;
}
if (htrLineString.equals(ocrLineString)){
// logger.debug("ocr and htr are the same - keep charparams as they are!!");
countEqualLines++;
continue;
}
countUnequalLines++;
/*
* this HTR correction with better OCR does not bring better results for an already good HTR
*/
//if (ocrLineString.replaceAll("\\s","").length() > htrLineString.replaceAll("\\s","").length()){
// if (ocrLineString.length() > htrLineString.length()
// && (ocrLineString.length() - htrLineString.length()>2)){
// logger.debug("OCR String longer then HTR string - OCR could be better");
// logger.debug("is ocr better? " + !ocrIsWorse);
// //System.in.read();
// //continue;
// }
//
// if (ocrLineString.length() > htrLineString.length()
// && (ocrLineString.length() - htrLineString
// .length()>2) && !ocrIsWorse){
// logger.debug("OCR String longer then HTR string - OCR wins");
// logger.debug("penaltyString " + penaltyString);
// //System.in.read();
// continue;
// }
// if(wordPenalty){
// System.in.read();
// }
boolean differentLength = nlCharParams.getLength() != htrLineString.length();
int nrOfChars = (htrLineString.length()>0 ? htrLineString.length() : ocrLineString.length());
double newCharWidth = Math.ceil(( (Integer.valueOf(right)-Integer.valueOf(left))/nrOfChars));
//logger.debug("new CharWidth is " + newCharWidth);
// if (ocrLineString.length() > htrLineString.length()){
// System.in.read();
// }
for (int k = 0; k<nlCharParams.getLength(); k++){
Node charParamInOCR = nlCharParams.item(k);
Character ocrChar = nlCharParams.item(k).getTextContent().charAt(0);
Character htrChar = k<htrLineString.length()? htrLineString.charAt(k) : null;
// NamedNodeMap nodeMap = charParamInOCR.getAttributes();
// for (int l = 0; l<nodeMap.getLength(); l++){
// logger.debug("node map name " + nodeMap.item(l).getNodeName());
// logger.debug("node map " + nodeMap.item(l).getNodeValue());
// }
/*
* cases to be considered
* (1) ocr line shorter than htr -> add charparams for all additional chars
* (2) htr line shorter than ocr -> delete needless chars
* (3) equal size -> only replace text content for unequal chars
* (4) empty char in htr text but not in ocr
*/
//case 2: pointless ocr charParams need to be deleted
if(htrChar == null){
// logger.debug("remove child: " + charParamInOCR.getTextContent());
//text node of this element needs to be removed as well - otherwise you get empty lines in xml
Node prevElem = charParamInOCR.getPreviousSibling();
if (prevElem != null &&
prevElem .getNodeType() == Node.TEXT_NODE &&
prevElem .getNodeValue().trim().length() == 0) {
charParamInOCR.getParentNode().removeChild(prevElem);
}
//System.in.read();
charParamInOCR.getParentNode().removeChild(charParamInOCR);
continue;
}
//if we deal with different length of htr and ocr we newly calculate the coordinates of the bounding box of each character
if (differentLength){
int l = (int) (lineLeft+newCharWidth*k);
int r = (int) (lineLeft+newCharWidth*(k+1));
Node leftCoord = charParamInOCR.getAttributes().getNamedItem("l");
leftCoord.setNodeValue(Integer.toString(l));
Node rightCoord = charParamInOCR.getAttributes().getNamedItem("r");
rightCoord.setNodeValue(Integer.toString(r));
}
//if chars differ: replace ocr with htr (includes case 3, valid for case 1 and 2 too)
if (ocrChar != htrChar){
//empty space - insert and add wordStart = 1;
if (Character.isSpaceChar(htrChar)){//.equals("\u0020")){
if (charParamInOCR.getNextSibling() != null && charParamInOCR.getNextSibling().getNextSibling() != null){
Node wordStart = charParamInOCR.getNextSibling().getNextSibling().getAttributes().getNamedItem("wordStart");
if (wordStart != null){
wordStart.setNodeValue("1");
}
else{
Element currNode = (Element) charParamInOCR.getNextSibling().getNextSibling();
currNode.setAttribute("wordStart", "1");
}
}
}
//set wordStart=0
else if (Character.isSpaceChar(ocrChar)){
if (charParamInOCR.getNextSibling() != null && charParamInOCR.getNextSibling().getNextSibling() != null){
//logger.debug(charParamInOCR.getNextSibling().getNextSibling().getNodeName());
Node wordStart = charParamInOCR.getNextSibling().getNextSibling().getAttributes().getNamedItem("wordStart");
if (wordStart != null){
wordStart.setNodeValue("0");
}
else{
Element currNode = (Element) charParamInOCR.getNextSibling().getNextSibling();
currNode.setAttribute("wordStart", "0");
}
}
}
deleteAllObsoleteAtttributes(charParamInOCR);
//Element additionalCharParam = ocrDocument.createElement("charParams");
//test if this is sufficient
charParamInOCR.setTextContent(htrChar.toString());
//charParamInOCR.getParentNode().replaceChild(charParamInOCR, charParamInOCR);
}
//nlCharParams.item(k).getParentNode().replaceChild(newChild, oldChild)
// logger.debug("node name: " + nlCharParams.item(k).getNodeName());
// if (nlCharParams.item(k).getNodeName().equals("charParams"))
// logger.debug("charParams: " + nlCharParams.item(k).getTextContent());
// if (k<htrLineString.length())
// logger.debug("vs. HTR char " + htrLineString.charAt(k));
}
//case 1:
int remaining = htrLineString.length()-ocrLineString.length();
if (remaining > 0){
//logger.debug("append node to line " + ocrLine.getTextContent());
for (int j = ocrLineString.length(); j<htrLineString.length(); j++){
/*
* calculate the left and right coordinates from lineWidth/numberOfHTRChars
* top and bottom are taken from line
*/
int l = (int) (lineLeft+newCharWidth*j);
int r = (int) (lineLeft+newCharWidth*(j+1));
Character htrChar = htrLineString.charAt(j);
Element additionalCharParam = ocrDocument.createElement("charParams");
additionalCharParam.setAttribute("l", Integer.toString(l));
additionalCharParam.setAttribute("t", top);
additionalCharParam.setAttribute("r", Integer.toString(r));
additionalCharParam.setAttribute("b", bottom);
additionalCharParam.appendChild(ocrDocument.createTextNode(htrChar.toString()));
if (formatting != null){
formatting.appendChild(additionalCharParam);
//logger.debug("node added " + node.getTextContent());
//System.in.read();
}
else{
ocrLine.appendChild(additionalCharParam);
}
}
}
//}
// for (char c : currLineString.toCharArray()){
//
// }
//logger.debug("ocr line length: " + nodeListOCR.item(i).getTextContent());
//logger.debug("child nodes of line: " + nodeListOCR.item(i).getFirstChild().getTextContent());
//logger.debug("ocr line length: " + nodeListOCR.item(i).getTextContent().length());
}
TransformerFactory tff = TransformerFactory.newInstance();
Transformer transformer = tff.newTransformer();
DOMSource xmlSource = new DOMSource(ocrDocument);
//File convertedAbbyyXml = new File(htrFile.getParentFile().getParentFile().getAbsolutePath() + File.separatorChar +"ocr" + File.separatorChar + htrFile.getName());
StreamResult outputTarget = new StreamResult(convertedFile);
transformer.transform(xmlSource, outputTarget);
logger.debug("Statistics of file " + ocrFile.getAbsolutePath() );
logger.debug("countEqualLines: "+countEqualLines);
logger.debug("countUnequalLines: " +countUnequalLines);
logger.debug("countEqualLineLengths: " +countEqualLineLengths);
logger.debug("countUnequalLinesLenths: " + countUnequalLinesLenths);
//System.in.read();
return convertedFile;
// System.out.println("nodeListOCR length " + nodeListOCR.getLength());
// for (int i = 0; i < nodeListOCR.getLength(); i++){
// logger.debug("node value: " + nodeListOCR.item(i).getTextContent().length());
// }
// Document doc1 = expandedData1.getOwnerDocument();
// // insert the nodes
// Node expandedData2 = (Node) xpath.evaluate("//expandedData", ocr, NODE);
// expandedData1.getParentNode()
// .replaceChild(doc1.adoptNode(expandedData2), expandedData1);
// // print results
// TransformerFactory.newInstance()
// .newTransformer()
// .transform(new DOMSource(doc1), new StreamResult(System.out));
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private static void deleteAllObsoleteAtttributes(Node charParamInOCR) throws IOException
{
//logger.debug("deleteAllObsoleteAtttributes " + charParamInOCR.getTextContent());
NamedNodeMap charParamAttributes = charParamInOCR.getAttributes();
ArrayList<String> attrName =new ArrayList<String>();
/*
* copy the attribute names - charParamAttributes shrinks with removing the attributes
* and with the attribute names we can find and remove the attribute
*/
for (int l = 0; l<charParamAttributes.getLength(); l++){
attrName.add(charParamAttributes.item(l).getNodeName());
}
for (int l = 0; l<attrName.size(); l++){
// logger.debug("l " + l);
// logger.debug("curr Attr: " + attrName.get(l));
if (!attrName.get(l).matches("l|r|b|t|wordStart")){
//logger.debug("delete: " + charParamAttributes.getNamedItem(attrName.get(l)));
charParamAttributes.removeNamedItem(attrName.get(l));
}
}
//System.in.read();
}
private static void compareVersions() {
StringUtils.getLevenshteinDistance("fly", "ant");
}
/**
* Method will create a PAGE XML from the given source files at pageOutFile.
* if no supported source file exists (abbyy/alto/txt), then a skeleton will be created if possible.
* <br/><br/>
* This method must NEVER return null. Many mechanisms in Transkribus
* depend on this method reliably creating a file.
*
* @param pageOutFile
* @param doOverwrite
* @param abbyyXml
* @param altoXml
* @param txtFile
* @param preserveOcrFontFamily
* @param preserveOcrTxtStyles
* @param replaceBadChars
* @param imgFile
* @param dim
* @return
* @throws FileNotFoundException
* @throws IOException
*/
protected static File createPageXml(File pageOutFile, boolean doOverwrite, File abbyyXml, boolean preserveOcrFontFamily, boolean preserveOcrTxtStyles,
boolean replaceBadChars, final String imgFileName, Dimension dim)
throws FileNotFoundException, IOException {
if(pageOutFile == null) {
throw new IllegalArgumentException("PAGE XML output File is null.");
}
if(pageOutFile.exists() && !doOverwrite) {
throw new IOException("PAGE XML already exists at: " + pageOutFile.getAbsolutePath());
}
if(StringUtils.isEmpty(imgFileName)) {
throw new IllegalArgumentException("Image filename must not be empty");
}
PcGtsType pc = null;
if(abbyyXml != null){
//try find Abbyy XML
pc = createPageFromAbbyy(imgFileName, abbyyXml, preserveOcrTxtStyles, preserveOcrFontFamily, replaceBadChars);
}
//from here we need the dimension of the image
if(dim == null) {
//set (0,0) here in order to make the following work
dim = new Dimension();
}
//if still null, there is no suitable file for this page yet => create one
if (pc == null) {
logger.warn("No Transcript XML found for img: " + FilenameUtils.getBaseName(imgFileName));
logger.info("Creating empty PageXml.");
pc = PageXmlUtils.createEmptyPcGtsType(imgFileName, dim);
}
//create the file
try{
JaxbUtils.marshalToFile(pc, pageOutFile);
} catch (JAXBException je) {
throw new IOException("Could not create PageXml on disk!", je);
}
return pageOutFile;
}
private static PcGtsType createPageFromAbbyy(final String imgFileName, File abbyyXml, boolean preserveOcrTxtStyles,
boolean preserveOcrFontFamily, boolean replaceBadChars) throws IOException {
try{
XmlFormat xmlFormat = XmlUtils.getXmlFormat(abbyyXml);
if(xmlFormat.equals(XmlFormat.ABBYY_10)){
logger.info(abbyyXml.getAbsolutePath() + ": Transforming Finereader10/11 XML to PAGE XML.");
PcGtsType pc = PageXmlUtils.createPcGtsTypeFromAbbyy(
abbyyXml, imgFileName,
preserveOcrTxtStyles, preserveOcrFontFamily,
replaceBadChars
);
return pc;
}
throw new IOException("Not a valid Finereader10/11 XML file.");
} catch(IOException | TransformerException ioe){
logger.error(ioe.getMessage(), ioe);
throw new IOException("Could not migrate file: " + abbyyXml.getAbsolutePath(), ioe);
} catch (ParserConfigurationException | SAXException xmle) {
logger.error(xmle.getMessage(), xmle);
throw new IOException("Could not transform XML file!", xmle);
} catch (JAXBException je) {
/* TODO This exception is only thrown when the pageXML is unmarshalled
* for inserting the image filename which is not included in the abbyy xml! */
logger.error(je.getMessage(), je);
throw new IOException("Transformation output is not a valid page XML!", je);
}
}
private static void usage() {
System.out.println("Use: java -jar jarFileName htrDirectoryName ocrDirectoryName\n"
+ "folders contain htr and ocr results and must contain the same number of files!");
return;
}
public static void displayFiles(File[] files) {
for (File file : files) {
System.out.printf("File: %-20s Last Modified:" + "\n", file.getName());
}
}
}
| gpl-3.0 |
cooked/NDT | sc.ndt.editor.fast.twr/src-gen/sc/ndt/editor/fast/fasttwr/nTwSSM2Sh6.java | 2203 | /**
*/
package sc.ndt.editor.fast.fasttwr;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>nTw SSM2 Sh6</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link sc.ndt.editor.fast.fasttwr.nTwSSM2Sh6#getValue <em>Value</em>}</li>
* <li>{@link sc.ndt.editor.fast.fasttwr.nTwSSM2Sh6#getName <em>Name</em>}</li>
* </ul>
* </p>
*
* @see sc.ndt.editor.fast.fasttwr.FasttwrPackage#getnTwSSM2Sh6()
* @model
* @generated
*/
public interface nTwSSM2Sh6 extends EObject
{
/**
* Returns the value of the '<em><b>Value</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Value</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Value</em>' attribute.
* @see #setValue(float)
* @see sc.ndt.editor.fast.fasttwr.FasttwrPackage#getnTwSSM2Sh6_Value()
* @model
* @generated
*/
float getValue();
/**
* Sets the value of the '{@link sc.ndt.editor.fast.fasttwr.nTwSSM2Sh6#getValue <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Value</em>' attribute.
* @see #getValue()
* @generated
*/
void setValue(float value);
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see sc.ndt.editor.fast.fasttwr.FasttwrPackage#getnTwSSM2Sh6_Name()
* @model
* @generated
*/
String getName();
/**
* Sets the value of the '{@link sc.ndt.editor.fast.fasttwr.nTwSSM2Sh6#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
} // nTwSSM2Sh6
| gpl-3.0 |
lu2cas/BarAccessControl | src/graphic_interface/AllClientsPanel.java | 1854 | package graphic_interface;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import business.*;
import persistence.ClientDAOMySQL;
public class AllClientsPanel extends JPanel {
private static final long serialVersionUID = 6804975934529384642L;
private JTable allClientsTable;
private JScrollPane scrollPane;
public AllClientsPanel() {}
public void makeForm() {
this.removeAll();
this.setBounds(0, 0, 600, 450);
this.setLayout(null);
try {
ClientDAOMySQL clientDAOMySQL = new ClientDAOMySQL();
ArrayList<Client> clients = clientDAOMySQL.getAllClients(true);
String[] column_names = {
"Id",
"Nome",
"CPF",
"Gênero",
"Categoria"
};
Object [][] data = new Object [clients.size()][5];
Client client;
for (int i = 0; i < clients.size(); i++) {
client = clients.get(i);
data[i] = new Object[] {
Integer.toString(client.getId()),
DataFormat.upperCaseWords(client.getName()),
DataFormat.formatCpf(client.getCpf()),
client.getFormattedGender(),
client.getFormattedCategory()
};
}
allClientsTable = new JTable(data, column_names);
allClientsTable.getColumnModel().getColumn(0).setPreferredWidth(10);
allClientsTable.getColumnModel().getColumn(1).setPreferredWidth(160);
allClientsTable.getColumnModel().getColumn(2).setPreferredWidth(80);
allClientsTable.getColumnModel().getColumn(3).setPreferredWidth(60);
allClientsTable.getColumnModel().getColumn(4).setPreferredWidth(60);
scrollPane = new JScrollPane(allClientsTable);
scrollPane.setBounds(10, 30, 575, 385);
allClientsTable.setFillsViewportHeight(true);
this.add(scrollPane);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
} | gpl-3.0 |
arcusys/Liferay-CIFS | source/java/org/alfresco/jlan/ftp/FTPDataSessionTable.java | 2656 | /*
* Copyright (C) 2006-2008 Alfresco Software Limited.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* As a special exception to the terms and conditions of version 2.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing"
*/
package org.alfresco.jlan.ftp;
import java.util.Hashtable;
/**
* FTP Data Session Table Class
*
* <p>Keeps track of FTP data session objects using the local port number as the index.
*
* @author gkspencer
*/
public class FTPDataSessionTable {
// Data session table
private Hashtable<Integer, FTPDataSession> m_sessTable;
/**
* Default constructor
*/
public FTPDataSessionTable() {
m_sessTable = new Hashtable<Integer, FTPDataSession>();
}
/**
* Add a session to the table
*
* @param port int
* @param sess FTPDataSession
*/
public final void addSession(int port, FTPDataSession sess) {
m_sessTable.put(new Integer(port), sess);
}
/**
* Find the session using the specified local port
*
* @param port int
* @return FTPDataSession
*/
public final FTPDataSession findSession(int port) {
return m_sessTable.get(new Integer(port));
}
/**
* Return the number of sessions in the table
*
* @return int
*/
public final int numberOfSessions() {
return m_sessTable.size();
}
/**
* Remove a session from the table
*
* @param sess FTPDataSession
* @return FTPDataSession
*/
public final FTPDataSession removeSession(FTPDataSession sess) {
return m_sessTable.remove(new Integer(sess.getAllocatedPort()));
}
/**
* Remove all sessions from the table
*/
public final void removeAllSessions() {
m_sessTable.clear();
}
}
| gpl-3.0 |
omnirom/android_packages_apps_Roadrunner | src/com/asksven/android/common/kernelutils/State.java | 4480 | /*
* Copyright (C) 2011 asksven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asksven.android.common.kernelutils;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.List;
import android.util.Log;
import com.asksven.android.common.privateapiproxies.Process;
import com.asksven.android.common.privateapiproxies.StatElement;
import com.google.gson.annotations.SerializedName;
/**
* Value holder for CpuState
* @author sven
*
*/
/** simple struct for states/time */
public class State extends StatElement implements Comparable<State>, Serializable
{
/**
* the tag for logging
*/
private transient static final String TAG = "Process";
private static final long serialVersionUID = 1L;
@SerializedName("freq")
public int m_freq = 0;
@SerializedName("duration_ms")
public long m_duration = 0;
public State(int freq, long duration)
{
m_freq = freq;
m_duration = duration;
}
public State clone()
{
State clone = new State(m_freq, m_duration);
clone.setTotal(this.getTotal());
return clone;
}
public String getName()
{
String ret = formatFreq(m_freq);
if (ret.equals("0 kHz"))
{
ret = "Deep Sleep";
}
return ret;
}
public String toString()
{
return getName() + " " + getData();
}
public String getData()
{
return formatDuration(m_duration) + " " + this.formatRatio(m_duration, getTotal());
}
/**
* returns a string representation of the data
*/
public String getVals()
{
return getName() + " " + this.formatDuration(m_duration) + " (" + m_duration/1000 + " s)"
+ " in " + this.formatDuration(getTotal()) + " (" + getTotal()/1000 + " s)"
+ " Ratio: " + formatRatio(m_duration, getTotal());
}
/**
* returns the values of the data
*/
public double[] getValues()
{
double[] retVal = new double[2];
retVal[0] = m_duration;
return retVal;
}
/**
* Formats a freq in Hz in a readable form
* @param freqHz
* @return
*/
String formatFreq(int freqkHz)
{
double freq = freqkHz;
double freqMHz = freq / 1000;
double freqGHz = freq / 1000 / 1000;
String formatedFreq = "";
DecimalFormat df = new DecimalFormat("#.##");
if (freqGHz >= 1)
{
formatedFreq = df.format(freqGHz) + " GHz";
}
else if (freqMHz >= 1)
{
formatedFreq = df.format(freqMHz) + " MHz";
}
else
{
formatedFreq = df.format(freqkHz) + " kHz";
}
return formatedFreq;
}
/**
* Substracts the values from a previous object
* found in myList from the current Process
* in order to obtain an object containing only the data since a referenc
* @param myList
*/
public void substractFromRef(List<StatElement> myList )
{
if (myList != null)
{
for (int i = 0; i < myList.size(); i++)
{
try
{
State myRef = (State) myList.get(i);
if ( (this.getName().equals(myRef.getName())) && (this.getuid() == myRef.getuid()) )
{
this.m_duration -= myRef.m_duration;
this.setTotal( this.getTotal() - myRef.getTotal() );
if (m_duration < 0)
{
Log.e(TAG, "substractFromRef generated negative values (" + this.m_duration + " - " + myRef.m_duration + ")");
}
break;
}
}
catch (ClassCastException e)
{
// just log as it is no error not to change the process
// being substracted from to do nothing
Log.e(TAG, "substractFromRef was called with a wrong list type");
}
}
}
}
/**
* Compare a given Wakelock with this object.
* If the duration of this object is
* greater than the received object,
* then this object is greater than the other.
*/
public int compareTo(State o)
{
// we want to sort in descending order
return ((int)( (o.m_duration) - (this.m_duration) ));
}
}
| gpl-3.0 |
jkiddo/jolivia | jolivia.protocol/src/main/java/org/dyndns/jkiddo/dmap/chunks/audio/SongSize.java | 1953 | /*******************************************************************************
* Copyright (c) 2013 Jens Kristian Villadsen.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Jens Kristian Villadsen - Lead developer, owner and creator
******************************************************************************/
/*
* Digital Audio Access Protocol (DAAP) Library
* Copyright (C) 2004-2010 Roger Kapsi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dyndns.jkiddo.dmap.chunks.audio;
import org.dyndns.jkiddo.dmp.chunks.UIntChunk;
/**
* The size of the Song in bytes.
*
* @author Roger Kapsi
*/
import org.dyndns.jkiddo.dmp.IDmapProtocolDefinition.DmapChunkDefinition;
import org.dyndns.jkiddo.dmp.DMAPAnnotation;
@DMAPAnnotation(type=DmapChunkDefinition.assz)
public class SongSize extends UIntChunk
{
/**
* Creates a new SongSize with 0-length You can change this value with {@see #setValue(int)}.
*/
public SongSize()
{
this(0);
}
/**
* Creates a new SongSize with the assigned size. You can change this value with {@see #setValue(int)}.
*
* @param <tt>size</tt> the size of this song in bytes.
*/
public SongSize(long size)
{
super("assz", "daap.songsize", size);
}
}
| gpl-3.0 |
flower-platform/flower-platform-4 | org.flowerplatform.core/src/org/flowerplatform/core/FlowerProperties.java | 6845 | /* license-start
*
* Copyright (C) 2008 - 2014 Crispico Software, <http://www.crispico.com/>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation version 3.
*
* 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, at <http://www.gnu.org/licenses/>.
*
* license-end
*/
package org.flowerplatform.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Central repository for configuration related properties.
*
* <p>
* For doc, rules and conventions, please see the wiki page http://csp1/dokuwiki/proiecte/flower/general_instructions/properties_and_configuration
*
* <p>
* Note : all new {@link AddProperty} validators must be added also in the wiki.
*
* @author Cristian Spiescu
* @author Cristina Constantinescu
* @author Cristina Brinza
*/
public class FlowerProperties extends Properties {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LoggerFactory.getLogger(FlowerProperties.class);
public static final long DB_VERSION = 0;
private static final String PROPERTIES_FILE = "META-INF/flower-platform.properties";
private static final String PROPERTIES_FILE_LOCAL = CoreConstants.FLOWER_PLATFORM_HOME + "/flower-platform.properties";
/**
*@author see class
**/
/* package */ FlowerProperties() {
super();
defaults = new Properties();
// get properties from global and local file, if exists
try {
// get properties from global file first
InputStream is = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE);
if (is != null) {
this.load(is);
IOUtils.closeQuietly(is);
}
} catch (IOException e) {
throw new RuntimeException(String.format("Error while loading properties from %s file.", PROPERTIES_FILE), e);
}
try {
// get properties from local file, if exists
File file = new File(PROPERTIES_FILE_LOCAL);
if (file.exists()) {
FileInputStream fis = new FileInputStream(file);
if (fis != null) {
this.load(fis);
IOUtils.closeQuietly(fis);
}
}
} catch (IOException e) {
throw new RuntimeException(String.format("Error while loading properties from %s file.", PROPERTIES_FILE_LOCAL), e);
}
}
/**
*@author see class
**/
public void addProperty(AddProperty p) {
if (p.propertyName == null || p.propertyDefaultValue == null) {
throw new IllegalArgumentException("Property name and default value shouldn't be null.");
}
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Adding property with name = {}, default value = {}, user value = {}",
new Object[] { p.propertyName, p.propertyDefaultValue, get(p.propertyName) });
}
defaults.put(p.propertyName, p.propertyDefaultValue);
String userValue = (String) get(p.propertyName);
if (userValue != null) {
// if the user has given a value, validate it
String validationErrorMessage = p.validateProperty(userValue);
if (validationErrorMessage != null) {
// validation failed;
LOGGER.error("Property Validation Error! Failed to set property = {} to value = {}; reverting to default = {}. Reason: {}",
new Object[] {p.propertyName, userValue, p.propertyDefaultValue, validationErrorMessage});
remove(p.propertyName);
}
} else {
if (p.inputFromFileMandatory) {
// Mariana: if the user did not provide a value and the property is mandatory => validation error
LOGGER.error("Property Validation Error! Failed to provide a value for mandatory property = {}; default value is set to = {}.",
new Object[] {p.propertyName, p.propertyDefaultValue});
}
}
}
public Properties getDefaults() {
return defaults;
}
/**
*@author see class
**/
public abstract static class AddProperty {
protected String propertyName;
protected String propertyDefaultValue;
protected boolean inputFromFileMandatory = false;
/**
*@author see class
**/
public AddProperty(String propertyName, String propertyDefaultValue) {
super();
this.propertyName = propertyName;
this.propertyDefaultValue = propertyDefaultValue;
}
/**
*@author see class
**/
protected abstract String validateProperty(String input);
/**
* Set to <code>true</code> if the user must provide a value for this property in the properties file.
* If the user fails to provide a value, a validation error will be logged at property validation.
* Default value is <code>false</code>, i.e. we allow <code>null</code> as a valid value for this property.
*
* @author Mariana
*/
public AddProperty setInputFromFileMandatory(boolean isInputFromFileMandatory) {
this.inputFromFileMandatory = isInputFromFileMandatory;
return this;
}
}
/**
* Accepts a boolean property; i.e. values can be 'true' or 'false'
*/
public static class AddBooleanProperty extends AddProperty {
/**
*@author see class
**/
public AddBooleanProperty(String propertyName,
String propertyDefaultValue) {
super(propertyName, propertyDefaultValue);
}
@Override
protected String validateProperty(String input) {
if ("true".equals(input) || "false".equals(input)) {
return null;
} else {
return "Value should be 'true' or 'false'";
}
}
}
/**
*@author see class
**/
public static class AddIntegerProperty extends AddProperty {
/**
*@author see class
**/
public AddIntegerProperty(String propertyName, String propertyDefaultValue) {
super(propertyName, propertyDefaultValue);
}
@Override
protected String validateProperty(String input) {
try {
Integer.valueOf(input);
return null;
} catch (Exception e) {
return "Value is not a valid integer";
}
}
}
/**
*@author see class
**/
public static class AddStringProperty extends AddProperty {
/**
*@author see class
**/
public AddStringProperty(String propertyName, String propertyDefaultValue) {
super(propertyName, propertyDefaultValue);
}
@Override
protected String validateProperty(String input) {
if (input == null || input.trim().length() == 0) {
return "Value is null or empty";
}
return null;
}
}
}
| gpl-3.0 |
otavanopisto/edelphi | edelphi-persistence/src/main/java/fi/internetix/edelphi/domainmodel/base/EmailMessage.java | 2923 | package fi.internetix.edelphi.domainmodel.base;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.TableGenerator;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import fi.internetix.edelphi.domainmodel.users.User;
@Entity
public class EmailMessage implements ArchivableEntity, ModificationTrackedEntity {
/**
* Returns internal unique id
*
* @return Internal unique id
*/
public Long getId() {
return id;
}
public void setArchived(Boolean archived) {
this.archived = archived;
}
public Boolean getArchived() {
return archived;
}
public void setCreator(User creator) {
this.creator = creator;
}
public User getCreator() {
return creator;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getCreated() {
return created;
}
public void setLastModifier(User lastModifier) {
this.lastModifier = lastModifier;
}
public User getLastModifier() {
return lastModifier;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public Date getLastModified() {
return lastModified;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="EmailMessage")
@TableGenerator(name="EmailMessage", initialValue=1, allocationSize=100, table = "hibernate_sequences", pkColumnName = "sequence_name", valueColumnName = "sequence_next_hi_value")
private Long id;
@NotNull
@Column(nullable = false)
private String fromAddress;
@NotNull
@Column (nullable=false)
private String toAddress;
private String subject;
@Column (length=1073741824)
private String content;
@NotNull
@Column(nullable = false)
private Boolean archived = Boolean.FALSE;
@ManyToOne
private User creator;
@NotNull
@Column (updatable=false, nullable=false)
@Temporal (value=TemporalType.TIMESTAMP)
private Date created;
@ManyToOne
private User lastModifier;
@NotNull
@Column (nullable=false)
@Temporal (value=TemporalType.TIMESTAMP)
private Date lastModified;
}
| gpl-3.0 |
glycoinfo/eurocarbdb | application/Eurocarbdb/src/java/org/eurocarbdb/action/EurocarbAction.java | 17149 | /*
* EuroCarbDB, a framework for carbohydrate bioinformatics
*
* Copyright (c) 2006-2009, Eurocarb project, or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.
*
* 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.
* A copy of this license accompanies this distribution in the file LICENSE.txt.
*
* 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.
*
* Last commit: $Rev: 1987 $ by $Author: glycoslave $ on $Date:: 2010-09-08 #$
*/
package org.eurocarbdb.action;
// stdlib imports
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.net.MalformedURLException;
import java.util.*;
// 3rd party imports
import org.apache.log4j.Logger;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ActionSupport;
import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.config.entities.ActionConfig;
import com.opensymphony.xwork.util.OgnlValueStack;
import com.opensymphony.webwork.interceptor.CookiesAware;
import com.opensymphony.webwork.interceptor.ParameterAware;
import com.opensymphony.webwork.config_browser.ConfigurationHelper;
import com.opensymphony.webwork.ServletActionContext;
import org.apache.commons.configuration.Configuration;
// eurocarb imports
import org.eurocarbdb.dataaccess.Eurocarb;
import org.eurocarbdb.dataaccess.EurocarbObject;
import org.eurocarbdb.dataaccess.core.Contributor;
import org.eurocarbdb.dataaccess.core.GlycanSequence;
import org.eurocarbdb.util.XmlSerialiser;
import org.eurocarbdb.gui.Navigation;
// static imports
import static org.eurocarbdb.util.StringUtils.join;
import static org.eurocarbdb.util.StringUtils.paramToInt;
import static org.eurocarbdb.util.StringUtils.lcfirst;
import static com.opensymphony.xwork.util.TextParseUtil.translateVariables;
/* class EurocarbAction *//****************************************
*<p>
* Base class for Eurocarb actions.
*</p>
*<p>
* A note on input parameters: when run in a web context, parameters
* passed to an Action class (ie: CGI parameters) may be obtained
* in 2 different ways: from the {@link Map} returned by
* {@link #getParameters}, or from the inclusion of a <tt>setAbcde</tt>
* method in the Action, where <tt>abcde</tt> is the name of a CGI
* parameter. <tt>setXxxxx</tt> methods will be called implicitly
* by the framework if there is a CGI parameter that matches a
* corresponding <tt>set</tt> method and the value of the CGI
* parameter can be coerced to the argument type of the set method.
*</p>
*
* @author mjh [glycoslave@gmail.com]
*/
public abstract class EurocarbAction extends ActionSupport
implements EurocarbObject, ParameterAware, CookiesAware
{
//~~~~~~~~~~~~~~~~~~~~~~ STATIC FIELDS ~~~~~~~~~~~~~~~~~~~~~~~~//
protected static final Logger log
= Logger.getLogger( EurocarbAction.class );
/** Auto-incrementing counter of instantiated actions, primarily used
* to identify which action is which in the logs. */
private static int actionCounter = 0;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~ FIELDS ~~~~~~~~~~~~~~~~~~~~~~~~~~//
/** Map of all parameters fed to this action, normally populated
* by webwork. @see #setParameters */
protected Map<String,String[]> params;
/** Identify which submit button in the form has been pressed */
protected String submitAction = "";
/** Specify the list of steps in a workflow */
protected String[] progress_steps = null;
/** Specify the current step in a workflow */
protected String current_step = null;
/** Cookies map */
protected Map cookiesMap = new HashMap<String,String>();
protected String sugar_image_notation = null;
/** Specifies the format to output from this Action. */
private String outputFormat = "html";
public String passErrorMessage=null;
/** Assigned at construction time to actionCounter, the index
* of this action relative to all other actions run since the
* code/server was started. Mainly useful for tracking action
* executions in the tomcat logs ;-) */
private final int actionId;
protected EurocarbAction()
{
actionId = ++actionCounter;
}
//~~~~~~~~~~~~~~~~~~~~~~ STATIC METHODS ~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~ METHODS ~~~~~~~~~~~~~~~~~~~~~~~~//
/* getCurrentContributor *//***********************************
*
* Returns the currently-active (ie: "logged on", for most
* intents and purposes) {@link Contributor}, if any, or the
* "guest" Contributor ({@link Contributor.getGuestContributor()})
* if no Contributor is active in the current {@link Thread}.
* Note that only one Contributor can be active per {@link Thread}
* at any one time (although the application may have many concurrent
* users/threads).
*
* @see Contributor.getGuestContributor()
* @see Eurocarb.getCurrentContributor()
*/
public Contributor getCurrentContributor()
{
return Contributor.getCurrentContributor();
}
/* setParameters *//*******************************************
*
* Sets a Map of input parameters to be used by this action.
* This method is implicitly called when run inside the
* webwork/struts framework with any incoming CGI parameters.
*/
@SuppressWarnings("unchecked")
public void setParameters( Map params )
{
// suppress-warnings is necessary because the webwork
// params hash is pre-java 1.5, and so is not typed.
// It does however contain String keys, String[] values
// so a direct unchecked cast should be ok.
this.params = (Map<String,String[]>) params;
if(this.params.containsKey("passErrorMessage"))
{
passErrorMessage=(this.params.get("passErrorMessage"))[0];
}
}
/* getParameters *//*******************************************
*<p>
* Gets the Map of input parameters that have been provided to
* this action. The keys of the map are parameter names, the values
* are an array of String values for those names.
*</p>
*<p>
* Note that this method of accessing input parameters is
* independent of the
*</p>
*/
public Map<String,String[]> getParameters() { return params; }
protected String[] parametersWhitelist()
{
ParameterChecking security =
this.getClass().getAnnotation(ParameterChecking.class);
if (security != null)
{
return security.whitelist();
}
return null;
}
protected String[] parametersBlacklist()
{
ParameterChecking security =
this.getClass().getAnnotation(ParameterChecking.class);
if (security != null)
{
return security.blacklist();
}
return null;
}
/**
* Use a whitelist/blacklist for this action, to determine which parameters we are going to allow
* @see ParameterChecking
*/
public boolean acceptableParameterName(String paramName)
{
String[] whitelist = parametersWhitelist();
String[] blacklist = parametersBlacklist();
boolean paramsOk = true;
if (whitelist != null)
{
paramsOk = paramsOk && (Arrays.binarySearch(whitelist,paramName) >= 0);
}
if (blacklist != null)
{
paramsOk = paramsOk && (Arrays.binarySearch(blacklist,paramName) < 0);
}
if (! paramsOk )
{
log.info("Denying setting of parameter "+paramName);
}
return paramsOk;
}
/* getProjectConfiguration *//************************************
*
* Returns global (project-wide) properties. These properties
* are derived from a eurocarb.properties file on application
* startup.
*
* @see Eurocarb#getConfiguration()
*/
//public Configuration getProjectConfiguration() { return Eurocarb.getConfiguration(); }
/* getProperty *//*********************************************
*
* Returns the value for a global (project-wide) property. These properties
* are derived from various .properties files on application startup,
* and from and user preferences if applicable.
*
* @see Eurocarb#getConfiguration()
*/
public Object getProperty( String property_name )
{
return Eurocarb.getConfiguration().getProperty( property_name );
}
/* getAllActions *//*******************************************
*
* Returns a Set view of all action names in the current namespace
* of the current application.
*
* @see Eurocarb#getProperties()
*/
public Set getAllActions()
{
// this currently gets only those actions in the ""
// webwork namespace i believe. this may change in the future.
return ConfigurationHelper.getActionNames( "" );
}
/* getCurrentActionName *//************************************
*
* Returns the name of the currently-running action.
*
* @see Eurocarb#getProperties()
*/
public String getCurrentActionName()
{
return ActionContext.getContext().getName();
}
/* getCurrentActionNamespace *//*******************************
*
* Returns the namespace of the currently-running action.
*
* @see Eurocarb#getProperties()
*/
public String getCurrentActionNamespace()
{
return ActionContext.getContext().getName();
}
/**
* Returns the current output format for this Action. Returns 'html'
* by default, unless the {@link #setOutput} has been called, eg:
* <code>my_action.action?output=xml</code>.
*/
public String getOutput()
{
return outputFormat;
}
/**
* Sets the current output format for this Action. Common values are:
* 'html' (the default), and 'xml'.
*/
public void setOutput( String output_format )
{
log.debug("setting output format = " + output_format );
this.outputFormat = output_format;
}
/**
* Returns true if the current action is capable of producing its results
* in XML format for the (default) result code 'success', according to
* the current application configuration.
*
* @see #getOutput
* @see #setOutput
*/
public boolean canGenerateXml()
{
return canGenerateXml( "success" );
}
/**
* Returns true if the current action is capable of producing its results
* in XML format for the given result code, according to the current
* application configuration - basically if there is a result named
* <code>"[result_code]-xml"</code>, then this method assumes that this
* {@link Action} is capable of generating an XML result.
*
* @see #getOutput
* @see #setOutput
*/
public boolean canGenerateXml( String result_code )
{
String action_name = this.getCurrentActionName();
String namespace = "";
ActionConfig ac = ConfigurationHelper.getActionConfig( namespace, action_name );
if ( ac == null )
return false;
return ac.getResults().containsKey( result_code + "-xml");
}
/**
* This method does not return anything useful at the moment, as
* Actions do not have {@link Version}s, per se, yet.
*/
public String getVersion()
{
return "";
}
//~~~ implementation of EurocarbObject interface methods ~~~//
/**
* Returns a value equivalent to the index of this Action in
* a list of all EurocarbActions instantiated since the code/server
* was started; primarily useful for indentifying which action
* invocation is which in the logs.
*/
public int getId()
{
return actionId;
}
public <T extends EurocarbObject> Class<T> getIdentifierClass()
{
return (Class<T>) this.getClass();
}
/**
* The "type" of an action is always "action".
* {@inheritDoc}
* @see EurocarbObject.getType()
*/
public final String getType()
{
return "action";
}
/** Set the value of the parameter used to identify which submit
* button in the form has been pressed.
* @deprecated actions should manage their own state internally
*/
@Deprecated
public void setSubmitAction(String s)
{
submitAction = s;
}
/**
* Get the name of the submit button in the form that has been pressed
* @deprecated actions should manage their own state internally
*/
@Deprecated
public String getSubmitAction()
{
return submitAction;
}
@Deprecated
public void setProgress( String s )
{
System.out.println("setProgress " + s);
if ( s == null )
{
progress_steps = null;
current_step =null;
return;
}
progress_steps = s.split(",");
for( int i=0; i<progress_steps.length; i++ )
{
if( progress_steps[i].startsWith("#") )
{
progress_steps[i] = progress_steps[i].substring(1);
current_step = progress_steps[i];
}
}
}
@Deprecated
public String[] getProgressSteps()
{
return progress_steps;
}
@Deprecated
public String getCurrentStep()
{
return current_step;
}
/** Called implicitly by webwork. */
@SuppressWarnings("unchecked")
public void setCookiesMap( Map cookies )
{
if ( cookies != null )
cookiesMap = cookies;
else
cookiesMap = new HashMap<String,String>();
if ( log.isDebugEnabled() )
{
StringBuilder sb = new StringBuilder("cookies set:\n");
for( Map.Entry e : (Set<Map.Entry>) cookies.entrySet() )
sb.append( "\t" + e.getKey() + " = " + e.getValue() + "\n" );
log.debug( sb.toString() );
}
}
public String getCookieValue( String name )
{
return cookiesMap.get(name).toString();
}
public void setSugarImageNotation( String n )
{
sugar_image_notation = n;
}
public String getSugarImageNotation()
{
return sugar_image_notation;
}
/**
* Use the entity manager to get an entity, parsing the parameter from the
* parameters hash, and adding errors to the action when this object is not
* present
*/
public <T extends EurocarbObject> T getObjectFromParams(Class<T> c, Map params)
{
String paramName = c.getName();
paramName = lcfirst(paramName.substring(paramName.lastIndexOf(".")+1));
paramName = paramName + "." + paramName + "Id";
log.debug("Getting parameter "+paramName);
T returnObject = getObjectFromParams(c, params, paramName);
if (returnObject == null)
{
this.addActionError("Must supply a valid ID for this action");
if (params.get(paramName) == null)
{
this.addFieldError(paramName, "No identifier provided");
} else
{
this.addActionError("Required identifier "+paramName+" not valid -"+paramToInt(params.get(paramName))+"-");
this.addFieldError(paramName, "Bad identifier provided: -"+ paramToInt(params.get(paramName))+"-");
}
} else
{
log.debug("Retrieved object for param with id of "+((EurocarbObject) returnObject).getId());
}
return returnObject;
}
/**
* Use the entity manager to get an entity, parsing the parameter from the
* parameters hash
*/
protected <T> T getObjectFromParams( Class<T> c, Map params, String paramName )
{
Object identifier;
if ((identifier = params.get(paramName)) != null)
{
return Eurocarb.getEntityManager().lookup( c , paramToInt(identifier) );
}
return null;
}
} // end class
| gpl-3.0 |
MusalaSoft/atmosphere-client | src/main/java/com/musala/atmosphere/client/PickerView.java | 4529 | // This file is part of the ATMOSPHERE mobile testing framework.
// Copyright (C) 2016 MusalaSoft
//
// ATMOSPHERE is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ATMOSPHERE 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 ATMOSPHERE. If not, see <http://www.gnu.org/licenses/>.
package com.musala.atmosphere.client;
import java.util.Calendar;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import com.musala.atmosphere.client.exceptions.InvalidCssQueryException;
import com.musala.atmosphere.client.exceptions.MultipleElementsFoundException;
import com.musala.atmosphere.commons.exceptions.UiElementFetchingException;
/**
* A class representing the Android picker widgets.
*
* @author delyan.dimitrov
*
*/
public abstract class PickerView {
protected Screen screen;
/**
* @param screen
* - a instance of the {@link Screen screen} object
*/
public PickerView(Screen screen) {
this.screen = screen;
}
/**
* Sets the value in the passed {@link Calendar} in the picker it represents.
*
* @param value
* - the value used to set the picker
*
* @return true if the value was set successfully, false otherwise
* @throws ParserConfigurationException
* if an error with internal XPath configuration occurs
* @throws UiElementFetchingException
* if no elements are found for the passed query
* @throws InvalidCssQueryException
* if the passed argument is invalid CSS query
* @throws XPathExpressionException
* if the conversion from CSS to XPath is unsuccessful for some reason
* @throws MultipleElementsFoundException
* if multiple elements are found for the passed query
*/
public abstract boolean setValue(Calendar value)
throws XPathExpressionException,
InvalidCssQueryException,
UiElementFetchingException,
ParserConfigurationException,
MultipleElementsFoundException;
/**
* Gets the value from the picker into a calendar object. The calendar object returned will have only its time or
* date set, depending on the picker.
*
* @return - a {@link Calendar} object with the value of the picker
* @throws ParserConfigurationException
* if an error with internal XPath configuration occurs
* @throws UiElementFetchingException
* if no elements are found for the passed query
* @throws InvalidCssQueryException
* if the passed argument is invalid CSS query
* @throws XPathExpressionException
* if the conversion from CSS to XPath is unsuccessful for some reason
* @throws MultipleElementsFoundException
* if multiple elements are found for the passed query
*/
public abstract Calendar getValue()
throws XPathExpressionException,
InvalidCssQueryException,
UiElementFetchingException,
ParserConfigurationException,
MultipleElementsFoundException;
/**
* Gets the value from the picker into a String object.
*
* @return String object with the picker's value
* @throws ParserConfigurationException
* if an error with internal XPath configuration occurs
* @throws UiElementFetchingException
* if no elements are found for the passed query
* @throws InvalidCssQueryException
* if the passed argument is invalid CSS query
* @throws XPathExpressionException
* if the conversion from CSS to XPath is unsuccessful for some reason
* @throws MultipleElementsFoundException
* if more than one element is found for the passed query
*/
public abstract String getStringValue()
throws XPathExpressionException,
InvalidCssQueryException,
UiElementFetchingException,
ParserConfigurationException,
MultipleElementsFoundException;
}
| gpl-3.0 |
TKlerx/JSAT | JSAT/src/jsat/classifiers/linear/NHERD.java | 10360 | package jsat.classifiers.linear;
import java.util.List;
import jsat.SingleWeightVectorModel;
import jsat.classifiers.BaseUpdateableClassifier;
import jsat.classifiers.CategoricalData;
import jsat.classifiers.CategoricalResults;
import jsat.classifiers.DataPoint;
import jsat.classifiers.calibration.BinaryScoreClassifier;
import jsat.exceptions.FailedToFitException;
import jsat.exceptions.UntrainedModelException;
import jsat.linear.DenseVector;
import jsat.linear.IndexValue;
import jsat.linear.Matrix;
import jsat.linear.Vec;
import jsat.parameters.Parameter;
import jsat.parameters.Parameterized;
/**
* Implementation of the Normal Herd (NHERD) algorithm for learning a linear
* binary classifier. It is related to both {@link AROW} and the PA-II variant
* of {@link PassiveAggressive}. <br>
* Unlike similar algorithms, several methods of using only the diagonal values
* of the covariance are available.
* <br>
* NOTE: This implementation does not add an implicit bias term, so the solution
* goes through the origin
* <br><br>
* See:<br>
* Crammer, K.,&Lee, D. D. (2010). <i>Learning via Gaussian Herding</i>.
* Pre-proceeding of NIPS (pp. 451–459). Retrieved from
* <a href="http://webee.technion.ac.il/Sites/People/koby/publications/gaussian_mob_nips10.pdf">
* here</a>
*
* @author Edward Raff
*/
public class NHERD extends BaseUpdateableClassifier implements BinaryScoreClassifier, Parameterized, SingleWeightVectorModel
{
private static final long serialVersionUID = -1186002893766449917L;
private Vec w;
/**
* Full covariance matrix
*/
private Matrix sigmaM;
/**
* Diagonal only covariance matrix
*/
private Vec sigmaV;
private CovMode covMode;
private double C;
/**
* Temp vector used to store Sigma * x_t
*/
private Vec Sigma_xt;
/**
* Sets what form of covariance matrix to use
*/
public static enum CovMode
{
/**
* Use the full covariance matrix
*/
FULL,
/**
* Standard diagonal method, only the diagonal values get updated by
* dropping the other terms.
*/
DROP,
/**
* Creates the diagonal by dropping the terms of the inverse of the
* covariance matrix that is used to perform the update. This authors
* suggest this is usually the best for diagonal covariance matrices
* from empirical testing.
*/
PROJECT,
/**
* Creates the diagonal by solving the derivative with respect to the
* specific objective function of NHERD
*/
EXACT
}
/**
* Creates a new NHERD learner
* @param C the aggressiveness parameter
* @param covMode how to form the covariance matrix
* @see #setC(double)
* @see #setCovMode(jsat.classifiers.linear.NHERD.CovMode)
*/
public NHERD(double C, CovMode covMode)
{
setC(C);
setCovMode(covMode);
}
/**
* Copy constructor
* @param other the object to copy
*/
protected NHERD(NHERD other)
{
this.C = other.C;
this.covMode = other.covMode;
if(other.w != null)
this.w = other.w.clone();
if(other.sigmaM != null)
this.sigmaM = other.sigmaM.clone();
if(other.sigmaV != null)
this.sigmaV = other.sigmaV.clone();
if(other.Sigma_xt != null)
this.Sigma_xt = other.Sigma_xt.clone();
}
/**
* Set the aggressiveness parameter. Increasing the value of this parameter
* increases the aggressiveness of the algorithm. It must be a positive
* value. This parameter essentially performs a type of regularization on
* the updates
*
* @param C the positive aggressiveness parameter
*/
public void setC(double C)
{
if(Double.isNaN(C) || Double.isInfinite(C) || C <= 0)
throw new IllegalArgumentException("C must be a postive constant, not " + C);
this.C = C;
}
/**
* Returns the aggressiveness parameter
* @return the aggressiveness parameter
*/
public double getC()
{
return C;
}
/**
* Sets the way in which the covariance matrix is formed. If using the full
* covariance matrix, rank-1 updates mean updates to the model take
* <i>O(d<sup>2</sup>)</i> time, where <i>d</i> is the dimension of the
* input. Runtime can be reduced by using only the diagonal of the matrix to
* perform updates in <i>O(s)</i> time, where <i>s ≤ d</i> is the number
* of non-zero values in the input
*
* @param covMode the way to form the covariance matrix
*/
public void setCovMode(CovMode covMode)
{
this.covMode = covMode;
}
/**
* Returns the mode for forming the covariance
* @return the mode for forming the covariance
*/
public CovMode getCovMode()
{
return covMode;
}
/**
* Returns the weight vector used to compute results via a dot product. <br>
* Do not modify this value, or you will alter the results returned.
* @return the learned weight vector for prediction
*/
public Vec getWeightVec()
{
return w;
}
@Override
public Vec getRawWeight()
{
return w;
}
@Override
public double getBias()
{
return 0;
}
@Override
public Vec getRawWeight(int index)
{
if(index < 1)
return getRawWeight();
else
throw new IndexOutOfBoundsException("Model has only 1 weight vector");
}
@Override
public double getBias(int index)
{
if (index < 1)
return getBias();
else
throw new IndexOutOfBoundsException("Model has only 1 weight vector");
}
@Override
public int numWeightsVecs()
{
return 1;
}
@Override
public NHERD clone()
{
return new NHERD(this);
}
@Override
public void setUp(CategoricalData[] categoricalAttributes, int numericAttributes, CategoricalData predicting)
{
if(numericAttributes <= 0)
throw new FailedToFitException("AROW requires numeric attributes to perform classification");
else if(predicting.getNumOfCategories() != 2)
throw new FailedToFitException("AROW is a binary classifier");
w = new DenseVector(numericAttributes);
Sigma_xt = new DenseVector(numericAttributes);
if(covMode != CovMode.FULL)
{
sigmaV = new DenseVector(numericAttributes);
sigmaV.mutableAdd(1);
}
else
sigmaM = Matrix.eye(numericAttributes);
}
@Override
public void update(DataPoint dataPoint, int targetClass)
{
Vec x_t = dataPoint.getNumericalValues();
double y_t = targetClass*2-1;
double pred = x_t.dot(w);
if(y_t*pred > 1)
return;//No update needed
//else, wrong label or margin too small
double alpha;
if(covMode != CovMode.FULL)
{
alpha = 0;
//Faster to set only the needed final values
for (IndexValue iv : x_t)
{
double x_ti = iv.getValue();
alpha += x_ti * x_ti * sigmaV.get(iv.getIndex());
}
}
else
{
sigmaM.multiply(x_t, 1, Sigma_xt);
alpha = x_t.dot(Sigma_xt);
}
final double loss = Math.max(0, 1 - y_t * pred);
final double w_c = y_t * loss / (alpha + 1 / C);
if (covMode == CovMode.FULL)
w.mutableAdd(w_c, Sigma_xt);
else
for (IndexValue iv : x_t)
w.increment(iv.getIndex(), w_c * iv.getValue() * sigmaV.get(iv.getIndex()));
double numer = C*(C*alpha+2);
double denom = (1+C*alpha)*(1+C*alpha);
switch (covMode)
{
case FULL:
Matrix.OuterProductUpdate(sigmaM, Sigma_xt, Sigma_xt, -numer/denom);
break;
case DROP:
final double c = -numer/denom;
for (IndexValue iv : x_t)
{
int idx = iv.getIndex();
double x_ti = iv.getValue()*sigmaV.get(idx);
sigmaV.increment(idx, c*x_ti*x_ti);
}
break;
case PROJECT:
for(IndexValue iv : x_t)//only the nonzero values in x_t will cause a change in value
{
int idx = iv.getIndex();
double x_r = iv.getValue();
double S_rr = sigmaV.get(idx);
sigmaV.set(idx, 1/(1/S_rr+numer*x_r*x_r));
}
break;
case EXACT:
for(IndexValue iv : x_t)//only the nonzero values in x_t will cause a change in value
{
int idx = iv.getIndex();
double x_r = iv.getValue();
double S_rr = sigmaV.get(idx);
sigmaV.set(idx, S_rr/(Math.pow(S_rr*x_r*x_r*C+1, 2)));
}
break;
}
//zero out temp space
if(covMode == CovMode.FULL)
Sigma_xt.zeroOut();
}
@Override
public CategoricalResults classify(DataPoint data)
{
if(w == null)
throw new UntrainedModelException("Model has not yet ben trained");
CategoricalResults cr = new CategoricalResults(2);
double score = getScore(data);
if(score < 0)
cr.setProb(0, 1.0);
else
cr.setProb(1, 1.0);
return cr;
}
@Override
public double getScore(DataPoint dp)
{
return w.dot(dp.getNumericalValues());
}
@Override
public boolean supportsWeightedData()
{
return false;
}
@Override
public List<Parameter> getParameters()
{
return Parameter.getParamsFromMethods(this);
}
@Override
public Parameter getParameter(String paramName)
{
return Parameter.toParameterMap(getParameters()).get(paramName);
}
}
| gpl-3.0 |
include110/codelibrary | src/com/net/connection/ChromeConnection.java | 2038 | package com.net.connection;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.Sleeper;
public class ChromeConnection {
public static void main(String[] args) {
System.setProperty("webdriver.firefox.bin", "D:/Program Files (x86)/Mozilla firefox/firefox.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://kyfw.12306.cn/otn/login/init");
WebElement name = driver.findElement(By.id("username"));
name.sendKeys("873059043@qq.com");
WebElement passwd = driver.findElement(By.id("password"));
passwd.sendKeys("china2013");
Sleeper(8000);
WebElement login = driver.findElement(By.id("loginSub"));
login.click();
driver.get("https://kyfw.12306.cn/otn/leftTicket/init");
driver.manage().window().maximize();
WebElement startbox = driver.findElement(By.id("fromStationText"));
startbox.click();
startbox.sendKeys("上海\n");
WebElement endbox = driver.findElement(By.id("toStationText"));
endbox.click();
endbox.sendKeys("南阳\n");
((JavascriptExecutor)driver).executeScript("document.getElementById(\"train_date\").value=\"2015-12-02\"");
WebElement box = driver.findElement(By.id("query_ticket"));
for(int i=0;i<2;i++){
Sleeper(2000);
box.click();
}
((JavascriptExecutor)driver).executeScript("document.getElementById(\"checkbox_14ksF8TbKJ\").click()");
((JavascriptExecutor)driver).executeScript("document.getElementsByClassName(\"btn72\")[0].click()");
// driver.close();
}
private static void Sleeper(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| gpl-3.0 |
ffipertani/FW | src/main/java/com/ff/app/ApplicationNameSpaceRegistry.java | 3412 | package com.ff.app;
import com.ff.app.tags.Button;
import com.ff.app.tags.Calendar;
import com.ff.app.tags.CheckBox;
import com.ff.app.tags.Column;
import com.ff.app.tags.ComboBox;
import com.ff.app.tags.Controller;
import com.ff.app.tags.Form;
import com.ff.app.tags.FreeText;
import com.ff.app.tags.Grid;
import com.ff.app.tags.Lookup;
import com.ff.app.tags.LookupGrid;
import com.ff.app.tags.Page;
import com.ff.app.tags.Script;
import com.ff.app.tags.Tab;
import com.ff.app.tags.TabPanel;
import com.ff.app.tags.Text;
import com.ff.app.tags.Toolbar;
import com.ff.app.tags.Window;
import com.ff.fw.template.NamespaceRegistry;
import com.ff.fw.template.TagRegistry;
//@Component
public class ApplicationNameSpaceRegistry extends NamespaceRegistry{
public ApplicationNameSpaceRegistry(){
TagRegistry jq = new TagRegistry();
jq.register("controller", "Controller", Controller.class);
jq.register("form", "JQForm", Form.class);
jq.register("script", "Script", Script.class);
jq.register("button", "JQButton", Button.class);
jq.register("page", "JQPage", Page.class);
jq.register("text", "JQText", Text.class);
jq.register("tabPanel", "JQTabPanel", TabPanel.class);
jq.register("tab", "JQTab", Tab.class);
jq.register("calendar", "JQCalendar", Calendar.class);
jq.register("comboBox", "JQComboBox", ComboBox.class);
jq.register("freeText", "JQFreeText", FreeText.class);
jq.register("checkBox", "JQCheckBox", CheckBox.class);
jq.register("grid", "JQGrid", Grid.class);
jq.register("column", "JQColumn", Column.class);
TagRegistry bs = new TagRegistry();
bs.register("controller", "Controller", Controller.class);
bs.register("script", "Script", Script.class);
bs.register("button", "BSButton", Button.class);
bs.register("page", "BSPage", Page.class);
bs.register("text", "BSText", Text.class);
bs.register("tabPanel", "BSTabPanel", TabPanel.class);
bs.register("tab", "BSTab", Tab.class);
bs.register("calendar", "BSCalendar", Calendar.class);
bs.register("comboBox", "BSComboBox", ComboBox.class);
bs.register("freeText", "BSFreeText", FreeText.class);
bs.register("checkBox", "BSCheckBox", CheckBox.class);
bs.register("grid", "BSGrid", Grid.class);
bs.register("column", "BSColumn", Column.class);
TagRegistry ext = new TagRegistry();
ext.register("window", "ExtWindow", Window.class);
ext.register("controller", "Controller", Controller.class);
ext.register("form", "ExtForm", Form.class);
ext.register("script", "Script", Script.class);
ext.register("button", "ExtButton", Button.class);
ext.register("page", "ExtPage", Page.class);
ext.register("text", "ExtText", Text.class);
ext.register("lookup", "ExtLookup", Lookup.class);
ext.register("lookupGrid", "ExtLookupGrid", LookupGrid.class);
ext.register("tabPanel", "ExtTabPanel", TabPanel.class);
ext.register("tab", "ExtTab", Tab.class);
ext.register("calendar", "ExtCalendar", Calendar.class);
ext.register("comboBox", "ExtComboBox", ComboBox.class);
ext.register("freeText", "ExtFreeText", FreeText.class);
ext.register("checkBox", "ExtCheckBox", CheckBox.class);
ext.register("grid", "ExtGrid", Grid.class);
ext.register("column", "ExtColumn", Column.class);
ext.register("toolbar", "ExtToolbar", Toolbar.class);
register("http://com.ff.fw.jq",jq);
register("http://com.ff.fw.bs",bs);
register("http://com.ff.fw.ext",ext);
}
}
| gpl-3.0 |
vanyle/Explorium | src/com/vanyle/sound/SoundGenerator.java | 6014 | package com.vanyle.sound;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
public class SoundGenerator {
public static double A4 = 440.;
private static int SAMPLE_RATE = 44100; // 16 * 1024 or ~16KHz
public static final byte FADE_NONE = 0;
public static final byte FADE_LINEAR = 1;
public static final byte FADE_QUADRATIC = 2;
public static final byte WAVE_SIN = 0;
public static final byte WAVE_SQUARE = 1;
public static final byte WAVE_TRIANGLE = 2;
public static final byte WAVE_SAWTOOTH = 3;
private static double BYTE_OSCI = 127.0; // max value for byte
private static double no_fade(double i,int max) {
return 1;
}
private static double linear_fade(double i,int max) {
return (max-(float)i) / max;
}
private static double quadratic_fade(double i,int max) {
return (-1/Math.pow(max, 2))*Math.pow(i, 2) + 1; // (-1/ max^2) * i^2 + 1
}
private static double sin_wave(double i,double period) {
return Math.sin(2.0 * Math.PI * i / period);
}
private static double square_wave(double i,double period) {
return (i % period) / period < .5 ? 1 : -1;
}
private static double triangle_wave(double i,double period) {
return Math.asin(Math.sin((2 * Math.PI) * (i / period)));
}
private static double sawtooth_wave(double i,double period) {
return -1 + 2 * ((i % period) / period);
}
public static void playGradient(double fstart,double fend,double duration,double volume,byte fadeend,byte wave) {
byte[] freqdata = new byte[(int)(duration * SAMPLE_RATE)];
// Generate the sound
for(int i = 0; i < freqdata.length; i++) {
freqdata[i] = (byte)generateValue(i, duration, fstart + (fend-fstart) * (i/(double)freqdata.length), volume, fadeend, wave);
}
// Play it
try {
final AudioFormat af = new AudioFormat(SAMPLE_RATE, 8, 1, true, true);
SourceDataLine line = AudioSystem.getSourceDataLine(af);
line.open(af, SAMPLE_RATE);
line.start();
line.write(freqdata, 0, freqdata.length);
line.drain();
line.close();
}catch(LineUnavailableException e) {
e.printStackTrace();
}
}
/**
* Same as playSound but plays several frequences at the same time<br/>
* <code>
* double[] freqs = {440.0,440*1.5}; <br/>
* SoundGenerator.playSound(freqs,1.0,0.5,SoundGenerator.FADE_LINEAR,SoundGenerator.WAVE_SIN);
* </code>
*
*/
public static void playSounds(double[] freqs,double duration,double volume,byte fade,byte wave) {
if(freqs.length == 0) {
System.err.println("No frequences to play !");
return;
}
volume = volume / freqs.length; // ease volume to avoid overflow
double[][] soundData = new double[freqs.length][];
for(int i = 0;i < soundData.length;i++) {
soundData[i] = generateSoundData(freqs[i],duration,volume,fade,wave);
}
byte[] freqdata = new byte[soundData[0].length];
for(int i = 0;i < soundData[0].length;i++) {
for(int j = 0;j < soundData.length;j++) {
freqdata[i] += (byte)(soundData[j][i]);
}
}
// Play it
try {
final AudioFormat af = new AudioFormat(SAMPLE_RATE, 8, 1, true, true);
SourceDataLine line = AudioSystem.getSourceDataLine(af);
line.open(af, SAMPLE_RATE);
line.start();
line.write(freqdata, 0, freqdata.length);
line.drain();
line.close();
}catch(LineUnavailableException e) {
e.printStackTrace();
}
}
/**
* Play a sound at a given frequency freq during duration (in seconds) with volume as strenght
* <br/><br/>
* <code>SoundGenerator.playSound(440.0,1.0,0.5,SoundGenerator.FADE_LINEAR,SoundGenerator.WAVE_SIN);</code><br/>
* Available fades : FADE_NONE, FADE_LINEAR, FADE_QUADRATIC<br/>
* Available waves : WAVE_SIN, WAVE_SQUARE, WAVE_TRIANGLE, WAVE_SAWTOOTH<br/>
*/
public static void playSound(double freq,double duration,double volume,byte fade,byte wave){
double[] soundData = generateSoundData(freq,duration,volume,fade,wave);
byte[] freqdata = new byte[soundData.length];
for(int i = 0;i < soundData.length;i++) {
freqdata[i] = (byte)soundData[i];
}
// Play it
try {
final AudioFormat af = new AudioFormat(SAMPLE_RATE, 8, 1, true, true);
SourceDataLine line = AudioSystem.getSourceDataLine(af);
line.open(af, SAMPLE_RATE);
line.start();
line.write(freqdata, 0, freqdata.length);
line.drain();
line.close();
}catch(LineUnavailableException e) {
e.printStackTrace();
}
}
public static double generateValue(double i,double duration,double freq,double volume,byte fade,byte wave) {
double period = (double)SAMPLE_RATE / freq;
double fade_data = 0;
double wave_data = 0;
int length = (int)(duration * SAMPLE_RATE);
switch(fade) {
case FADE_NONE:
fade_data = no_fade(i,length);
break;
case FADE_LINEAR:
fade_data = linear_fade(i, length);
break;
case FADE_QUADRATIC:
fade_data = quadratic_fade(i, length);
break;
}
switch(wave) {
case WAVE_SIN:
wave_data = sin_wave(i, period);
break;
case WAVE_SQUARE:
wave_data = square_wave(i, period);
break;
case WAVE_TRIANGLE:
wave_data = triangle_wave(i, period);
break;
case WAVE_SAWTOOTH:
wave_data = sawtooth_wave(i, period);
break;
}
return (wave_data * BYTE_OSCI * fade_data*volume);
}
public static double[] generateSoundData(double freq,double duration,double volume,byte fade,byte wave) {
double[] freqdata = new double[(int)(duration * SAMPLE_RATE)];
// Generate the sound
for(int i = 0; i < freqdata.length; i++) {
freqdata[i] = generateValue(i, duration, freq, volume, fade, wave);
}
return freqdata;
}
public static void sampleRate(int sr){
SAMPLE_RATE = sr;
}
public static int sampleRate(){
return SAMPLE_RATE;
}
}
| gpl-3.0 |
andrey-gabchak/GoJavaOnlineLabs | src/test/java/ua/goit/Practice/Practice1/MatrixTraversalTest.java | 2275 | package ua.goit.Practice.Practice1;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by coura on 24.04.2016.
*/
public class MatrixTraversalTest {
MatrixTraversal matrixTraversal = new MatrixTraversal();
@Test
public void testPrint() throws Exception {
int[][] inputArray = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
int[] expectedArray = {1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10};
int[] resultArray = matrixTraversal.print(inputArray);
assertArrayEquals(expectedArray, resultArray);
}
@Test
public void testPrint4x3() throws Exception {
int[][] inputArray = {
{1, 2, 3, 4,},
{5, 6, 7, 8,},
{9, 10, 11, 12,},
};
int[] expectedArray = {1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7};
int[] resultArray = matrixTraversal.print(inputArray);
assertArrayEquals(expectedArray, resultArray);
}
@Test
public void testPrint5x5() throws Exception {
int[][] inputArray = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20}
};
int[] expectedArray = {1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12};
int[] resultArray = matrixTraversal.print(inputArray);
assertArrayEquals(expectedArray, resultArray);
}
@Test
public void testPrintEmptyArray() throws Exception {
int[][] inputArray = {{}};
int[] expectedArray = {};
int[] resultArray = matrixTraversal.print(inputArray);
assertArrayEquals(expectedArray, resultArray);
}
@Test
public void testPrintEmptyValueInArray() throws Exception {
int[][] inputArray = {
{1, 2, 3, 4,},
{5, 6, 7, 8,},
{9, 10, 11, 12,},
{13, 14, 15, 16,}
};
int[] expectedArray = {1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10};
int[] resultArray = matrixTraversal.print(inputArray);
assertArrayEquals(expectedArray, resultArray);
}
} | gpl-3.0 |
rla/old-blog | src/main/java/ee/pri/rl/blog/web/page/category/CategoryAddPage.java | 3103 | /**
* Copyright (C) 2009 Raivo Laanemets <rl@starline.ee>
*
* This file is part of rl-blog.
*
* Foobar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar 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 rl-blog. If not, see <http://www.gnu.org/licenses/>.
*/
package ee.pri.rl.blog.web.page.category;
import java.io.Serializable;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;
import ee.pri.rl.blog.exception.CategoryExistsException;
import ee.pri.rl.blog.web.BlogServiceHolder;
import ee.pri.rl.blog.web.page.BasePage;
import ee.pri.rl.blog.web.page.auth.AuthPageMarker;
import ee.pri.rl.blog.web.page.common.form.CancelButton;
import ee.pri.rl.blog.web.page.common.message.LocalFeedbackPanel;
import ee.pri.rl.blog.web.page.index.IndexPage;
/**
* Page for adding a new category.
*
* @author Raivo Laanemets
*/
public class CategoryAddPage extends BasePage implements AuthPageMarker {
private static final Logger log = Logger.getLogger(CategoryAddPage.class);
public CategoryAddPage() {
add(new AddCategoryForm("addForm"));
}
private static class AddCategoryForm extends Form<CategoryFormModel> {
private static final long serialVersionUID = 1L;
public AddCategoryForm(String id) {
super(id, new CompoundPropertyModel<CategoryFormModel>(new CategoryFormModel()));
add(new LocalFeedbackPanel("feedback", this));
add(new TextField<Void>("name"));
add(new Button("save") {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
CategoryFormModel category = AddCategoryForm.this.getModelObject();
if (StringUtils.isEmpty(category.getName())) {
error("Category name must not be empty");
} else {
try {
BlogServiceHolder.get().newCategory(category.getName());
getSession().info("Category added");
setRedirect(true);
setResponsePage(IndexPage.class);
} catch (CategoryExistsException e) {
log.warn("Category " + category.getName() + " exists already", e);
error("Category already exists");
}
}
}
});
add(new CancelButton("cancel", IndexPage.class));
}
}
private static class CategoryFormModel implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
| gpl-3.0 |
royken/bracongoProBackend | src/main/java/com/bracongo/sqlservertest/entities/projection/Vente.java | 2391 | package com.bracongo.sqlservertest.entities.projection;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author vr.kenfack
*/
/**
*
* @author Kenfack Valmy-Roi <roykenvalmy@gmail.com>
*/
@XmlRootElement(name = "vente")
@XmlAccessorType(XmlAccessType.FIELD)
public class Vente implements Serializable {
private static final long serialVersionUID = 1L;
private int date;
private Double quantiteBiere;
private Double quantiteBg;
private Double quantitePet;
private Double chiffreBierre;
private Double chiffreBg;
private Double chiffrePet;
public Vente() {
}
public Vente(int date, Double quantiteBiere, Double quantiteBg, Double quantitePet, Double chiffreBierre, Double chiffreBg, Double chiffrePet) {
this.date = date;
this.quantiteBiere = quantiteBiere;
this.quantiteBg = quantiteBg;
this.quantitePet = quantitePet;
this.chiffreBierre = chiffreBierre;
this.chiffreBg = chiffreBg;
this.chiffrePet = chiffrePet;
}
public int getDate() {
return date;
}
public void setDate(int date) {
this.date = date;
}
public Double getQuantiteBiere() {
return quantiteBiere;
}
public void setQuantiteBiere(Double quantiteBiere) {
this.quantiteBiere = quantiteBiere;
}
public Double getQuantiteBg() {
return quantiteBg;
}
public void setQuantiteBg(Double quantiteBg) {
this.quantiteBg = quantiteBg;
}
public Double getQuantitePet() {
return quantitePet;
}
public void setQuantitePet(Double quantitePet) {
this.quantitePet = quantitePet;
}
public Double getChiffreBierre() {
return chiffreBierre;
}
public void setChiffreBierre(Double chiffreBierre) {
this.chiffreBierre = chiffreBierre;
}
public Double getChiffreBg() {
return chiffreBg;
}
public void setChiffreBg(Double chiffreBg) {
this.chiffreBg = chiffreBg;
}
public Double getChiffrePet() {
return chiffrePet;
}
public void setChiffrePet(Double chiffrePet) {
this.chiffrePet = chiffrePet;
}
}
| gpl-3.0 |
austil/uhabits | app/src/main/java/org/isoron/uhabits/io/HabitsCSVExporter.java | 9048 | /*
* Copyright (C) 2016 Álinson Santos Xavier <isoron@gmail.com>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.io;
import android.support.annotation.*;
import org.isoron.uhabits.models.*;
import org.isoron.uhabits.utils.*;
import java.io.*;
import java.text.*;
import java.util.*;
import java.util.zip.*;
/**
* Class that exports the application data to CSV files.
*/
public class HabitsCSVExporter
{
private List<Habit> selectedHabits;
private List<String> generateDirs;
private List<String> generateFilenames;
private String exportDirName;
/**
* Delimiter used in a CSV file.
*/
private final String DELIMITER = ",";
@NonNull
private final HabitList allHabits;
public HabitsCSVExporter(@NonNull HabitList allHabits,
@NonNull List<Habit> selectedHabits,
@NonNull File dir)
{
this.allHabits = allHabits;
this.selectedHabits = selectedHabits;
this.exportDirName = dir.getAbsolutePath() + "/";
generateDirs = new LinkedList<>();
generateFilenames = new LinkedList<>();
}
public String writeArchive() throws IOException
{
String zipFilename;
writeHabits();
zipFilename = writeZipFile();
cleanup();
return zipFilename;
}
private void addFileToZip(ZipOutputStream zos, String filename)
throws IOException
{
FileInputStream fis =
new FileInputStream(new File(exportDirName + filename));
ZipEntry ze = new ZipEntry(filename);
zos.putNextEntry(ze);
int length;
byte bytes[] = new byte[1024];
while ((length = fis.read(bytes)) >= 0) zos.write(bytes, 0, length);
zos.closeEntry();
fis.close();
}
private void cleanup()
{
for (String filename : generateFilenames)
new File(exportDirName + filename).delete();
for (String filename : generateDirs)
new File(exportDirName + filename).delete();
new File(exportDirName).delete();
}
@NonNull
private String sanitizeFilename(String name)
{
String s = name.replaceAll("[^ a-zA-Z0-9\\._-]+", "");
return s.substring(0, Math.min(s.length(), 100));
}
private void writeHabits() throws IOException
{
String filename = "Habits.csv";
new File(exportDirName).mkdirs();
FileWriter out = new FileWriter(exportDirName + filename);
generateFilenames.add(filename);
allHabits.writeCSV(out);
out.close();
for (Habit h : selectedHabits)
{
String sane = sanitizeFilename(h.getName());
String habitDirName =
String.format("%03d %s", allHabits.indexOf(h) + 1, sane);
habitDirName = habitDirName.trim() + "/";
new File(exportDirName + habitDirName).mkdirs();
generateDirs.add(habitDirName);
writeScores(habitDirName, h.getScores());
writeCheckmarks(habitDirName, h.getCheckmarks());
}
writeMultipleHabits();
}
private void writeScores(String habitDirName, ScoreList scores)
throws IOException
{
String path = habitDirName + "Scores.csv";
FileWriter out = new FileWriter(exportDirName + path);
generateFilenames.add(path);
scores.writeCSV(out);
out.close();
}
private void writeCheckmarks(String habitDirName, CheckmarkList checkmarks)
throws IOException
{
String filename = habitDirName + "Checkmarks.csv";
FileWriter out = new FileWriter(exportDirName + filename);
generateFilenames.add(filename);
checkmarks.writeCSV(out);
out.close();
}
/**
* Writes a scores file and a checkmarks file containing scores and checkmarks of every habit.
* The first column corresponds to the date. Subsequent columns correspond to a habit.
* Habits are taken from the list of selected habits.
* Dates are determined from the oldest repetition date to the newest repetition date found in
* the list of habits.
*
* @throws IOException if there was problem writing the files
*/
private void writeMultipleHabits() throws IOException
{
String scoresFileName = "Scores.csv";
String checksFileName = "Checkmarks.csv";
generateFilenames.add(scoresFileName);
generateFilenames.add(checksFileName);
FileWriter scoresWriter = new FileWriter(exportDirName + scoresFileName);
FileWriter checksWriter = new FileWriter(exportDirName + checksFileName);
writeMultipleHabitsHeader(scoresWriter);
writeMultipleHabitsHeader(checksWriter);
long[] timeframe = getTimeframe();
long oldest = timeframe[0];
long newest = DateUtils.getStartOfToday();
List<int[]> checkmarks = new ArrayList<>();
List<double[]> scores = new ArrayList<>();
for (Habit h : selectedHabits)
{
checkmarks.add(h.getCheckmarks().getValues(oldest, newest));
scores.add(h.getScores().getValues(oldest, newest));
}
int days = DateUtils.getDaysBetween(oldest, newest);
SimpleDateFormat dateFormat = DateFormats.getCSVDateFormat();
for (int i = 0; i <= days; i++)
{
Date day = new Date(newest - i * DateUtils.millisecondsInOneDay);
String date = dateFormat.format(day);
StringBuilder sb = new StringBuilder();
sb.append(date).append(DELIMITER);
checksWriter.write(sb.toString());
scoresWriter.write(sb.toString());
for(int j = 0; j < selectedHabits.size(); j++)
{
checksWriter.write(String.valueOf(checkmarks.get(j)[i]));
checksWriter.write(DELIMITER);
String score =
String.format("%.4f", ((float) scores.get(j)[i]));
scoresWriter.write(score);
scoresWriter.write(DELIMITER);
}
checksWriter.write("\n");
scoresWriter.write("\n");
}
scoresWriter.close();
checksWriter.close();
}
/**
* Writes the first row, containing header information, using the given writer.
* This consists of the date title and the names of the selected habits.
*
* @param out the writer to use
* @throws IOException if there was a problem writing
*/
private void writeMultipleHabitsHeader(Writer out) throws IOException
{
out.write("Date" + DELIMITER);
for (Habit h : selectedHabits) {
out.write(h.getName());
out.write(DELIMITER);
}
out.write("\n");
}
/**
* Gets the overall timeframe of the selected habits.
* The timeframe is an array containing the oldest timestamp among the habits and the
* newest timestamp among the habits.
* Both timestamps are in milliseconds.
*
* @return the timeframe containing the oldest timestamp and the newest timestamp
*/
private long[] getTimeframe()
{
long oldest = Long.MAX_VALUE;
long newest = -1;
for (Habit h : selectedHabits)
{
if(h.getRepetitions().getOldest() == null || h.getRepetitions().getNewest() == null)
continue;
long currOld = h.getRepetitions().getOldest().getTimestamp();
long currNew = h.getRepetitions().getNewest().getTimestamp();
oldest = currOld > oldest ? oldest : currOld;
newest = currNew < newest ? newest : currNew;
}
return new long[]{oldest, newest};
}
private String writeZipFile() throws IOException
{
SimpleDateFormat dateFormat = DateFormats.getCSVDateFormat();
String date = dateFormat.format(DateUtils.getStartOfToday());
String zipFilename =
String.format("%s/Loop Habits CSV %s.zip", exportDirName, date);
FileOutputStream fos = new FileOutputStream(zipFilename);
ZipOutputStream zos = new ZipOutputStream(fos);
for (String filename : generateFilenames)
addFileToZip(zos, filename);
zos.close();
fos.close();
return zipFilename;
}
}
| gpl-3.0 |
DISID/ci-jenkins | spring-roo-restfulshop/src/main/java/com/disid/restful/web/CustomerOrderDeserializer.java | 1345 | package com.disid.restful.web;
import com.disid.restful.model.CustomerOrder;
import com.disid.restful.service.api.CustomerOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jackson.JsonObjectDeserializer;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.convert.ConversionService;
import org.springframework.roo.addon.web.mvc.controller.annotations.config.RooDeserializer;
/**
* = CustomerOrderDeserializer
*
* TODO Auto-generated class documentation
*
*/
@RooDeserializer(entity = CustomerOrder.class)
public class CustomerOrderDeserializer extends JsonObjectDeserializer<CustomerOrder> {
/**
* TODO Auto-generated attribute documentation
*
*/
private CustomerOrderService customerOrderService;
/**
* TODO Auto-generated attribute documentation
*
*/
private ConversionService conversionService;
/**
* TODO Auto-generated constructor documentation
*
* @param customerOrderService
* @param conversionService
*/
@Autowired
public CustomerOrderDeserializer(@Lazy CustomerOrderService customerOrderService, ConversionService conversionService) {
this.customerOrderService = customerOrderService;
this.conversionService = conversionService;
}
}
| gpl-3.0 |
Minecolonies/minecolonies | src/main/java/com/minecolonies/coremod/colony/requestsystem/data/StandardRequestSystemBuildingDataStore.java | 17780 | package com.minecolonies.coremod.colony.requestsystem.data;
import com.google.common.reflect.TypeToken;
import com.minecolonies.api.colony.requestsystem.StandardFactoryController;
import com.minecolonies.api.colony.requestsystem.data.IRequestSystemBuildingDataStore;
import com.minecolonies.api.colony.requestsystem.factory.FactoryVoidInput;
import com.minecolonies.api.colony.requestsystem.factory.IFactory;
import com.minecolonies.api.colony.requestsystem.factory.IFactoryController;
import com.minecolonies.api.colony.requestsystem.token.IToken;
import com.minecolonies.api.util.NBTUtils;
import com.minecolonies.api.util.constant.TypeConstants;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.Tuple;
import net.minecraftforge.common.util.Constants;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.stream.Collectors;
import static com.minecolonies.api.util.constant.NbtTagConstants.*;
public class StandardRequestSystemBuildingDataStore implements IRequestSystemBuildingDataStore
{
private IToken<?> id;
private final Map<TypeToken<?>, Collection<IToken<?>>> openRequestsByRequestableType;
private final Map<Integer, Collection<IToken<?>>> openRequestsByCitizen;
private final Map<Integer, Collection<IToken<?>>> completedRequestsByCitizen;
private final Map<IToken<?>, Integer> citizenByOpenRequest;
public StandardRequestSystemBuildingDataStore(
final IToken<?> id,
final Map<TypeToken<?>, Collection<IToken<?>>> openRequestsByRequestableType,
final Map<Integer, Collection<IToken<?>>> openRequestsByCitizen,
final Map<Integer, Collection<IToken<?>>> completedRequestsByCitizen,
final Map<IToken<?>, Integer> citizenByOpenRequest)
{
this.id = id;
this.openRequestsByRequestableType = openRequestsByRequestableType;
this.openRequestsByCitizen = openRequestsByCitizen;
this.completedRequestsByCitizen = completedRequestsByCitizen;
this.citizenByOpenRequest = citizenByOpenRequest;
}
public StandardRequestSystemBuildingDataStore()
{
this(StandardFactoryController.getInstance().getNewInstance(TypeConstants.ITOKEN),
new HashMap<>(),
new HashMap<>(),
new HashMap<>(),
new HashMap<>());
}
@Override
public Map<TypeToken<?>, Collection<IToken<?>>> getOpenRequestsByRequestableType()
{
return openRequestsByRequestableType;
}
@Override
public Map<Integer, Collection<IToken<?>>> getOpenRequestsByCitizen()
{
return openRequestsByCitizen;
}
@Override
public Map<Integer, Collection<IToken<?>>> getCompletedRequestsByCitizen()
{
return completedRequestsByCitizen;
}
@Override
public Map<IToken<?>, Integer> getCitizensByRequest()
{
return citizenByOpenRequest;
}
@Override
public IToken<?> getId()
{
return id;
}
@Override
public void setId(final IToken<?> id)
{
this.id = id;
}
public static class Factory implements IFactory<FactoryVoidInput, StandardRequestSystemBuildingDataStore>
{
@NotNull
@Override
public TypeToken<? extends StandardRequestSystemBuildingDataStore> getFactoryOutputType()
{
return TypeToken.of(StandardRequestSystemBuildingDataStore.class);
}
@NotNull
@Override
public TypeToken<? extends FactoryVoidInput> getFactoryInputType()
{
return TypeConstants.FACTORYVOIDINPUT;
}
@NotNull
@Override
public StandardRequestSystemBuildingDataStore getNewInstance(
@NotNull final IFactoryController factoryController, @NotNull final FactoryVoidInput factoryVoidInput, @NotNull final Object... context) throws IllegalArgumentException
{
return new StandardRequestSystemBuildingDataStore();
}
@NotNull
@Override
public CompoundNBT serialize(
@NotNull final IFactoryController controller, @NotNull final StandardRequestSystemBuildingDataStore standardRequestSystemBuildingDataStore)
{
final CompoundNBT compound = new CompoundNBT();
compound.put(TAG_TOKEN, controller.serialize(standardRequestSystemBuildingDataStore.id));
compound.put(TAG_OPEN_REQUESTS_BY_TYPE, standardRequestSystemBuildingDataStore.openRequestsByRequestableType.keySet().stream().map(typeToken -> {
final CompoundNBT entryCompound = new CompoundNBT();
entryCompound.put(TAG_TOKEN, controller.serialize(typeToken));
entryCompound.put(TAG_LIST, standardRequestSystemBuildingDataStore.openRequestsByRequestableType.get(typeToken)
.stream()
.map(controller::serialize)
.collect(NBTUtils.toListNBT()));
return entryCompound;
}).collect(NBTUtils.toListNBT()));
compound.put(TAG_OPEN_REQUESTS_BY_CITIZEN, standardRequestSystemBuildingDataStore.openRequestsByCitizen.keySet().stream().map(integer -> {
final CompoundNBT entryCompound = new CompoundNBT();
entryCompound.put(TAG_TOKEN, controller.serialize(integer));
entryCompound.put(TAG_LIST, standardRequestSystemBuildingDataStore.openRequestsByCitizen.get(integer)
.stream()
.map(controller::serialize)
.collect(NBTUtils.toListNBT()));
return entryCompound;
}).collect(NBTUtils.toListNBT()));
compound.put(TAG_COMPLETED_REQUESTS_BY_CITIZEN, standardRequestSystemBuildingDataStore.completedRequestsByCitizen.keySet().stream().map(integer -> {
final CompoundNBT entryCompound = new CompoundNBT();
entryCompound.put(TAG_TOKEN, controller.serialize(integer));
entryCompound.put(TAG_LIST, standardRequestSystemBuildingDataStore.completedRequestsByCitizen.get(integer)
.stream()
.map(controller::serialize)
.collect(NBTUtils.toListNBT()));
return entryCompound;
}).collect(NBTUtils.toListNBT()));
compound.put(TAG_CITIZEN_BY_OPEN_REQUEST, standardRequestSystemBuildingDataStore.citizenByOpenRequest.keySet().stream().map(iToken -> {
final CompoundNBT entryCompound = new CompoundNBT();
entryCompound.put(TAG_TOKEN, controller.serialize(iToken));
entryCompound.put(TAG_VALUE, controller.serialize(standardRequestSystemBuildingDataStore.citizenByOpenRequest.get(iToken)));
return entryCompound;
}).collect(NBTUtils.toListNBT()));
return compound;
}
@NotNull
@Override
public StandardRequestSystemBuildingDataStore deserialize(@NotNull final IFactoryController controller, @NotNull final CompoundNBT nbt) throws Throwable
{
final IToken<?> token = controller.deserialize(nbt.getCompound(TAG_TOKEN));
final Map<TypeToken<?>, Collection<IToken<?>>> openRequestsByRequestableType = NBTUtils
.streamCompound(nbt.getList(TAG_OPEN_REQUESTS_BY_TYPE, Constants.NBT.TAG_COMPOUND))
.map(CompoundNBT -> {
final TypeToken<?> key =
controller.deserialize(CompoundNBT.getCompound(TAG_TOKEN));
final Collection<IToken<?>> values = NBTUtils.streamCompound(CompoundNBT.getList(
TAG_LIST,
Constants.NBT.TAG_COMPOUND))
.map(elementCompound -> (IToken<?>) controller
.deserialize(
elementCompound))
.collect(Collectors.toList());
return new Tuple<>(key, values);
})
.collect(Collectors.toMap(Tuple::getA, Tuple::getB));
final Map<Integer, Collection<IToken<?>>> openRequestsByCitizen = NBTUtils
.streamCompound(nbt.getList(TAG_OPEN_REQUESTS_BY_CITIZEN, Constants.NBT.TAG_COMPOUND))
.map(CompoundNBT -> {
final Integer key = controller.deserialize(CompoundNBT.getCompound(TAG_TOKEN));
final Collection<IToken<?>> values =
NBTUtils.streamCompound(CompoundNBT.getList(TAG_LIST, Constants.NBT.TAG_COMPOUND))
.map(elementCompound -> (IToken<?>) controller.deserialize(elementCompound))
.collect(Collectors.toList());
return new Tuple<>(key, values);
})
.collect(Collectors.toMap(Tuple::getA, Tuple::getB));
final Map<Integer, Collection<IToken<?>>> completedRequestsByCitizen = NBTUtils
.streamCompound(nbt.getList(TAG_COMPLETED_REQUESTS_BY_CITIZEN, Constants.NBT.TAG_COMPOUND))
.map(CompoundNBT -> {
final Integer key = controller.deserialize(CompoundNBT.getCompound(TAG_TOKEN));
final Collection<IToken<?>> values =
NBTUtils.streamCompound(CompoundNBT.getList(TAG_LIST, Constants.NBT.TAG_COMPOUND))
.map(elementCompound -> (IToken<?>) controller.deserialize(elementCompound))
.collect(Collectors.toList());
return new Tuple<>(key, values);
})
.collect(Collectors.toMap(Tuple::getA, Tuple::getB));
final Map<IToken<?>, Integer> citizenByOpenRequest = NBTUtils
.streamCompound(nbt.getList(TAG_CITIZEN_BY_OPEN_REQUEST, Constants.NBT.TAG_COMPOUND)).map(CompoundNBT -> {
final IToken<?> key = controller.deserialize(CompoundNBT.getCompound(TAG_TOKEN));
final Integer value = controller.deserialize(CompoundNBT.getCompound(TAG_VALUE));
return new Tuple<>(key, value);
}).collect(Collectors.toMap(Tuple::getA, Tuple::getB));
return new StandardRequestSystemBuildingDataStore(token, openRequestsByRequestableType, openRequestsByCitizen, completedRequestsByCitizen, citizenByOpenRequest);
}
@Override
public void serialize(
IFactoryController controller, StandardRequestSystemBuildingDataStore input,
PacketBuffer packetBuffer)
{
controller.serialize(packetBuffer, input.id);
packetBuffer.writeInt(input.openRequestsByRequestableType.size());
input.openRequestsByRequestableType.forEach((key, value) -> {
controller.serialize(packetBuffer, key);
packetBuffer.writeInt(value.size());
value.forEach(token -> controller.serialize(packetBuffer, token));
});
packetBuffer.writeInt(input.openRequestsByCitizen.size());
input.openRequestsByCitizen.forEach((key, value) -> {
packetBuffer.writeInt(key);
packetBuffer.writeInt(value.size());
value.forEach(token -> controller.serialize(packetBuffer, token));
});
packetBuffer.writeInt(input.completedRequestsByCitizen.size());
input.completedRequestsByCitizen.forEach((key, value) -> {
packetBuffer.writeInt(key);
packetBuffer.writeInt(value.size());
value.forEach(token -> controller.serialize(packetBuffer, token));
});
packetBuffer.writeInt(input.citizenByOpenRequest.size());
input.citizenByOpenRequest.forEach((key, value) -> {
controller.serialize(packetBuffer, key);
controller.serialize(packetBuffer, value);
});
}
@Override
public StandardRequestSystemBuildingDataStore deserialize(IFactoryController controller, PacketBuffer buffer)
throws Throwable
{
final IToken<?> id = controller.deserialize(buffer);
final Map<TypeToken<?>, Collection<IToken<?>>> openRequestsByRequestableType = new HashMap<>();
final int openRequestsByRequestableTypeSize = buffer.readInt();
for (int i = 0; i < openRequestsByRequestableTypeSize; ++i)
{
final TypeToken<?> key = controller.deserialize(buffer);
final List<IToken<?>> tokens = new ArrayList<>();
final int tokensSize = buffer.readInt();
for (int ii = 0; ii < tokensSize; ++ii)
{
tokens.add(controller.deserialize(buffer));
}
openRequestsByRequestableType.put(key, tokens);
}
final Map<Integer, Collection<IToken<?>>> openRequestsByCitizen = new HashMap<>();
final int openRequestsByCitizenSize = buffer.readInt();
for (int i = 0; i < openRequestsByCitizenSize; ++i)
{
final int key = buffer.readInt();
final List<IToken<?>> tokens = new ArrayList<>();
final int tokensSize = buffer.readInt();
for (int ii = 0; ii < tokensSize; ++ii)
{
tokens.add(controller.deserialize(buffer));
}
openRequestsByCitizen.put(key, tokens);
}
final Map<Integer, Collection<IToken<?>>> completedRequestsByCitizen = new HashMap<>();
final int completedRequestsByCitizenSize = buffer.readInt();
for (int i = 0; i < completedRequestsByCitizenSize; ++i)
{
final int key = buffer.readInt();
final List<IToken<?>> tokens = new ArrayList<>();
final int tokensSize = buffer.readInt();
for (int ii = 0; ii < tokensSize; ++ii)
{
tokens.add(controller.deserialize(buffer));
}
completedRequestsByCitizen.put(key, tokens);
}
final Map<IToken<?>, Integer> citizenByOpenRequest = new HashMap<>();
final int citizenByOpenRequestSize = buffer.readInt();
for (int i = 0; i < citizenByOpenRequestSize; ++i)
{
citizenByOpenRequest.put(controller.deserialize(buffer), controller.deserialize(buffer));
}
return new StandardRequestSystemBuildingDataStore(id, openRequestsByRequestableType, openRequestsByCitizen, completedRequestsByCitizen, citizenByOpenRequest);
}
@Override
public short getSerializationId()
{
return 37;
}
}
}
| gpl-3.0 |
frmichetti/workix | src/main/java/br/com/codecode/workix/dto/Contact.java | 1757 | package br.com.codecode.workix.dto;
import br.com.codecode.workix.interfaces.Buildable;
import javax.xml.bind.annotation.XmlTransient;
import java.io.Serializable;
public class Contact implements Serializable {
private static final long serialVersionUID = -2482737185460142872L;
private long mobilePhone;
/**
* Public Default Constructor for JPA Compatibility Only
*/
public Contact(){}
/**
* Public Constructor for {@link Builder} Compatibility
*
* @see Buildable
* @param builder
* Builder for Generate a New Contact
*/
public Contact(Builder builder) {
this.mobilePhone = builder.getMobilePhone();
}
/**
* Creates builder to build {@link Contact}.
* @return created builder
*/
@XmlTransient
public static Builder builder() {
return new Builder();
}
/**
* @return the Mobile Phone
*/
public long getMobilePhone() {
return mobilePhone;
}
/**
* @param mobilePhone
* the Mobile Phone to set
*/
public void setMobilePhone(long mobilePhone) {
this.mobilePhone = mobilePhone;
}
/**
* Builder NestedClass for {@link Contact}
*
* @author felipe
* @since 1.0
* @version 1.0
* @see Contact
* @see Buildable
*/
public final static class Builder extends Contact implements Buildable<Contact> {
private static final long serialVersionUID = -6671372786495157443L;
/**
* Disabled Empty Constructor
*/
private Builder(){}
/**
* @return a new Contact
*/
@Override
public Contact build() {
return new Contact(this);
}
/**
* @param mobilePhone
* the Mobile Phone to set
* @return Builder
*/
public Builder withMobilePhone(long mobilePhone) {
this.setMobilePhone(mobilePhone);
return this;
}
}
}
| gpl-3.0 |
iCarto/siga | libRemoteServices/src/org/gvsig/remoteClient/wfs/wfs_1_0_0/WFSFeature1_0_0.java | 7327 | package org.gvsig.remoteClient.wfs.wfs_1_0_0;
import java.io.IOException;
import org.gvsig.remoteClient.gml.GMLTags;
import org.gvsig.remoteClient.gml.schemas.XMLNameSpace;
import org.gvsig.remoteClient.utils.BoundaryBox;
import org.gvsig.remoteClient.utils.CapabilitiesTags;
import org.gvsig.remoteClient.utils.Utilities;
import org.gvsig.remoteClient.wfs.WFSFeature;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParserException;
/* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana
*
* Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA.
*
* For more information, contact:
*
* Generalitat Valenciana
* Conselleria d'Infraestructures i Transport
* Av. Blasco Ibáñez, 50
* 46010 VALENCIA
* SPAIN
*
* +34 963862235
* gvsig@gva.es
* www.gvsig.gva.es
*
* or
*
* IVER T.I. S.A
* Salamanca 50
* 46005 Valencia
* Spain
*
* +34 963163400
* dac@iver.es
*/
/* CVS MESSAGES:
*
* $Id$
* $Log$
* Revision 1.8 2007-09-20 09:30:12 jaume
* removed unnecessary imports
*
* Revision 1.7 2007/02/09 14:11:01 jorpiell
* Primer piloto del soporte para WFS 1.1 y para WFS-T
*
* Revision 1.6 2006/07/12 06:23:31 jorpiell
* Soportados tipos más complejos
*
* Revision 1.5 2006/06/15 09:05:06 jorpiell
* Actualizados los WFS
*
* Revision 1.4 2006/05/23 13:23:22 jorpiell
* Se ha cambiado el final del bucle de parseado y se tiene en cuenta el online resource
*
* Revision 1.2 2006/04/20 16:39:16 jorpiell
* Añadida la operacion de describeFeatureType y el parser correspondiente.
*
* Revision 1.1 2006/04/19 12:51:35 jorpiell
* Añadidas algunas de las clases del servicio WFS
*
*
*/
/**
* @author Jorge Piera Llodrá (piera_jor@gva.es)
*/
public class WFSFeature1_0_0 extends WFSFeature{
public WFSFeature1_0_0() {
}
public WFSFeature1_0_0(String name) {
super(name);
}
/**
* <p>Parses the contents of the parser(WMSCapabilities)
* to extract the information about an WMSLayer</p>
* @throws IOException
* @throws XmlPullParserException
*
*/
public void parse(KXmlParser parser) throws XmlPullParserException, IOException{
int currentTag;
boolean end = false;
parser.require(KXmlParser.START_TAG, null, CapabilitiesTags.WFS_FEATURETYPE);
for (int i=0 ; i<parser.getAttributeCount() ; i++){
String[] attName = parser.getAttributeName(i).split(":");
if (attName.length == 2){
if (attName[0].compareTo(GMLTags.XML_NAMESPACE)==0){
XMLNameSpace nameSpace = new XMLNameSpace(attName[1],parser.getAttributeValue(i));
this.setNamespace(nameSpace);
}
}
}
currentTag = parser.next();
while (!end)
{
switch(currentTag)
{
case KXmlParser.START_TAG:
if (parser.getName().compareToIgnoreCase(CapabilitiesTags.NAME)==0)
{
this.setName(parser.nextText());
}
if (parser.getName().compareToIgnoreCase(CapabilitiesTags.TITLE)==0)
{
this.setTitle(parser.nextText());
}
if (parser.getName().compareToIgnoreCase(CapabilitiesTags.WFS_KEYWORDS)==0)
{
String keyword = parser.nextText();
if ((keyword != null) || (!(keyword.equals("")))){
this.addKeyword(keyword);
}
}
if (parser.getName().compareToIgnoreCase(CapabilitiesTags.KEYWORD)==0)
{
this.addKeyword(parser.nextText());
}
if (parser.getName().compareToIgnoreCase(CapabilitiesTags.SRS)==0)
{
String value = parser.nextText();
if (value != null){
String[] mySRSs = value.split(" ");
for (int i = 0; i < mySRSs.length; i++) {
this.addSRS(mySRSs[i]);
}
}
}
if (parser.getName().compareToIgnoreCase(CapabilitiesTags.LATLONGBOUNDINGBOX)==0)
{
BoundaryBox bbox = new BoundaryBox();
bbox.setSrs(CapabilitiesTags.EPSG_4326);
String value = parser.getAttributeValue("",CapabilitiesTags.MINX);
if ((value != null) && (Utilities.isNumber(value)))
bbox.setXmin(Double.parseDouble(value));
value = parser.getAttributeValue("",CapabilitiesTags.MINY);
if ((value != null) && (Utilities.isNumber(value)))
bbox.setYmin(Double.parseDouble(value));
value = parser.getAttributeValue("",CapabilitiesTags.MAXX);
if ((value != null) && (Utilities.isNumber(value)))
bbox.setXmax(Double.parseDouble(value));
value = parser.getAttributeValue("",CapabilitiesTags.MAXY);
if ((value != null) && (Utilities.isNumber(value)))
bbox.setYmax(Double.parseDouble(value));
this.addBBox(bbox);
this.setLatLonBbox(bbox);
}
if (parser.getName().compareTo(CapabilitiesTags.BOUNDINGBOX)==0)
{
BoundaryBox bbox = new BoundaryBox();
String value = parser.getAttributeValue("",CapabilitiesTags.SRS);
if (value != null)
bbox.setSrs(value);
value = parser.getAttributeValue("",CapabilitiesTags.MINX);
if ((value != null) && (Utilities.isNumber(value)))
bbox.setXmin(Double.parseDouble(value));
value = parser.getAttributeValue("",CapabilitiesTags.MINY);
if ((value != null) && (Utilities.isNumber(value)))
bbox.setYmin(Double.parseDouble(value));
value = parser.getAttributeValue("",CapabilitiesTags.MAXX);
if ((value != null) && (Utilities.isNumber(value)))
bbox.setXmax(Double.parseDouble(value));
value = parser.getAttributeValue("",CapabilitiesTags.MAXY);
if ((value != null) && (Utilities.isNumber(value)))
bbox.setYmax(Double.parseDouble(value));
if (bbox.getSrs() != null){
this.addBBox(bbox);
this.addSRS(bbox.getSrs());
}
}
break;
case KXmlParser.END_TAG:
if (parser.getName().compareTo(CapabilitiesTags.WFS_FEATURETYPE) == 0)
end = true;
break;
case KXmlParser.TEXT:
break;
}
if (!end){
currentTag = parser.next();
}
}
}
}
| gpl-3.0 |
Sharpcastle33/CustomDurability | src/main/java/com/elonxxiii/durability/RepairListener.java | 148 | package com.elonxxiii.durability;
import org.bukkit.event.Listener;
public class RepairListener extends CustomDurability implements Listener {
}
| gpl-3.0 |
KoaGex/ImageBattleFx | ImageBattleFx/src/main/java/org/imagebattle/Database.java | 17934 | package org.imagebattle;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javafx.util.Pair;
import javax.sql.DataSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* A database to store everything the media battle application wants to save.
*
* @author KoaGex
*
*/
final class Database {
private static final Logger LOG = LogManager.getLogger();
private static final String IGNORED = "ignored";
private static final String FILES = "files";
private static final String MEDIA_OBJECTS = "media_objects";
private static final String EDGES = "edges";
private final DataSource dataSource;
/**
* Constructor.
*
* @param dataSource
* This looks like any {@link DataSource} can be used but currently it assumes a
* {@link SqliteDatabase}. Should the parameter type be changed to that class or keep
* using the interface?
*/
Database(final DataSource dataSource) {
this.dataSource = dataSource;
final Collection<String> tables = tables();
final BiConsumer<String, Runnable> createIfMissing = (tableName, createMethod) -> {
if (!tables.contains(tableName)) {
createMethod.run();
}
};
createIfMissing.accept(MEDIA_OBJECTS, this::createMediaObjectsTable);
createIfMissing.accept(FILES, this::createFilesTable);
createIfMissing.accept(IGNORED, this::createIgnoredTable);
createIfMissing.accept(EDGES, this::createEdgesTable);
createIfMissing.accept("folders", this::createFoldersTable);
}
protected void addEdge(final File winner, final File loser) {
final int winnerId = mediaId(winner);
final int loserId = mediaId(loser);
if (winnerId == loserId) {
throw new IllegalArgumentException(
"These files have the same content. An edge between them is forbidden: " + winner + " , "
+ loser);
}
final String insert = "insert into " + EDGES + " values (" + winnerId + "," + loserId + ")";
executeSql(insert);
}
protected void removeFromEdges(final File file) {
final int id = mediaId(file);
final String delete = "delete from " + EDGES + " where winner = " + id + " or loser = " + id;
executeSql(delete);
}
TransitiveDiGraph queryEdges() {
LOG.debug("start");
final String query = "select f_win.absolute_path, f_los.absolute_path " + //
" from " + EDGES + " e " + //
" join " + MEDIA_OBJECTS + " m_win" + //
" on m_win.id = e.winner " + //
" join " + FILES + " f_win " + //
" on f_win.media_object = m_win.id " + //
" join " + MEDIA_OBJECTS + " m_los" + //
" on m_los.id = e.loser " + //
" join " + FILES + " f_los " + //
" on f_los.media_object = m_los.id " //
;
final RowMapper<Pair<String, String>> rowMapper = resultSet -> new Pair<String, String>(
resultSet.getString(1), resultSet.getString(2));
final List<Pair<String, String>> filesPaths = query(query, rowMapper);
LOG.debug(filesPaths.size());
final TransitiveDiGraph result = new TransitiveDiGraph();
result.addNormalEdges(filesPaths);
LOG.debug("finished building graph");
return result;
}
TransitiveDiGraph queryEdges(//
final File chosenDirectory, //
final Predicate<? super File> matchesFileRegex, //
final Boolean recursive //
) {
LOG.debug("start");
/*
* Regex can not be used in sqlite by default:
* http://stackoverflow.com/questions/5071601/how-do-i-use-regex-in-a-sqlite-query#8338515
*/
final String query = "select f_win.absolute_path, f_los.absolute_path " + //
" from " + EDGES + " e " + //
" join " + MEDIA_OBJECTS + " m_win" + //
" on m_win.id = e.winner " + //
" join " + FILES + " f_win " + //
" on f_win.media_object = m_win.id " + //
" join " + MEDIA_OBJECTS + " m_los" + //
" on m_los.id = e.loser " + //
" join " + FILES + " f_los " + //
" on f_los.media_object = m_los.id " + //
" where f_win.absolute_path like '" + chosenDirectory.getAbsolutePath() + "%'"//
;
final RowMapper<Pair<String, String>> rowMapper = resultSet -> new Pair<String, String>(
resultSet.getString(1), //
resultSet.getString(2)//
);
final List<Pair<String, String>> filesPaths = query(query, rowMapper);
LOG.debug("query finished");
final Predicate<File> containedRecursively = file -> {
return file.getAbsolutePath().startsWith(chosenDirectory.getAbsolutePath());
};
final Predicate<File> containedDirectly = file -> {
final List<File> directorFiles = Arrays.asList(chosenDirectory.listFiles());
return directorFiles.contains(file);
};
final Predicate<File> matchesChosenDirectory = recursive ? containedRecursively
: containedDirectly;
final Predicate<File> acceptFile = matchesChosenDirectory.and(matchesFileRegex)
.and(File::exists);
final List<Pair<String, String>> matchingPairs = filesPaths.stream()//
.filter(pair -> {
final File winner = new File(pair.getKey());
final File loser = new File(pair.getValue());
return acceptFile.test(winner) && acceptFile.test(loser);
})//
.collect(Collectors.toList());
LOG.info("finished matching pairs. count: {}", matchingPairs.size());
final Set<File> duplicateFiles = Stream
.concat(matchingPairs.stream().map(pair -> pair.getKey()),
// TODO why are we calculating file hashes of image files when audio battle was started?
matchingPairs.stream().map(pair -> pair.getKey()))//
.distinct()//
.map(File::new)//
.filter(File::isFile)//
.collect(Collectors.groupingBy(file -> new FileContentHash(file).hash()))//
.entrySet()//
.stream()//
.map(Entry::getValue)//
.flatMap(list -> list.stream().skip(1))//
.collect(Collectors.toSet());
LOG.info("duplicate files {}", duplicateFiles);
final TransitiveDiGraph result = new TransitiveDiGraph();
for (Pair<String, String> pair : matchingPairs) {
final String winnerString = pair.getKey();
final String loserString = pair.getValue();
final File winner = new File(winnerString);
final File loser = new File(loserString);
if (!duplicateFiles.contains(winner) && !duplicateFiles.contains(loser)) {
result.addVertex(winner);
result.addVertex(loser);
result.addEdge(winner, loser);
}
}
return result;
}
/**
* @param mediaObject
*/
void addToIgnore(File file) {
final int id = mediaId(file);
final String insert = "insert into " + IGNORED + " values (" + id + ")";
executeSql(insert);
}
private int mediaId(File file) {
final Optional<Integer> lookupIdByFile = lookupFile(file);
int id;
if (lookupIdByFile.isPresent()) {
id = lookupIdByFile.get();
} else {
final String hash = new FileContentHash(file).hash();
final Optional<Integer> lookupMediaItemId = lookupMediaItemId(hash);
if (lookupMediaItemId.isPresent()) {
id = lookupMediaItemId.get();
} else {
addMediaObject(hash, detectMediaType(file));
id = lookupMediaItemId(hash).orElseThrow(RuntimeException::new);
}
addFile(id, file);
}
return id;
}
/**
* @param file
*/
void removeFromIgnore(File file) {
final int id = mediaId(file);
final String delete = "delete from " + IGNORED + " where media_object = " + id;
executeSql(delete);
}
/**
* @return Set containing all existing files that are ignored.
*/
Set<File> queryIgnored() {
LOG.debug("start");
final String query = "select files.absolute_path from " + FILES + " join " + MEDIA_OBJECTS
+ " on " + MEDIA_OBJECTS + ".id =" + FILES + ".media_object join " + IGNORED + " on "
+ IGNORED + ".media_object = " + MEDIA_OBJECTS + ".id";
final List<String> filesPaths = query(query, resultSet -> resultSet.getString(1));
LOG.debug(filesPaths.size());
return filesPaths.stream()//
.map(File::new)//
.filter(File::exists)//
.collect(Collectors.groupingBy(file -> new FileContentHash(file).hash()))//
.entrySet()//
.stream()//
.map(Entry::getValue)//
.map(list -> list.get(0))//
.collect(Collectors.toSet());
}
Set<File> queryIgnored(File chosenDirectory, MediaType mediaType, Boolean recursive) {
final String query = "select files.absolute_path from " + FILES + //
" join " + MEDIA_OBJECTS + //
" on " + MEDIA_OBJECTS + ".id =" + FILES + ".media_object " + //
" join " + IGNORED + //
" on " + IGNORED + ".media_object = " + MEDIA_OBJECTS + ".id" + //
" where " + MEDIA_OBJECTS + ".media_type = '" + mediaType.name() + "'";
final RowMapper<String> rowMapper = resultSet -> resultSet.getString(1);
// block copied from CentralStorage
final Predicate<File> containedRecursively = file -> {
return file.getAbsolutePath().startsWith(chosenDirectory.getAbsolutePath());
};
final Predicate<File> containedDirectly = file -> {
final List<File> directorFiles = Arrays.asList(chosenDirectory.listFiles());
return directorFiles.contains(file);
};
final Predicate<File> matchesChosenDirectory = recursive ? containedRecursively
: containedDirectly;
final List<String> filesPaths = query(query, rowMapper);
return filesPaths.stream()//
.map(File::new)//
.filter(File::exists)//
.filter(matchesChosenDirectory)//
.collect(Collectors.toSet());
}
/**
* @return Names of all tables in the sqlite database.
*/
protected Collection<String> tables() {
final String queryAllTableNames = "SELECT name FROM sqlite_master WHERE type='table'";
return query(queryAllTableNames, resultSet -> resultSet.getString(1));
}
/**
* This table stores the hashes of files. The table storing the edges will use the integer ids of
* this table.
*
*/
private void createMediaObjectsTable() {
final String createTable = " create table " + MEDIA_OBJECTS + "("
+ "id INTEGER PRIMARY KEY, hash TEXT, media_type TEXT) ";
executeSql(createTable);
}
/**
* Depends on {@link #createMediaObjectsTable(Connection)}.
*
*/
private void createFilesTable() {
final String createTable = " create table " + FILES + "(" + //
" media_object INTEGER NON NULL," + //
" absolute_path TEXT," + //
" FOREIGN KEY(media_object) REFERENCES " + MEDIA_OBJECTS + "(id) ) ";
executeSql(createTable);
}
private void createIgnoredTable() {
final String createTable = " create table " + IGNORED + "(" + //
" media_object INTEGER NON NULL," + //
" FOREIGN KEY(media_object) REFERENCES " + MEDIA_OBJECTS + "(id) ) ";
executeSql(createTable);
}
private void createEdgesTable() {
final String createTable = " create table " + EDGES + "(" + //
" winner INTEGER NON NULL," + //
" loser INTEGER NON NULL," + //
" FOREIGN KEY(winner) REFERENCES " + MEDIA_OBJECTS + "(id) , " + //
" FOREIGN KEY(loser) REFERENCES " + MEDIA_OBJECTS + "(id) ) ";
executeSql(createTable);
}
private void createFoldersTable() {
final String createTable = //
" CREATE TABLE folders ( " + //
" name TEXT NOT NULL, " + //
" media_type TEXT NOT NULL, " + //
" directory TEXT NOT NULL, " + //
" recursive TEXT NOT NULL " + //
" ) "//
;
executeSql(createTable);
}
/**
* Add one item to the media_objects table. One mediaObject represents one image, musicTrack or
* whatever else may be added.
*
* @param hash
* Hash should be created by SHA-256 over the whole file content. It should uniquely
* identify the mediaObject. This way an image can be recognized after it was moved.
* @param mediaType
* Currently String is allowed. This may later become an enum.
*/
void addMediaObject(final String hash, final MediaType mediaType) {
final String insert = " insert into " + MEDIA_OBJECTS + "(hash,media_type) values ('" + hash
+ "','" + mediaType.name() + "')";
executeSql(insert);
}
/**
* @param mediaObjectId
* @param file
*/
void addFile(final int mediaObjectId, final File file) {
// TODO preparedStatement? test performance
final String insert = "insert into " + FILES + " (media_object, absolute_path) values ("
+ mediaObjectId + ",'" + file.getAbsolutePath().replace("'", "''") + "')";
executeSql(insert);
}
/**
* @param file
* @return
*/
protected Optional<Integer> lookupFile(final File file) {
final String query = "select media_object from " + FILES + " where absolute_path = '"
+ file.getAbsolutePath().replace("'", "''") + "'";
LOG.trace(query);
final List<Integer> files = query(query, rs -> rs.getInt(1));
return files.stream()//
.findAny();
}
Optional<Integer> lookupMediaItemId(String hash) {
final String query = "select id from " + MEDIA_OBJECTS + " where hash = '" + hash + "'";
final List<Integer> ids = query(query, resultSet -> resultSet.getInt(1));
return ids.stream().findAny();
}
/**
* @return Zero or more {@link MediaObject} that match the given criteria.
*/
Collection<MediaObject> queryMediaObjects() {
String query = "select * from " + MEDIA_OBJECTS;
RowMapper<MediaObject> mediaObjectMapper = resultSet -> {
int id = resultSet.getInt("id");
String hash = resultSet.getString("hash");
String mediaTypeString = resultSet.getString("media_type");
MediaType mediaType = MediaType.valueOf(mediaTypeString);
MediaObject mediaObject = new MediaObject(id, hash, mediaType);
return mediaObject;
};
List<MediaObject> result = query(query, mediaObjectMapper);
return result;
}
/**
* @param files
* for each determine hash and create it in the files and media_object table if not
* already present.
*/
void registerFiles(final Collection<File> files) {
for (final File file : files) {
mediaId(file);
}
}
List<ImageBattleFolder> queryFolders(CentralStorage centralStorage) {
String query = "select * from folders";
RowMapper<ImageBattleFolder> mediaObjectMapper = resultSet -> {
String name = resultSet.getString("name");
String mediaTypeString = resultSet.getString("media_type");
MediaType mediaType = MediaType.valueOf(mediaTypeString);
String directory = resultSet.getString("directory");
File chosenDirectory = new File(directory);
boolean recursive = Boolean.parseBoolean(resultSet.getString("recursive"));
return new ImageBattleFolder(centralStorage, chosenDirectory, mediaType, recursive, name);
};
return query(query, mediaObjectMapper);
}
void addFolder(ImageBattleFolder folder) {
final String insert = "insert into folders values ("//
+ "'" + folder.getName() + "'," //
+ "'" + folder.getMediaType().name() + "'," //
+ "'" + folder.getDirectory().getAbsolutePath() + "'," //
+ "'" + folder.isRecursive() + "')";
LOG.debug(insert);
executeSql(insert);
}
/**
* @param connection
* Use {@link #getSqliteConnection(File)}.
* @param sql
* Any sql statement you want to be executed and don't expect an result from.
*/
private void executeSql(final String sql) {
try (Connection connection = dataSource.getConnection()) {
final Statement statement = connection.createStatement();
statement.execute(sql);
statement.close();
} catch (SQLException e) {
throw new IllegalStateException("sql execute error", e);
}
}
private <T> List<T> query(String query, RowMapper<T> rowMapper) {
final List<T> result = new LinkedList<>();
try (Connection connection = dataSource.getConnection()) {
try (Statement statement = connection.createStatement()) {
try (ResultSet resultSet = statement.executeQuery(query)) {
while (resultSet.next()) {
result.add(rowMapper.map(resultSet));
}
}
}
} catch (SQLException e) {
throw new IllegalStateException("sql query error", e);
}
return result;
}
private MediaType detectMediaType(final File file) {
// TODO im not 100% happy with this. Create a class MediaFile that detects type while creating?
return Arrays.stream(MediaType.values()).filter(type -> type.matches(file))//
.findAny()//
.orElseThrow(() -> new IllegalStateException("File type of " + file.getAbsolutePath()
+ " could not be detected. It should probably not be in the media battle."));
}
}
| gpl-3.0 |
dryabkov/activiti-modeler-experiment | platform extensions/bpmn20xmlbasic/src/de/hpi/bpmn2_0/model/data_object/DataObject.java | 2724 | /*******************************************************************************
* Signavio Core Components
* Copyright (C) 2012 Signavio GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package de.hpi.bpmn2_0.model.data_object;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.namespace.QName;
import de.hpi.bpmn2_0.transformation.Visitor;
/**
* <p>Java class for tDataObject complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="tDataObject">
* <complexContent>
* <extension base="{http://www.omg.org/bpmn20}tFlowElement">
* <sequence>
* <element ref="{http://www.omg.org/bpmn20}dataState" minOccurs="0"/>
* </sequence>
* <attribute name="itemSubjectRef" type="{http://www.w3.org/2001/XMLSchema}QName" />
* <attribute name="isCollection" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" />
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "tDataObject")
public class DataObject
extends AbstractDataObject
{
@XmlAttribute
protected QName itemSubjectRef;
public void acceptVisitor(Visitor v){
v.visitDataObject(this);
}
/**
* Gets the value of the itemSubjectRef property.
*
* @return
* possible object is
* {@link QName }
*
*/
public QName getItemSubjectRef() {
return itemSubjectRef;
}
/**
* Sets the value of the itemSubjectRef property.
*
* @param value
* allowed object is
* {@link QName }
*
*/
public void setItemSubjectRef(QName value) {
this.itemSubjectRef = value;
}
}
| gpl-3.0 |
robward-scisys/sldeditor | modules/application/src/main/java/com/sldeditor/datasource/extension/filesystem/FileSystemUtils.java | 1810 | /*
* SLD Editor - The Open Source Java SLD Editor
*
* Copyright (C) 2016, SCISYS UK Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sldeditor.datasource.extension.filesystem;
import com.sldeditor.common.utils.ExternalFilenames;
import java.io.File;
import java.util.List;
/**
* The Class FileSystemUtils.
*
* @author Robert Ward (SCISYS)
*/
public class FileSystemUtils {
/** Private default constructor */
private FileSystemUtils() {
// Private default constructor
}
/**
* Checks if is file extension supported.
*
* @param file the file
* @param fileExtensionList the file extension list
* @return true, if is file extension supported
*/
public static boolean isFileExtensionSupported(File file, List<String> fileExtensionList) {
if (file == null) {
return false;
}
String fileExtension = ExternalFilenames.getFileExtension(file.getAbsolutePath());
for (String allowedFileExtension : fileExtensionList) {
if (fileExtension.compareToIgnoreCase(allowedFileExtension) == 0) {
return true;
}
}
return false;
}
}
| gpl-3.0 |
RavikumarKatakam/DS-ALGO | src/org/ds/linkedlist/LinkedListShuffele.java | 486 | package org.ds.linkedlist;
public class LinkedListShuffele {
public Node shuffeleNodes(Node node) {
Node current = node;
Node prev = null;
Node temp = null;
while(current != null) {
prev = current;
current = current.next;
if (current == null) {
break;
} else {
if(temp == null) {
temp = current;
} else {
temp.next = current;
}
prev.next = current.next;
current = current.next;
}
}
prev.next = temp;
return node;
}
}
| gpl-3.0 |
leonardolb95/RegistroAEventos | app/src/main/java/mx/gob/jovenes/guanajuato/fragments/CustomFragment.java | 1477 | package mx.gob.jovenes.guanajuato.fragments;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import mx.gob.jovenes.guanajuato.R;
import mx.gob.jovenes.guanajuato.activities.SegundaActivity;
/**
* Created by Uriel on 01/02/2016.
*/
public class CustomFragment extends Fragment {
private int menu_id;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
int string_title = getArguments().getInt("string_title");
if(((AppCompatActivity)getActivity()).getSupportActionBar() != null) {
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(string_title);
}
}
public static CustomFragment newInstance(int menu_id, int string_title, Class classFragment) throws IllegalAccessException, java.lang.InstantiationException {
CustomFragment myFragment = (CustomFragment)classFragment.newInstance();
Bundle args = new Bundle();
args.putInt("menu_id", menu_id);
args.putInt("string_title", string_title);
myFragment.setArguments(args);
return myFragment;
}
}
| gpl-3.0 |
nickbattle/vdmj | vdmj/src/main/java/com/fujitsu/vdmj/in/patterns/INConcatenationPattern.java | 6298 | /*******************************************************************************
*
* Copyright (c) 2016 Fujitsu Services Ltd.
*
* Author: Nick Battle
*
* This file is part of VDMJ.
*
* VDMJ is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* VDMJ 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 VDMJ. If not, see <http://www.gnu.org/licenses/>.
* SPDX-License-Identifier: GPL-3.0-or-later
*
******************************************************************************/
package com.fujitsu.vdmj.in.patterns;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import com.fujitsu.vdmj.in.patterns.visitors.INPatternVisitor;
import com.fujitsu.vdmj.lex.LexLocation;
import com.fujitsu.vdmj.runtime.Context;
import com.fujitsu.vdmj.runtime.PatternMatchException;
import com.fujitsu.vdmj.runtime.ValueException;
import com.fujitsu.vdmj.util.Permutor;
import com.fujitsu.vdmj.values.NameValuePair;
import com.fujitsu.vdmj.values.NameValuePairList;
import com.fujitsu.vdmj.values.NameValuePairMap;
import com.fujitsu.vdmj.values.SeqValue;
import com.fujitsu.vdmj.values.Value;
import com.fujitsu.vdmj.values.ValueList;
public class INConcatenationPattern extends INPattern
{
private static final long serialVersionUID = 1L;
public final INPattern left;
public final INPattern right;
public INConcatenationPattern(INPattern left, LexLocation location, INPattern right)
{
super(location);
this.left = left;
this.right = right;
}
@Override
public String toString()
{
return left + " ^ " + right;
}
@Override
public int getLength()
{
int llen = left.getLength();
int rlen = right.getLength();
return (llen == ANY || rlen == ANY) ? ANY : llen + rlen;
}
@Override
public List<NameValuePairList> getAllNamedValues(Value expval, Context ctxt)
throws PatternMatchException
{
ValueList values = null;
try
{
values = expval.seqValue(ctxt);
}
catch (ValueException e)
{
patternFail(e);
}
int llen = left.getLength();
int rlen = right.getLength();
int size = values.size();
if ((llen == ANY && rlen > size) ||
(rlen == ANY && llen > size) ||
(rlen != ANY && llen != ANY && size != llen + rlen))
{
patternFail(4108, "Sequence concatenation pattern does not match expression");
}
// If the left and right sizes are ANY (ie. flexible) then we have to
// generate a set of splits of the values, and offer these to sub-matches
// to see whether they fit. Otherwise, there is just one split at this level.
List<Integer> leftSizes = new Vector<Integer>();
if (llen == ANY)
{
if (rlen == ANY)
{
// if (size == 0)
// {
// // Can't match a ^ b with []
// }
// else
if (size % 2 == 1)
{
// Odd => add the middle, then those either side
int half = size/2 + 1;
if (half > 0) leftSizes.add(half);
for (int delta=1; half - delta > 0; delta++)
{
leftSizes.add(half + delta);
leftSizes.add(half - delta);
}
leftSizes.add(0);
}
else
{
// Even => add those either side of the middle
int half = size/2;
if (half > 0) leftSizes.add(half);
for (int delta=1; half - delta > 0; delta++)
{
leftSizes.add(half + delta);
leftSizes.add(half - delta);
}
leftSizes.add(size);
leftSizes.add(0);
}
}
else
{
leftSizes.add(size - rlen);
}
}
else
{
leftSizes.add(llen);
}
// Now loop through the various splits and attempt to match the l/r
// sub-patterns to the split sequence value.
List<NameValuePairList> finalResults = new Vector<NameValuePairList>();
for (Integer lsize: leftSizes)
{
Iterator<Value> iter = values.iterator();
ValueList head = new ValueList();
for (int i=0; i<lsize; i++)
{
head.add(iter.next());
}
ValueList tail = new ValueList();
while (iter.hasNext()) // Everything else in second
{
tail.add(iter.next());
}
List<List<NameValuePairList>> nvplists = new Vector<List<NameValuePairList>>();
int psize = 2;
int[] counts = new int[psize];
try
{
List<NameValuePairList> lnvps = left.getAllNamedValues(new SeqValue(head), ctxt);
nvplists.add(lnvps);
counts[0] = lnvps.size();
List<NameValuePairList> rnvps = right.getAllNamedValues(new SeqValue(tail), ctxt);
nvplists.add(rnvps);
counts[1] = rnvps.size();
}
catch (PatternMatchException e)
{
continue;
}
Permutor permutor = new Permutor(counts);
while (permutor.hasNext())
{
try
{
NameValuePairMap results = new NameValuePairMap();
int[] selection = permutor.next();
for (int p=0; p<psize; p++)
{
for (NameValuePair nvp: nvplists.get(p).get(selection[p]))
{
Value v = results.get(nvp.name);
if (v == null)
{
results.put(nvp);
}
else // Names match, so values must also
{
if (!v.equals(nvp.value))
{
patternFail(4109, "Values do not match concatenation pattern");
}
}
}
}
finalResults.add(results.asList()); // Consistent set of nvps
}
catch (PatternMatchException pme)
{
// try next perm
}
}
}
if (finalResults.isEmpty())
{
patternFail(4109, "Values do not match concatenation pattern");
}
return finalResults;
}
@Override
public boolean isConstrained()
{
return left.isConstrained() || right.isConstrained();
}
@Override
public <R, S> R apply(INPatternVisitor<R, S> visitor, S arg)
{
return visitor.caseConcatenationPattern(this, arg);
}
}
| gpl-3.0 |
bozhbo12/demo-spring-server | spring-game/src/main/java/com/spring/game/game/core/GameLogService.java | 78294 | package com.snail.webgame.game.core;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.snail.webgame.game.cache.HeroInfoMap;
import com.snail.webgame.game.common.FightInfo;
import com.snail.webgame.game.common.fightdata.ArmyFightingInfo;
import com.snail.webgame.game.common.fightdata.DropInfo;
import com.snail.webgame.game.common.fightdata.FightArmyDataInfo;
import com.snail.webgame.game.common.fightdata.FightSideData;
import com.snail.webgame.game.condtion.AbstractConditionCheck;
import com.snail.webgame.game.condtion.ConditionType;
import com.snail.webgame.game.dao.GameLogDAO;
import com.snail.webgame.game.info.EquipInfo;
import com.snail.webgame.game.info.HeroInfo;
import com.snail.webgame.game.info.MailInfo;
import com.snail.webgame.game.info.QuestInProgressInfo;
import com.snail.webgame.game.info.RoleInfo;
import com.snail.webgame.game.info.log.ChallengeLog;
import com.snail.webgame.game.info.log.CompetitiveLog;
import com.snail.webgame.game.info.log.ConfigType;
import com.snail.webgame.game.info.log.DefendFightLog;
import com.snail.webgame.game.info.log.GamePVELog;
import com.snail.webgame.game.info.log.GamePvp3Log;
import com.snail.webgame.game.info.log.MapFightLog;
import com.snail.webgame.game.info.log.MineFightLog;
import com.snail.webgame.game.info.log.RoleArenaLog;
import com.snail.webgame.game.info.log.RoleCampLog;
import com.snail.webgame.game.info.log.StatLog;
import com.snail.webgame.game.info.log.WorldBossFightLog;
import com.snail.webgame.game.protocal.fight.fightend.BattlePrize;
import com.snail.webgame.game.protocal.fight.startFight.StartFightPosInfo;
public class GameLogService {
private static final Logger logger = LoggerFactory.getLogger("logs");
private static GameLogDAO gameLogDAO = GameLogDAO.getInstance();
/**
* 行为日志(默认完成)
* @param roleInfo
* @param gameAction
* @param actValue
* @return
*/
public static void insertPlayActionLog(RoleInfo roleInfo, int gameAction, String actValue) {
insertPlayActionLog(roleInfo, gameAction, 1, actValue);
}
/**
* 行为日志
* @param roleInfo
* @param gameAction
* @param type 0-开始,1-完成,2-未完成
* @param actValue
* @return
*/
public static void insertPlayActionLog(RoleInfo roleInfo, int gameAction, int type, String actValue) {
/*PlayActionLog log = new PlayActionLog();
log.setAccount(roleInfo.getAccount());
log.setRoleName(roleInfo.getRoleName());
log.setRoleName(log.getRoleName().replace("\\", ""));
log.setCreateTime(new Timestamp(System.currentTimeMillis()));
log.setActId(String.valueOf(gameAction));
log.setType(type);
log.setActValue(actValue);
gameLogDAO.insertPlayActionLog(log);*/
StringBuffer buffer = GameLogDAO.palyActionLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(String.valueOf(gameAction));
buffer.append("'");
buffer.append(",");
buffer.append(type);
buffer.append(",");
buffer.append("'");
buffer.append(actValue);
buffer.append("'");
buffer.append("),");
GameLogDAO.actionLogCount++;
gameLogDAO.insertPlayActionLog();
}
}
/**
* 用户登录 登出日志
* @param roleInfo
* @param ip
* @param mac
* @param comment
* @return
*/
public static void insertRoleLog(RoleInfo roleInfo, String ip, String mac, String osType, Timestamp loginTime,
Timestamp logoutTime, String comment) {
/*RoleLog log = new RoleLog();
String ser = UUID.randomUUID().toString();
roleInfo.setLoginId(UUID.randomUUID().toString().replace("-", ""));
log.setSerial(ser.replace("-", ""));
log.setAccount(roleInfo.getAccount());
log.setRoleName(roleInfo.getRoleName());*/
roleInfo.setLoginLogId(UUID.randomUUID().toString().replace("-", ""));
HeroInfo heroInfo = HeroInfoMap.getMainHeroInfo(roleInfo);
//INSERT INTO ROLE_LOG
//(S_SERIAL,S_ACCOUNT,N_HERO_NO,S_ROLE,S_IP,D_LOGINTIME,D_LOGOUTTIME, S_MAC,S_OS_TYPE, S_COMMENT)VALUES
/*log.setHeroNo(heroInfo == null ? 0 : heroInfo.getHeroNo());
log.setIp(ip);
log.setLoginTime(loginTime);
log.setLogoutTime(logoutTime);
log.setMac(mac);
log.setOsType(osType);
log.setComment(comment);
gameLogDAO.insertRoleLog(roleInfo, log);*/
StringBuffer buffer = GameLogDAO.roleLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append("'");
buffer.append(roleInfo.getLoginLogId());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(heroInfo == null ? 0 : heroInfo.getHeroNo());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(ip);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(loginTime);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(logoutTime);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(mac);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(osType);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(comment);
buffer.append("'");
buffer.append("),");
GameLogDAO.roleLogCount++;
gameLogDAO.insertRoleLogin();
}
}
/**
* 任务日志
* @param roleInfo
* @param info
* @param actType 承接:0,完成:1,放弃:2
* @return
*/
public static void insertTaskLog(RoleInfo roleInfo, QuestInProgressInfo info, int actType) {
/*List<TaskLog> logs = new ArrayList<TaskLog>();
TaskLog log = new TaskLog();
log.setTaskId(ConfigType.task.getType()+"-"+info.getQuestProtoNo());
log.setAccount(roleInfo.getAccount());
log.setRoleName(roleInfo.getRoleName());
log.setActType(actType);
log.setCreateTime(new Timestamp(System.currentTimeMillis()));
logs.add(log);*/
//INSERT INTO TASK_LOG (S_TASK_ID,S_ACCOUNT,S_ROLE_NAME,N_ACT_TYPE,D_CREATE)
StringBuffer buffer = GameLogDAO.taskLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append("'");
buffer.append(ConfigType.task.getType()+"-"+info.getQuestProtoNo());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(actType);
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append("),");
GameLogDAO.taskLogCount++;
gameLogDAO.insertTaskLog();
}
}
/**
* 任务日志
* @param roleInfo
* @param info
* @param actType 承接:0,完成:1,放弃:2
* @return
*/
public static void insertTaskLog(RoleInfo roleInfo, List<QuestInProgressInfo> list, int actType) {
StringBuffer buffer = GameLogDAO.taskLogBuffer;
synchronized(buffer)
{
for (QuestInProgressInfo info : list) {
/*TaskLog log = new TaskLog();
log.setTaskId(ConfigType.task.getType()+"-"+info.getQuestProtoNo());
log.setAccount(roleInfo.getAccount());
log.setRoleName(roleInfo.getRoleName());
log.setActType(actType);
log.setCreateTime(new Timestamp(System.currentTimeMillis()));
logs.add(log);*/
//INSERT INTO TASK_LOG (S_TASK_ID,S_ACCOUNT,S_ROLE_NAME,N_ACT_TYPE,D_CREATE)
buffer.append("(");
buffer.append("'");
buffer.append(ConfigType.task.getType()+"-"+info.getQuestProtoNo());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(actType);
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append("),");
GameLogDAO.taskLogCount++;
}
gameLogDAO.insertTaskLog();
}
}
/**
* 用户资源变动日志
* @param roleInfo
* @param gameAction
* @param type money银子 gold金子 sp体力 soul战魂 tech科技点 exp角色经验
* @param eventType 获得0,失去1
* @param before
* @param after
* @param drop 消耗资源未涉及到购买物品,则置空
* @return
*/
public static void insertMoneyLog(RoleInfo roleInfo, int gameAction, ConditionType type, int eventType, int before,
int after,DropInfo drop) {
int moneyType = 0;
if (AbstractConditionCheck.isResourceType(type.getName())) {
moneyType = type.getType();
} else {
logger.error("it is not exit resource:" + type.getName());
return;
}
/*MoneyLog info = new MoneyLog();
info.setAccount(roleInfo.getAccount());
info.setRoleName(roleInfo.getRoleName());
info.setRoleName(info.getRoleName().replace("\\", ""));
info.setCreateTime(new Timestamp(System.currentTimeMillis()));
info.setMoneyType(moneyType);
info.setEventId(String.valueOf(gameAction));
info.setEventType(eventType);
info.setMoney(Math.abs((int) after - (int) before));
info.setRecvAccount("");
info.setRecvRoleName("");
info.setSceneId("");
info.setGuildId("");
info.setState("1");// 异动状态 失败:0,成功:1
info.setRoleLevel(HeroInfoMap.getMainHeroLv(roleInfo.getId()));
info.setTotalLogtime(0);
info.setBefore(before);
info.setAfter(after);
info.setTradeId(0);
info.setTradeFlag("0");// 是否交易 不是:0,是:1
info.setComment("");
if(drop==null){
info.setItemId("");
info.setCount(0);
}else{
info.setItemId(drop.getItemNo());
info.setCount(drop.getItemNum());
}*/
StringBuffer buffer = GameLogDAO.moneyLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
buffer.append(moneyType);
buffer.append(",");
buffer.append("'");
buffer.append(String.valueOf(gameAction));
buffer.append("'");
buffer.append(",");
buffer.append(eventType);
buffer.append(",");
if(drop==null){
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append(",");
buffer.append(0);
buffer.append(",");
}else{
buffer.append("'");
buffer.append(drop.getItemNo());
buffer.append("'");
buffer.append(",");
buffer.append(drop.getItemNum());
buffer.append(",");
}
buffer.append(Math.abs((int) after - (int) before));
buffer.append(",");
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append("1");
buffer.append("'");
buffer.append(",");
buffer.append(HeroInfoMap.getMainHeroLv(roleInfo.getId()));
buffer.append(",");
buffer.append(0);
buffer.append(",");
buffer.append(before);
buffer.append(",");
buffer.append(after);
buffer.append(",");
buffer.append(0);
buffer.append(",");
buffer.append("'");
buffer.append("0");
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append("),");
GameLogDAO.moneyLogCount++;
gameLogDAO.insertMoneyLog();
}
}
/**
* 用户背包变动日志
* @param roleInfo
* @param gameAction
* @param eventType 获得0,失去1
* @param itemNo
* @param before
* @param after
* @return
*/
public static void insertItemLog(RoleInfo roleInfo, int gameAction, int eventType, int itemNo, int before, int after) {
/*ItemLog log = new ItemLog();
log.setAccount(roleInfo.getAccount());
log.setRoleName(roleInfo.getRoleName());
log.setRoleName(log.getRoleName().replace("\\", ""));
log.setCreateTime(new Timestamp(System.currentTimeMillis()));
log.setEventId(gameAction + "");
log.setEventType(eventType);
log.setItemId(String.valueOf(itemNo));
log.setCount(Math.abs(after - before));
log.setRecvAccount("");
log.setRecvRoleName("");
log.setSceneId("");
log.setGuildId("");
log.setState("1");
log.setBefore(before);
log.setAfter(after);
log.setTradeId(0);
log.setTradeFlag("0");// 是否交易 不是:0,是:1
log.setComment("");*/
StringBuffer buffer = GameLogDAO.itemLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
buffer.append(gameAction);
buffer.append(",");
buffer.append(eventType);
buffer.append(",");
buffer.append("'");
buffer.append(itemNo);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(Math.abs(after - before));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(1);
buffer.append("'");
buffer.append(",");
buffer.append(before);
buffer.append(",");
buffer.append(after);
buffer.append(",");
buffer.append(0);
buffer.append(",");
buffer.append("'");
buffer.append(0);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append("),");
GameLogDAO.itemLogCount++;
gameLogDAO.insertItemLog();
}
}
/**
* 玩家升级日志表
* @param roleInfo
* @param logType
* @param before
* @param after
* @param skillId
*/
public static void insertRoleUpgradeLog(RoleInfo roleInfo, int logType, int before, int after, int skillId) {
/*RoleUpgradeLog log = new RoleUpgradeLog();
String ser = UUID.randomUUID().toString();
log.setSerial(ser.replace("-", ""));
log.setCreateTime(new Timestamp(System.currentTimeMillis()));
log.setAccount(roleInfo.getAccount());
log.setRoleName(roleInfo.getRoleName());
log.setLogType(logType);
log.setBefore(before);
log.setAfter(after);
log.setSkillId(skillId);*/
//S_SERIAL,D_TIME,S_ACCOUNT,S_ROLE,N_LOGTYPE,N_LEVEL_BEFORE,N_LEVEL_AFTER,S_SKILL_ID
StringBuffer buffer = GameLogDAO.roleUpLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append("'");
buffer.append(UUID.randomUUID().toString().replace("-", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(logType);
buffer.append(",");
buffer.append(before);
buffer.append(",");
buffer.append(after);
buffer.append(",");
buffer.append(skillId);
buffer.append("),");
GameLogDAO.roleUpLogCount++;
gameLogDAO.insertRoleUpgradeLog();
}
}
/**
* 副本日志
* @param roleId
* @param instanceId 副本实例的ID (fightId)
* @param instanceTypeId 副本id (fightType+"+"+defendStr)
* @param startTime 实例创建时间
* @param endTime 实例结束时间
* @param troopCount1 副本创建时组队人数
* @param troopCount2 副本完成时组队人数
*/
public static void insertInstanceLog(int roleId, FightInfo fightInfo) {
/*long now = System.currentTimeMillis();
InstanceLog instanceLog = new InstanceLog();
instanceLog.setSerial(UUID.randomUUID().toString().replace("-", ""));
instanceLog.setRoleId(roleId);
instanceLog.setInstanceId(String.valueOf(fightInfo.getFightId()));
instanceLog.setInstanceTypeId(fightInfo.getInstanceTypeId());
instanceLog.setStartTime(new Timestamp(fightInfo.getFightTime()));
instanceLog.setEndTime(new Timestamp(System.currentTimeMillis()));
instanceLog.setDuration((int) (now - fightInfo.getFightTime()) / 1000);*/
int troopCount1 = 0;
if (fightInfo.getFightDataList() != null) {
for (FightSideData fightSide : fightInfo.getFightDataList()) {
if (fightSide.getSideId() == 0) {
for (FightArmyDataInfo army : fightSide.getArmyInfos()) {
if (army.getCurrHp() > 0) {
troopCount1++;
}
}
for (FightArmyDataInfo army : fightSide.getAddArmyInfos()) {
if (army.getCurrHp() > 0) {
troopCount1++;
}
}
}
}
}
//instanceLog.setTroopCount1(troopCount1);
int troopCount2 = 0;
if (fightInfo.getArmyFightingInfos() != null) {
for (ArmyFightingInfo army : fightInfo.getArmyFightingInfos()) {
if (army.getSideId() == 0 && army.getCurrentHp() > 0) {
troopCount2++;
}
}
}
//instanceLog.setTroopCount2(troopCount2);
//INSERT INTO INSTANCE_LOG
//(S_SERIAL,N_ROLE_ID,S_INSTANCEID,S_INSTANCETYPEID,D_STARTTIME,D_ENDTIME,N_DURATION,N_TROOP_COUNT1,N_TROOP_COUNT2)
StringBuffer buffer = GameLogDAO.instanceLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append("'");
buffer.append(UUID.randomUUID().toString().replace("-", ""));
buffer.append("'");
buffer.append(",");
buffer.append(roleId);
buffer.append(",");
buffer.append("'");
buffer.append(String.valueOf(fightInfo.getFightId()));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(fightInfo.getInstanceTypeId());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(fightInfo.getFightTime()));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
buffer.append((int) (System.currentTimeMillis() - fightInfo.getFightTime()) / 1000);
buffer.append(",");
buffer.append(troopCount1);
buffer.append(",");
buffer.append(troopCount2);
buffer.append("),");
GameLogDAO.instanceLogCount++;
gameLogDAO.insertInstanceLog();
}
}
/**
* 记录惩罚玩家日志
* @param roleInfo
* @param punishType 0-解禁 1-禁言 2-冻结
* @param minutes 被禁言或冻结的分钟数
* @param operator
*/
public static void insertPunishLog(RoleInfo roleInfo, byte punishType, int minutes, String operator) {
/*PunishLog log = new PunishLog();
String ser = UUID.randomUUID().toString();
log.setSerial(ser.replace("-", ""));
log.setCreateTime(new Timestamp(System.currentTimeMillis()));
log.setOperator(operator);
log.setRoleName(roleInfo.getRoleName());
log.setAccount(roleInfo.getAccount());
log.setMinutes(minutes);
log.setPunishType(punishType);*/
//INSERT INTO PUNISH_LOG(S_SERIAL,D_TIME,S_OPERATOR,S_ROLE,S_ACCOUNT,N_MINUTES,N_PUNISH_TYPE)
StringBuffer buffer = GameLogDAO.punishLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append("'");
buffer.append(UUID.randomUUID().toString().replace("-", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(operator);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(minutes);
buffer.append(",");
buffer.append("'");
buffer.append(punishType);
buffer.append("'");
buffer.append("),");
GameLogDAO.punishLogCount++;
gameLogDAO.insertPunishLog();
}
}
/**
* 英雄觉醒动日志
* @param roleInfo
* @param heroId
* @param gameAction
* @param upType 变动类型 0-获得 1-等级 2-星级 3-品阶 4-亲密度
* @param before
* @param after
* @return
*/
public static void insertHeroUpLog(RoleInfo roleInfo,int heroNo, int gameAction, int upType, int before,
int after) {
/*HeroUpLog log = new HeroUpLog();
log.setRoleId(roleInfo.getId());
log.setAccount(roleInfo.getAccount());
log.setRoleName(roleInfo.getRoleName());
log.setHeroNo(heroNo);
log.setTime(new Timestamp(System.currentTimeMillis()));
log.setEventId(gameAction + "");
log.setUpType(upType);// 1-等级 2-星级
log.setBefore(before);
log.setAfter(after);*/
//INSERT INTO GAME_HERO_UP_LOG(N_ROLE_ID,S_ACCOUNT, S_ROLE_NAME, N_HERO_NO, D_TIME,S_EVENT_ID,N_UP_TYPE,N_BEFORE,N_AFTER)
StringBuffer buffer = GameLogDAO.heroUpLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append(roleInfo.getId());
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(heroNo);
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(gameAction);
buffer.append("'");
buffer.append(",");
buffer.append(upType);
buffer.append(",");
buffer.append(before);
buffer.append(",");
buffer.append(after);
buffer.append("),");
GameLogDAO.heroUpLogCount++;
gameLogDAO.insertHeroUpLog();
}
}
/**
* 神兵升级日志
* @param roleInfo
* @param heroId
* @param gameAction
* @param upType 0-神兵升级
* @param before
* @param after
* @return
*/
public static void insertWeaponUpLog(RoleInfo roleInfo, int gameAction, int upType, int before,
int after, int weaponId, int weaponNo) {
/*WeaponUpLog log = new WeaponUpLog();
log.setRoleId(roleInfo.getId());
log.setAccount(roleInfo.getAccount());
log.setRoleName(roleInfo.getRoleName());
log.setWeaponId(weaponId);
log.setWeaponNo(weaponNo);
log.setTime(new Timestamp(System.currentTimeMillis()));
log.setEventId(gameAction + "");
log.setUpType(upType);
log.setBefore(before);
log.setAfter(after);*/
//INSERT INTO GAME_WEAPON_UP_LOG(N_ROLE_ID,S_ACCOUNT, S_ROLE_NAME,N_WEAPON_ID,N_WEAPON_NO,D_TIME,S_EVENT,N_UP_TYPE,N_BEFORE,N_AFTER)
StringBuffer buffer = GameLogDAO.weapUpLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append(roleInfo.getId());
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(weaponId);
buffer.append(",");
buffer.append(weaponNo);
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(gameAction);
buffer.append("'");
buffer.append(",");
buffer.append(upType);
buffer.append(",");
buffer.append(before);
buffer.append(",");
buffer.append(after);
buffer.append("),");
GameLogDAO.weapUpLogCount++;
gameLogDAO.insertWeaponUpLog();
}
}
/**
* 英雄装备变动日志
* @param roleInfo
* @param bagItem
* @param gameAction
* @param eventType 获得0,失去1
* @return
*/
public static void insertEquipInfoLog(RoleInfo roleInfo, EquipInfo heroEquipInfo, int gameAction, int eventType) {
if (heroEquipInfo != null) {
/*EquipInfoLog log = new EquipInfoLog();
log.setRoleId(roleInfo.getId());
log.setAccount(roleInfo.getAccount());
log.setRoleName(roleInfo.getRoleName());
log.setRoleName(log.getRoleName().replace("\\", ""));
// log.setHeroId(heroEquipInfo.getHeroId());
log.setItemId(heroEquipInfo.getId());
log.setItemNo(heroEquipInfo.getEquipNo());
log.setItemLevel(heroEquipInfo.getLevel());
log.setItemStar(0);
log.setExp(0);
log.setColour(0);
log.setTime(new Timestamp(System.currentTimeMillis()));
log.setEventId(String.valueOf(gameAction));
log.setEventType(eventType);
log.setState("1");
log.setComment("");*/
//INSERT INTO GAME_EQUIP_INFO_LOG
//(N_ROLE_ID,S_ACCOUNT, S_ROLE_NAME, N_HERO_ID,N_ITEM_ID,N_ITEM_NO,N_ITEM_LEVEL, N_ITEM_STAR,
//N_EXP,N_COLOUR,D_TIME,S_EVENT_ID,N_EVENT_TYPE,S_STATE,S_COMMENT)
StringBuffer buffer = GameLogDAO.equipInfoLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append(roleInfo.getId());
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(0);
buffer.append(",");
buffer.append(heroEquipInfo.getId());
buffer.append(",");
buffer.append(heroEquipInfo.getEquipNo());
buffer.append(",");
buffer.append(heroEquipInfo.getLevel());
buffer.append(",");
buffer.append(0);
buffer.append(",");
buffer.append(0);
buffer.append(",");
buffer.append(0);
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(gameAction);
buffer.append("'");
buffer.append(",");
buffer.append(eventType);
buffer.append(",");
buffer.append("'");
buffer.append(1);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append("),");
GameLogDAO.equipInfoLogCount++;
gameLogDAO.insertEquipInfoLog();
}
}
}
/**
* 装备升级日志
* @param roleInfo
* @param gameAction
* @param heroId
* @param equipId
* @param equipNo
* @param before
* @param after
* @return
*/
public static void insertEquipUpLog(RoleInfo roleInfo, int gameAction, long heroId, long equipId, int equipNo,
int before, int after) {
/*EquipUpLog log = new EquipUpLog();
log.setRoleId(roleInfo.getId());
log.setAccount(roleInfo.getAccount());
log.setRoleName(roleInfo.getRoleName());
log.setHeroId(heroId);
log.setItemId(equipId);
log.setEquipNo(equipNo);
log.setTime(new Timestamp(System.currentTimeMillis()));
log.setEventId(gameAction + "");
log.setBefore(before);
log.setAfter(after);*/
//INSERT INTO GAME_EQUIP_UP_LOG(N_ROLE_ID,S_ACCOUNT, S_ROLE_NAME, N_HERO_ID,N_EQUIP_ID,N_EQUIP_NO,D_TIME,S_EVENT,N_BEFORE,N_AFTER)
StringBuffer buffer = GameLogDAO.equipUpLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append(roleInfo.getId());
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(heroId);
buffer.append(",");
buffer.append(equipId);
buffer.append(",");
buffer.append(equipNo);
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(gameAction);
buffer.append("'");
buffer.append(",");
buffer.append(before);
buffer.append(",");
buffer.append(after);
buffer.append("),");
GameLogDAO.equipUpLogCount++;
gameLogDAO.insertEquipUpLog();
}
}
/**
* 记录极效日志
* @param method
* @param guid
* @param targetRoleName
* @param targetRoleAcc
* @param xmlIdStr
* @param msgContent
* @param operator
* @param successful
* @return
*/
public static void insertToolOperatLog(String method, String guid, String targetRoleName, String targetRoleAcc,
String xmlIdStr, String msgContent, String operator, String successful) {
/*ToolOperateLog log = new ToolOperateLog();
log.setMsgType(method);
log.setGuid(guid);
log.setTargetRoleName(targetRoleName);
log.setTargetRoleAcc(targetRoleAcc);
log.setXmlIdStr(xmlIdStr);
log.setMsgContent(msgContent);
log.setOperator(operator);
log.setReserve("");
log.setOperateTime(new Timestamp(System.currentTimeMillis()));
log.setSuccess("1".equals(successful));*/
//INSERT INTOGAME_TOOL_OPERATE_LOG
//(S_MESSAGE_TYPE, S_GUID, S_TARGET_ROLE_NAME, S_TARGET_ROLE_ACCOUNT,S_XML_NAME_STR, S_MESSAGE_CONTENT, S_OPERATOR_ACCOUNT,
//D_OPERATE_TIME, N_IS_SUCC, S_RESERVE)
StringBuffer buffer = GameLogDAO.toolOperateLogBuffer;
synchronized(buffer){
buffer.append("(");
buffer.append("'");
buffer.append(method);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(guid);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(targetRoleName.replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(targetRoleAcc);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(xmlIdStr);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append(",");
logger.warn("method="+method+",guid="+guid+",msgContent="+msgContent);
buffer.append("'");
buffer.append(operator);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
buffer.append("1".equals(successful));
buffer.append(",");
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append("),");
GameLogDAO.toolOperateLogCount++;
gameLogDAO.insertGameToolOperateLog();
}
}
/**
* 保存邮件日志
* @param list
* @param type 0-领取附件 1-发送附件 2-删除邮件
* @return
*/
public static void saveMailInfoLog(List<MailInfo> list, int type) {
if(list == null){
return;
}
//List<MailInfoLog> logs = new ArrayList<MailInfoLog>();
//MailInfoLog log = null;
StringBuffer buffer = GameLogDAO.mailLogBuffer;
synchronized(buffer)
{
for (MailInfo info : list) {
/*log = new MailInfoLog();
log.setMailId(info.getId());
log.setSendRoleName(info.getSendRoleName());
log.setReceiveRoleName(info.getReceiveRoleName());
log.setTime(new Timestamp(System.currentTimeMillis()));
log.setActType(0);
log.setAttachment(info.getAttachmentStr());
log.setRecAcc(info.getRecAcc());
log.setRecId(info.getReceiveRoleId());
logs.add(log);*/
//INSERT INTO GAME_MAIL_LOG(N_ID,S_SENDNAME,S_RECEIVENAME,D_DEAL_TIME,N_TYPE,S_ATTACHMENT,S_REC_ACC)
buffer.append("(");
buffer.append(info.getId());
buffer.append(",");
buffer.append("'");
buffer.append(info.getSendRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(info.getReceiveRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
buffer.append(0);
buffer.append(",");
buffer.append("'");
buffer.append(info.getAttachmentStr());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(info.getRecAcc());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(info.getMailTitle());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(info.getMailContent());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(info.getReserve());
buffer.append("'");
buffer.append("),");
GameLogDAO.mailLogCount++;
}
gameLogDAO.insertMailInfoLog();
}
}
/**
* 记录在线用户日志
* @param nAmount
* @param time
*/
public static void addStatOnline(int nAmount, long time) {
StatLog statOnlineLog = new StatLog();
statOnlineLog.setnAmount(nAmount);
statOnlineLog.setTimestamp(new Timestamp(time));
gameLogDAO.addStatOnline(statOnlineLog);
}
/**
* 记录注册用户日志
* @param nAmount
* @param time
*/
public static void addStatNewAccount(int nAmount, long time) {
StatLog statOnlineLog = new StatLog();
statOnlineLog.setnAmount(nAmount);
statOnlineLog.setTimestamp(new Timestamp(time));
gameLogDAO.addStatNewAccount(statOnlineLog);
}
/**
* 记录开卡用户日志
* @param nAmount
* @param time
*/
public static void addStatNewCard(int nAmount, long time) {
StatLog statOnlineLog = new StatLog();
statOnlineLog.setnAmount(nAmount);
statOnlineLog.setTimestamp(new Timestamp(time));
gameLogDAO.addStatNewCard(statOnlineLog);
}
/**
* 记录角色名变动日志
* @param roleInfo
* @param before
* @param after
*/
public static void insertRoleNameLog(RoleInfo roleInfo, String before, String after) {
//INSERT INTO GAME_ROLE_NAME_LOG
//(N_ROLE_ID,S_U_ID,S_ACCOUNT, S_BEFORE,S_AFTER, D_CREATE)VALUES
/*RoleNameLog log = new RoleNameLog();
log.setRoleId(roleInfo.getId());
log.setAccount(roleInfo.getAccount());
log.setUid(roleInfo.getUid());
log.setBefore(before);
log.setAfter(after);
log.setCreateTime(new Timestamp(System.currentTimeMillis()));*/
StringBuffer buffer = GameLogDAO.roleNameLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append(roleInfo.getId());
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getUid());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(before.replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(after.replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append("),");
GameLogDAO.roleNameLogCount++;
gameLogDAO.insertRoleNameLog();
}
}
/**
* 商店物品购买日志
* @param roleInfo
* @param itemNo
* @param itemNum
* @param storeType
*/
public static void insertStoreBuyItemLog(RoleInfo roleInfo,byte storeType,int itemNo,int itemNum,String sourceType,int sourceNum) {
/*StoreBuyItemLog log = new StoreBuyItemLog();
log.setAccount(roleInfo.getAccount());
log.setRoleName(roleInfo.getRoleName());
log.setRoleId(roleInfo.getId());
log.setStoreType(storeType);
log.setItemNo(itemNo);
log.setItemNum(itemNum);
log.setSourceType(sourceType);
log.setSourceNum(sourceNum);
log.setCreateTime(new Timestamp(System.currentTimeMillis()));*/
//INSERT INTO GAME_STORE_BUY_ITEM_LOG(S_ACCOUNT,S_ROLE_NAME, N_ROLE_ID,N_SOTRE_TYPE,N_ITEM_NO,N_ITEM_NUM,S_SOURCE_TYPE,N_USED_SOURCE,D_CREATE)
StringBuffer buffer = GameLogDAO.storeBugLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(roleInfo.getId());
buffer.append(",");
buffer.append(storeType);
buffer.append(",");
buffer.append(itemNo);
buffer.append(",");
buffer.append(itemNum);
buffer.append(",");
buffer.append("'");
buffer.append(sourceType);
buffer.append("'");
buffer.append(",");
buffer.append(sourceNum);
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append("),");
GameLogDAO.storeBugLogCount++;
gameLogDAO.insertStoreBuyItemLog();
}
}
/**
* 镖车日志
* @param roleInfo
* @param itemNo
* @param itemNum
* @param storeType
*/
public static void insertBiaocheLog(RoleInfo roleInfo,int action,int num,int getSilver,int lostSilver,int usedCoin,byte biaocheType,int result) {
/*BiaocheLog log = new BiaocheLog();
log.setAccount(roleInfo.getAccount());
log.setRoleName(roleInfo.getRoleName());
log.setRoleId(roleInfo.getId());
log.setAction(action);
log.setNum(num);
log.setSilverChange(getSilver);
log.setLostSilver(lostSilver);
log.setUsedCoin(usedCoin);
log.setBiaocheType(biaocheType);
log.setTime(new Timestamp(System.currentTimeMillis()));
log.setResult((byte) result);*/
//INSERT INTO GAME_BIAO_CHE_LOG
//(S_ACCOUNT,S_ROLE_NAME, N_ROLE_ID,N_ACTION,N_NUM,N_SILVER_CHANGE,D_CREATE,S_CONTENT,N_RESULT,N_LOST_SILVER,N_USED_COIN,N_BIAO_CHE_TYPE)
StringBuffer buffer = GameLogDAO.biaocheLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(roleInfo.getId());
buffer.append(",");
buffer.append(action);
buffer.append(",");
buffer.append(num);
buffer.append(",");
buffer.append(getSilver);
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append(",");
buffer.append(result);
buffer.append(",");
buffer.append(lostSilver);
buffer.append(",");
buffer.append(usedCoin);
buffer.append(",");
buffer.append(biaocheType);
buffer.append("),");
GameLogDAO.biaocheLogCount++;
gameLogDAO.insertBiaocheLog();
}
}
/**
* 兵种升级日志
* @param roleInfo
* @param itemNo
* @param itemNum
* @param storeType
*/
public static void insertSoliderUpLog(RoleInfo roleInfo,byte soliderType,byte isUp,int beforeLv,int afterLv,int useMoney,int useItemNo,int useItemNum) {
/*SoliderUpLog log = new SoliderUpLog();
log.setAccount(roleInfo.getAccount());
log.setRoleName(roleInfo.getRoleName());
log.setRoleId(roleInfo.getId());
log.setSoliderType(soliderType);
log.setIsUp(isUp);
log.setBeforeLv(beforeLv);
log.setAtterLv(afterLv);
log.setUseMoney(useMoney);
log.setUseItemNo(useItemNo);
log.setUseItemNum(useItemNum);
log.setTime(new Timestamp(System.currentTimeMillis()));*/
//INSERT INTO GAME_SOLDIER_UP_LOG
//(S_ACCOUNT,S_ROLE_NAME, N_ROLE_ID,N_SOLDIER_TYPE,N_IS_UP,N_BEFORE_LV,N_AFTER_LV,D_CREATE,S_CONTENT,N_USE_MONEY,N_USE_ITEM_NO,N_USE_ITEM_NUM)
StringBuffer buffer = GameLogDAO.soliderUpLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(roleInfo.getId());
buffer.append(",");
buffer.append(soliderType);
buffer.append(",");
buffer.append(isUp);
buffer.append(",");
buffer.append(beforeLv);
buffer.append(",");
buffer.append(afterLv);
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append(",");
buffer.append(useMoney);
buffer.append(",");
buffer.append(useItemNo);
buffer.append(",");
buffer.append(useItemNum);
buffer.append("),");
GameLogDAO.soliderUpLogCount++;
gameLogDAO.insertSoliderUpLog();
}
}
/**
* 记录技能升级
* @param roleInfo
* @param id
* @param gameHeroAction5
* @param i
* @param currLv
* @param nextLv
*/
public static void insertHeroSkillUpLog(RoleInfo roleInfo, int heroNo, int skillNo, int action, int currLv,
int nextLv) {
/*HeroSkillUpLog log = new HeroSkillUpLog();
log.setRoleId(roleInfo.getId());
log.setRoleName(roleInfo.getRoleName());
log.setAccount(roleInfo.getAccount());
log.setHeroNo(heroNo);
log.setSkillNo(skillNo);
log.setTime(new Timestamp(System.currentTimeMillis()));
log.setEventId(action + "");
log.setBefore(currLv);
log.setAfter(nextLv);*/
//INSERT INTO GAME_HERO_SKILL_UP_LOG
//(N_ROLE_ID,S_ACCOUNT, S_ROLE_NAME, N_HERO_NO, N_SKILL_NO, D_TIME, S_EVENT_ID, N_BEFORE, N_AFTER)
StringBuffer buffer = GameLogDAO.heroSkillUpLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append(roleInfo.getId());
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(heroNo);
buffer.append(",");
buffer.append(skillNo);
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(action);
buffer.append("'");
buffer.append(",");
buffer.append(currLv);
buffer.append(",");
buffer.append(nextLv);
buffer.append("),");
GameLogDAO.heroSkillUpLogCount++;
gameLogDAO.insertHeroSkillUpLog();
}
}
/**
* 记录点金手日志
* @param log
*/
public static void insertGoldBuyLog(RoleInfo roleInfo,int action,ConditionType moneyType,int before,int after,int cost,int beforeNum,int afterNum){
/*GoldBuyLog log = new GoldBuyLog();
log.setRoleId(roleInfo.getId());
log.setAccount(roleInfo.getAccount());
log.setRoleName(roleInfo.getRoleName());
log.setTime(new Timestamp(System.currentTimeMillis()));
log.setEventId(action + "");
log.setMoneyType(moneyType.getType());
log.setBefore(before);
log.setAfter(after);
log.setCost(cost);
log.setBeforeNum(beforeNum);
log.setAfterNum(afterNum);*/
//INSERT INTO GAME_GOLD_BUY_LOG
//(N_ROLE_ID,S_ACCOUNT, S_ROLE_NAME, D_TIME, S_EVENT_ID,N_MONEY_TYPE,N_BEFORE, N_AFTER,N_COST,N_BEFORE_NUM, N_AFTER_NUM)
StringBuffer buffer = GameLogDAO.goldBuyLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append(roleInfo.getId());
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(action);
buffer.append("'");
buffer.append(",");
buffer.append(moneyType.getType());
buffer.append(",");
buffer.append(before);
buffer.append(",");
buffer.append(after);
buffer.append(",");
buffer.append(cost);
buffer.append(",");
buffer.append(beforeNum);
buffer.append(",");
buffer.append(afterNum);
buffer.append("),");
GameLogDAO.goldBuyLogCount++;
gameLogDAO.insertGoldBuyLog();
}
}
/**
* 好友关系
* @param roleInfo
* @param relRoleId
* @param relation
* @param time
*/
public static void insertRoleRelationLog(RoleInfo roleInfo, int relRoleId, int relation, long time) {
/*RoleRelationLog to = new RoleRelationLog();
to.setAccount(roleInfo.getAccount());
to.setRoleId(roleInfo.getId());
to.setRoleName(roleInfo.getRoleName());
to.setRelRoleId(relRoleId);
to.setTime(new Timestamp(time));
to.setRelation(relation);*/
//INSERT INTO GAME_ROLE_RELATION_LOG
//(N_ROLE_ID,S_ACCOUNT, S_ROLE_NAME, N_REL_ROLE_ID, N_RELATION,D_TIME)
StringBuffer buffer = GameLogDAO.roleRelationLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append(roleInfo.getId());
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(relRoleId);
buffer.append(",");
buffer.append(relation);
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append("),");
GameLogDAO.roleRelationLogCount++;
gameLogDAO.insertRoleRelationLog();
}
}
/**
* 公会日志
* @param roleInfo
* @param clubId
* @param type
* @param time
*/
public static void insertRoleClubLog(RoleInfo roleInfo, int clubId, int type) {
/*RoleClubLog logTo = new RoleClubLog();
logTo.setRoleId(roleInfo.getId());
logTo.setAccount(roleInfo.getAccount());
logTo.setRoleName(roleInfo.getRoleName());
logTo.setClubId(clubId);
logTo.setType(type);
logTo.setTime(new Timestamp(System.currentTimeMillis()));*/
//INSERT INTO GAME_ROLE_CLUB_LOG
//(N_ROLE_ID,S_ACCOUNT, S_ROLE_NAME, N_CLUB_ID, N_TYPE, D_TIME)
StringBuffer buffer = GameLogDAO.roleClubLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append(roleInfo.getId());
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(clubId);
buffer.append(",");
buffer.append(type);
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append("),");
GameLogDAO.roleClubLogCount++;
gameLogDAO.insertRoleClubLog();
}
}
/**
* 装备熔炼
* @param roleInfo
* @param clubId
* @param type
* @param time
*/
public static void insertEquipResolveLog(RoleInfo roleInfo, String resolveEquips, String addItems, int type, long time) {
/*EquipResolveLog to = new EquipResolveLog();
to.setRoleId(roleInfo.getId());
to.setAccount(roleInfo.getAccount());
to.setRoleName(roleInfo.getRoleName());
to.setResolveEquips(resolveEquips);
to.setAddItems(addItems);
to.setType(type);
to.setTime(new Timestamp(time));*/
//INSERT INTO GAME_EQUIP_RESOLVE_LOG
//(N_ROLE_ID,S_ACCOUNT, S_ROLE_NAME, S_RESOLVE_EQUIPS, S_ADD_ITEMS, N_TYPE, D_TIME)
StringBuffer buffer = GameLogDAO.equipResolveLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append(roleInfo.getId());
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(resolveEquips);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(addItems);
buffer.append("'");
buffer.append(",");
buffer.append(type);
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append("),");
GameLogDAO.equipResolveLogCount++;
gameLogDAO.insertEquipResolveLog();
}
}
/**
*练兵场日志
* @param roleId
* @param activityTypeId 练兵场No
* @param startTime 实例创建时间
* @param endTime 实例结束时间
* @param pos 布阵
* @param drop 掉落
*/
public static void insertActivityLog(RoleInfo roleInfo, FightInfo fightInfo, List<BattlePrize> dropList)
{
/*ActivityLog activityLog = new ActivityLog();
activityLog.setAccount(roleInfo.getAccount());
activityLog.setRoleName(roleInfo.getRoleName());
activityLog.setRoleId(roleInfo.getId());
HeroInfo heroInfo = HeroInfoMap.getMainHeroInfo(roleInfo);
if(heroInfo != null)
{
activityLog.setHeroNo(heroInfo.getHeroNo());
}
activityLog.setActivityTypeId(fightInfo.getDefendStr());
activityLog.setStartTime(new Timestamp(fightInfo.getFightTime()));
activityLog.setEndTime(new Timestamp(System.currentTimeMillis()));*/
String pos = "";
List<StartFightPosInfo> chgposList = fightInfo.getChgPosInfos();
if(chgposList != null && chgposList.size() > 0)
{
for(StartFightPosInfo info : chgposList)
{
HeroInfo heroInfo1 = HeroInfoMap.getHeroInfo(roleInfo.getId(), info.getHeroId());
if(heroInfo1 == null || heroInfo1.getDeployStatus() == 1)
{
continue;
}
pos = pos + info.getDeployPos() + "," + heroInfo1.getHeroNo()+ ";";
}
}
/*if(pos != null && pos.length() > 0)
{
activityLog.setPos(pos.substring(0, pos.length()-1));
}*/
String drop = "";
if(dropList != null && dropList.size() > 0)
{
for(BattlePrize prize : dropList)
{
drop = drop + prize.getNo() + "," + prize.getNum() +";";
}
}
/*if(drop != null && drop.length() > 0)
{
activityLog.setDrop(drop.substring(0, drop.length()-1));
}*/
//INSERT INTO ACTIVITY_LOG
//(S_ACCOUNT,S_NAME,N_HERO_NO,N_ROLE_ID,S_ACTIVITY,D_STARTTIME,D_ENDTIME,S_POS,S_DROP)
StringBuffer buffer = GameLogDAO.activeLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
HeroInfo heroInfo1 = HeroInfoMap.getMainHeroInfo(roleInfo);
if(heroInfo1 != null)
{
buffer.append(heroInfo1.getHeroNo());
buffer.append(",");
}
else
{
buffer.append(0);
buffer.append(",");
}
buffer.append(roleInfo.getId());
buffer.append(",");
buffer.append("'");
buffer.append(fightInfo.getDefendStr());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(fightInfo.getFightTime()));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
if(pos != null && pos.length() > 0)
{
buffer.append("'");
buffer.append(pos.substring(0, pos.length()-1));
buffer.append("'");
buffer.append(",");
}
else
{
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append(",");
}
if(drop != null && drop.length() > 0)
{
buffer.append("'");
buffer.append(drop.substring(0, drop.length()-1));
buffer.append("'");
}
else
{
buffer.append("'");
buffer.append("");
buffer.append("'");
}
buffer.append("),");
GameLogDAO.activeLogCount++;
gameLogDAO.insertActivityLog();
}
}
/**
* 你争我夺日志
* @param to
*/
public static void insertSnatchLog(RoleInfo roleInfo, int defendRoleId, String defendRoleName, int stoneNo,
byte lootSuccess, int lootTimes, String getItem, int useEnergy) {
/*SnatchLog to = new SnatchLog();
to.setRoleId(roleInfo.getId());
to.setAccount(roleInfo.getAccount());
to.setRoleName(roleInfo.getRoleName());
to.setRoleName(to.getRoleName().replace("\\", ""));
to.setDefendRoleId(defendRoleId);
to.setDefendRoleName(defendRoleName);
to.setDefendRoleName(to.getDefendRoleName().replace("\\", ""));
to.setStoneNo(stoneNo);
to.setLootSuccess(lootSuccess);
to.setLootTimes(lootTimes);
to.setGetItem(getItem);
to.setUseEnergy(useEnergy);
to.setComment("");
to.setCreateTime(new Timestamp(System.currentTimeMillis()));*/
//INSERT INTO GAME_SNATCH_LOG
//(S_ACCOUNT, S_ROLE_NAME, N_ROLE_ID,S_DEFEND_NAME,N_DEFEND_ID,N_STONE_NO,N_LOOT_SUCCESS,N_LOOT_TIMES,S_GET_ITEM,N_USE_ENGER,S_CONTENT,D_TIME)
StringBuffer buffer = GameLogDAO.snatchLogBuffer;
synchronized(buffer){
buffer.append("(");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(roleInfo.getId());
buffer.append(",");
buffer.append("'");
buffer.append(defendRoleName.replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(defendRoleId);
buffer.append(",");
buffer.append(stoneNo);
buffer.append(",");
buffer.append(lootSuccess);
buffer.append(",");
buffer.append(lootTimes);
buffer.append(",");
buffer.append("'");
buffer.append(getItem);
buffer.append("'");
buffer.append(",");
buffer.append(useEnergy);
buffer.append(",");
buffer.append("'");
buffer.append("");
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append("),");
GameLogDAO.snatchLogCount++;
GameLogDAO.getInstance().insertSnatchLog();
}
}
/**
* 矿收益奖励
* @param roleInfo
* @param action
* @param prizeList
*/
public static void insertMineGetLog(RoleInfo roleInfo, int action, List<BattlePrize> prizeList) {
//MineGetLog log = null;
for (BattlePrize prize : prizeList) {
/*log = new MineGetLog();
log.setAccount(roleInfo.getAccount());
log.setRoleName(roleInfo.getRoleName());
log.setEventId(action + "");
log.setItemNo(prize.getNo());
log.setItemNum(prize.getNum());
log.setState((byte) 1);
log.setTime(new Timestamp(System.currentTimeMillis()));*/
//INSERT INTO MINE_GET_LOG
//(S_ACCOUNT,S_ROLE_NAME,S_EVENT_ID,S_ITEM_NO,N_ITEM_NUM,N_STATE,D_TIME)
StringBuffer buffer = GameLogDAO.mineGetLogBuffer;
synchronized(buffer){
buffer.append("(");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(action);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(prize.getNo());
buffer.append("'");
buffer.append(",");
buffer.append(prize.getNum());
buffer.append(",");
buffer.append(1);
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append("),");
GameLogDAO.mineGetLogCount++;
gameLogDAO.insertMineGetLog();
}
}
}
/**
* 充值日志
* @param to
*/
public static void insertRoleChargeLog(String roleAcc, String roleName, String orderId, int chargeType, int chargeEvent) {
/*RoleChargeLog to = new RoleChargeLog();
to.setRoleAcc(roleAcc);
to.setRoleName(roleName);
to.setOrderId(orderId);
to.setChargeType(chargeType);
to.setChargeEvent(chargeEvent);
to.setCreateTime(new Timestamp(System.currentTimeMillis()));*/
//INSERT INTO ROLE_CHARGE_LOG
//(S_ROLE_ACC,S_ROLE_NAME,S_ORDER_ID,N_CHARGE_TYPE,N_CHARGE_EVENT,D_CREATE_TIME)
StringBuffer buffer = GameLogDAO.roleChargeLogBuffer;
synchronized(buffer){
buffer.append("(");
buffer.append("'");
buffer.append(roleAcc);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleName.replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(orderId);
buffer.append("'");
buffer.append(",");
buffer.append(chargeType);
buffer.append(",");
buffer.append(chargeEvent);
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append("),");
GameLogDAO.roleChargeLogCount++;
gameLogDAO.insertRoleChargeLog();
}
}
/**
* 副本日志
* @param to
*/
public static void insertChallengeLog(ChallengeLog log) {
//INSERT INTO CHALLENGE_LOG (N_ROLE_ID,S_ROLE_NAME,S_ACCOUNT, N_ACT_TYPE, S_CHALLENGE_NO, D_TIME, N_STAR,D_START_TIME)
StringBuffer buffer = GameLogDAO.challengeLogBuffer;
synchronized(buffer){
buffer.append("(");
buffer.append(log.getRoleId());
buffer.append(",");
buffer.append("'");
buffer.append(log.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append(log.getAction());
buffer.append(",");
buffer.append("'");
buffer.append(log.getChallengeNO());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getTime());
buffer.append("'");
buffer.append(",");
buffer.append(log.getStar());
buffer.append(",");
buffer.append("'");
buffer.append(log.getStartTime());
buffer.append("'");
buffer.append("),");
GameLogDAO.challengeLogCount++;
gameLogDAO.insertChallengeLog();
}
}
/**
* 副本异常日志
* @param roleId
* @param roleName
* @param account
* @param challengeNo
* @param startTime
* @param endTime
* @param star 1-检验次数异常(20%异常) 2-未发检验次数(外挂可能屏蔽或秒结算) 3-副本时间异常 4-副本,世界BOSS属性被篡改
* @param comment
*/
public static void insertChallengeUnusualLog(int roleId,String roleName,String account,String challengeNo,long startTime,long endTime,int star,String comment) {
//INSERT INTO CHALLENGE_UNUSUAL_LOG (N_ROLE_ID,S_ROLE_NAME,S_ACCOUNT, S_CHALLENGE_NO,D_START_TIME, D_TIME, N_STAR,S_COMMENT)
StringBuffer buffer = GameLogDAO.challengeUnusualLogBuffer;
synchronized(buffer){
buffer.append("(");
buffer.append(roleId);
buffer.append(",");
buffer.append("'");
buffer.append(roleName.replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(account);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(challengeNo);
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(startTime));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(endTime));
buffer.append("'");
buffer.append(",");
buffer.append(star);
buffer.append(",");
buffer.append("'");
buffer.append(comment);
buffer.append("'");
buffer.append("),");
GameLogDAO.challengeUnusualLogCount++;
gameLogDAO.insertChallengeUnusualLog();
}
}
/**
* 狭路相逢
* @param to
*/
public static void insertPVELog(GamePVELog log) {
//INSERT INTO GAME_PVE_LOG
//(N_ROLE_ID,S_ACCOUNT, S_ROLE_NAME, N_DEFENSE_ID,S_DEFENSE_NAME,S_REWARD,D_START_TIME,D_ENDTIME,N_BATTLE_RESULT)
StringBuffer buffer = GameLogDAO.pveLogBuffer;
synchronized(buffer){
buffer.append("(");
buffer.append(log.getRoleId());
buffer.append(",");
buffer.append("'");
buffer.append(log.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(log.getDefenseId());
buffer.append(",");
buffer.append("'");
if(log.getDefenseName() != null){
buffer.append(log.getDefenseName().replace("\\", ""));
}
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getReward());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getStartTime());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getEndTime());
buffer.append("'");
buffer.append(",");
buffer.append(log.getFightResult());
buffer.append("),");
GameLogDAO.pveLogCount++;
gameLogDAO.insertGamePVELog();
}
}
/**
* 竞技场
* @param to
*/
public static void insertArenaLog(RoleArenaLog log) {
//INSERT INTO GAME_ROLE_ARENA_LOG
//(S_ACCOUNT, S_ROLE_NAME, N_ROLE_ID,S_DEFEND_NAME,N_DEFEND_ID,N_BATTLE_RESULT,
// N_BEFORE_PLACE,N_AFTER_PLACE,S_GET_ITEM,N_USE_ENGER,S_CONTENT,D_TIME,
// N_ROLE_MAIN_HERO,S_ROLE_HEROS,N_DEFEND_MAIN_HERO,S_DEFEND_HEROS)
// VALUES
StringBuffer buffer = GameLogDAO.arenaLogBuffer;
synchronized(buffer){
buffer.append("(");
buffer.append("'");
buffer.append(log.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(log.getRoleId());
buffer.append(",");
buffer.append("'");
buffer.append(log.getDefendRoleName() == null ? null : log.getDefendRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(log.getDefendRoleId());
buffer.append(",");
buffer.append(log.getBattleResult());
buffer.append(",");
buffer.append(log.getBeforePlace());
buffer.append(",");
buffer.append(log.getAfterPlace());
buffer.append(",");
buffer.append("'");
buffer.append(log.getGetItem());
buffer.append("'");
buffer.append(",");
buffer.append(log.getUseEnergy());
buffer.append(",");
buffer.append("'");
buffer.append(log.getComment());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(System.currentTimeMillis()));
buffer.append("'");
buffer.append(",");
buffer.append(log.getRoleMainHero());
buffer.append(",");
buffer.append("'");
buffer.append(log.getRoleHeros());
buffer.append("'");
buffer.append(",");
buffer.append(log.getDefendMainHero());
buffer.append(",");
buffer.append("'");
buffer.append(log.getDefendHeros());
buffer.append("'");
buffer.append("),");
GameLogDAO.arenaLogCount++;
gameLogDAO.insertRoleAreanLog();
}
}
/**
* 兵来将挡
* @param to
*/
public static void insertDefendLog(DefendFightLog log) {
//INSERT INTO DEFEND_FIGHT_LOG
//(S_ACCOUNT,S_NAME,N_ROLE_ID,N_HERO_NO,N_FIGHT_LV,D_STARTTIME,D_ENDTIME,S_POS,S_DROP,N_FIGHT_RESULT) alues
StringBuffer buffer = GameLogDAO.defendLogBuffer;
synchronized(buffer){
buffer.append("(");
buffer.append("'");
buffer.append(log.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(log.getRoleId());
buffer.append(",");
buffer.append(log.getMainHeroId());
buffer.append(",");
buffer.append(log.getBattleResult());
buffer.append(",");
buffer.append(log.getFightLv());
buffer.append(",");
buffer.append("'");
buffer.append(log.getBeginTime());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getEndTime());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getPos());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getDrop());
buffer.append("'");
buffer.append(",");
buffer.append(log.getBattleResult());
buffer.append("),");
GameLogDAO.defendLogCount++;
gameLogDAO.insertDefendFightLog();
}
}
/**
* 世界打野
* @param to
*/
public static void insertMapFightLog(MapFightLog log) {
//INSERT INTO MAP_FIGHT_LOG
//(S_ACCOUNT,S_NAME,N_ROLE_ID,N_HERO_NO,N_NPC_ID,N_COME_ROLEID,D_STARTTIME,D_ENDTIME,S_POS,S_DROP,N_FIGHT_RESULT) values
StringBuffer buffer = GameLogDAO.mapFightLogBuffer;
synchronized(buffer){
buffer.append("(");
buffer.append("'");
buffer.append(log.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(log.getRoleId());
buffer.append(",");
buffer.append(log.getMainHeroId());
buffer.append(",");
buffer.append(log.getNpcId());
buffer.append(",");
buffer.append(log.getNpcId());
buffer.append(",");
buffer.append("'");
buffer.append(log.getBeginTime());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getEndTime());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getPos());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getDrop());
buffer.append("'");
buffer.append(",");
buffer.append(log.getFightResult());
buffer.append("),");
GameLogDAO.mapFightLogCount++;
gameLogDAO.insertMapFightLog();
}
}
/**
* 采矿战斗
* @param to
*/
public static void insertMineFightLog(MineFightLog log) {
//INSERT INTO MINE_FIGHT_LOG
//(N_POSITION,N_MINE_NO,N_ROLE_ID,S_ROLE_NAME,S_ACCOUNT,N_ROLE_HERO_NO,N_ROLE_LEVEL,
//N_ATTACK_ROLE_ID,S_ATTACK_ROLE_NAME,S_ATTACK_ACCOUNT,N_ATTACK_ROLE_HERO_NO,N_ATTACK_ROLE_LEVEL,
//N_FIGHT_RESULT,D_TIME) values
StringBuffer buffer = GameLogDAO.mineFightLogBuffer;
synchronized(buffer){
buffer.append("(");
buffer.append(log.getPosition());
buffer.append(",");
buffer.append(log.getMineNo());
buffer.append(",");
buffer.append(log.getRoleId());
buffer.append(",");
buffer.append("'");
buffer.append(log.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append(log.getRoleHeroNo());
buffer.append(",");
buffer.append(log.getRoleLevel());
buffer.append(",");
buffer.append(log.getAttackRoleId());
buffer.append(",");
buffer.append("'");
buffer.append(log.getAttackRoleName() == null ? null : log.getAttackRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getAttackAccount());
buffer.append("'");
buffer.append(",");
buffer.append(log.getAttackRoleHeroNo());
buffer.append(",");
buffer.append(log.getAttackRoleLevel());
buffer.append(",");
buffer.append(log.getFightResult());
buffer.append(",");
buffer.append("'");
buffer.append(log.getTime());
buffer.append("'");
buffer.append("),");
GameLogDAO.mineFightLogCount++;
gameLogDAO.insertMineFightLog();
}
}
/**
* 攻城略地
* @param to
*/
public static void insertCampLog(RoleCampLog log) {
//INSERT INTO GAME_CAMP_LOG
//(S_ACCOUNT, S_ROLE_NAME, N_ROLE_ID,N_CAMP_NO,N_BATTLE_RESULT,S_PRIZE, D_START_TIME,D_END_TIME,S_COMMENT)VALUES
StringBuffer buffer = GameLogDAO.campLogBuffer;
synchronized(buffer){
buffer.append("(");
buffer.append("'");
buffer.append(log.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(log.getRoleId());
buffer.append(",");
buffer.append(log.getCampNo());
buffer.append(",");
buffer.append(log.getBattleResult());
buffer.append(",");
buffer.append("'");
buffer.append(log.getPrize());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getStartTime());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getEndTime());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getComent());
buffer.append("'");
buffer.append("),");
GameLogDAO.campLogCount++;
gameLogDAO.insertRoleCampLog();
}
}
/**
* 记录PVP竞技场日志
* @param to
*/
public static void insertCompetitiveLog(CompetitiveLog log) {
//INSERT INTO COMPETITIVE_LOG
//(S_SEND_ACCOUNT,S_SEND_ROLE,N_ROLE_ID,N_HERO_NO,D_CREATE,N_BEFORE_STAGE_VALUE,N_AFTER_STAGE_VALUE,
// N_BEFORE_STAGE,N_AFTER_STAGE,N_BEFORE_RANK,N_AFTER_RANK,S_GET_ITEM,N_USE_ENERGY,S_MATCH_ROLE,
// N_TARGET_HERO_NO,S_COMMENT,N_BATTLE_RESULT,S_HERO_IDS)VALUES
StringBuffer buffer = GameLogDAO.competitiveLogBuffer;
synchronized(buffer){
buffer.append("(");
buffer.append("'");
buffer.append(log.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(log.getRoleId());
buffer.append(",");
buffer.append(log.getHeroNo());
buffer.append(",");
buffer.append("'");
buffer.append(log.getCreateTime());
buffer.append("'");
buffer.append(",");
buffer.append(log.getBeforeStageValue());
buffer.append(",");
buffer.append(log.getAfterStageValue());
buffer.append(",");
buffer.append(log.getBeforeStage());
buffer.append(",");
buffer.append(log.getAfterStage());
buffer.append(",");
buffer.append(log.getBeforeRank());
buffer.append(",");
buffer.append(log.getAfterRank());
buffer.append(",");
buffer.append("'");
buffer.append(log.getGetItem());
buffer.append("'");
buffer.append(",");
buffer.append(log.getUseEnergy());
buffer.append(",");
buffer.append("'");
buffer.append(log.getMatchRole());
buffer.append("'");
buffer.append(",");
buffer.append(log.getTargetHeroNo());
buffer.append(",");
buffer.append("'");
buffer.append(log.getComment());
buffer.append("'");
buffer.append(",");
buffer.append(log.getBattleResult());
buffer.append(",");
buffer.append("'");
buffer.append(log.getHeroNos());
buffer.append("'");
buffer.append("),");
GameLogDAO.competitiveLogCount++;
gameLogDAO.insertCompetitiveLog();
}
}
/**
* 记录多人PVP日志
* @param to
*/
public static void insertPVP3Log(GamePvp3Log log) {
//INSERT INTO GAME_PVP_3_LOG
//(N_ROLE_ID,S_ACCOUNT,S_ROLE_NAME,N_RESULT,N_POINT,N_BEFORE_POINT,N_AFTER_POINT,D_START_TIME,D_END_TIME) VALUES
StringBuffer buffer = GameLogDAO.pvp3LogBuffer;
synchronized(buffer){
buffer.append("(");
buffer.append(log.getRoleId());
buffer.append(",");
buffer.append("'");
buffer.append(log.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append(log.getResult());
buffer.append(",");
buffer.append(log.getPoint());
buffer.append(",");
buffer.append(log.getBeforePoint());
buffer.append(",");
buffer.append(log.getAfterPoint());
buffer.append(",");
buffer.append("'");
buffer.append(log.getStartTime());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(log.getEndTime());
buffer.append("'");
buffer.append("),");
GameLogDAO.pvp3LogCount++;
gameLogDAO.insertPvp3Log();
}
}
/**
* 世界BOSS日志
* @param roleInfo
* @param before
* @param after
*/
public static void insertWorldBossLog(WorldBossFightLog bossLog) {
//INSERT INTO WORLD_BOSS_FIGHT_LOG
//(S_ACCOUNT, S_ROLENAME, D_BEGINTIME,D_ENGTIME,N_HURT)VALUES
StringBuffer buffer = GameLogDAO.worldBossLogBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append("'");
buffer.append(bossLog.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(bossLog.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(bossLog.getBeginTime());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(bossLog.getEndTime());
buffer.append("'");
buffer.append(",");
buffer.append(bossLog.getHurt());
buffer.append("),");
GameLogDAO.worldBossLogCount++;
gameLogDAO.insertWorldBossFightLog();
}
}
/**
* 获取掉落str
* @param prizeList
* @param fpPrizeList
* @return
*/
public static String getItem(List<BattlePrize> prizeList, List<BattlePrize> fpPrizeList) {
Map<String, Integer> getMap = new HashMap<String, Integer>();
if (prizeList != null && prizeList.size() > 0) {
for (BattlePrize prize : prizeList) {
Integer oldValue = getMap.get(prize.getNo().trim());
if (oldValue == null) {
getMap.put(prize.getNo().trim(), prize.getNum());
} else {
getMap.put(prize.getNo().trim(), prize.getNum() + oldValue);
}
}
}
if (fpPrizeList != null && fpPrizeList.size() > 0) {
Integer oldValue = getMap.get(fpPrizeList.get(0).getNo().trim());
if (oldValue == null) {
getMap.put(fpPrizeList.get(0).getNo().trim(), fpPrizeList.get(0).getNum());
} else {
getMap.put(fpPrizeList.get(0).getNo().trim(), fpPrizeList.get(0).getNum() + oldValue);
}
}
StringBuffer getItem = new StringBuffer();
for (String itemNo : getMap.keySet()) {
if (getItem.length() > 0) {
getItem.append(",");
}
getItem.append(itemNo);
getItem.append(":");
getItem.append(getMap.get(itemNo));
}
return getItem.toString();
}
/**
* 记录加速玩家日志
* @param roleInfo
* @param before
* @param after
*/
public static void insertCheckTimeLog(RoleInfo roleInfo,Long curTime,Long preTime,int num) {
//INSERT INTO CHECK_TIME_LOG(S_ACCOUNT, S_ROLENAME, D_CUR_TIME,D_PRE_TIME,N_NUM) VALUES
StringBuffer buffer = GameLogDAO.checkTimeBuffer;
synchronized(buffer)
{
buffer.append("(");
buffer.append("'");
buffer.append(roleInfo.getAccount());
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(roleInfo.getRoleName().replace("\\", ""));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(curTime));
buffer.append("'");
buffer.append(",");
buffer.append("'");
buffer.append(new Timestamp(preTime));
buffer.append("'");
buffer.append(",");
buffer.append(num);
buffer.append("),");
GameLogDAO.checkTimeLogCount++;
gameLogDAO.insertCheckTimeLog();
}
}
}
| gpl-3.0 |
DSI-Ville-Noumea/pdc | src/test/java/nc/noumea/mairie/pdc/EditiqueTest.java | 1771 | package nc.noumea.mairie.pdc;
/*
* #%L
* Logiciel de Gestion des Permis de Construire de la Ville de Nouméa
* %%
* Copyright (C) 2013 - 2016 Mairie de Nouméa, Nouvelle-Calédonie
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import org.junit.Assert;
import org.junit.Test;
import nc.noumea.mairie.pdc.enums.Commune;
public class EditiqueTest {
@Test
public void getNomFichier() {
for (Commune commune : Commune.values()) {
Assert.assertEquals(Editique.PIECE_MANQUANTE.getNomFichier(commune), "piece_manquante.docx"); //
}
}
@Test
public void isApplicableSurCommune() {
Assert.assertTrue(Editique.ARRETE_ERREUR_MATERIELLE.isApplicableSurCommune(Commune.NOUMEA));
Assert.assertFalse(Editique.ARRETE_ERREUR_MATERIELLE.isApplicableSurCommune(Commune.DUMBEA));
Assert.assertFalse(Editique.ARRETE_ERREUR_MATERIELLE.isApplicableSurCommune(null));
Assert.assertTrue(Editique.ARRETE_AUTORISATION.isApplicableSurCommune(Commune.NOUMEA));
Assert.assertTrue(Editique.ARRETE_AUTORISATION.isApplicableSurCommune(Commune.DUMBEA));
Assert.assertFalse(Editique.ARRETE_AUTORISATION.isApplicableSurCommune(null));
}
}
| gpl-3.0 |
cosminrentea/roda | src/main/java/ro/roda/webjson/admin/UserMessagesController.java | 1188 | package ro.roda.webjson.admin;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import ro.roda.domainjson.UserMessages;
import ro.roda.service.UserManagementService;
@RequestMapping("/adminjson/usermessages")
@Controller
public class UserMessagesController {
@Autowired
UserManagementService userManagementService;
@RequestMapping(value = "/{id}", headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<String> listUserMessagesJson(@PathVariable("id") Integer id) {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json; charset=utf-8");
List<UserMessages> result = userManagementService.findUserMessages(id);
return new ResponseEntity<String>(UserMessages.toJsonArray(result), headers, HttpStatus.OK);
}
}
| gpl-3.0 |
leandrocruz/xingu | container/src/test/java/br/com/ibnetwork/xingu/container/components/impl/CircularTwoImpl.java | 595 | package br.com.ibnetwork.xingu.container.components.impl;
import org.apache.avalon.framework.activity.Initializable;
import xingu.container.Inject;
import br.com.ibnetwork.xingu.container.components.CircularOne;
import br.com.ibnetwork.xingu.container.components.CircularTwo;
public class CircularTwoImpl
implements CircularTwo, Initializable
{
@Inject
private CircularOne one;
@Override
public String two()
{
return "two + " + one.three();
}
@Override
public void initialize()
throws Exception
{
System.out.println("Initializing " + this.getClass().getSimpleName());
}
}
| gpl-3.0 |
chrisduran/CMap3D | libraries/proxml/src/proxml/test/Flickr.java | 978 | package proxml.test;
import processing.core.PApplet;
import processing.core.PImage;
import proxml.*;
public class Flickr extends PApplet{
// xml element to store and load the drawn ellipses
XMLElement flickr;
XMLInOut xmlInOut;
int xPos = 0;
int yPos = 0;
public void setup(){
size(400, 400);
smooth();
background(255);
//load ellipses from file if it exists
try{
//folder is a field of PApplet
//giving you the path to your sketch folder
xmlInOut = new XMLInOut(this);
xmlInOut.loadElement("flickr.xml");
}catch (InvalidDocumentException ide){
ide.printStackTrace();
println("File does not exist");
}
}
public void xmlEvent(XMLElement i_element){
flickr = i_element;
flickr.printElementTree(" ");
println(flickr.getChild(0).countChildren());
}
public void draw(){
}
public static void main(String[] args){
PApplet.main(new String[] {Flickr.class.getName()});
}
} | gpl-3.0 |
Team5818/Rogue-Cephalopod-FRC2017 | src/org/usfirst/frc/team5818/robot/commands/ExposureHigh.java | 1463 | /*
* This file is part of Rogue-Cephalopod, licensed under the GNU General Public License (GPLv3).
*
* Copyright (c) Riviera Robotics <https://github.com/Team5818>
* Copyright (c) contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.usfirst.frc.team5818.robot.commands;
import org.usfirst.frc.team5818.robot.Robot;
import org.usfirst.frc.team5818.robot.subsystems.CameraController;
import edu.wpi.first.wpilibj.command.Command;
/**
* Puts the camera into high exposure mode.
*/
public class ExposureHigh extends Command {
private CameraController cont;
public ExposureHigh() {
cont = Robot.runningRobot.camCont;
requires(cont);
}
@Override
protected void initialize() {
cont.setHighExposure();
}
@Override
protected boolean isFinished() {
return true;
}
}
| gpl-3.0 |
AdyKalra/Frameworks | Java/frameworkium-master/src/test/java/com/tfl/web/pages/JourneyPlannerResultsPage.java | 693 | package com.tfl.web.pages;
import com.frameworkium.core.ui.annotations.Visible;
import com.frameworkium.core.ui.pages.BasePage;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import ru.yandex.qatools.htmlelements.annotations.Name;
public class JourneyPlannerResultsPage extends BasePage<JourneyPlannerResultsPage> {
@Visible
@Name("Results viewport")
@FindBy(css = ".journey-planner-results")
private WebElement resultsViewport;
@Visible
@Name("Page Title Area")
@FindBy(css = "h1 span.hero-headline")
private WebElement pageTitleArea;
public String getTitleText() {
return pageTitleArea.getText();
}
}
| gpl-3.0 |
jmsanzg/myPlan | src/com/conzebit/myplan/core/msisdn/MsisdnType.java | 2347 | /*
* This file is part of myPlan.
*
* Plan is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Plan 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 myPlan. If not, see <http://www.gnu.org/licenses/>.
*/
package com.conzebit.myplan.core.msisdn;
public enum MsisdnType {
ES_AMENA ("Amena", true),
ES_EROSKIMOVIL ("Eroski", true),
ES_HAPPYMOVIL ("Happymovil", true),
ES_JAZZTEL ("Jazztel", true),
ES_MASMOVIL ("Más movil", true),
ES_MOVISTAR ("Movistar", true),
ES_PEPEPHONE ("PepePhone", true),
ES_ORANGE ("Orange", true),
ES_SIMYO ("Simyo", true),
ES_TUENTI ("Tuenti", true),
ES_VODAFONE ("Vodafone", true),
ES_YOIGO ("Yoigo", true),
UNKNOWN ("Móvil Desconocido", true),
ES_LAND_LINE ("Telefono Fijo", false),
ES_LAND_LINE_SPECIAL ("Especial (90x)", false),
ES_SPECIAL ("Especial (091, 112)", false),
ES_SPECIAL_ZER0 ("Coste 0", false),
ES_INTERNATIONAL ("Internacional", false);
private String name = null;
private boolean mobile = false;
private static String[] names;
static {
names = new String[MsisdnType.values().length];
for (int i = 0; i < names.length; i++) {
names[i] = MsisdnType.values()[i].getName();
}
}
MsisdnType(String name, boolean mobile) {
this.name = name;
this.mobile = mobile;
}
public static MsisdnType fromString(String value) {
if (value != null) {
for (MsisdnType type : MsisdnType.values()) {
if (value.equalsIgnoreCase(type.getName())) {
return type;
}
}
}
return UNKNOWN;
}
public String getName() {
return this.name;
}
public static String[] getNames() {
return names;
}
public boolean isMobile() {
return this.mobile;
}
public String toString() {
return this.name;
}
}
| gpl-3.0 |
nikolamilosevic86/TableAnnotator | src/Tests/InfoClassTests.java | 2694 | package Tests;
import static org.junit.Assert.*;
import java.util.LinkedList;
import org.junit.Test;
import IEArmBased.ArmExtractor;
import InfoClassExtractor.InfoClassExtractionRule;
import InfoClassExtractor.InfoClassFilesReader;
import InfoClassExtractor.TypeParser;
import Utils.DecomposedValue;
import Utils.NumberFormat;
import Utils.SingleDecomposedValue;
import Utils.Utilities;
public class InfoClassTests {
@Test
public void ReadInfoClassesTest() {
String path = "InformationClasses";
InfoClassFilesReader fr = new InfoClassFilesReader();
fr.ReadInfoClasses(path);
if(fr.InfoClasses.size()!=2)
fail("Number of extracted information classes is not correct");
if(!fr.InfoClasses.get(0).getInformationClass().equals("BMI"))
fail("Information class name not correctly read for the first list item");
if(!fr.InfoClasses.get(1).getInformationClass().equals("BMIA"))
fail("Information class name not correctly read for the second list item");
if(!fr.InfoClasses.get(0).triggerWords.get(0).equals("bmi"))
fail("Trigger Word not read correctly");
if(!fr.InfoClasses.get(1).triggerWords.get(0).equals("bmi"))
fail("Trigger Word not read correctly");
if(!fr.InfoClasses.get(0).StopWords.get(0).equals("change"))
fail("Stop Word not read correctly");
if(!fr.InfoClasses.get(0).NavigationalPatterns.get(0).equals("N=%d"))
fail("NavigationalPatterns not read correctly");
if(!fr.InfoClasses.get(0).FreeTextPatterns.get(0).equals("%d patients[3]"))
fail("FreeTextPatterns not read correctly");
if(!fr.InfoClasses.get(0).DataCellPatterns.get(0).equals("%f"))
fail("DataCellPatterns not read correctly");
if(!fr.InfoClasses.get(0).isCanBeInCaption())
fail("Failed reading can be in caption");
//%f
}
@Test
public void InfoClassExtractionRuleTest() {
InfoClassExtractionRule icer = new InfoClassExtractionRule("%d patients[5]");
if(!icer.Rule.get(0).token.equals("\\b\\d*\\b"))
fail();
icer = new InfoClassExtractionRule("%d (%d-%d)");
if(!icer.Rule.get(0).token.equals("\\b\\d*\\b"))
fail();
if(!icer.Rule.get(5).token.equals(")"))
fail();
}
@Test
public void TypeParserTest() {
String s = TypeParser.getSemiNumeric("abc 17");
if(!s.equals("17"))
fail();
s = TypeParser.getSemiNumeric("abc 17.72 (12-19)");
if(!s.equals("17.72 (12-19)"))
fail();
s = TypeParser.getSemiNumeric("abc 17.72 (12-19) asdwe");
if(!s.equals("17.72 (12-19)"))
fail();
s = TypeParser.getSemiNumeric("abc 17.72 (12/19) asdwe");
if(!s.equals("17.72 (12/19)"))
fail();
s = TypeParser.getSemiNumeric("abc 17.72 (-12 ± 19) asdwe");
if(!s.equals("17.72 (-12 ± 19)"))
fail();
}
}
| gpl-3.0 |
cgd/drake-genetics | modules/drake-genetics-client/src/java/org/jax/drakegenetics/shareddata/client/SpeciesGenomeDescription.java | 6309 | /*
* Copyright (c) 2010 The Jackson Laboratory
*
* This is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This software 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 software. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jax.drakegenetics.shareddata.client;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Constains metadata describing the structure of a particular species' genome.
* @author <A HREF="mailto:keith.sheppard@jax.org">Keith Sheppard</A>
*/
public class SpeciesGenomeDescription implements Serializable
{
/**
* every {@link java.io.Serializable} is supposed to have one of these
*/
private static final long serialVersionUID = -4935021442131156304L;
private String name;
private Map<String, ChromosomeDescription> chromosomeDescriptions;
private int autosomeCount;
/**
* Constructor
*/
public SpeciesGenomeDescription()
{
}
/**
* Constructor
* @param name
* the species name
* @param chromosomeDescriptions
* the chromosome descriptions
*/
public SpeciesGenomeDescription(
String name,
Map<String, ChromosomeDescription> chromosomeDescriptions)
{
this.name = name;
this.chromosomeDescriptions = chromosomeDescriptions;
this.autosomeCount = 0;
for(String chrId : chromosomeDescriptions.keySet())
{
if(!ChromosomeDescription.isSexChromosome(chrId))
{
this.autosomeCount++;
}
}
}
/**
* Getter for the species name
* @return the name
*/
public String getName()
{
return this.name;
}
/**
* Setter for the name
* @param name the name to set
*/
public void setName(String name)
{
this.name = name;
}
/**
* Getter for the chromosome descriptions
* @return the chromosome descriptions
*/
public Map<String, ChromosomeDescription> getChromosomeDescriptions()
{
return this.chromosomeDescriptions;
}
/**
* Setter for the chromosome descriptions
* @param chromosomeDescriptions the chromosome descriptions to set
*/
public void setChromosomeDescriptions(Map<String, ChromosomeDescription> chromosomeDescriptions)
{
this.chromosomeDescriptions = chromosomeDescriptions;
}
/**
* Determine if the given genome is aneuploid
* @param genome
* the genome to test for aneuploidy
* @return
* true iff it's an aneuploid
*/
public boolean isAneuploid(DiploidGenome genome)
{
return
this.isHaploidAneuploid(genome.getMaternalHaploid()) ||
this.isHaploidAneuploid(genome.getPaternalHaploid());
}
/**
* Determines if there is any aneuploidy in the given haploid chromosome
* given the autosomes that we expect (we also expect a single sex
* chromosome)
* @param haploidChromosomes
* the haploid chromosomes
* @return true if there is any aneuploidy
*/
public boolean isHaploidAneuploid(Collection<Chromosome> haploidChromosomes)
{
boolean foundSexChromosome = false;
Set<String> autosomesFound = new HashSet<String>();
for(Chromosome chromosome : haploidChromosomes)
{
String name = chromosome.getChromosomeName();
if(ChromosomeDescription.isSexChromosome(name))
{
if(foundSexChromosome)
{
// two sex chromosomes should not be in a normal haploid
return true;
}
foundSexChromosome = true;
}
else
{
if(autosomesFound.contains(name))
{
// two copies of the same autosome should not be in a normal haploid
return true;
}
autosomesFound.add(name);
}
}
// a normal haploid must contain all autosomes and one of "X" or "Y"
return autosomesFound.size() != this.autosomeCount || !foundSexChromosome;
}
/**
* Returns true for aneuploidy which is lethal (does not account for
* alleles which may also lead to lethal)
* @param genome the genome to test
* @return true if this {@link #isAneuploid(DiploidGenome)} and the
* aneuploidy is lethal
*/
public boolean isLethal(DiploidGenome genome)
{
return
this.isHaploidLethal(genome.getMaternalHaploid()) ||
this.isHaploidLethal(genome.getPaternalHaploid());
}
/**
* Returns true for aneuploidy which is lethal (does not account for
* alleles which may also lead to lethal)
* @param haploidChromosomes the haploid to test
* @return true if it's lethal
*/
public boolean isHaploidLethal(Collection<Chromosome> haploidChromosomes)
{
Set<String> autosomesFound = new HashSet<String>();
for(Chromosome chromosome : haploidChromosomes)
{
String name = chromosome.getChromosomeName();
if(!ChromosomeDescription.isSexChromosome(name))
{
if(autosomesFound.contains(name))
{
// two copies of the same autosome are lethal
return true;
}
autosomesFound.add(name);
}
}
// a normal haploid must contain all autosomes
return autosomesFound.size() != this.autosomeCount;
}
}
| gpl-3.0 |
trackplus/Genji | src/main/java/com/aurel/track/persist/BaseTApplicationContextPeer.java | 38929 | /**
* Genji Scrum Tool and Issue Tracker
* Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions
* <a href="http://www.trackplus.com">Genji Scrum Tool</a>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* $Id:$ */
package com.aurel.track.persist;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.torque.NoRowsException;
import org.apache.torque.TooManyRowsException;
import org.apache.torque.Torque;
import org.apache.torque.TorqueException;
import org.apache.torque.TorqueRuntimeException;
import org.apache.torque.map.MapBuilder;
import org.apache.torque.map.TableMap;
import org.apache.torque.om.DateKey;
import org.apache.torque.om.NumberKey;
import org.apache.torque.om.StringKey;
import org.apache.torque.om.ObjectKey;
import org.apache.torque.om.SimpleKey;
import org.apache.torque.util.BasePeer;
import org.apache.torque.util.Criteria;
import com.workingdogs.village.DataSetException;
import com.workingdogs.village.QueryDataSet;
import com.workingdogs.village.Record;
// Local classes
import com.aurel.track.persist.map.*;
/**
*/
public abstract class BaseTApplicationContextPeer
extends BasePeer
{
/** the default database name for this class */
public static final String DATABASE_NAME;
/** the table name for this class */
public static final String TABLE_NAME;
/**
* @return the map builder for this peer
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @deprecated Torque.getMapBuilder(TApplicationContextMapBuilder.CLASS_NAME) instead
*/
public static MapBuilder getMapBuilder()
throws TorqueException
{
return Torque.getMapBuilder(TApplicationContextMapBuilder.CLASS_NAME);
}
/** the column name for the OBJECTID field */
public static final String OBJECTID;
/** the column name for the LOGGEDFULLUSERS field */
public static final String LOGGEDFULLUSERS;
/** the column name for the LOGGEDLIMITEDUSERS field */
public static final String LOGGEDLIMITEDUSERS;
/** the column name for the REFRESHCONFIGURATION field */
public static final String REFRESHCONFIGURATION;
/** the column name for the FIRSTTIME field */
public static final String FIRSTTIME;
/** the column name for the MOREPROPS field */
public static final String MOREPROPS;
static
{
DATABASE_NAME = "track";
TABLE_NAME = "TAPPLICATIONCONTEXT";
OBJECTID = "TAPPLICATIONCONTEXT.OBJECTID";
LOGGEDFULLUSERS = "TAPPLICATIONCONTEXT.LOGGEDFULLUSERS";
LOGGEDLIMITEDUSERS = "TAPPLICATIONCONTEXT.LOGGEDLIMITEDUSERS";
REFRESHCONFIGURATION = "TAPPLICATIONCONTEXT.REFRESHCONFIGURATION";
FIRSTTIME = "TAPPLICATIONCONTEXT.FIRSTTIME";
MOREPROPS = "TAPPLICATIONCONTEXT.MOREPROPS";
if (Torque.isInit())
{
try
{
Torque.getMapBuilder(TApplicationContextMapBuilder.CLASS_NAME);
}
catch (TorqueException e)
{
log.error("Could not initialize Peer", e);
throw new TorqueRuntimeException(e);
}
}
else
{
Torque.registerMapBuilder(TApplicationContextMapBuilder.CLASS_NAME);
}
}
/** number of columns for this peer */
public static final int numColumns = 6;
/** A class that can be returned by this peer. */
protected static final String CLASSNAME_DEFAULT =
"com.aurel.track.persist.TApplicationContext";
/** A class that can be returned by this peer. */
protected static final Class CLASS_DEFAULT = initClass(CLASSNAME_DEFAULT);
/**
* Class object initialization method.
*
* @param className name of the class to initialize
* @return the initialized class
*/
private static Class initClass(String className)
{
Class c = null;
try
{
c = Class.forName(className);
}
catch (Throwable t)
{
log.error("A FATAL ERROR has occurred which should not "
+ "have happened under any circumstance. Please notify "
+ "the Torque developers <torque-dev@db.apache.org> "
+ "and give as many details as possible (including the error "
+ "stack trace).", t);
// Error objects should always be propagated.
if (t instanceof Error)
{
throw (Error) t.fillInStackTrace();
}
}
return c;
}
/**
* Get the list of objects for a ResultSet. Please not that your
* resultset MUST return columns in the right order. You can use
* getFieldNames() in BaseObject to get the correct sequence.
*
* @param results the ResultSet
* @return the list of objects
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<TApplicationContext> resultSet2Objects(java.sql.ResultSet results)
throws TorqueException
{
try
{
QueryDataSet qds = null;
List<Record> rows = null;
try
{
qds = new QueryDataSet(results);
rows = getSelectResults(qds);
}
finally
{
if (qds != null)
{
qds.close();
}
}
return populateObjects(rows);
}
catch (SQLException e)
{
throw new TorqueException(e);
}
catch (DataSetException e)
{
throw new TorqueException(e);
}
}
/**
* Method to do inserts.
*
* @param criteria object used to create the INSERT statement.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static ObjectKey doInsert(Criteria criteria)
throws TorqueException
{
return BaseTApplicationContextPeer
.doInsert(criteria, (Connection) null);
}
/**
* Method to do inserts. This method is to be used during a transaction,
* otherwise use the doInsert(Criteria) method. It will take care of
* the connection details internally.
*
* @param criteria object used to create the INSERT statement.
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static ObjectKey doInsert(Criteria criteria, Connection con)
throws TorqueException
{
correctBooleans(criteria);
setDbName(criteria);
if (con == null)
{
return BasePeer.doInsert(criteria);
}
else
{
return BasePeer.doInsert(criteria, con);
}
}
/**
* Add all the columns needed to create a new object.
*
* @param criteria object containing the columns to add.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void addSelectColumns(Criteria criteria)
throws TorqueException
{
criteria.addSelectColumn(OBJECTID);
criteria.addSelectColumn(LOGGEDFULLUSERS);
criteria.addSelectColumn(LOGGEDLIMITEDUSERS);
criteria.addSelectColumn(REFRESHCONFIGURATION);
criteria.addSelectColumn(FIRSTTIME);
criteria.addSelectColumn(MOREPROPS);
}
/**
* changes the boolean values in the criteria to the appropriate type,
* whenever a booleanchar or booleanint column is involved.
* This enables the user to create criteria using Boolean values
* for booleanchar or booleanint columns
* @param criteria the criteria in which the boolean values should be corrected
* @throws TorqueException if the database map for the criteria cannot be
obtained.
*/
public static void correctBooleans(Criteria criteria) throws TorqueException
{
correctBooleans(criteria, getTableMap());
}
/**
* Create a new object of type cls from a resultset row starting
* from a specified offset. This is done so that you can select
* other rows than just those needed for this object. You may
* for example want to create two objects from the same row.
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static TApplicationContext row2Object(Record row,
int offset,
Class cls)
throws TorqueException
{
try
{
TApplicationContext obj = (TApplicationContext) cls.newInstance();
TApplicationContextPeer.populateObject(row, offset, obj);
obj.setModified(false);
obj.setNew(false);
return obj;
}
catch (InstantiationException e)
{
throw new TorqueException(e);
}
catch (IllegalAccessException e)
{
throw new TorqueException(e);
}
}
/**
* Populates an object from a resultset row starting
* from a specified offset. This is done so that you can select
* other rows than just those needed for this object. You may
* for example want to create two objects from the same row.
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void populateObject(Record row,
int offset,
TApplicationContext obj)
throws TorqueException
{
try
{
obj.setObjectID(row.getValue(offset + 0).asIntegerObj());
obj.setLoggedFullUsers(row.getValue(offset + 1).asIntegerObj());
obj.setLoggedLimitedUsers(row.getValue(offset + 2).asIntegerObj());
obj.setRefreshConfiguration(row.getValue(offset + 3).asIntegerObj());
obj.setFirstTime(row.getValue(offset + 4).asIntegerObj());
obj.setMoreProps(row.getValue(offset + 5).asString());
}
catch (DataSetException e)
{
throw new TorqueException(e);
}
}
/**
* Method to do selects.
*
* @param criteria object used to create the SELECT statement.
* @return List of selected Objects
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<TApplicationContext> doSelect(Criteria criteria) throws TorqueException
{
return populateObjects(doSelectVillageRecords(criteria));
}
/**
* Method to do selects within a transaction.
*
* @param criteria object used to create the SELECT statement.
* @param con the connection to use
* @return List of selected Objects
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<TApplicationContext> doSelect(Criteria criteria, Connection con)
throws TorqueException
{
return populateObjects(doSelectVillageRecords(criteria, con));
}
/**
* Grabs the raw Village records to be formed into objects.
* This method handles connections internally. The Record objects
* returned by this method should be considered readonly. Do not
* alter the data and call save(), your results may vary, but are
* certainly likely to result in hard to track MT bugs.
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<Record> doSelectVillageRecords(Criteria criteria)
throws TorqueException
{
return BaseTApplicationContextPeer
.doSelectVillageRecords(criteria, (Connection) null);
}
/**
* Grabs the raw Village records to be formed into objects.
* This method should be used for transactions
*
* @param criteria object used to create the SELECT statement.
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<Record> doSelectVillageRecords(Criteria criteria, Connection con)
throws TorqueException
{
if (criteria.getSelectColumns().size() == 0)
{
addSelectColumns(criteria);
}
correctBooleans(criteria);
setDbName(criteria);
// BasePeer returns a List of Value (Village) arrays. The array
// order follows the order columns were placed in the Select clause.
if (con == null)
{
return BasePeer.doSelect(criteria);
}
else
{
return BasePeer.doSelect(criteria, con);
}
}
/**
* The returned List will contain objects of the default type or
* objects that inherit from the default.
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<TApplicationContext> populateObjects(List<Record> records)
throws TorqueException
{
List<TApplicationContext> results = new ArrayList<TApplicationContext>(records.size());
// populate the object(s)
for (int i = 0; i < records.size(); i++)
{
Record row = records.get(i);
results.add(TApplicationContextPeer.row2Object(row, 1,
TApplicationContextPeer.getOMClass()));
}
return results;
}
/**
* The class that the Peer will make instances of.
* If the BO is abstract then you must implement this method
* in the BO.
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static Class getOMClass()
throws TorqueException
{
return CLASS_DEFAULT;
}
/**
* Method to do updates.
*
* @param criteria object containing data that is used to create the UPDATE
* statement.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doUpdate(Criteria criteria) throws TorqueException
{
BaseTApplicationContextPeer
.doUpdate(criteria, (Connection) null);
}
/**
* Method to do updates. This method is to be used during a transaction,
* otherwise use the doUpdate(Criteria) method. It will take care of
* the connection details internally.
*
* @param criteria object containing data that is used to create the UPDATE
* statement.
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doUpdate(Criteria criteria, Connection con)
throws TorqueException
{
Criteria selectCriteria = new Criteria(DATABASE_NAME, 2);
correctBooleans(criteria);
selectCriteria.put(OBJECTID, criteria.remove(OBJECTID));
setDbName(criteria);
if (con == null)
{
BasePeer.doUpdate(selectCriteria, criteria);
}
else
{
BasePeer.doUpdate(selectCriteria, criteria, con);
}
}
/**
* Method to do deletes.
*
* @param criteria object containing data that is used DELETE from database.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doDelete(Criteria criteria) throws TorqueException
{
TApplicationContextPeer
.doDelete(criteria, (Connection) null);
}
/**
* Method to do deletes. This method is to be used during a transaction,
* otherwise use the doDelete(Criteria) method. It will take care of
* the connection details internally.
*
* @param criteria object containing data that is used DELETE from database.
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doDelete(Criteria criteria, Connection con)
throws TorqueException
{
correctBooleans(criteria);
setDbName(criteria);
if (con == null)
{
BasePeer.doDelete(criteria, TABLE_NAME);
}
else
{
BasePeer.doDelete(criteria, TABLE_NAME, con);
}
}
/**
* Method to do selects
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<TApplicationContext> doSelect(TApplicationContext obj) throws TorqueException
{
return doSelect(buildSelectCriteria(obj));
}
/**
* Method to do inserts
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doInsert(TApplicationContext obj) throws TorqueException
{
obj.setPrimaryKey(doInsert(buildCriteria(obj)));
obj.setNew(false);
obj.setModified(false);
}
/**
* @param obj the data object to update in the database.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doUpdate(TApplicationContext obj) throws TorqueException
{
doUpdate(buildCriteria(obj));
obj.setModified(false);
}
/**
* @param obj the data object to delete in the database.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doDelete(TApplicationContext obj) throws TorqueException
{
doDelete(buildSelectCriteria(obj));
}
/**
* Method to do inserts. This method is to be used during a transaction,
* otherwise use the doInsert(TApplicationContext) method. It will take
* care of the connection details internally.
*
* @param obj the data object to insert into the database.
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doInsert(TApplicationContext obj, Connection con)
throws TorqueException
{
obj.setPrimaryKey(doInsert(buildCriteria(obj), con));
obj.setNew(false);
obj.setModified(false);
}
/**
* Method to do update. This method is to be used during a transaction,
* otherwise use the doUpdate(TApplicationContext) method. It will take
* care of the connection details internally.
*
* @param obj the data object to update in the database.
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doUpdate(TApplicationContext obj, Connection con)
throws TorqueException
{
doUpdate(buildCriteria(obj), con);
obj.setModified(false);
}
/**
* Method to delete. This method is to be used during a transaction,
* otherwise use the doDelete(TApplicationContext) method. It will take
* care of the connection details internally.
*
* @param obj the data object to delete in the database.
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doDelete(TApplicationContext obj, Connection con)
throws TorqueException
{
doDelete(buildSelectCriteria(obj), con);
}
/**
* Method to do deletes.
*
* @param pk ObjectKey that is used DELETE from database.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doDelete(ObjectKey pk) throws TorqueException
{
BaseTApplicationContextPeer
.doDelete(pk, (Connection) null);
}
/**
* Method to delete. This method is to be used during a transaction,
* otherwise use the doDelete(ObjectKey) method. It will take
* care of the connection details internally.
*
* @param pk the primary key for the object to delete in the database.
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static void doDelete(ObjectKey pk, Connection con)
throws TorqueException
{
doDelete(buildCriteria(pk), con);
}
/** Build a Criteria object from an ObjectKey */
public static Criteria buildCriteria( ObjectKey pk )
{
Criteria criteria = new Criteria();
criteria.add(OBJECTID, pk);
return criteria;
}
/** Build a Criteria object from the data object for this peer */
public static Criteria buildCriteria( TApplicationContext obj )
{
Criteria criteria = new Criteria(DATABASE_NAME);
if (!obj.isNew())
criteria.add(OBJECTID, obj.getObjectID());
criteria.add(LOGGEDFULLUSERS, obj.getLoggedFullUsers());
criteria.add(LOGGEDLIMITEDUSERS, obj.getLoggedLimitedUsers());
criteria.add(REFRESHCONFIGURATION, obj.getRefreshConfiguration());
criteria.add(FIRSTTIME, obj.getFirstTime());
criteria.add(MOREPROPS, obj.getMoreProps());
return criteria;
}
/** Build a Criteria object from the data object for this peer, skipping all binary columns */
public static Criteria buildSelectCriteria( TApplicationContext obj )
{
Criteria criteria = new Criteria(DATABASE_NAME);
if (!obj.isNew())
{
criteria.add(OBJECTID, obj.getObjectID());
}
criteria.add(LOGGEDFULLUSERS, obj.getLoggedFullUsers());
criteria.add(LOGGEDLIMITEDUSERS, obj.getLoggedLimitedUsers());
criteria.add(REFRESHCONFIGURATION, obj.getRefreshConfiguration());
criteria.add(FIRSTTIME, obj.getFirstTime());
criteria.add(MOREPROPS, obj.getMoreProps());
return criteria;
}
/**
* Retrieve a single object by pk
*
* @param pk the primary key
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @throws NoRowsException Primary key was not found in database.
* @throws TooManyRowsException Primary key was not found in database.
*/
public static TApplicationContext retrieveByPK(Integer pk)
throws TorqueException, NoRowsException, TooManyRowsException
{
return retrieveByPK(SimpleKey.keyFor(pk));
}
/**
* Retrieve a single object by pk
*
* @param pk the primary key
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @throws NoRowsException Primary key was not found in database.
* @throws TooManyRowsException Primary key was not found in database.
*/
public static TApplicationContext retrieveByPK(Integer pk, Connection con)
throws TorqueException, NoRowsException, TooManyRowsException
{
return retrieveByPK(SimpleKey.keyFor(pk), con);
}
/**
* Retrieve a single object by pk
*
* @param pk the primary key
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @throws NoRowsException Primary key was not found in database.
* @throws TooManyRowsException Primary key was not found in database.
*/
public static TApplicationContext retrieveByPK(ObjectKey pk)
throws TorqueException, NoRowsException, TooManyRowsException
{
Connection db = null;
TApplicationContext retVal = null;
try
{
db = Torque.getConnection(DATABASE_NAME);
retVal = retrieveByPK(pk, db);
}
finally
{
Torque.closeConnection(db);
}
return retVal;
}
/**
* Retrieve a single object by pk
*
* @param pk the primary key
* @param con the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @throws NoRowsException Primary key was not found in database.
* @throws TooManyRowsException Primary key was not found in database.
*/
public static TApplicationContext retrieveByPK(ObjectKey pk, Connection con)
throws TorqueException, NoRowsException, TooManyRowsException
{
Criteria criteria = buildCriteria(pk);
List<TApplicationContext> v = doSelect(criteria, con);
if (v.size() == 0)
{
throw new NoRowsException("Failed to select a row.");
}
else if (v.size() > 1)
{
throw new TooManyRowsException("Failed to select only one row.");
}
else
{
return (TApplicationContext)v.get(0);
}
}
/**
* Retrieve a multiple objects by pk
*
* @param pks List of primary keys
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<TApplicationContext> retrieveByPKs(List<ObjectKey> pks)
throws TorqueException
{
Connection db = null;
List<TApplicationContext> retVal = null;
try
{
db = Torque.getConnection(DATABASE_NAME);
retVal = retrieveByPKs(pks, db);
}
finally
{
Torque.closeConnection(db);
}
return retVal;
}
/**
* Retrieve a multiple objects by pk
*
* @param pks List of primary keys
* @param dbcon the connection to use
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static List<TApplicationContext> retrieveByPKs( List<ObjectKey> pks, Connection dbcon )
throws TorqueException
{
List<TApplicationContext> objs = null;
if (pks == null || pks.size() == 0)
{
objs = new LinkedList<TApplicationContext>();
}
else
{
Criteria criteria = new Criteria();
criteria.addIn( OBJECTID, pks );
objs = doSelect(criteria, dbcon);
}
return objs;
}
/**
* Returns the TableMap related to this peer.
*
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public static TableMap getTableMap()
throws TorqueException
{
return Torque.getDatabaseMap(DATABASE_NAME).getTable(TABLE_NAME);
}
private static void setDbName(Criteria crit)
{
// Set the correct dbName if it has not been overridden
// crit.getDbName will return the same object if not set to
// another value so == check is okay and faster
if (crit.getDbName() == Torque.getDefaultDB())
{
crit.setDbName(DATABASE_NAME);
}
}
// The following methods wrap some methods in BasePeer
// to have more support for Java5 generic types in the Peer
/**
* Utility method which executes a given sql statement. This
* method should be used for select statements only. Use
* executeStatement for update, insert, and delete operations.
*
* @param queryString A String with the sql statement to execute.
* @return List of Record objects.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#executeQuery(String)
*/
public static List<Record> executeQuery(String queryString) throws TorqueException
{
return BasePeer.executeQuery(queryString);
}
/**
* Utility method which executes a given sql statement. This
* method should be used for select statements only. Use
* executeStatement for update, insert, and delete operations.
*
* @param queryString A String with the sql statement to execute.
* @param dbName The database to connect to.
* @return List of Record objects.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#executeQuery(String,String)
*/
public static List<Record> executeQuery(String queryString, String dbName)
throws TorqueException
{
return BasePeer.executeQuery(queryString,dbName);
}
/**
* Method for performing a SELECT. Returns all results.
*
* @param queryString A String with the sql statement to execute.
* @param dbName The database to connect to.
* @param singleRecord Whether or not we want to select only a
* single record.
* @return List of Record objects.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#executeQuery(String,String,boolean)
*/
public static List<Record> executeQuery(
String queryString,
String dbName,
boolean singleRecord)
throws TorqueException
{
return BasePeer.executeQuery(queryString,dbName,singleRecord);
}
/**
* Method for performing a SELECT. Returns all results.
*
* @param queryString A String with the sql statement to execute.
* @param singleRecord Whether or not we want to select only a
* single record.
* @param con A Connection.
* @return List of Record objects.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#executeQuery(String,boolean,Connection)
*/
public static List<Record> executeQuery(
String queryString,
boolean singleRecord,
Connection con)
throws TorqueException
{
return BasePeer.executeQuery(queryString,singleRecord,con);
}
/**
* Method for performing a SELECT.
*
* @param queryString A String with the sql statement to execute.
* @param start The first row to return.
* @param numberOfResults The number of rows to return.
* @param dbName The database to connect to.
* @param singleRecord Whether or not we want to select only a
* single record.
* @return List of Record objects.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#executeQuery(String,int,int,String,boolean)
*/
public static List<Record> executeQuery(
String queryString,
int start,
int numberOfResults,
String dbName,
boolean singleRecord)
throws TorqueException
{
return BasePeer.executeQuery(queryString,start,numberOfResults,dbName,singleRecord);
}
/**
* Method for performing a SELECT. Returns all results.
*
* @param queryString A String with the sql statement to execute.
* @param start The first row to return.
* @param numberOfResults The number of rows to return.
* @param singleRecord Whether or not we want to select only a
* single record.
* @param con A Connection.
* @return List of Record objects.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#executeQuery(String,int,int,String,boolean,Connection)
*/
public static List<Record> executeQuery(
String queryString,
int start,
int numberOfResults,
boolean singleRecord,
Connection con)
throws TorqueException
{
return BasePeer.executeQuery(queryString,start,numberOfResults,singleRecord,con);
}
/**
* Returns all records in a QueryDataSet as a List of Record
* objects. Used for functionality like util.LargeSelect.
*
* @see #getSelectResults(QueryDataSet, int, int, boolean)
* @param qds the QueryDataSet
* @return a List of Record objects
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#getSelectResults(QueryDataSet)
*/
public static List<Record> getSelectResults(QueryDataSet qds)
throws TorqueException
{
return BasePeer.getSelectResults(qds);
}
/**
* Returns all records in a QueryDataSet as a List of Record
* objects. Used for functionality like util.LargeSelect.
*
* @see #getSelectResults(QueryDataSet, int, int, boolean)
* @param qds the QueryDataSet
* @param singleRecord
* @return a List of Record objects
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#getSelectResults(QueryDataSet,boolean)
*/
public static List<Record> getSelectResults(QueryDataSet qds, boolean singleRecord)
throws TorqueException
{
return BasePeer.getSelectResults(qds,singleRecord);
}
/**
* Returns numberOfResults records in a QueryDataSet as a List
* of Record objects. Starting at record 0. Used for
* functionality like util.LargeSelect.
*
* @see #getSelectResults(QueryDataSet, int, int, boolean)
* @param qds the QueryDataSet
* @param numberOfResults
* @param singleRecord
* @return a List of Record objects
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#getSelectResults(QueryDataSet,int,boolean)
*/
public static List<Record> getSelectResults(
QueryDataSet qds,
int numberOfResults,
boolean singleRecord)
throws TorqueException
{
return BasePeer.getSelectResults(qds,numberOfResults,singleRecord);
}
/**
* Returns numberOfResults records in a QueryDataSet as a List
* of Record objects. Starting at record start. Used for
* functionality like util.LargeSelect.
*
* @param qds The <code>QueryDataSet</code> to extract results
* from.
* @param start The index from which to start retrieving
* <code>Record</code> objects from the data set.
* @param numberOfResults The number of results to return (or
* <code> -1</code> for all results).
* @param singleRecord Whether or not we want to select only a
* single record.
* @return A <code>List</code> of <code>Record</code> objects.
* @exception TorqueException If any <code>Exception</code> occurs.
* @see org.apache.torque.util.BasePeer#getSelectResults(QueryDataSet,int,int,boolean)
*/
public static List getSelectResults(
QueryDataSet qds,
int start,
int numberOfResults,
boolean singleRecord)
throws TorqueException
{
return BasePeer.getSelectResults(qds,start,numberOfResults,singleRecord);
}
/**
* Performs a SQL <code>select</code> using a PreparedStatement.
* Note: this method does not handle null criteria values.
*
* @param criteria
* @param con
* @return a List of Record objects.
* @throws TorqueException Error performing database query.
* @see org.apache.torque.util.BasePeer#doPSSelect(Criteria,Connection)
*/
public static List<Record> doPSSelect(Criteria criteria, Connection con)
throws TorqueException
{
return BasePeer.doPSSelect(criteria,con);
}
/**
* Do a Prepared Statement select according to the given criteria
*
* @param criteria
* @return a List of Record objects.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
* @see org.apache.torque.util.BasePeer#doPSSelect(Criteria)
*/
public static List<Record> doPSSelect(Criteria criteria) throws TorqueException
{
return BasePeer.doPSSelect(criteria);
}
}
| gpl-3.0 |
FunKyWizzarD/KingRising | serveur/src/main/java/fr/univ/lille1/kr/server/api/PlayerResource.java | 2077 | package fr.univ.lille1.kr.server.api;
import java.util.List;
import java.util.UUID;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.univ.lille1.kr.server.model.Entity;
import fr.univ.lille1.kr.server.model.Message;
import fr.univ.lille1.kr.server.model.MoveEntity;
import fr.univ.lille1.kr.server.model.PlayerEntity;
@Path("/player")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class PlayerResource {
final static Logger logger = LoggerFactory.getLogger(PlayerResource.class);
final static int maxPlayer = 4;
public PlayerResource() {
}
@GET
public Message getUUID() {
Message msg = new Message();
if (DataBoard.getInstance().nbPlayers < maxPlayer) {
String uuid = UUID.randomUUID().toString();
int x = (int) (Math.random() * 300 + 10);
int y = (int) (Math.random() * 300 + 10);
PlayerEntity player = new PlayerEntity(uuid, x, y);
DataBoard.getInstance().add(player);
// logger.debug("UUID : " + uuid);
msg.setMsg(uuid);
return msg;
}
msg.setMsg("SERVER FULL");
return msg;
}
@GET
@Path("/refresh")
public List<Entity> getBoard() {
if (Math.random() < (double) maxPlayer / 8) {
DataBoard.getInstance().addNewPit();
}
// logger.debug(DataBoard.getInstance().getEntityList().get(0).toString());
DataBoard.getInstance().updateEntities();
return DataBoard.getInstance().getEntityList();
}
@GET
@Path("/clear")
public Message clearBoard() {
DataBoard.getInstance().clear();
Message msg = new Message();
msg.setMsg("OK");
return msg;
}
@POST
@Path("/move")
public Message movePlayer(MoveEntity moveE) {
Message msg = new Message();
if (DataBoard.getInstance().updatePlayer(moveE.getUuid(), moveE.getX(), moveE.getY())) {
msg.setMsg("OK : " + moveE.getX() + ", " + moveE.getY());
return msg;
} else {
msg.setMsg("ERROR : NOT MOVING");
return msg;
}
}
}
| gpl-3.0 |
ghsy158/fgh-framework | fgh-sys/src/main/java/fgh/sys/web/SystemIndexController.java | 2224 | package fgh.sys.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
import fgh.common.util.FastJsonConvert;
import fgh.sys.entity.SysUser;
import fgh.sys.facade.SysUserFacade;
/**
* <b>系统名称:</b><br>
* <b>模块名称:</b><br>
* <b>中文类名:</b><br>
* <b>概要说明:</b><br>
* @author fgh
* @since 2016年5月29日下午9:32:49
*/
@Controller
public class SystemIndexController {
@Autowired
private SysUserFacade sysUserFacade;
/**
*
* <b>方法名称:</b><br>
* <b>概要说明:</b><br>
* @throws Exception
*/
@RequestMapping("/sysindex.html")
public ModelAndView index(HttpServletRequest request,HttpServletResponse response) throws Exception {
ModelAndView ret = new ModelAndView();
System.out.println(this.sysUserFacade);
SysUser sysUser = this.sysUserFacade.getUser();
System.out.println(sysUser.getName());
// ret.addObject("sysUsser", sysUser);
List<JSONObject> list = this.sysUserFacade.getList();
for(JSONObject jsonObject:list){
System.out.println(jsonObject);
}
System.out.println("getById="+this.sysUserFacade.getById("admin"));
System.out.println("generateKey="+this.sysUserFacade.generateKey());
return ret;
}
@ResponseBody
@RequestMapping(value = "/getList.json", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public String getList(HttpServletRequest request,HttpServletResponse response) throws Exception {
List<JSONObject> list = this.sysUserFacade.getList();
for(JSONObject jsonObject:list){
System.out.println(jsonObject);
}
String json = FastJsonConvert.convertObjectToJSON(list);
System.out.println(json);
return json;
}
}
| gpl-3.0 |
b3dgs/lionengine | lionengine-core-awt/src/main/java/com/b3dgs/lionengine/awt/graphic/ScreenFullAwt.java | 7595 | /*
* Copyright (C) 2013-2022 Byron 3D Games Studio (www.b3dgs.com) Pierre-Alexandre (contact@b3dgs.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.b3dgs.lionengine.awt.graphic;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.DisplayMode;
import com.b3dgs.lionengine.Check;
import com.b3dgs.lionengine.Config;
import com.b3dgs.lionengine.Constant;
import com.b3dgs.lionengine.Generated;
import com.b3dgs.lionengine.LionEngineException;
import com.b3dgs.lionengine.Resolution;
import com.b3dgs.lionengine.awt.Keyboard;
import com.b3dgs.lionengine.awt.Mouse;
/**
* Full screen implementation.
*
* @see Keyboard
* @see Mouse
*/
final class ScreenFullAwt extends ScreenBaseAwt
{
/** Error message unsupported full screen. */
static final String ERROR_UNSUPPORTED_FULLSCREEN = "Unsupported resolution: ";
/** Unable to switch to full screen. */
static final String ERROR_SWITCH = "Unable to switch to full screen mode !";
/** Minimum length. */
private static final int MIN_LENGTH = 18;
/**
* Format resolution to string.
*
* @param resolution The resolution reference.
* @param depth The depth reference.
* @return The formatted string.
*/
private static String formatResolution(Resolution resolution, int depth)
{
return new StringBuilder(MIN_LENGTH).append(String.valueOf(resolution.getWidth()))
.append(Constant.STAR)
.append(String.valueOf(resolution.getHeight()))
.append(Constant.STAR)
.append(depth)
.append(Constant.SPACE)
.append(Constant.AT)
.append(String.valueOf(resolution.getRate()))
.append(Constant.UNIT_RATE)
.toString();
}
/**
* Internal constructor.
*
* @param config The config reference.
* @throws LionEngineException If renderer is <code>null</code> or no available display.
*/
ScreenFullAwt(Config config)
{
super(config);
frame.setUndecorated(true);
}
/**
* Prepare fullscreen mode.
*
* @param output The output resolution
* @param depth The bit depth color.
* @throws LionEngineException If unsupported resolution.
*/
private void initFullscreen(Resolution output, int depth)
{
final java.awt.Window window = new java.awt.Window(frame, conf);
window.setBackground(Color.BLACK);
window.setIgnoreRepaint(true);
window.setPreferredSize(new Dimension(output.getWidth(), output.getHeight()));
dev.setFullScreenWindow(window);
final DisplayMode disp = isSupported(new DisplayMode(output.getWidth(),
output.getHeight(),
depth,
output.getRate()));
if (disp == null)
{
throw new LionEngineException(ScreenFullAwt.ERROR_UNSUPPORTED_FULLSCREEN
+ formatResolution(output, depth)
+ getSupportedResolutions());
}
checkDisplayChangeSupport();
dev.setDisplayMode(disp);
window.validate();
ToolsAwt.createBufferStrategy(window, conf);
buf = window.getBufferStrategy();
// Set input listeners
componentForKeyboard = frame;
componentForMouse = window;
componentForCursor = window;
frame.validate();
}
/**
* Check support of display change.
*/
@Generated
private void checkDisplayChangeSupport()
{
if (!dev.isDisplayChangeSupported())
{
throw new LionEngineException(ScreenFullAwt.ERROR_SWITCH);
}
}
/**
* Get the supported resolution information.
*
* @return The supported resolutions.
*/
private String getSupportedResolutions()
{
final StringBuilder builder = new StringBuilder(Constant.HUNDRED);
int i = 0;
for (final DisplayMode display : dev.getDisplayModes())
{
final StringBuilder widthSpace = new StringBuilder();
final int width = display.getWidth();
if (width < Constant.THOUSAND)
{
widthSpace.append(Constant.SPACE);
}
final StringBuilder heightSpace = new StringBuilder();
final int height = display.getHeight();
if (height < Constant.THOUSAND)
{
heightSpace.append(System.lineSeparator());
}
final StringBuilder freqSpace = new StringBuilder();
final int freq = display.getRefreshRate();
if (freq < Constant.HUNDRED)
{
freqSpace.append(Constant.SPACE);
}
builder.append("Supported display mode:")
.append(System.lineSeparator())
.append('[')
.append(widthSpace)
.append(width)
.append(Constant.STAR)
.append(heightSpace)
.append(height)
.append(Constant.STAR)
.append(display.getBitDepth())
.append(Constant.SPACE)
.append(Constant.AT)
.append(freqSpace)
.append(freq)
.append(Constant.UNIT_RATE)
.append(']')
.append(Constant.SPACE);
i++;
final int linesPerDisplay = 5;
if (i % linesPerDisplay == 0)
{
builder.append(System.lineSeparator());
}
}
return builder.toString();
}
/**
* Check if the display mode is supported.
*
* @param display The display mode to check.
* @return Supported display, <code>null</code> else.
*/
private DisplayMode isSupported(DisplayMode display)
{
final DisplayMode[] supported = dev.getDisplayModes();
for (final DisplayMode current : supported)
{
if (ToolsAwt.sameDisplay(display, current))
{
return current;
}
}
return null;
}
/*
* ScreenAwt
*/
@Override
protected void setResolution(Resolution output)
{
Check.notNull(output);
initFullscreen(output, config.getDepth());
super.setResolution(output);
}
@Override
public void start()
{
frame.setVisible(true);
super.start();
}
}
| gpl-3.0 |
developer-vtnetzwelt/almsmobile | src/org/digitalcampus/oppia/fragments/ScorecardFragment.java | 4506 | /*
* This file is part of OppiaMobile - https://digital-campus.org/
*
* OppiaMobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OppiaMobile 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 OppiaMobile. If not, see <http://www.gnu.org/licenses/>.
*/
package org.digitalcampus.oppia.fragments;
import java.util.ArrayList;
import org.digitalcampus.mobile.learning.R;
import org.digitalcampus.oppia.activity.PrefsActivity;
import org.digitalcampus.oppia.adapter.ScorecardListAdapter;
import org.digitalcampus.oppia.application.DatabaseManager;
import org.digitalcampus.oppia.application.DbHelper;
import org.digitalcampus.oppia.model.Course;
import org.digitalcampus.oppia.utils.ScorecardPieChart;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import com.androidplot.pie.PieChart;
public class ScorecardFragment extends Fragment{
public static final String TAG = ScorecardFragment.class.getSimpleName();
private SharedPreferences prefs;
private Course course = null;
private boolean firstTimeOpened = true;
private ScorecardListAdapter scorecardListAdapter;
public static ScorecardFragment newInstance() {
ScorecardFragment myFragment = new ScorecardFragment();
return myFragment;
}
public static ScorecardFragment newInstance(Course course) {
ScorecardFragment myFragment = new ScorecardFragment();
Bundle args = new Bundle();
args.putSerializable(Course.TAG, course);
myFragment.setArguments(args);
return myFragment;
}
public ScorecardFragment(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
prefs = PreferenceManager.getDefaultSharedPreferences(super.getActivity());
View vv = null;
if( getArguments() != null && getArguments().containsKey(Course.TAG)){
vv = super.getLayoutInflater(savedInstanceState).inflate(R.layout.fragment_scorecard, null);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
vv.setLayoutParams(lp);
// refresh course to get most recent info (otherwise gets the info from when course first opened)
this.course = (Course) getArguments().getSerializable(Course.TAG);
DbHelper db = new DbHelper(super.getActivity());
long userId = db.getUserId(prefs.getString(PrefsActivity.PREF_USER_NAME, ""));
this.course = db.getCourse(this.course.getCourseId(), userId);
DatabaseManager.getInstance().closeDatabase();
} else {
vv = super.getLayoutInflater(savedInstanceState).inflate(R.layout.fragment_scorecards, null);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
vv.setLayoutParams(lp);
}
return vv;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(super.getActivity());
if(this.course != null){
PieChart pie = (PieChart) super.getActivity().findViewById(R.id.scorecardPieChart);
ScorecardPieChart spc = new ScorecardPieChart(super.getActivity(), pie, this.course);
spc.drawChart(50, true, firstTimeOpened);
firstTimeOpened = false;
} else {
DbHelper db = new DbHelper(super.getActivity());
long userId = db.getUserId(prefs.getString(PrefsActivity.PREF_USER_NAME, ""));
ArrayList<Course> courses = db.getCourses(userId);
DatabaseManager.getInstance().closeDatabase();
scorecardListAdapter = new ScorecardListAdapter(super.getActivity(), courses);
ListView listView = (ListView) super.getActivity().findViewById(R.id.scorecards_list);
listView.setAdapter(scorecardListAdapter);
}
}
}
| gpl-3.0 |
msf-ch/msf-malnutrition | msf-mobilemrs-forms/src/org/msf/mobilemrs/forms/HtmlUtils.java | 939 | /**
*
*/
package org.msf.mobilemrs.forms;
import java.util.List;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
/**
* @author Nicholas Wilkie
*
*/
public final class HtmlUtils {
public static void copyAttributes(Node source, Node dest, List<String> ignore) {
Attributes attrs = source.attributes();
List<Attribute> attrsList = attrs.asList();
String key;
for(Attribute attr : attrsList) {
key = attr.getKey();
if (ignore != null) {
for (String ignoreTest : ignore) {
if (ignoreTest.equalsIgnoreCase(key)) {
continue;
}
}
}
dest.attr(attr.getKey(), attr.getValue());
}
}
public static void replaceAndRetainChildren(Node oldElement, Element newElement) {
for (Node sourceChild : oldElement.childNodes()) {
newElement.appendChild(sourceChild);
}
oldElement.replaceWith(newElement);
}
}
| gpl-3.0 |
bozhbo12/demo-spring-server | spring-game/src/main/java/org/epilot/ccf/filter/codec/CodeFactory.java | 623 | package org.epilot.ccf.filter.codec;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolEncoder;
public class CodeFactory implements ProtocolCodecFactory {
private final ProtocolEncoder encoder;
private final ProtocolDecoder decoder;
public CodeFactory(String name)
{
encoder=new RequestEncoder(name);
decoder =new RequestDecode(name);
}
public ProtocolDecoder getDecoder() throws Exception {
return decoder;
}
public ProtocolEncoder getEncoder() throws Exception {
return encoder;
}
}
| gpl-3.0 |
mfearby/magnificat | src/main/java/com/marcfearby/magnificat.java | 299 | package com.marcfearby;
public class magnificat {
// If the main class extends 'javafx.application.Application' then the uber jar won't work.
// See this: https://github.com/javafxports/openjdk-jfx/issues/236
public static void main(String[] args) {
App.startup(args);
}
}
| gpl-3.0 |
bozhbo12/demo-spring-server | spring-game/src/main/java/com/spring/game/game/protocal/scene/biaocheRef/BiaocheRefResp.java | 1680 | package com.snail.webgame.game.protocal.scene.biaocheRef;
import org.epilot.ccf.core.protocol.MessageBody;
import org.epilot.ccf.core.protocol.ProtocolSequence;
/**
* 镖车刷新
* @author hongfm
*
*/
public class BiaocheRefResp extends MessageBody {
private int result;
private byte biaocheType;//镖车类型
private byte sourceType;//1:银子 2:金子
private int sourceChange;//资源变动数,正值为增加,负值为减少
private byte biaocheRefNum;//镖车已刷新次数
private byte biaocheFreeRefNum;//剩余镖车免费刷新次数
@Override
protected void setSequnce(ProtocolSequence ps)
{
ps.add("result", 0);
ps.add("biaocheType", 0);
ps.add("sourceType", 0);
ps.add("sourceChange", 0);
ps.add("biaocheRefNum", 0);
ps.add("biaocheFreeRefNum", 0);
}
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public byte getBiaocheType() {
return biaocheType;
}
public void setBiaocheType(byte biaocheType) {
this.biaocheType = biaocheType;
}
public byte getSourceType() {
return sourceType;
}
public void setSourceType(byte sourceType) {
this.sourceType = sourceType;
}
public int getSourceChange() {
return sourceChange;
}
public void setSourceChange(int sourceChange) {
this.sourceChange = sourceChange;
}
public byte getBiaocheRefNum() {
return biaocheRefNum;
}
public void setBiaocheRefNum(byte biaocheRefNum) {
this.biaocheRefNum = biaocheRefNum;
}
public byte getBiaocheFreeRefNum() {
return biaocheFreeRefNum;
}
public void setBiaocheFreeRefNum(byte biaocheFreeRefNum) {
this.biaocheFreeRefNum = biaocheFreeRefNum;
}
}
| gpl-3.0 |
sumanthmamidi/sumanthmp-pad | src/name/vbraun/view/write/Transformation.java | 1032 | package name.vbraun.view.write;
public class Transformation {
protected float offset_x = 0f;
protected float offset_y = 0f;
protected float scale = 1.0f;
public float applyX(float x) {
return x*scale + offset_x;
}
public float scaleText(float fontSize){
// Based on ThinkPad Tablet
return scale/1232f * fontSize;
}
public float applyY(float y) {
return y*scale + offset_y;
}
public float inverseX(float x) {
return (x-offset_x)/scale;
}
public float inverseY(float y) {
return (y-offset_y)/scale;
}
public Transformation offset(float dx, float dy) {
Transformation result = new Transformation();
result.offset_x = offset_x + dx;
result.offset_y = offset_y + dy;
result.scale = scale;
return result;
}
public Transformation copy() {
Transformation t = new Transformation();
t.offset_x = offset_x;
t.offset_y = offset_y;
t.scale = scale;
return t;
}
protected void set(Transformation t) {
offset_x = t.offset_x;
offset_y = t.offset_y;
scale = t.scale;
}
}
| gpl-3.0 |
bdceo/bd-codes | src/main/java/com/bdsoft/bdceo/thinkinjava/threads/AtomicityTest.java | 2007 | package com.bdsoft.bdceo.thinkinjava.threads;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 线程,原子性测试
*/
public class AtomicityTest implements Runnable {
private int i = 0;
// 非线程安全,且容易读到中间状态的值-奇数
public int getValue() {
// public synchronized int getValue() {
return i;
}
// 偶数递增,线程安全,原子性
public synchronized void evenIncrement() {
i++;
i++;
}
@Override
public void run() {
while (true) {
evenIncrement();
}
}
/**
* 入口
*/
public static void main(String[] args) throws Exception {
// test1(); // 发现奇数,退出
test2(); // 不会退出
}
static void test1() {
AtomicityTest at = new AtomicityTest();
new Thread(at).start();
// 发现奇数,程序退出
while (true) {
int val = at.getValue();
if (val % 2 != 0) {
System.out.println(val); // 1,13,7
System.exit(0);
}
}
}
static void test2() {
AtomicityTest2 at = new AtomicityTest2();
new Thread(at).start();
// 程序不会退出
while (true) {
int val = at.getValue();
if (val % 2 != 0) {
System.out.println(val);
System.exit(0);
}
}
}
}
/**
* 使用AtomicInteger 替代基础类型int,使用其特有api进行原子更新操作
*/
class AtomicityTest2 implements Runnable {
private AtomicInteger i = new AtomicInteger(0);
// 方法无需同步,api保证其线程安全
public int getValue() {
return i.get();
}
// 方法无需同步,api保证其线程安全
public void evenIncrement() {
i.addAndGet(2);
}
@Override
public void run() {
while (true) {
evenIncrement();
}
}
}
| gpl-3.0 |
alikemalocalan/MicroBlog | src/main/java/com/microblog/service/dto/UserDTO.java | 3697 | package com.microblog.service.dto;
import com.microblog.config.Constants;
import com.microblog.domain.Authority;
import com.microblog.domain.User;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.time.Instant;
import java.util.Set;
import java.util.stream.Collectors;
/**
* A DTO representing a user, with his authorities.
*/
public class UserDTO {
private String id;
@NotBlank
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
private String login;
@Size(max = 50)
private String firstName;
@Size(max = 50)
private String lastName;
@Email
@Size(min = 5, max = 100)
private String email;
@Size(max = 256)
private String imageUrl;
private boolean activated = false;
@Size(min = 2, max = 5)
private String langKey;
private String createdBy;
private Instant createdDate;
private String lastModifiedBy;
private Instant lastModifiedDate;
private Set<String> authorities;
public UserDTO() {
// Empty constructor needed for Jackson.
}
public UserDTO(User user) {
this(user.getId(), user.getLogin(), user.getFirstName(), user.getLastName(),
user.getEmail(), user.getActivated(), user.getImageUrl(), user.getLangKey(),
user.getCreatedBy(), user.getCreatedDate(), user.getLastModifiedBy(), user.getLastModifiedDate(),
user.getAuthorities().stream().map(Authority::getName)
.collect(Collectors.toSet()));
}
public UserDTO(String id, String login, String firstName, String lastName,
String email, boolean activated, String imageUrl, String langKey,
String createdBy, Instant createdDate, String lastModifiedBy, Instant lastModifiedDate,
Set<String> authorities) {
this.id = id;
this.login = login;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.activated = activated;
this.imageUrl = imageUrl;
this.langKey = langKey;
this.createdBy = createdBy;
this.createdDate = createdDate;
this.lastModifiedBy = lastModifiedBy;
this.lastModifiedDate = lastModifiedDate;
this.authorities = authorities;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public String getImageUrl() {
return imageUrl;
}
public boolean isActivated() {
return activated;
}
public String getLangKey() {
return langKey;
}
public String getCreatedBy() {
return createdBy;
}
public Instant getCreatedDate() {
return createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public Instant getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
public Set<String> getAuthorities() {
return authorities;
}
@Override
public String toString() {
return "UserDTO{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated=" + activated +
", langKey='" + langKey + '\'' +
", createdBy=" + createdBy +
", createdDate=" + createdDate +
", lastModifiedBy='" + lastModifiedBy + '\'' +
", lastModifiedDate=" + lastModifiedDate +
", authorities=" + authorities +
"}";
}
}
| gpl-3.0 |
nadiajolanda/fx2048-trudu-fulgheri | src/game2048/GameManager.java | 22282 | package game2048;
import giocatoreAutomatico.player.MyGriglia;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.IntBinaryOperator;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.ParallelTransition;
import javafx.animation.Timeline;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;
/**
*
* @author Chicca e Nady
*/
public class GameManager extends Group {
private static final int FINAL_VALUE_TO_WIN = 2048;
public static final int CELL_SIZE = 128;
private static final int DEFAULT_GRID_SIZE = 4;
private static final int BORDER_WIDTH = (14 + 2) / 2;
// grid_width=4*cell_size + 2*cell_stroke/2d (14px css)+2*grid_stroke/2d (2 px css)
private static final int GRID_WIDTH = CELL_SIZE * DEFAULT_GRID_SIZE + BORDER_WIDTH * 2;
private static final int TOP_HEIGHT = 92;
private volatile boolean movingTiles = false;
private final int gridSize;
private final List<Integer> traversalX;
private final List<Integer> traversalY;
private final List<Location> locations = new ArrayList<>();
private final Map<Location, Tile> gameGrid;
private final BooleanProperty gameWonProperty = new SimpleBooleanProperty(false);
private final BooleanProperty gameOverProperty = new SimpleBooleanProperty(false);
private final IntegerProperty gameScoreProperty = new SimpleIntegerProperty(0);
private final IntegerProperty gameMovePoints = new SimpleIntegerProperty(0);
private final Set<Tile> mergedToBeRemoved = new HashSet<>();
private final ParallelTransition parallelTransition = new ParallelTransition();
private final BooleanProperty layerOnProperty = new SimpleBooleanProperty(false);
//variabili pubbliche per permettere la lettura diretta
final MyGriglia myGriglia;
boolean gameOver=false;
boolean gameWon=false;
// User Interface controls
private final VBox vGame = new VBox(50);
private final Group gridGroup = new Group();
private final HBox hTop = new HBox(0);
private final Label lblScore = new Label("0");
private final Label lblPoints = new Label();
private final HBox hOvrLabel = new HBox();
private final HBox hOvrButton = new HBox();
// private final Button btn;
public GameManager() {
this(DEFAULT_GRID_SIZE);
}
public GameManager(int gridSize) {
this.gameGrid = new HashMap<>();
this.myGriglia = new MyGriglia(); //myGriglia inizializzata con caselle a -1
this.gridSize = gridSize;
this.traversalX = IntStream.range(0, gridSize).boxed().collect(Collectors.toList());
this.traversalY = IntStream.range(0, gridSize).boxed().collect(Collectors.toList());
createScore();
createGrid();
initGameProperties();
initializeGrid();
this.setManaged(false);
}
public void move(Direction direction) {
if (layerOnProperty.get()) {
return;
}
synchronized (gameGrid) {
if (movingTiles) {
return;
}
}
gameMovePoints.set(0);
Collections.sort(traversalX, direction.getX() == 1 ? Collections.reverseOrder() : Integer::compareTo);
Collections.sort(traversalY, direction.getY() == 1 ? Collections.reverseOrder() : Integer::compareTo);
final int tilesWereMoved = traverseGrid((int x, int y) -> {
Location thisloc = new Location(x, y);
Tile tile = gameGrid.get(thisloc);
if (tile == null) {
return 0;
}
Location farthestLocation = findFarthestLocation(thisloc, direction); // farthest available location
Location nextLocation = farthestLocation.offset(direction); // calculates to a possible merge
Tile tileToBeMerged = nextLocation.isValidFor(gridSize) ? gameGrid.get(nextLocation) : null;
if (tileToBeMerged != null && tileToBeMerged.getValue().equals(tile.getValue()) && !tileToBeMerged.isMerged()) {
tileToBeMerged.merge(tile);
//all aggiornamento di gameGrid viene aggiornata anche myGriglia
gameGrid.put(nextLocation, tileToBeMerged);
myGriglia.put(nextLocation, tileToBeMerged.getValue());
gameGrid.replace(tile.getLocation(), null);
myGriglia.replace(tile.getLocation(), -1);
parallelTransition.getChildren().add(animateExistingTile(tile, tileToBeMerged.getLocation()));
parallelTransition.getChildren().add(hideTileToBeMerged(tile));
mergedToBeRemoved.add(tile);
gameMovePoints.set(gameMovePoints.get() + tileToBeMerged.getValue());
gameScoreProperty.set(gameScoreProperty.get() + tileToBeMerged.getValue());
if (tileToBeMerged.getValue() == FINAL_VALUE_TO_WIN) {
gameWonProperty.set(true);
gameWon=true;
}
return 1;
} else if (farthestLocation.equals(tile.getLocation()) == false) {
parallelTransition.getChildren().add(animateExistingTile(tile, farthestLocation));
//all aggiornamento di gameGrid viene aggiornata anche myGriglia
gameGrid.put(farthestLocation, tile);
myGriglia.put(farthestLocation, tile.getValue());
gameGrid.replace(tile.getLocation(), null);
myGriglia.replace(tile.getLocation(), null);
tile.setLocation(farthestLocation);
return 1;
}
return 0;
});
if (gameMovePoints.get() > 0) {
animateScore(gameMovePoints.getValue().toString()).play();
}
parallelTransition.setOnFinished(e -> {
synchronized (gameGrid) {
movingTiles = false;
}
gridGroup.getChildren().removeAll(mergedToBeRemoved);
// game is over if there is no more moves
Location randomAvailableLocation = findRandomAvailableLocation();
if (randomAvailableLocation == null && !mergeMovementsAvailable()) {
gameOverProperty.set(true);
gameOver=true;
} else if (randomAvailableLocation != null && tilesWereMoved > 0) {
addAndAnimateRandomTile(randomAvailableLocation);
}
mergedToBeRemoved.clear();
// reset merged after each movement
gameGrid.values().stream().filter(Objects::nonNull).forEach(Tile::clearMerge);
});
synchronized (gameGrid) {
movingTiles = true;
}
parallelTransition.play();
parallelTransition.getChildren().clear();
}
private Location findFarthestLocation(Location location, Direction direction) {
Location farthest;
do {
farthest = location;
location = farthest.offset(direction);
} while (location.isValidFor(gridSize) && gameGrid.get(location) == null);
return farthest;
}
private int traverseGrid(IntBinaryOperator func) {
AtomicInteger at = new AtomicInteger();
traversalX.forEach(t_x -> {
traversalY.forEach(t_y -> {
at.addAndGet(func.applyAsInt(t_x, t_y));
});
});
return at.get();
}
private boolean mergeMovementsAvailable() {
final SimpleBooleanProperty foundMergeableTile = new SimpleBooleanProperty(false);
Stream.of(Direction.UP, Direction.LEFT).parallel().forEach(direction -> {
int mergeableFound = traverseGrid((x, y) -> {
Location thisloc = new Location(x, y);
Tile tile = gameGrid.get(thisloc);
if (tile != null) {
Location nextLocation = thisloc.offset(direction); // calculates to a possible merge
if (nextLocation.isValidFor(gridSize)) {
Tile tileToBeMerged = gameGrid.get(nextLocation);
if (tile.isMergeable(tileToBeMerged)) {
return 1;
}
}
}
return 0;
});
if (mergeableFound > 0) {
foundMergeableTile.set(true);
}
});
return foundMergeableTile.getValue();
}
private void createScore() {
Label lblTitle = new Label("2048");
lblTitle.getStyleClass().add("title");
Label lblSubtitle = new Label("FX");
lblSubtitle.getStyleClass().add("subtitle");
HBox hFill = new HBox();
HBox.setHgrow(hFill, Priority.ALWAYS);
hFill.setAlignment(Pos.CENTER);
VBox vScore = new VBox();
vScore.setAlignment(Pos.CENTER);
vScore.getStyleClass().add("vbox");
Label lblTit = new Label("SCORE");
lblTit.getStyleClass().add("titScore");
lblScore.getStyleClass().add("score");
lblScore.textProperty().bind(gameScoreProperty.asString());
vScore.getChildren().addAll(lblTit, lblScore);
hTop.getChildren().addAll(lblTitle, lblSubtitle, hFill, vScore);
hTop.setMinSize(GRID_WIDTH, TOP_HEIGHT);
hTop.setPrefSize(GRID_WIDTH, TOP_HEIGHT);
hTop.setMaxSize(GRID_WIDTH, TOP_HEIGHT);
vGame.getChildren().add(hTop);
getChildren().add(vGame);
lblPoints.getStyleClass().add("points");
getChildren().add(lblPoints);
}
private void createGrid() {
final double arcSize = CELL_SIZE / 6d;
IntStream.range(0, gridSize)
.mapToObj(i -> IntStream.range(0, gridSize).mapToObj(j -> {
Location loc = new Location(i, j);
locations.add(loc);
Rectangle rect2 = new Rectangle(i * CELL_SIZE, j * CELL_SIZE, CELL_SIZE, CELL_SIZE);
rect2.setArcHeight(arcSize);
rect2.setArcWidth(arcSize);
rect2.getStyleClass().add("grid-cell");
return rect2;
}))
.flatMap(s -> s)
.forEach(gridGroup.getChildren()::add);
gridGroup.getStyleClass().add("grid");
gridGroup.setManaged(false);
gridGroup.setLayoutX(BORDER_WIDTH);
gridGroup.setLayoutY(BORDER_WIDTH);
HBox hBottom = new HBox();
hBottom.getStyleClass().add("backGrid");
hBottom.setMinSize(GRID_WIDTH, GRID_WIDTH);
hBottom.setPrefSize(GRID_WIDTH, GRID_WIDTH);
hBottom.setMaxSize(GRID_WIDTH, GRID_WIDTH);
hBottom.getChildren().add(gridGroup);
vGame.getChildren().add(hBottom);
}
private void initGameProperties() {
gameOverProperty.addListener((observable, oldValue, newValue) -> {
if (newValue) {
layerOnProperty.set(true);
hOvrLabel.getStyleClass().setAll("over");
hOvrLabel.setMinSize(GRID_WIDTH, GRID_WIDTH);
Label lblOver = new Label("Game over!");
lblOver.getStyleClass().add("lblOver");
hOvrLabel.setAlignment(Pos.CENTER);
hOvrLabel.getChildren().setAll(lblOver);
hOvrLabel.setTranslateY(TOP_HEIGHT + vGame.getSpacing());
this.getChildren().add(hOvrLabel);
hOvrButton.setMinSize(GRID_WIDTH, GRID_WIDTH / 2);
Button bTry = new Button("Try again");
bTry.getStyleClass().setAll("try");
bTry.setOnTouchPressed(e -> resetGame());
bTry.setOnAction(e -> resetGame());
hOvrButton.setAlignment(Pos.CENTER);
hOvrButton.getChildren().setAll(bTry);
hOvrButton.setTranslateY(TOP_HEIGHT + vGame.getSpacing() + GRID_WIDTH / 2);
this.getChildren().add(hOvrButton);
}
});
gameWonProperty.addListener((observable, oldValue, newValue) -> {
if (newValue) {
layerOnProperty.set(true);
hOvrLabel.getStyleClass().setAll("won");
hOvrLabel.setMinSize(GRID_WIDTH, GRID_WIDTH);
Label lblWin = new Label("You win!");
lblWin.getStyleClass().add("lblWon");
hOvrLabel.setAlignment(Pos.CENTER);
hOvrLabel.getChildren().setAll(lblWin);
hOvrLabel.setTranslateY(TOP_HEIGHT + vGame.getSpacing());
this.getChildren().add(hOvrLabel);
hOvrButton.setMinSize(GRID_WIDTH, GRID_WIDTH / 2);
hOvrButton.setSpacing(10);
Button bContinue = new Button("Keep going");
bContinue.getStyleClass().add("try");
bContinue.setOnAction(e -> {
layerOnProperty.set(false);
getChildren().removeAll(hOvrLabel, hOvrButton);
});
Button bTry = new Button("Try again");
bTry.getStyleClass().add("try");
bTry.setOnTouchPressed(e -> resetGame());
bTry.setOnAction(e -> resetGame());
hOvrButton.setAlignment(Pos.CENTER);
hOvrButton.getChildren().setAll(bContinue, bTry);
hOvrButton.setTranslateY(TOP_HEIGHT + vGame.getSpacing() + GRID_WIDTH / 2);
this.getChildren().add(hOvrButton);
}
});
}
private void clearGame() {
List<Node> collect = gridGroup.getChildren().filtered(c -> c instanceof Tile).stream().collect(Collectors.toList());
gridGroup.getChildren().removeAll(collect);
gameGrid.clear();
getChildren().removeAll(hOvrLabel, hOvrButton);
layerOnProperty.set(false);
gameScoreProperty.set(0);
gameWonProperty.set(false);
gameOverProperty.set(false);
initializeLocationsInGameGrid();
}
private void resetGame() {
clearGame();
initializeGrid();
}
/**
* Clears the grid and redraws all tiles in the <code>gameGrid</code> object
*/
private void redrawTilesInGameGrid() {
gameGrid.values().stream().filter(Objects::nonNull).forEach(t -> {
double layoutX = t.getLocation().getLayoutX(CELL_SIZE) - (t.getMinWidth() / 2);
double layoutY = t.getLocation().getLayoutY(CELL_SIZE) - (t.getMinHeight() / 2);
t.setLayoutX(layoutX);
t.setLayoutY(layoutY);
gridGroup.getChildren().add(t);
});
}
private Timeline animateScore(String v1) {
final Timeline timeline = new Timeline();
lblPoints.setText("+" + v1);
lblPoints.setOpacity(1);
lblPoints.setLayoutX(400);
lblPoints.setLayoutY(20);
final KeyValue kvO = new KeyValue(lblPoints.opacityProperty(), 0);
final KeyValue kvY = new KeyValue(lblPoints.layoutYProperty(), 100);
Duration animationDuration = Duration.millis(600);
final KeyFrame kfO = new KeyFrame(animationDuration, kvO);
final KeyFrame kfY = new KeyFrame(animationDuration, kvY);
timeline.getKeyFrames().add(kfO);
timeline.getKeyFrames().add(kfY);
return timeline;
}
interface AddTile {
void add(int value, int x, int y);
}
/**
* Initializes all cells in gameGrid map to null
*/
private void initializeLocationsInGameGrid() {
traverseGrid((x, y) -> {
Location thisloc = new Location(x, y);
gameGrid.put(thisloc, null);
System.out.println(thisloc);
return 0;
});
}
private void initializeGrid() {
initializeLocationsInGameGrid();
Tile tile0 = Tile.newRandomTile();
List<Location> randomLocs = new ArrayList<>(locations);
Collections.shuffle(randomLocs);
Iterator<Location> locs = randomLocs.stream().limit(2).iterator();
tile0.setLocation(locs.next());
Tile tile1 = null;
if (new Random().nextFloat() <= 0.8) { // gives 80% chance to add a second tile
tile1 = Tile.newRandomTile();
if (tile1.getValue() == 4 && tile0.getValue() == 4) {
tile1 = Tile.newTile(2);
}
tile1.setLocation(locs.next());
}
Arrays.asList(tile0, tile1).forEach(t -> {
if (t == null) {
return;
}
gameGrid.put(t.getLocation(), t);
//inizializza myGriglia
myGriglia.put(t.getLocation(),t.getValue());
//System.out.print(myGriglia.get(t.getLocation()));
});
redrawTilesInGameGrid();
}
/**
* Finds a random location or returns null if none exist
*
* @return a random location or <code>null</code> if there are no more
* locations available
*/
private Location findRandomAvailableLocation() {
List<Location> availableLocations = locations.stream().filter(l -> gameGrid.get(l) == null).collect(Collectors.toList());
if (availableLocations.isEmpty()) {
return null;
}
Collections.shuffle(availableLocations);
Location randomLocation = availableLocations.get(new Random().nextInt(availableLocations.size()));
return randomLocation;
}
private void addAndAnimateRandomTile(Location randomLocation) {
Tile tile = Tile.newRandomTile();
tile.setLocation(randomLocation);
double layoutX = tile.getLocation().getLayoutX(CELL_SIZE) - (tile.getMinWidth() / 2);
double layoutY = tile.getLocation().getLayoutY(CELL_SIZE) - (tile.getMinHeight() / 2);
tile.setLayoutX(layoutX);
tile.setLayoutY(layoutY);
tile.setScaleX(0);
tile.setScaleY(0);
//inizializza myGriglia come gameGrid
gameGrid.put(tile.getLocation(), tile);//restituisce la posizione finale
myGriglia.put(tile.getLocation(),tile.getValue())//restituisce il valore finale della nuova casella ottenuta dalla somma delle precedenti
gridGroup.getChildren().add(tile);//restituisce la casella figlia
animateNewlyAddedTile(tile).play();
}
myGriglia.put(tile.getLocation(),tile.getValue());
gridGroup.getChildren().add(tile);
animateNewlyAddedTile(tile).play();
}
private static final Duration ANIMATION_EXISTING_TILE = Duration.millis(125);
private Timeline animateExistingTile(Tile tile, Location newLocation) {
Timeline timeline = new Timeline();
KeyValue kvX = new KeyValue(tile.layoutXProperty(), newLocation.getLayoutX(CELL_SIZE) - (tile.getMinHeight() / 2));
KeyValue kvY = new KeyValue(tile.layoutYProperty(), newLocation.getLayoutY(CELL_SIZE) - (tile.getMinHeight() / 2));
KeyFrame kfX = new KeyFrame(ANIMATION_EXISTING_TILE, kvX);
KeyFrame kfY = new KeyFrame(ANIMATION_EXISTING_TILE, kvY);
timeline.getKeyFrames().add(kfX);
timeline.getKeyFrames().add(kfY);
return timeline;
}
// after last movement on full grid, check if there are movements available
private EventHandler<ActionEvent> onFinishNewlyAddedTile = e -> {
if (this.gameGrid.values().parallelStream().noneMatch(Objects::isNull) && !mergeMovementsAvailable()) {
this.gameOverProperty.set(true);
}
};
private static final Duration ANIMATION_NEWLY_ADDED_TILE = Duration.millis(125);
private Timeline animateNewlyAddedTile(Tile tile) {
Timeline timeline = new Timeline();
KeyValue kvX = new KeyValue(tile.scaleXProperty(), 1);
KeyValue kvY = new KeyValue(tile.scaleYProperty(), 1);
KeyFrame kfX = new KeyFrame(ANIMATION_NEWLY_ADDED_TILE, kvX);
KeyFrame kfY = new KeyFrame(ANIMATION_NEWLY_ADDED_TILE, kvY);
timeline.getKeyFrames().add(kfX);
timeline.getKeyFrames().add(kfY);
timeline.setOnFinished(onFinishNewlyAddedTile);
return timeline;
}
private static final Duration ANIMATION_TILE_TO_BE_MERGED = Duration.millis(150);
private Timeline hideTileToBeMerged(Tile tile) {
Timeline timeline = new Timeline();
KeyValue kv = new KeyValue(tile.opacityProperty(), 0);
KeyFrame kf = new KeyFrame(ANIMATION_TILE_TO_BE_MERGED, kv);
timeline.getKeyFrames().add(kf);
return timeline;
}
public void saveSession() {
SessionManager sessionManager = new SessionManager(DEFAULT_GRID_SIZE);
sessionManager.saveSession(gameGrid, gameScoreProperty.getValue());
}
public void restoreSession() {
SessionManager sessionManager = new SessionManager(DEFAULT_GRID_SIZE);
clearGame();
int score = sessionManager.restoreSession(gameGrid);
if (score >= 0) {
gameScoreProperty.set(score);
redrawTilesInGameGrid();
} else {
// not session found, restart again
resetGame();
}
}
}
| gpl-3.0 |
powerstackers/FTC-5029-Res-Q | SwerveRoboticsLibrary/src/main/java/org/swerverobotics/library/exceptions/BNO055InitializationException.java | 487 | package org.swerverobotics.library.exceptions;
import org.swerverobotics.library.interfaces.IBNO055IMU;
/**
* A BNO055InitializationException is thrown if a BNO055 fails to initialize successfully
*/
public class BNO055InitializationException extends RuntimeException
{
public final IBNO055IMU imu;
public BNO055InitializationException(IBNO055IMU imu, String message)
{
super(String.format("BNO055: %s", message));
this.imu = imu;
}
}
| gpl-3.0 |
ivoanjo/phd-jaspexmls | jaspex-mls/src/jaspex/util/HashUtils.java | 1997 | /*
* jaspex-mls: a Java Software Speculative Parallelization Framework
* Copyright (C) 2015 Ivo Anjo <ivo.anjo@ist.utl.pt>
*
* This file is part of jaspex-mls.
*
* jaspex-mls is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* jaspex-mls 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 jaspex-mls. If not, see <http://www.gnu.org/licenses/>.
*/
package jaspex.util;
import java.io.*;
import java.security.*;
import java.math.BigInteger;
public class HashUtils {
public static String hashFile(File f) {
try {
return hashBytesToString(md5().digest(IOUtils.readFile(f)));
} catch (IOException e) { throw new Error(e); }
}
private static void hashSubtree(File dir, MessageDigest md) throws IOException {
if (!dir.isDirectory()) throw new RuntimeException("Argument is not a directory");
for (File f : dir.listFiles()) {
if (f.isFile()) md.update(IOUtils.readFile(f));
else if (f.isDirectory()) hashSubtree(f, md);
}
}
public static byte[] hashSubtree(File directory) {
try {
MessageDigest md = md5();
hashSubtree(directory, md);
return md.digest();
} catch (IOException e) { throw new Error(e); }
}
public static String hashString(String s) {
return hashBytesToString(md5().digest(s.getBytes()));
}
public static String hashBytesToString(byte[] hashBytes) {
return String.format("%032x", new BigInteger(1, hashBytes));
}
public static MessageDigest md5() {
try {
return MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) { throw new Error(e); }
}
}
| gpl-3.0 |
wkwan163/CMPUT-301-Assignment-1 | src/com/wkwan/cmput301assignment1/MainActivity.java | 2495 | package com.wkwan.cmput301assignment1;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
// This main activity class displays any and all claims that a user has
// previously created, allowing the user to review and modify any claims they wish.
public class MainActivity extends Activity {
private ClaimShow claimListModifier = null;
@Override
protected void onCreate(Bundle persistentinfo) {
super.onCreate(persistentinfo);
setContentView(R.layout.activity_main);
SummaryPersistence.initManager(this.getApplicationContext());
ArrayList<ClaimCreate> claims = SummaryAccess.getClaimList().getClaims();
claimListModifier = new ClaimShow(this, R.layout.claims_storage, claims);
ListView listScreen = (ListView) findViewById(R.id.claim_list_view);
listScreen.setAdapter(claimListModifier);
listScreen.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
ClaimCreate claim = claimListModifier.getItem(position);
int claimset = SummaryAccess.getClaimList().orderOf(claim);
Intent intent = new Intent(MainActivity.this, ReviewAndChange.class);
intent.putExtra(ReviewAndChange.claimOrder, claimset);
startActivity(intent);
}
});
}
@Override
protected void onResume() {
if (claimListModifier != null) claimListModifier.notifyDataSetChanged();
super.onResume();
}
public void recordClaim() {
Intent intent = new Intent(MainActivity.this, ClaimModify.class);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_add_claim) {
recordClaim();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | packages/apps/Settings/src/com/android/settings/ZonePicker.java | 13093 | /*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.ListFragment;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.xmlpull.v1.XmlPullParserException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import libcore.icu.ICU;
import libcore.icu.TimeZoneNames;
/**
* The class displaying a list of time zones that match a filter string
* such as "Africa", "Europe", etc. Choosing an item from the list will set
* the time zone. Pressing Back without choosing from the list will not
* result in a change in the time zone setting.
*/
public class ZonePicker extends ListFragment {
private static final String TAG = "ZonePicker";
public static interface ZoneSelectionListener {
// You can add any argument if you really need it...
public void onZoneSelected(TimeZone tz);
}
private static final String KEY_ID = "id"; // value: String
private static final String KEY_DISPLAYNAME = "name"; // value: String
private static final String KEY_GMT = "gmt"; // value: String
private static final String KEY_OFFSET = "offset"; // value: int (Integer)
private static final String XMLTAG_TIMEZONE = "timezone";
private static final int HOURS_1 = 60 * 60000;
private static final int MENU_TIMEZONE = Menu.FIRST+1;
private static final int MENU_ALPHABETICAL = Menu.FIRST;
private boolean mSortedByTimezone;
private SimpleAdapter mTimezoneSortedAdapter;
private SimpleAdapter mAlphabeticalAdapter;
private ZoneSelectionListener mListener;
/**
* Constructs an adapter with TimeZone list. Sorted by TimeZone in default.
*
* @param sortedByName use Name for sorting the list.
*/
public static SimpleAdapter constructTimezoneAdapter(Context context,
boolean sortedByName) {
return constructTimezoneAdapter(context, sortedByName,
R.layout.date_time_setup_custom_list_item_2);
}
/**
* Constructs an adapter with TimeZone list. Sorted by TimeZone in default.
*
* @param sortedByName use Name for sorting the list.
*/
public static SimpleAdapter constructTimezoneAdapter(Context context,
boolean sortedByName, int layoutId) {
final String[] from = new String[] {KEY_DISPLAYNAME, KEY_GMT};
final int[] to = new int[] {android.R.id.text1, android.R.id.text2};
final String sortKey = (sortedByName ? KEY_DISPLAYNAME : KEY_OFFSET);
final MyComparator comparator = new MyComparator(sortKey);
ZoneGetter zoneGetter = new ZoneGetter();
final List<HashMap<String, Object>> sortedList = zoneGetter.getZones(context);
Collections.sort(sortedList, comparator);
final SimpleAdapter adapter = new SimpleAdapter(context,
sortedList,
layoutId,
from,
to);
return adapter;
}
/**
* Searches {@link TimeZone} from the given {@link SimpleAdapter} object, and returns
* the index for the TimeZone.
*
* @param adapter SimpleAdapter constructed by
* {@link #constructTimezoneAdapter(Context, boolean)}.
* @param tz TimeZone to be searched.
* @return Index for the given TimeZone. -1 when there's no corresponding list item.
* returned.
*/
public static int getTimeZoneIndex(SimpleAdapter adapter, TimeZone tz) {
final String defaultId = tz.getID();
final int listSize = adapter.getCount();
for (int i = 0; i < listSize; i++) {
// Using HashMap<String, Object> induces unnecessary warning.
final HashMap<?,?> map = (HashMap<?,?>)adapter.getItem(i);
final String id = (String)map.get(KEY_ID);
if (defaultId.equals(id)) {
// If current timezone is in this list, move focus to it
return i;
}
}
return -1;
}
/**
* @param item one of items in adapters. The adapter should be constructed by
* {@link #constructTimezoneAdapter(Context, boolean)}.
* @return TimeZone object corresponding to the item.
*/
public static TimeZone obtainTimeZoneFromItem(Object item) {
return TimeZone.getTimeZone((String)((Map<?, ?>)item).get(KEY_ID));
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final Activity activity = getActivity();
mTimezoneSortedAdapter = constructTimezoneAdapter(activity, false);
mAlphabeticalAdapter = constructTimezoneAdapter(activity, true);
// Sets the adapter
setSorting(true);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = super.onCreateView(inflater, container, savedInstanceState);
final ListView list = (ListView) view.findViewById(android.R.id.list);
Utils.forcePrepareCustomPreferencesList(container, view, list, false);
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.add(0, MENU_ALPHABETICAL, 0, R.string.zone_list_menu_sort_alphabetically)
.setIcon(android.R.drawable.ic_menu_sort_alphabetically);
menu.add(0, MENU_TIMEZONE, 0, R.string.zone_list_menu_sort_by_timezone)
.setIcon(R.drawable.ic_menu_3d_globe);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
if (mSortedByTimezone) {
menu.findItem(MENU_TIMEZONE).setVisible(false);
menu.findItem(MENU_ALPHABETICAL).setVisible(true);
} else {
menu.findItem(MENU_TIMEZONE).setVisible(true);
menu.findItem(MENU_ALPHABETICAL).setVisible(false);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_TIMEZONE:
setSorting(true);
return true;
case MENU_ALPHABETICAL:
setSorting(false);
return true;
default:
return false;
}
}
public void setZoneSelectionListener(ZoneSelectionListener listener) {
mListener = listener;
}
private void setSorting(boolean sortByTimezone) {
final SimpleAdapter adapter =
sortByTimezone ? mTimezoneSortedAdapter : mAlphabeticalAdapter;
setListAdapter(adapter);
mSortedByTimezone = sortByTimezone;
final int defaultIndex = getTimeZoneIndex(adapter, TimeZone.getDefault());
if (defaultIndex >= 0) {
setSelection(defaultIndex);
}
}
static class ZoneGetter {
private final List<HashMap<String, Object>> mZones =
new ArrayList<HashMap<String, Object>>();
private final HashSet<String> mLocalZones = new HashSet<String>();
private final Date mNow = Calendar.getInstance().getTime();
private final SimpleDateFormat mZoneNameFormatter = new SimpleDateFormat("zzzz");
private List<HashMap<String, Object>> getZones(Context context) {
for (String olsonId : TimeZoneNames.forLocale(Locale.getDefault())) {
mLocalZones.add(olsonId);
}
try {
XmlResourceParser xrp = context.getResources().getXml(R.xml.timezones);
while (xrp.next() != XmlResourceParser.START_TAG) {
continue;
}
xrp.next();
while (xrp.getEventType() != XmlResourceParser.END_TAG) {
while (xrp.getEventType() != XmlResourceParser.START_TAG) {
if (xrp.getEventType() == XmlResourceParser.END_DOCUMENT) {
return mZones;
}
xrp.next();
}
if (xrp.getName().equals(XMLTAG_TIMEZONE)) {
String olsonId = xrp.getAttributeValue(0);
addTimeZone(olsonId);
}
while (xrp.getEventType() != XmlResourceParser.END_TAG) {
xrp.next();
}
xrp.next();
}
xrp.close();
} catch (XmlPullParserException xppe) {
Log.e(TAG, "Ill-formatted timezones.xml file");
} catch (java.io.IOException ioe) {
Log.e(TAG, "Unable to read timezones.xml file");
}
return mZones;
}
private void addTimeZone(String olsonId) {
// We always need the "GMT-07:00" string.
final TimeZone tz = TimeZone.getTimeZone(olsonId);
// For the display name, we treat time zones within the country differently
// from other countries' time zones. So in en_US you'd get "Pacific Daylight Time"
// but in de_DE you'd get "Los Angeles" for the same time zone.
String displayName;
if (mLocalZones.contains(olsonId)) {
// Within a country, we just use the local name for the time zone.
mZoneNameFormatter.setTimeZone(tz);
displayName = mZoneNameFormatter.format(mNow);
} else {
// For other countries' time zones, we use the exemplar location.
final String localeName = Locale.getDefault().toString();
displayName = TimeZoneNames.getExemplarLocation(localeName, olsonId);
}
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put(KEY_ID, olsonId);
map.put(KEY_DISPLAYNAME, displayName);
map.put(KEY_GMT, DateTimeSettings.getTimeZoneText(tz, false));
map.put(KEY_OFFSET, tz.getOffset(mNow.getTime()));
mZones.add(map);
}
}
@Override
public void onListItemClick(ListView listView, View v, int position, long id) {
// Ignore extra clicks
if (!isResumed()) return;
final Map<?, ?> map = (Map<?, ?>)listView.getItemAtPosition(position);
final String tzId = (String) map.get(KEY_ID);
// Update the system timezone value
final Activity activity = getActivity();
final AlarmManager alarm = (AlarmManager) activity.getSystemService(Context.ALARM_SERVICE);
alarm.setTimeZone(tzId);
final TimeZone tz = TimeZone.getTimeZone(tzId);
if (mListener != null) {
mListener.onZoneSelected(tz);
} else {
getActivity().onBackPressed();
}
}
private static class MyComparator implements Comparator<HashMap<?, ?>> {
private String mSortingKey;
public MyComparator(String sortingKey) {
mSortingKey = sortingKey;
}
public void setSortingKey(String sortingKey) {
mSortingKey = sortingKey;
}
public int compare(HashMap<?, ?> map1, HashMap<?, ?> map2) {
Object value1 = map1.get(mSortingKey);
Object value2 = map2.get(mSortingKey);
/*
* This should never happen, but just in-case, put non-comparable
* items at the end.
*/
if (!isComparable(value1)) {
return isComparable(value2) ? 1 : 0;
} else if (!isComparable(value2)) {
return -1;
}
return ((Comparable) value1).compareTo(value2);
}
private boolean isComparable(Object value) {
return (value != null) && (value instanceof Comparable);
}
}
}
| gpl-3.0 |
thedreamer979/Arionide | src/ch/innovazion/arionide/threading/timing/TimerRing.java | 1781 | /*******************************************************************************
* This file is part of Arionide.
*
* Arionide is an IDE used to conceive applications and algorithms in a three-dimensional environment.
* It is the work of Arion Zimmermann for his final high-school project at Calvin College (Geneva, Switzerland).
* Copyright (C) 2016-2020 Innovazion. All rights reserved.
*
* Arionide is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Arionide 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 Arionide. If not, see <http://www.gnu.org/licenses/>.
*
* The copy of the GNU General Public License can be found in the 'LICENSE.txt' file inside the src directory or inside the JAR archive.
*******************************************************************************/
package ch.innovazion.arionide.threading.timing;
import java.util.TimerTask;
import ch.innovazion.arionide.events.TimerEvent;
import ch.innovazion.arionide.events.dispatching.IEventDispatcher;
public final class TimerRing extends TimerTask {
private final IEventDispatcher dispatcher;
private final Object target;
protected TimerRing(IEventDispatcher dispatcher, Object target) {
this.dispatcher = dispatcher;
this.target = target;
}
public void run() {
this.dispatcher.fire(new TimerEvent(this.target));
}
} | gpl-3.0 |
msf-ch/msf-malnutrition | msf-malnutrition/src/org/msf/android/rest/JsonOpenMRSObjectArrayDeserializer.java | 1551 | package org.msf.android.rest;
import java.io.IOException;
import java.util.Iterator;
import org.msf.android.openmrs.OpenMRSObject;
import org.msf.android.utilities.MSFCommonUtils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
public class JsonOpenMRSObjectArrayDeserializer extends StdDeserializer<String>
implements ContextualDeserializer {
public JsonOpenMRSObjectArrayDeserializer() {
super(String.class);
}
@Override
public String deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
Iterator<OpenMRSObject> it = jp.readValuesAs(OpenMRSObject.class);
StringBuffer sb = new StringBuffer();
OpenMRSObject o;
while (it.hasNext()) {
o = it.next();
String uuid = o.getUuid();
sb.append(uuid);
sb.append(UuidListTools.UUID_SEPARATOR);
}
//and just take off that last comma...
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
@Override
public JsonDeserializer<String> createContextual(
DeserializationContext ctxt, BeanProperty property)
throws JsonMappingException {
return this;
}
}
| gpl-3.0 |
Smarty0/LavaCraft | src/main/java/com/Smarty/LavaCraft/client/gui/ModGuiConfig.java | 788 | package com.Smarty.LavaCraft.client.gui;
import com.Smarty.LavaCraft.handler.ConfigurationHandler;
import com.Smarty.LavaCraft.reference.Reference;
import cpw.mods.fml.client.config.GuiConfig;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
public class ModGuiConfig extends GuiConfig
{
public ModGuiConfig(GuiScreen guiScreen)
{
super(guiScreen,
new ConfigElement(ConfigurationHandler.configuration.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements(),
Reference.MOD_ID,
false,
false,
GuiConfig.getAbridgedConfigPath(ConfigurationHandler.configuration.toString()));
}
} | gpl-3.0 |
OpenSourceShift/OpenARMS-API | app/api/requests/DeleteChoiceRequest.java | 571 | package api.requests;
import api.responses.EmptyResponse;
import api.responses.Response;
/**
* A request for the service: Deletes a choice
*/
public class DeleteChoiceRequest extends Request {
public Long choice_id;
public DeleteChoiceRequest (Long l) {
this.choice_id = l;
}
@Override
public String getURL() {
return "/choice/" + choice_id;
}
@Override
public Class<? extends Response> getExpectedResponseClass() {
return EmptyResponse.class;
}
@Override
public Method getHttpMethod() {
return Method.DELETE;
}
}
| gpl-3.0 |
AlbRoehm/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/data/SocialRepository.java | 2963 | package com.habitrpg.android.habitica.data;
import com.habitrpg.android.habitica.models.AchievementResult;
import com.habitrpg.android.habitica.models.inventory.Quest;
import com.habitrpg.android.habitica.models.members.Member;
import com.habitrpg.android.habitica.models.responses.PostChatMessageResult;
import com.habitrpg.android.habitica.models.social.Challenge;
import com.habitrpg.android.habitica.models.social.ChatMessage;
import com.habitrpg.android.habitica.models.social.Group;
import com.habitrpg.android.habitica.models.user.User;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.realm.RealmResults;
import rx.Observable;
public interface SocialRepository extends BaseRepository {
Observable<List<ChatMessage>> retrieveGroupChat(String groupId);
Observable<RealmResults<ChatMessage>> getGroupChat(String groupId);
void markMessagesSeen(String seenGroupId);
Observable<Void> flagMessage(ChatMessage chatMessage);
Observable<ChatMessage> likeMessage(ChatMessage chatMessage);
Observable<Void> deleteMessage(ChatMessage chatMessage);
Observable<PostChatMessageResult> postGroupChat(String groupId, HashMap<String, String> messageObject);
Observable<PostChatMessageResult> postGroupChat(String groupId, String message);
Observable<Group> retrieveGroup(String id);
Observable<Group> getGroup(String id);
Observable<Group> leaveGroup(String id);
Observable<Group> joinGroup(String id);
Observable<Void> updateGroup(Group group, String name, String description, String leader, String privacy);
Observable<List<Group>> retrieveGroups(String type);
Observable<RealmResults<Group>> getGroups(String type);
Observable<RealmResults<Group>> getPublicGuilds();
Observable<PostChatMessageResult> postPrivateMessage(HashMap<String, String> messageObject);
Observable<PostChatMessageResult> postPrivateMessage(String recipientId, String message);
Observable<RealmResults<Member>> getGroupMembers(String id);
Observable<List<Member>> retrieveGroupMembers(String id, boolean includeAllPublicFields);
Observable<List<Void>> inviteToGroup(String id, Map<String, Object> inviteData);
Observable<List<Challenge>> getUserChallenges();
Observable<Member> getMember(String userId);
Observable<Void> markPrivateMessagesRead(User user);
Observable<RealmResults<Group>> getUserGroups();
Observable<Void> acceptQuest(User user, String partyId);
Observable<Void> rejectQuest(User user, String partyId);
Observable<Void> leaveQuest(String partyId);
Observable<Void> cancelQuest(String partyId);
Observable<Quest> abortQuest(String partyId);
Observable<Void> rejectGroupInvite(String groupId);
Observable<Quest> forceStartQuest(Group party);
Observable<AchievementResult> getMemberAchievements(String userId);
}
| gpl-3.0 |
peramikic/ARviewer | src/com/libresoft/sdk/ARviewer/Types/GeoNode.java | 4728 | /*
*
* Copyright (C) 2008-2011 GSyC/LibreSoft, Universidad Rey Juan Carlos
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
* Author : Roberto Calvo Palomino <rocapal@libresoft.es>
*
*/
package com.libresoft.sdk.ARviewer.Types;
import java.io.Serializable;
import android.location.Location;
/**
* This class provides the essential Node of social Network. All the
* contents must inherit of this class.
*
* @author Roberto Calvo
* @author <a href="mailto:rocapal@libresoft.es">rocapal@libresoft.es</a>
* @author <a target="_blank" href="http://libregeosocial.morfeo-project.org/">http://libregeosocial.morfeo-project.org/</a>
* @version 0.1
*/
public class GeoNode implements Serializable {
// Serializable UID
private static final long serialVersionUID = -9121943636715457236L;
private Integer mId;
private Double mRadius;
private String mSince;
private Double mLatitude;
private Double mLongitude;
private Double mAltitude;
private String mPosition_since;
private String mUsername;
private Integer mUser_id;
private ExtenalInfo mExtInfo;
private GenericLayer mFatherLayer = null;
/**
* Constructor used to create this object.
* @param id Identifier of social network (can be 0)
* @param latitude The latitude of the node position
* @param longitude The longitude of the node position
* @param altitude The Altitude of the node posicion
* @param radius The radius/error of the node position
* @param since The time when the node was created
*/
public GeoNode(Integer id, Double latitude, Double longitude, Double altitude, Double radius, String since,
String position_since)
{
super();
mId = id;
mRadius = radius;
mLatitude = latitude;
mLongitude = longitude;
mAltitude = altitude;
mPosition_since = position_since;
mSince = since;
mExtInfo=null;
}
public void setFatherLayer (GenericLayer layer)
{
mFatherLayer = layer;
}
public GenericLayer getFatherLayer ()
{
return mFatherLayer;
}
/**
* Return the Identifier asociated to social network
*/
public Integer getId() {
return mId;
}
/**
* Return the latitude of the node
*/
public Double getLatitude() {
return mLatitude;
}
/**
* Return the longitude of the node
*/
public Double getLongitude() {
return mLongitude;
}
/**
* Return the altitude of the node
*/
public Double getAltitude(){
return mAltitude;
}
/**
* Return the radius of the node
*/
public Double getRadius() {
return mRadius;
}
public String getPosition_since(){
return mPosition_since;
}
/**
* Set the latitude of the node
*
* @param latitude The latitude of the position node
*/
public void setLatitude(Double latitude){
mLatitude = latitude;
getLocation();
}
/**
* Set the longitude of the node
*
* @param longitude The latitude of the position node
*/
public void setLongitude(Double longitude){
mLongitude = longitude;
getLocation();
}
public Location getLocation ()
{
Location myLocation = new Location ("gps");
myLocation.setLatitude(mLatitude);
myLocation.setLongitude(mLongitude);
myLocation.setAltitude(mAltitude);
return myLocation;
}
public void setAltitude(float altitude){
mAltitude = (double) altitude;
getLocation();
}
public void setSince (String since)
{
mSince = since;
}
public String getSince ()
{
return mSince;
}
public void setExternalInfo (ExtenalInfo extInfo)
{
mExtInfo = extInfo;
}
public ExtenalInfo getExternalInfo ()
{
return mExtInfo;
}
public void setId(Integer id){
mId = id;
}
public void setRadius(Double radius){
mRadius = radius;
}
public void setPosition_since(String position_since){
mPosition_since = position_since;
}
//uploader info
public void setUser_id(Integer user_id){
mUser_id = user_id;
}
public void setUsername(String username){
mUsername = username;
}
public String getUsername(){
return mUsername;
}
public Integer getUser_id(){
return mUser_id;
}
}
| gpl-3.0 |
sysnetlab/SensorDataCollector | SensorDataCollector/src/sysnetlab/android/sdc/ui/fragments/ExperimentEditTagsFragment.java | 5647 | /*
* Copyright (c) 2014, the SenSee authors. Please see the AUTHORS file
* for details.
*
* Licensed under the GNU Public License, Version 3.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.gnu.org/copyleft/gpl.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sysnetlab.android.sdc.ui.fragments;
import java.util.ArrayList;
import sysnetlab.android.sdc.R;
import sysnetlab.android.sdc.datacollector.Tag;
import sysnetlab.android.sdc.ui.CreateExperimentActivity;
import sysnetlab.android.sdc.ui.ViewExperimentActivity;
import sysnetlab.android.sdc.ui.adapters.TagListAdapter;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.app.Activity;
public class ExperimentEditTagsFragment extends Fragment {
private OnFragmentClickListener mCallback;
private View mView;
private TagListAdapter mTagListAdapter;
public interface OnFragmentClickListener {
public boolean onBtnAddTagClicked_ExperimentEditTagsFragment(String strTag,
String strDescription);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO: handle configuration changes
mView = inflater.inflate(R.layout.fragment_experiment_tag_editing, container, false);
ListView lv = (ListView) mView.findViewById(R.id.listview_tags);
ArrayList<Tag> tmpTags;
Activity activity = getActivity();
if (activity instanceof CreateExperimentActivity) {
tmpTags = (ArrayList<Tag>) ((CreateExperimentActivity) activity).getExperiment()
.getTags();
} else {
tmpTags = (ArrayList<Tag>) ((ViewExperimentActivity) activity).getExperiment()
.getTags();
}
mTagListAdapter = new TagListAdapter(activity, tmpTags);
Log.d("SensorDataCollector", "ExperimentEditTagsFragment.onCreateView: tmpTags = "
+ tmpTags);
Log.d("SensorDataCollector", "ExperimentEditTagsFragment.onCreateView: lv = " + lv);
Log.d("SensorDataCollector", "ExperimentEditTagsFragment.onCreateView: adapter = "
+ mTagListAdapter);
if (activity instanceof CreateExperimentActivity) {
lv.setAdapter(mTagListAdapter);
}
else
Log.d("SensorDataCollector", "not yet implemented for ViewExperimentActivity");
return mView;
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// TODO: handle configuration changes
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnFragmentClickListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentClickListener");
}
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
((Button) mView.findViewById(R.id.btn_add_tag))
.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("ExperimentEditTagsFragment", "Add Tag Clicked");
EditText editTextTag = (EditText) mView.findViewById(R.id.edittext_tag);
EditText editTextDescription = (EditText) mView
.findViewById(R.id.edittext_description);
if (mCallback.onBtnAddTagClicked_ExperimentEditTagsFragment(editTextTag
.getText().toString(),
editTextDescription.getText().toString()))
{
mTagListAdapter.notifyDataSetChanged();
editTextTag.setText("");
editTextDescription.setText("");
}
}
});
}
public ArrayAdapter<Tag> getTagListAdapter() {
return mTagListAdapter;
}
public boolean hasTags() {
String tagName = ((EditText) mView.findViewById(R.id.edittext_tag))
.getText().toString();
if (!tagName.trim().equals(""))
return true;
String tagDescription = ((EditText) mView.findViewById(R.id.edittext_description))
.getText().toString();
if (!tagDescription.trim().equals(""))
return true;
return false;
}
}
| gpl-3.0 |
jintli/ruhua | ruhua-common/src/main/java/com/ruhua/common/map/CoordinationUtil.java | 1723 | package com.ruhua.common.map;
import com.ruhua.domain.geo.Coordinate;
/**
* 坐标相关
* Created with IntelliJ IDEA.
* User: lijing3
* Date: 14-4-8
* Time: 上午9:35
* To change this template use File | Settings | File Templates.
*/
public class CoordinationUtil {
/**
* 坐标纠偏 从百度地图坐标系到腾讯地图(微信使用的是腾讯地图)
* @param baiduCoordination
* @return
*/
public static Coordinate rectifyFromBDToTC(Coordinate baiduCoordination) {
double pi = 3.14159265358979324 * 3000.0 / 180.0;
double lng = baiduCoordination.getLng() - 0.0065;
double lat = baiduCoordination.getLat() - 0.006;
double z = Math.sqrt(lng * lng + lat * lat) - 0.00002 * Math.sin(lat * pi);
double theta = Math.atan2(lat, lng) - 0.000003 * Math.cos(lng * pi);
double newLng = z * Math.cos(theta);
double newLat = z * Math.sin(theta);
return new Coordinate(newLng,newLat);
}
/**
* 坐标纠偏 从腾讯地图坐标系到百度地图(门店系统使用的是百度地图)
* @param tencentCoordination
* @return
*/
public static Coordinate rectifyFromTCToBD(Coordinate tencentCoordination) {
double pi = 3.14159265358979324 * 3000.0 / 180.0;
double lng = tencentCoordination.getLng();
double lat = tencentCoordination.getLat();
double z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * pi);
double theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * pi);
double newLng = z * Math.cos(theta) + 0.0065;
double newLat = z * Math.sin(theta) + 0.006;
return new Coordinate(newLng,newLat);
}
}
| gpl-3.0 |
sebkur/live-cg | project/src/main/java/de/topobyte/livecg/ui/misc/LicenseAction.java | 1256 | /* This file is part of LiveCG.
*
* Copyright (C) 2013 Sebastian Kuerten
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.topobyte.livecg.ui.misc;
import java.awt.event.ActionEvent;
import de.topobyte.swing.util.action.SimpleAction;
public class LicenseAction extends SimpleAction
{
public LicenseAction()
{
super("License", "Display the license of this sowftware");
setIcon("org/freedesktop/tango/22x22/status/dialog-information.png");
}
private static final long serialVersionUID = -3413663891048957511L;
@Override
public void actionPerformed(ActionEvent e)
{
AboutDialog.showDialog(AboutDialog.PAGE_LICENSE);
}
}
| gpl-3.0 |
baskerbill/Core | Core/android/Jumpers/src/jumpers/jump/SoundManager.java | 1063 | package jumpers.jump;
import java.util.HashMap;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
public class SoundManager {
SoundManager(){
}
private SoundPool mSoundPool;
private HashMap<Integer,Integer> mSoundPoolMap;
private AudioManager mAudioManager;
private Context mContext;
public void initSounds(Context theContext) {
mContext = theContext;
mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
mSoundPoolMap = new HashMap<Integer,Integer>();
mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
}
public void addSound(int index, int SoundID)
{
mSoundPoolMap.put(index, mSoundPool.load(mContext, SoundID, 1));
}
public void playSound(int index)
{
float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);
}
}
| gpl-3.0 |