blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1e4edef72c3e2f6a06a51615b4875c08478a81ef | 9,448,928,095,663 | ed7a75ad812aac464e60203fa1a577f03f38aedd | /src/main/java/com/betfair/caching/ReadAheadInvalidatingLRUCache.java | d3506f84d2eec8e17c00d11c34a11b1658da1585 | [
"Apache-2.0"
]
| permissive | eswdd/local-caching | https://github.com/eswdd/local-caching | eb947c2b1d190fb3d6f140213d65ed03bd5fc95f | 93049764e7b8efb78c0ae6909923c6a24aa55bf3 | refs/heads/master | 2020-12-13T21:47:21.522000 | 2014-05-29T21:53:03 | 2014-05-29T21:53:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.betfair.caching;
import com.google.common.base.Function;
import com.google.common.collect.MapMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
@ManagedResource
public class ReadAheadInvalidatingLRUCache<K, V> implements InspectableCache<K, V> {
private static final Logger log = LoggerFactory.getLogger(ReadAheadInvalidatingLRUCache.class);
private static final double HARD_CAP_RATIO = 1.1;
private static final Object ACTIVE_KEY = new Object();
private static final Object INVALIDATED_KEY = new Object();
private static final Object WRITTEN_KEY = new Object();
private static InvalidatingLRUCache.TimeProvider timeProvider = new InvalidatingLRUCache.TimeProvider();
private static final Timer pruneTimer = new Timer("PruneServiceTimer", true);
private static final long MILLI_TO_NANO = 1000000L;
private final ConcurrentMap<K, ValueHolder<V>> map;
private final long ttl;
private final Loader<K, V> loader;
private final String name;
private final boolean pruning;
private AtomicLong pruneFrom;
private AtomicLong pruneTo;
private final int pruneInterval;
private final ReadAheadService readAheadService;
private final int bulkLoadCount;
private Date lastPruneTime;
private long lastPruneDuration;
private long lastPruneRemovals;
private PruneCommand pruneTask;
private final AtomicLong pruneCount = new AtomicLong();
private final AtomicLong forcedPruneCount = new AtomicLong();
private final AtomicLong clearCount = new AtomicLong();
private final AtomicLong invalidationCount = new AtomicLong();
private final AtomicLong hits = new AtomicLong();
private final AtomicLong misses = new AtomicLong();
private final AtomicLong readthroughMisses = new AtomicLong();
private final AtomicLong reloadOnInvalidationCount = new AtomicLong();
/**
* Constructs a read-through cache, no pruning, no read-ahead.
*
* @param name cache name
* @param loader a loader
* @param ttl time records will be stored for/expired after
*/
public ReadAheadInvalidatingLRUCache(String name, Loader<K, V> loader, long ttl) {
this(name, loader, ttl, 0, 0, 0, null, 0);
}
/**
* Constructs a read-through cache, no pruning, but with read-ahead services.
* <p/>
* <p>Like in Coherence, the read-ahead time is configured as a percentage of the entry's
* expiration time; for instance, if specified as 0.75, an entry with a one minute
* expiration time that is accessed within fifteen seconds of its expiration will
* be scheduled for an asynchronous reload.
* <p/>
* <p>ExecutorService instance must be supplied for asynchronous read-ahead threads as
* it might be shared between different cache instances
*
* @param name cache name
* @param loader a loader
* @param ttl time records will be stored for/expired after
* @param readAheadService an executor service for asynchronous read-ahead threads
* @param readAheadRatio a read-ahead ratio of records' TTL
*/
public ReadAheadInvalidatingLRUCache(String name, Loader<K, V> loader, long ttl,
ExecutorService readAheadService, double readAheadRatio) {
this(name, loader, ttl, 0, 0, 0, readAheadService, readAheadRatio);
}
/**
* Constructs a read-through cache, with pruning, but no read-ahead service.
* Prune logic is to evict least recently accessed records.
* <p/>
* <p>ExecutorService instance must be supplied for pruning as it might be shared
* between different cache instances
*
* @param name cache name
* @param loader a loader
* @param ttl time records will be stored for/expired after
* @param pruneInterval prune interval
* @param pruneFrom prune if cache's size is bigger than this param
* @param pruneTo prune cache to this size
*/
public ReadAheadInvalidatingLRUCache(String name, Loader<K, V> loader, long ttl,
int pruneInterval, int pruneFrom, int pruneTo) {
this(name, loader, ttl, pruneInterval, pruneFrom, pruneTo, null, 0);
}
/**
* Constructs a read-through cache, with both pruning and read-ahead services.
* <p/>
* <p>Prune logic is to evict least recently accessed records.
* <p/>
* <p>Like in Coherence, the read-ahead time is configured as a percentage of the entry's
* expiration time; for instance, if specified as 0.75, an entry with a one minute
* expiration time that is accessed within fifteen seconds of its expiration will
* be scheduled for an asynchronous reload.
* <p/>
* <p>ExecutorService instance must be supplied for asynchronous read-ahead threads
* as it might be shared between different cache instances
*
* @param name cache name
* @param loader a loader
* @param ttl time records will be stored for/ expired after
* @param pruneInterval prune interval
* @param pruneFrom prune if cache's size is bigger than this param
* @param pruneTo prune cache to this size
* @param svc an executor service for asynchronous read-ahead threads
* @param readAheadRatio a read-ahead ratio of records' TTL
*/
public ReadAheadInvalidatingLRUCache(String name, Loader<K, V> loader, long ttl,
int pruneInterval, int pruneFrom, int pruneTo,
ExecutorService svc, double readAheadRatio) {
if (loader == null) throw new IllegalArgumentException("Loader is null");
this.name = name;
this.ttl = ttl;
this.loader = loader;
this.readAheadService = new ReadAheadService(svc, ttl, readAheadRatio, loader);
Function<K, ValueHolder<V>> readthrough = new Function<K, ValueHolder<V>>() {
@Override
public ValueHolder<V> apply(K key) {
misses.incrementAndGet();
readAheadService.invalidateInflightRead(key); // not interested in read aheads for this key
V value = ReadAheadInvalidatingLRUCache.this.loader.load(key);
if (value == null) {
readthroughMisses.incrementAndGet();
}
return new ValueHolder<V>(value, true);
}
};
MapMaker mapMaker = new MapMaker();
if (ttl != 0) {
mapMaker.expiration(ttl, TimeUnit.MILLISECONDS);
}
map = mapMaker.makeComputingMap(readthrough);
log.info("Creating LRU cache (" + name + ") with expiry:" + ttl +
", prune interval:" + pruneInterval + ", prune from:" + pruneFrom + ", prune to:" + pruneTo +
", read-ahead service:" + svc + ", read-ahead ratio:" + readAheadRatio);
if (this.loader.isBulkLoadSupported()) {
long time = System.currentTimeMillis();
Map<K, V> initialData = this.loader.bulkLoad();
for (Map.Entry<K, V> entry : initialData.entrySet()) {
map.put(entry.getKey(), new ValueHolder<V>(entry.getValue(), false));
}
time = System.currentTimeMillis() - time;
bulkLoadCount = initialData.size();
log.info("Bulk loaded cache ({}) with {} entries in {} milliseconds", new Object[]{name, bulkLoadCount, time});
} else {
bulkLoadCount = 0;
}
this.pruneFrom = new AtomicLong(pruneFrom);
this.pruneTo = new AtomicLong(pruneTo);
this.pruneInterval = pruneInterval;
if (pruneInterval > 0 && pruneFrom > pruneTo && pruneTo > 0) {
this.pruneTask = new PruneCommand();
pruneTimer.scheduleAtFixedRate(pruneTask, pruneInterval, pruneInterval);
pruning = true;
} else {
pruning = false;
}
}
public void shutdown() {
if (pruneTimer != null) {
pruneTimer.cancel();
}
}
// Mostly for testing.
public void prune() {
if (pruneTo.get() > 0) {
new PruneCommand().run();
} else {
throw new IllegalArgumentException("Invalid pruneTo value:" + pruneTo);
}
}
/**
* Retrieves a value from the cache for a key.
* Loads a value if needed, and blocks if value is being loaded by another thread.
* Additionally might fire a read-ahead request to reload value for the key supplied.
*
* @param key a key
* @return a value
*/
public V get(K key) {
ValueHolder<V> holder = map.get(key);
long nanoTime = timeProvider.getNanoTime();
if (!holder.firstLoad.getAndSet(false)) {
hits.incrementAndGet();
// if it wasn't a first load i.e. it wasn't a read-through
// then we request async reload
if (readAheadService.enabled && (nanoTime - holder.loadTime >= readAheadService.readAheadMargin)) {
readAheadService.scheduleReload(key);
}
}
holder.lastAccess = nanoTime;
checkSizeAndPrune();
return holder.value;
}
public Map<K, V> getAll(Collection<K> key) {
Map<K, V> result = new HashMap<K, V>();
for (K keyVar : key) {
result.put(keyVar, this.get(keyVar));
}
return result;
}
@Override
public boolean containsKey(K key) {
return map.containsKey(key);
}
@Override
public boolean invalidate(K key) {
invalidationCount.incrementAndGet();
if (map.containsKey(key)) {
readAheadService.invalidateInflightRead(key);
return loadKey(key);
}
return false;
}
@Override
@ManagedOperation
public int invalidateAll() {
int oldSize = map.size();
readAheadService.invalidateAllInflightReads();
for (K k : map.keySet()) {
loadKey(k);
}
// May not be 100% accurate as the map could have mutated between the
// size and clear calls.
clearCount.incrementAndGet();
return oldSize;
}
private boolean loadKey(K key) {
reloadOnInvalidationCount.incrementAndGet();
if (isReadAheadEnabled()) {
// Do it on the read ahead service
readAheadService.scheduleReload(key);
return true;
} else {
// Do it on the thread invoking invalidation
V value = ReadAheadInvalidatingLRUCache.this.loader.load(key);
return (map.put(key, new ValueHolder<V>(value, false)) != null);
}
}
/**
* {@code ReadAheadService} submits a task to refresh value for a key
* taking into account last accessed time and read-ahead ratio,
* but ignores a request if there is already a refresh task submitted
* for that key.
* <p/>
* <p>Like in Coherence, the read-ahead time is configured as a percentage of the entry's
* expiration time; for instance, if specified as 0.75, an entry with a one minute
* expiration time that is accessed within fifteen seconds of its expiration will
* be scheduled for an asynchronous reload.
*/
private class ReadAheadService {
private final long readAheadMargin;
private final ExecutorService threadPool;
private volatile ConcurrentMap<K, Object> readAheadRegistry = new ConcurrentHashMap<K, Object>();
private final boolean enabled;
private final AtomicLong readAheadRequests = new AtomicLong();
private final AtomicLong readAheadMisses = new AtomicLong();
private final AtomicLong inflightReadsInvalidated = new AtomicLong();
private final AtomicLong clearAllInflightReads = new AtomicLong();
/**
* Creates a new instance
*
* @param threadPool an ExecutorService to submit tasks to,
* @param ttl expiration period for entries in cache
* @param readAheadRatio read-ahead ratio, must belong to [0,1) range
*/
private ReadAheadService(ExecutorService threadPool, long ttl, double readAheadRatio, Loader loader) {
if (readAheadRatio >= 1 || readAheadRatio < 0)
throw new IllegalArgumentException("ReadAheadRatio must belong to [0,1) range");
this.readAheadMargin = Math.round(ttl * readAheadRatio) * MILLI_TO_NANO;
this.threadPool = threadPool;
this.enabled = threadPool != null && ttl > 0 && readAheadRatio > 0;
}
/**
* Submits a reload task for a key if:
* <p/>
* <ol>
* <li>read ahead service is enabled,</li>
* <li>there is no task submitted already for this key</li>
* <li>and current time is within read ahead period, i.e.close enough to entry's expiration time</li>
* </ol>
*
* @param key a key
*/
public void scheduleReload(final K key) {
if (enabled && readAheadRegistry.putIfAbsent(key, ACTIVE_KEY) == null) {
readAheadRequests.incrementAndGet();
threadPool.submit(new Runnable() {
@Override
public void run() {
try {
applyNewKey(key, loader.load(key));
} finally {
readAheadRegistry.remove(key);
}
}
});
}
}
private void applyNewKey(K key, V value) {
try {
if (value == null) {
readAheadMisses.incrementAndGet();
}
if (readAheadRegistry.replace(key, ACTIVE_KEY, WRITTEN_KEY) && value != null) {
map.put(key, new ValueHolder<V>(value, false));
}
} finally {
readAheadRegistry.remove(key);
}
}
/**
* invalidate any in flight reads if the key is being queued for readahead
*
* @param key a key
*/
public void invalidateInflightRead(final K key) {
if (enabled) {
if (readAheadRegistry.remove(key, ACTIVE_KEY)) {
inflightReadsInvalidated.incrementAndGet();
}
}
}
/**
* Remove all keys in the queue
*/
public void invalidateAllInflightReads() {
if (enabled) {
clearAllInflightReads.incrementAndGet();
// Zap everything in the registry
readAheadRegistry.clear();
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
// cache pruning
//////////////////////////////////////////////////////////////////////////////////////
private class PruneCommand extends TimerTask {
private AtomicBoolean running = new AtomicBoolean(false);
@Override
public void run() {
if (!running.getAndSet(true)) {
try {
int removals = 0;
long pruneFrom = ReadAheadInvalidatingLRUCache.this.pruneFrom.get();
long pruneTo = ReadAheadInvalidatingLRUCache.this.pruneTo.get();
if (map.size() > pruneFrom) {
lastPruneTime = new Date();
pruneCount.incrementAndGet();
long timeTaken = -timeProvider.getNanoTime();
// We create a sorted set of the current cache
List<LRUInfo> lru = new ArrayList<LRUInfo>();
for (Map.Entry<K, ValueHolder<V>> e : map.entrySet()) {
lru.add(new LRUInfo(e.getValue().lastAccess, e.getKey()));
}
Collections.sort(lru);
// and remove until we get to the target size
long numToPrune = lru.size() - pruneTo;
for (int i = 0; i < numToPrune; i++) {
map.remove(lru.get(i).key);
++removals;
}
timeTaken += timeProvider.getNanoTime();
lastPruneRemovals = removals;
lastPruneDuration = timeTaken / 1000;
}
} finally {
running.set(false);
}
}
}
}
private class LRUInfo implements Comparable<LRUInfo> {
final long lastAccess;
final K key;
public LRUInfo(long lastAccess, K key) {
this.lastAccess = lastAccess;
this.key = key;
}
public int compareTo(LRUInfo o) {
long thisVal = this.lastAccess;
long anotherVal = o.lastAccess;
return (thisVal < anotherVal ? -1 : (thisVal == anotherVal ? 0 : 1));
}
}
/**
* Checks if current cache size is bigger than {@link com.betfair.caching.ReadAheadInvalidatingLRUCache#HARD_CAP_RATIO} * pruneFrom and
* does pruning in current thread.
*/
private void checkSizeAndPrune() {
if (pruneFrom.get() != 0 && pruneTask != null) {
if (this.map.size() > this.pruneFrom.get() * HARD_CAP_RATIO) {
forcedPruneCount.incrementAndGet();
this.pruneTask.run();
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
// value holder
//////////////////////////////////////////////////////////////////////////////////////
private static final class ValueHolder<V> implements Comparable<ValueHolder<V>> {
final long loadTime = timeProvider.getNanoTime();
volatile long lastAccess = loadTime;
final AtomicBoolean firstLoad;
final V value;
public ValueHolder(V value, boolean fromReadThrough) {
this.value = value;
firstLoad = new AtomicBoolean(fromReadThrough);
}
@Override
public int compareTo(ValueHolder<V> o) {
return (lastAccess < o.lastAccess ? -1 : (lastAccess == o.lastAccess ? 0 : 1));
}
}
//////////////////////////////////////////////////////////////////////////////////////
// JMX
// ////////////////////////////////////////////////////////////////////////////////////
@ManagedOperation
public void resetStats() {
this.lastPruneTime = null;
lastPruneDuration = 0;
lastPruneRemovals = 0;
pruneCount.set(0);
clearCount.set(0);
invalidationCount.set(0);
hits.set(0);
misses.set(0);
readthroughMisses.set(0);
readAheadService.readAheadRequests.set(0);
readAheadService.readAheadMisses.set(0);
readAheadService.inflightReadsInvalidated.set(0);
readAheadService.clearAllInflightReads.set(0);
reloadOnInvalidationCount.set(0);
}
@ManagedAttribute
public long getClearCount() {
return clearCount.get();
}
@ManagedAttribute
public long getInvalidationCount() {
return invalidationCount.get();
}
@ManagedAttribute
public int getSize() {
return map.size();
}
@ManagedAttribute
public long getHits() {
return hits.get();
}
@ManagedAttribute
public long getMisses() {
return misses.get();
}
@ManagedAttribute
public long getReadthroughMisses() {
return readthroughMisses.get();
}
@ManagedAttribute
public long getReadAheadRequests() {
return readAheadService.readAheadRequests.get();
}
@ManagedAttribute
public long getReadAheadMisses() {
return readAheadService.readAheadMisses.get();
}
@ManagedAttribute
public long getReadAheadQueueSize() {
return readAheadService.readAheadRegistry.size();
}
@ManagedAttribute
public long getReadAheadMargin() {
return readAheadService.readAheadMargin / MILLI_TO_NANO;
}
@ManagedAttribute
public boolean isReadAheadEnabled() {
return readAheadService.enabled;
}
@ManagedAttribute
public long getInflightReadAheadsInvalidated() {
return readAheadService.inflightReadsInvalidated.get();
}
@ManagedAttribute
public long getInflightReadAheadsCleared() {
return readAheadService.clearAllInflightReads.get();
}
@ManagedAttribute
public long getPruneCount() {
return pruneCount.get();
}
@ManagedAttribute
public long getForcedPruneCount() {
return forcedPruneCount.get();
}
@ManagedAttribute
public long getTtl() {
return ttl;
}
@ManagedAttribute
public String getName() {
return name;
}
@ManagedAttribute
public boolean isPruning() {
return pruning;
}
@ManagedAttribute
public long getPruneFrom() {
return pruneFrom.get();
}
@ManagedAttribute
public long getPruneTo() {
return pruneTo.get();
}
@ManagedAttribute
public void setPruneFrom(long newValue) {
this.pruneFrom.set(newValue);
}
@ManagedAttribute
public void setPruneTo(long newValue) {
this.pruneTo.set(newValue);
}
@ManagedAttribute
public int getPruneInterval() {
return pruneInterval;
}
@ManagedAttribute
public Date getLastPruneTime() {
return lastPruneTime;
}
@ManagedAttribute(description = "last prune duration in microseconds")
public long getLastPruneDuration() {
return lastPruneDuration;
}
@ManagedAttribute
public long getLastPruneRemovals() {
return lastPruneRemovals;
}
@ManagedAttribute
public int getBulkLoadCount() {
return bulkLoadCount;
}
@ManagedAttribute
public long getReloadOnInvalidationCount() {
return reloadOnInvalidationCount.get();
}
//--- for testing purposes only
static void setTimeProvider(InvalidatingLRUCache.TimeProvider tp) {
timeProvider = tp;
}
}
| UTF-8 | Java | 23,004 | java | ReadAheadInvalidatingLRUCache.java | Java | []
| null | []
| package com.betfair.caching;
import com.google.common.base.Function;
import com.google.common.collect.MapMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
@ManagedResource
public class ReadAheadInvalidatingLRUCache<K, V> implements InspectableCache<K, V> {
private static final Logger log = LoggerFactory.getLogger(ReadAheadInvalidatingLRUCache.class);
private static final double HARD_CAP_RATIO = 1.1;
private static final Object ACTIVE_KEY = new Object();
private static final Object INVALIDATED_KEY = new Object();
private static final Object WRITTEN_KEY = new Object();
private static InvalidatingLRUCache.TimeProvider timeProvider = new InvalidatingLRUCache.TimeProvider();
private static final Timer pruneTimer = new Timer("PruneServiceTimer", true);
private static final long MILLI_TO_NANO = 1000000L;
private final ConcurrentMap<K, ValueHolder<V>> map;
private final long ttl;
private final Loader<K, V> loader;
private final String name;
private final boolean pruning;
private AtomicLong pruneFrom;
private AtomicLong pruneTo;
private final int pruneInterval;
private final ReadAheadService readAheadService;
private final int bulkLoadCount;
private Date lastPruneTime;
private long lastPruneDuration;
private long lastPruneRemovals;
private PruneCommand pruneTask;
private final AtomicLong pruneCount = new AtomicLong();
private final AtomicLong forcedPruneCount = new AtomicLong();
private final AtomicLong clearCount = new AtomicLong();
private final AtomicLong invalidationCount = new AtomicLong();
private final AtomicLong hits = new AtomicLong();
private final AtomicLong misses = new AtomicLong();
private final AtomicLong readthroughMisses = new AtomicLong();
private final AtomicLong reloadOnInvalidationCount = new AtomicLong();
/**
* Constructs a read-through cache, no pruning, no read-ahead.
*
* @param name cache name
* @param loader a loader
* @param ttl time records will be stored for/expired after
*/
public ReadAheadInvalidatingLRUCache(String name, Loader<K, V> loader, long ttl) {
this(name, loader, ttl, 0, 0, 0, null, 0);
}
/**
* Constructs a read-through cache, no pruning, but with read-ahead services.
* <p/>
* <p>Like in Coherence, the read-ahead time is configured as a percentage of the entry's
* expiration time; for instance, if specified as 0.75, an entry with a one minute
* expiration time that is accessed within fifteen seconds of its expiration will
* be scheduled for an asynchronous reload.
* <p/>
* <p>ExecutorService instance must be supplied for asynchronous read-ahead threads as
* it might be shared between different cache instances
*
* @param name cache name
* @param loader a loader
* @param ttl time records will be stored for/expired after
* @param readAheadService an executor service for asynchronous read-ahead threads
* @param readAheadRatio a read-ahead ratio of records' TTL
*/
public ReadAheadInvalidatingLRUCache(String name, Loader<K, V> loader, long ttl,
ExecutorService readAheadService, double readAheadRatio) {
this(name, loader, ttl, 0, 0, 0, readAheadService, readAheadRatio);
}
/**
* Constructs a read-through cache, with pruning, but no read-ahead service.
* Prune logic is to evict least recently accessed records.
* <p/>
* <p>ExecutorService instance must be supplied for pruning as it might be shared
* between different cache instances
*
* @param name cache name
* @param loader a loader
* @param ttl time records will be stored for/expired after
* @param pruneInterval prune interval
* @param pruneFrom prune if cache's size is bigger than this param
* @param pruneTo prune cache to this size
*/
public ReadAheadInvalidatingLRUCache(String name, Loader<K, V> loader, long ttl,
int pruneInterval, int pruneFrom, int pruneTo) {
this(name, loader, ttl, pruneInterval, pruneFrom, pruneTo, null, 0);
}
/**
* Constructs a read-through cache, with both pruning and read-ahead services.
* <p/>
* <p>Prune logic is to evict least recently accessed records.
* <p/>
* <p>Like in Coherence, the read-ahead time is configured as a percentage of the entry's
* expiration time; for instance, if specified as 0.75, an entry with a one minute
* expiration time that is accessed within fifteen seconds of its expiration will
* be scheduled for an asynchronous reload.
* <p/>
* <p>ExecutorService instance must be supplied for asynchronous read-ahead threads
* as it might be shared between different cache instances
*
* @param name cache name
* @param loader a loader
* @param ttl time records will be stored for/ expired after
* @param pruneInterval prune interval
* @param pruneFrom prune if cache's size is bigger than this param
* @param pruneTo prune cache to this size
* @param svc an executor service for asynchronous read-ahead threads
* @param readAheadRatio a read-ahead ratio of records' TTL
*/
public ReadAheadInvalidatingLRUCache(String name, Loader<K, V> loader, long ttl,
int pruneInterval, int pruneFrom, int pruneTo,
ExecutorService svc, double readAheadRatio) {
if (loader == null) throw new IllegalArgumentException("Loader is null");
this.name = name;
this.ttl = ttl;
this.loader = loader;
this.readAheadService = new ReadAheadService(svc, ttl, readAheadRatio, loader);
Function<K, ValueHolder<V>> readthrough = new Function<K, ValueHolder<V>>() {
@Override
public ValueHolder<V> apply(K key) {
misses.incrementAndGet();
readAheadService.invalidateInflightRead(key); // not interested in read aheads for this key
V value = ReadAheadInvalidatingLRUCache.this.loader.load(key);
if (value == null) {
readthroughMisses.incrementAndGet();
}
return new ValueHolder<V>(value, true);
}
};
MapMaker mapMaker = new MapMaker();
if (ttl != 0) {
mapMaker.expiration(ttl, TimeUnit.MILLISECONDS);
}
map = mapMaker.makeComputingMap(readthrough);
log.info("Creating LRU cache (" + name + ") with expiry:" + ttl +
", prune interval:" + pruneInterval + ", prune from:" + pruneFrom + ", prune to:" + pruneTo +
", read-ahead service:" + svc + ", read-ahead ratio:" + readAheadRatio);
if (this.loader.isBulkLoadSupported()) {
long time = System.currentTimeMillis();
Map<K, V> initialData = this.loader.bulkLoad();
for (Map.Entry<K, V> entry : initialData.entrySet()) {
map.put(entry.getKey(), new ValueHolder<V>(entry.getValue(), false));
}
time = System.currentTimeMillis() - time;
bulkLoadCount = initialData.size();
log.info("Bulk loaded cache ({}) with {} entries in {} milliseconds", new Object[]{name, bulkLoadCount, time});
} else {
bulkLoadCount = 0;
}
this.pruneFrom = new AtomicLong(pruneFrom);
this.pruneTo = new AtomicLong(pruneTo);
this.pruneInterval = pruneInterval;
if (pruneInterval > 0 && pruneFrom > pruneTo && pruneTo > 0) {
this.pruneTask = new PruneCommand();
pruneTimer.scheduleAtFixedRate(pruneTask, pruneInterval, pruneInterval);
pruning = true;
} else {
pruning = false;
}
}
public void shutdown() {
if (pruneTimer != null) {
pruneTimer.cancel();
}
}
// Mostly for testing.
public void prune() {
if (pruneTo.get() > 0) {
new PruneCommand().run();
} else {
throw new IllegalArgumentException("Invalid pruneTo value:" + pruneTo);
}
}
/**
* Retrieves a value from the cache for a key.
* Loads a value if needed, and blocks if value is being loaded by another thread.
* Additionally might fire a read-ahead request to reload value for the key supplied.
*
* @param key a key
* @return a value
*/
public V get(K key) {
ValueHolder<V> holder = map.get(key);
long nanoTime = timeProvider.getNanoTime();
if (!holder.firstLoad.getAndSet(false)) {
hits.incrementAndGet();
// if it wasn't a first load i.e. it wasn't a read-through
// then we request async reload
if (readAheadService.enabled && (nanoTime - holder.loadTime >= readAheadService.readAheadMargin)) {
readAheadService.scheduleReload(key);
}
}
holder.lastAccess = nanoTime;
checkSizeAndPrune();
return holder.value;
}
public Map<K, V> getAll(Collection<K> key) {
Map<K, V> result = new HashMap<K, V>();
for (K keyVar : key) {
result.put(keyVar, this.get(keyVar));
}
return result;
}
@Override
public boolean containsKey(K key) {
return map.containsKey(key);
}
@Override
public boolean invalidate(K key) {
invalidationCount.incrementAndGet();
if (map.containsKey(key)) {
readAheadService.invalidateInflightRead(key);
return loadKey(key);
}
return false;
}
@Override
@ManagedOperation
public int invalidateAll() {
int oldSize = map.size();
readAheadService.invalidateAllInflightReads();
for (K k : map.keySet()) {
loadKey(k);
}
// May not be 100% accurate as the map could have mutated between the
// size and clear calls.
clearCount.incrementAndGet();
return oldSize;
}
private boolean loadKey(K key) {
reloadOnInvalidationCount.incrementAndGet();
if (isReadAheadEnabled()) {
// Do it on the read ahead service
readAheadService.scheduleReload(key);
return true;
} else {
// Do it on the thread invoking invalidation
V value = ReadAheadInvalidatingLRUCache.this.loader.load(key);
return (map.put(key, new ValueHolder<V>(value, false)) != null);
}
}
/**
* {@code ReadAheadService} submits a task to refresh value for a key
* taking into account last accessed time and read-ahead ratio,
* but ignores a request if there is already a refresh task submitted
* for that key.
* <p/>
* <p>Like in Coherence, the read-ahead time is configured as a percentage of the entry's
* expiration time; for instance, if specified as 0.75, an entry with a one minute
* expiration time that is accessed within fifteen seconds of its expiration will
* be scheduled for an asynchronous reload.
*/
private class ReadAheadService {
private final long readAheadMargin;
private final ExecutorService threadPool;
private volatile ConcurrentMap<K, Object> readAheadRegistry = new ConcurrentHashMap<K, Object>();
private final boolean enabled;
private final AtomicLong readAheadRequests = new AtomicLong();
private final AtomicLong readAheadMisses = new AtomicLong();
private final AtomicLong inflightReadsInvalidated = new AtomicLong();
private final AtomicLong clearAllInflightReads = new AtomicLong();
/**
* Creates a new instance
*
* @param threadPool an ExecutorService to submit tasks to,
* @param ttl expiration period for entries in cache
* @param readAheadRatio read-ahead ratio, must belong to [0,1) range
*/
private ReadAheadService(ExecutorService threadPool, long ttl, double readAheadRatio, Loader loader) {
if (readAheadRatio >= 1 || readAheadRatio < 0)
throw new IllegalArgumentException("ReadAheadRatio must belong to [0,1) range");
this.readAheadMargin = Math.round(ttl * readAheadRatio) * MILLI_TO_NANO;
this.threadPool = threadPool;
this.enabled = threadPool != null && ttl > 0 && readAheadRatio > 0;
}
/**
* Submits a reload task for a key if:
* <p/>
* <ol>
* <li>read ahead service is enabled,</li>
* <li>there is no task submitted already for this key</li>
* <li>and current time is within read ahead period, i.e.close enough to entry's expiration time</li>
* </ol>
*
* @param key a key
*/
public void scheduleReload(final K key) {
if (enabled && readAheadRegistry.putIfAbsent(key, ACTIVE_KEY) == null) {
readAheadRequests.incrementAndGet();
threadPool.submit(new Runnable() {
@Override
public void run() {
try {
applyNewKey(key, loader.load(key));
} finally {
readAheadRegistry.remove(key);
}
}
});
}
}
private void applyNewKey(K key, V value) {
try {
if (value == null) {
readAheadMisses.incrementAndGet();
}
if (readAheadRegistry.replace(key, ACTIVE_KEY, WRITTEN_KEY) && value != null) {
map.put(key, new ValueHolder<V>(value, false));
}
} finally {
readAheadRegistry.remove(key);
}
}
/**
* invalidate any in flight reads if the key is being queued for readahead
*
* @param key a key
*/
public void invalidateInflightRead(final K key) {
if (enabled) {
if (readAheadRegistry.remove(key, ACTIVE_KEY)) {
inflightReadsInvalidated.incrementAndGet();
}
}
}
/**
* Remove all keys in the queue
*/
public void invalidateAllInflightReads() {
if (enabled) {
clearAllInflightReads.incrementAndGet();
// Zap everything in the registry
readAheadRegistry.clear();
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
// cache pruning
//////////////////////////////////////////////////////////////////////////////////////
private class PruneCommand extends TimerTask {
private AtomicBoolean running = new AtomicBoolean(false);
@Override
public void run() {
if (!running.getAndSet(true)) {
try {
int removals = 0;
long pruneFrom = ReadAheadInvalidatingLRUCache.this.pruneFrom.get();
long pruneTo = ReadAheadInvalidatingLRUCache.this.pruneTo.get();
if (map.size() > pruneFrom) {
lastPruneTime = new Date();
pruneCount.incrementAndGet();
long timeTaken = -timeProvider.getNanoTime();
// We create a sorted set of the current cache
List<LRUInfo> lru = new ArrayList<LRUInfo>();
for (Map.Entry<K, ValueHolder<V>> e : map.entrySet()) {
lru.add(new LRUInfo(e.getValue().lastAccess, e.getKey()));
}
Collections.sort(lru);
// and remove until we get to the target size
long numToPrune = lru.size() - pruneTo;
for (int i = 0; i < numToPrune; i++) {
map.remove(lru.get(i).key);
++removals;
}
timeTaken += timeProvider.getNanoTime();
lastPruneRemovals = removals;
lastPruneDuration = timeTaken / 1000;
}
} finally {
running.set(false);
}
}
}
}
private class LRUInfo implements Comparable<LRUInfo> {
final long lastAccess;
final K key;
public LRUInfo(long lastAccess, K key) {
this.lastAccess = lastAccess;
this.key = key;
}
public int compareTo(LRUInfo o) {
long thisVal = this.lastAccess;
long anotherVal = o.lastAccess;
return (thisVal < anotherVal ? -1 : (thisVal == anotherVal ? 0 : 1));
}
}
/**
* Checks if current cache size is bigger than {@link com.betfair.caching.ReadAheadInvalidatingLRUCache#HARD_CAP_RATIO} * pruneFrom and
* does pruning in current thread.
*/
private void checkSizeAndPrune() {
if (pruneFrom.get() != 0 && pruneTask != null) {
if (this.map.size() > this.pruneFrom.get() * HARD_CAP_RATIO) {
forcedPruneCount.incrementAndGet();
this.pruneTask.run();
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
// value holder
//////////////////////////////////////////////////////////////////////////////////////
private static final class ValueHolder<V> implements Comparable<ValueHolder<V>> {
final long loadTime = timeProvider.getNanoTime();
volatile long lastAccess = loadTime;
final AtomicBoolean firstLoad;
final V value;
public ValueHolder(V value, boolean fromReadThrough) {
this.value = value;
firstLoad = new AtomicBoolean(fromReadThrough);
}
@Override
public int compareTo(ValueHolder<V> o) {
return (lastAccess < o.lastAccess ? -1 : (lastAccess == o.lastAccess ? 0 : 1));
}
}
//////////////////////////////////////////////////////////////////////////////////////
// JMX
// ////////////////////////////////////////////////////////////////////////////////////
@ManagedOperation
public void resetStats() {
this.lastPruneTime = null;
lastPruneDuration = 0;
lastPruneRemovals = 0;
pruneCount.set(0);
clearCount.set(0);
invalidationCount.set(0);
hits.set(0);
misses.set(0);
readthroughMisses.set(0);
readAheadService.readAheadRequests.set(0);
readAheadService.readAheadMisses.set(0);
readAheadService.inflightReadsInvalidated.set(0);
readAheadService.clearAllInflightReads.set(0);
reloadOnInvalidationCount.set(0);
}
@ManagedAttribute
public long getClearCount() {
return clearCount.get();
}
@ManagedAttribute
public long getInvalidationCount() {
return invalidationCount.get();
}
@ManagedAttribute
public int getSize() {
return map.size();
}
@ManagedAttribute
public long getHits() {
return hits.get();
}
@ManagedAttribute
public long getMisses() {
return misses.get();
}
@ManagedAttribute
public long getReadthroughMisses() {
return readthroughMisses.get();
}
@ManagedAttribute
public long getReadAheadRequests() {
return readAheadService.readAheadRequests.get();
}
@ManagedAttribute
public long getReadAheadMisses() {
return readAheadService.readAheadMisses.get();
}
@ManagedAttribute
public long getReadAheadQueueSize() {
return readAheadService.readAheadRegistry.size();
}
@ManagedAttribute
public long getReadAheadMargin() {
return readAheadService.readAheadMargin / MILLI_TO_NANO;
}
@ManagedAttribute
public boolean isReadAheadEnabled() {
return readAheadService.enabled;
}
@ManagedAttribute
public long getInflightReadAheadsInvalidated() {
return readAheadService.inflightReadsInvalidated.get();
}
@ManagedAttribute
public long getInflightReadAheadsCleared() {
return readAheadService.clearAllInflightReads.get();
}
@ManagedAttribute
public long getPruneCount() {
return pruneCount.get();
}
@ManagedAttribute
public long getForcedPruneCount() {
return forcedPruneCount.get();
}
@ManagedAttribute
public long getTtl() {
return ttl;
}
@ManagedAttribute
public String getName() {
return name;
}
@ManagedAttribute
public boolean isPruning() {
return pruning;
}
@ManagedAttribute
public long getPruneFrom() {
return pruneFrom.get();
}
@ManagedAttribute
public long getPruneTo() {
return pruneTo.get();
}
@ManagedAttribute
public void setPruneFrom(long newValue) {
this.pruneFrom.set(newValue);
}
@ManagedAttribute
public void setPruneTo(long newValue) {
this.pruneTo.set(newValue);
}
@ManagedAttribute
public int getPruneInterval() {
return pruneInterval;
}
@ManagedAttribute
public Date getLastPruneTime() {
return lastPruneTime;
}
@ManagedAttribute(description = "last prune duration in microseconds")
public long getLastPruneDuration() {
return lastPruneDuration;
}
@ManagedAttribute
public long getLastPruneRemovals() {
return lastPruneRemovals;
}
@ManagedAttribute
public int getBulkLoadCount() {
return bulkLoadCount;
}
@ManagedAttribute
public long getReloadOnInvalidationCount() {
return reloadOnInvalidationCount.get();
}
//--- for testing purposes only
static void setTimeProvider(InvalidatingLRUCache.TimeProvider tp) {
timeProvider = tp;
}
}
| 23,004 | 0.588419 | 0.585376 | 661 | 33.801815 | 28.486296 | 139 | false | false | 0 | 0 | 0 | 0 | 87 | 0.022605 | 0.493192 | false | false | 0 |
8a7a811a4ee99556be865c45fc40d909ab3cfc79 | 38,139,309,611,076 | e40fd48db20776021552c164776953906df9ac06 | /hw07-0036506181/src/test/java/hr/fer/zemris/java/custom/scripting/exec/ObjectMultistackTest.java | b384a9a50740076a54aec105de551a11a5d506af | []
| no_license | m43/fer-java-course | https://github.com/m43/fer-java-course | d5c816629414f19565994fb31520747baa608b79 | 6defab2db598d83f0ef19459a94cc1dae7cf580d | refs/heads/main | 2023-08-28T15:28:11.247000 | 2021-11-02T13:06:29 | 2021-11-02T13:07:28 | 423,845,897 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hr.fer.zemris.java.custom.scripting.exec;
import static org.junit.jupiter.api.Assertions.*;
import java.util.EmptyStackException;
import org.junit.jupiter.api.Test;
@SuppressWarnings("javadoc")
class ObjectMultistackTest {
@Test
void testPushOneElement() {
ObjectMultistack s = new ObjectMultistack();
s.push("key", new ValueWrapper(1));
}
@Test
void testPushMultipleElementsToSameKey() {
ObjectMultistack s = new ObjectMultistack();
s.push("key", new ValueWrapper(1));
s.push("key", new ValueWrapper(2));
s.push("key", new ValueWrapper(3));
s.push("key", new ValueWrapper(4));
}
@Test
void testPushToDifferentKeys() {
ObjectMultistack s = new ObjectMultistack();
s.push("key1", new ValueWrapper(1));
s.push("key2", new ValueWrapper(1));
s.push("key3", new ValueWrapper(1));
s.push("key4", new ValueWrapper(2));
s.push("key1", new ValueWrapper(1));
s.push("key2", new ValueWrapper(2));
s.push("key3keykey", new ValueWrapper(3));
s.push("????123", new ValueWrapper(4));
s.push("gsuydzfj;o", new ValueWrapper(1));
s.push("oooo", new ValueWrapper(2));
s.push("eee", new ValueWrapper(3));
s.push("0", new ValueWrapper(4));
}
@Test
void testPushAndPop() {
ObjectMultistack s = new ObjectMultistack();
s.push("key", new ValueWrapper(1));
assertNotNull(s.pop("key"));
}
@Test
void testPushAndPopMultiple() {
ObjectMultistack s = new ObjectMultistack();
s.push("key", new ValueWrapper(1));
s.push("key", new ValueWrapper(2));
s.push("key", new ValueWrapper(1));
s.push("key", new ValueWrapper(1));
assertNotNull(s.pop("key"));
assertNotNull(s.pop("key"));
assertNotNull(s.pop("key"));
assertNotNull(s.pop("key"));
}
@Test
void testPushThrowsWhenNullValuesGiven() {
ObjectMultistack s = new ObjectMultistack();
assertThrows(NullPointerException.class, () -> s.push("key", null));
assertThrows(NullPointerException.class, () -> s.push(null, new ValueWrapper(3)));
assertThrows(NullPointerException.class, () -> s.push(null, null));
}
@Test
void testPushDoesntThrowWhenNullIsWrapped() {
ObjectMultistack s = new ObjectMultistack();
s.push("key", new ValueWrapper(null));
}
@Test
void testPeek() {
ObjectMultistack s = new ObjectMultistack();
ValueWrapper v = new ValueWrapper(1);
s.push("key", v);
assertEquals(v, s.peek("key"));
}
@Test
void testPeekDoesntRemoveTheElement() {
ObjectMultistack s = new ObjectMultistack();
ValueWrapper v = new ValueWrapper(1);
s.push("key", v);
assertEquals(v, s.peek("key"));
assertEquals(v, s.peek("key"));
assertEquals(v, s.peek("key"));
}
@Test
void testPeekThrowsWhenEmpty() {
ObjectMultistack s = new ObjectMultistack();
assertThrows(EmptyStackException.class, () -> s.peek("wut"));
}
@Test
void testIsEmpty() {
ObjectMultistack s = new ObjectMultistack();
s.push("key", new ValueWrapper(1));
assertTrue(s.isEmpty("a"));
assertTrue(s.isEmpty("b"));
assertTrue(s.isEmpty("aea ofuhsdfilh assadf"));
assertFalse(s.isEmpty("key"));
}
@Test
void testIsEmptyAfterTheStackGotEmpty() {
ObjectMultistack s = new ObjectMultistack();
s.push("key", new ValueWrapper(1));
assertFalse(s.isEmpty("key"));
s.pop("key");
assertTrue(s.isEmpty("key"));
}
@Test
void testIsEmptyDoesntChangeStacks() {
ObjectMultistack s = new ObjectMultistack();
ValueWrapper v = new ValueWrapper(1);
s.push("key", v);
assertFalse(s.isEmpty("key"));
assertFalse(s.isEmpty("key"));
assertEquals(v, s.pop("key"));
;
assertTrue(s.isEmpty("key"));
assertTrue(s.isEmpty("key"));
}
@Test
void testIsEmptyThrowsWhenAskedForKeyNull() {
ObjectMultistack s = new ObjectMultistack();
assertThrows(NullPointerException.class, () -> s.isEmpty(null));
}
@Test
void testPop() {
ObjectMultistack s = new ObjectMultistack();
ValueWrapper v = new ValueWrapper(3);
s.push("key", v);
assertEquals(v, s.pop("key"));
}
@Test
void testPoppingMultipleElements() {
ObjectMultistack s = new ObjectMultistack();
ValueWrapper v1 = new ValueWrapper(1);
ValueWrapper v2 = new ValueWrapper(2);
ValueWrapper v3 = new ValueWrapper(34);
ValueWrapper v4 = new ValueWrapper(44);
s.push("key", v1);
s.push("key", v2);
s.push("key", v3);
s.push("key", v4);
s.push("key1", v4);
s.push("key1", v4);
assertEquals(v4, s.pop("key"));
assertEquals(v3, s.pop("key"));
assertEquals(v2, s.pop("key"));
assertEquals(v1, s.pop("key"));
assertEquals(v4, s.pop("key1"));
assertEquals(v4, s.pop("key1"));
}
@Test
void testPopThrowsWhenEmpty() {
ObjectMultistack s = new ObjectMultistack();
assertThrows(EmptyStackException.class, () -> s.pop("wut"));
}
@Test
void testComplicatedWorkflowWithMultistack() {
ObjectMultistack s = new ObjectMultistack();
ValueWrapper v1 = new ValueWrapper(1);
ValueWrapper v2 = new ValueWrapper(2);
ValueWrapper v3 = new ValueWrapper(3);
s.push("key1", v1);
s.push("key1", v2);
s.push("key1", v3);
s.push("key2", v3);
s.push("key2", v3);
s.push("key2", v3);
assertEquals(v3, s.peek("key1"));
assertEquals(v3, s.pop("key1"));
assertFalse(s.isEmpty("key1"));
assertEquals(v2, s.peek("key1"));
assertEquals(v2, s.pop("key1"));
assertFalse(s.isEmpty("key1"));
assertEquals(v1, s.peek("key1"));
assertEquals(v1, s.pop("key1"));
assertTrue(s.isEmpty("key1"));
assertEquals(v3, s.peek("key2"));
assertEquals(v3, s.pop("key2"));
assertFalse(s.isEmpty("key2"));
assertEquals(v3, s.peek("key2"));
assertEquals(v3, s.pop("key2"));
assertFalse(s.isEmpty("key2"));
assertEquals(v3, s.peek("key2"));
assertEquals(v3, s.pop("key2"));
assertTrue(s.isEmpty("key2"));
}
}
| UTF-8 | Java | 5,690 | java | ObjectMultistackTest.java | Java | []
| null | []
| package hr.fer.zemris.java.custom.scripting.exec;
import static org.junit.jupiter.api.Assertions.*;
import java.util.EmptyStackException;
import org.junit.jupiter.api.Test;
@SuppressWarnings("javadoc")
class ObjectMultistackTest {
@Test
void testPushOneElement() {
ObjectMultistack s = new ObjectMultistack();
s.push("key", new ValueWrapper(1));
}
@Test
void testPushMultipleElementsToSameKey() {
ObjectMultistack s = new ObjectMultistack();
s.push("key", new ValueWrapper(1));
s.push("key", new ValueWrapper(2));
s.push("key", new ValueWrapper(3));
s.push("key", new ValueWrapper(4));
}
@Test
void testPushToDifferentKeys() {
ObjectMultistack s = new ObjectMultistack();
s.push("key1", new ValueWrapper(1));
s.push("key2", new ValueWrapper(1));
s.push("key3", new ValueWrapper(1));
s.push("key4", new ValueWrapper(2));
s.push("key1", new ValueWrapper(1));
s.push("key2", new ValueWrapper(2));
s.push("key3keykey", new ValueWrapper(3));
s.push("????123", new ValueWrapper(4));
s.push("gsuydzfj;o", new ValueWrapper(1));
s.push("oooo", new ValueWrapper(2));
s.push("eee", new ValueWrapper(3));
s.push("0", new ValueWrapper(4));
}
@Test
void testPushAndPop() {
ObjectMultistack s = new ObjectMultistack();
s.push("key", new ValueWrapper(1));
assertNotNull(s.pop("key"));
}
@Test
void testPushAndPopMultiple() {
ObjectMultistack s = new ObjectMultistack();
s.push("key", new ValueWrapper(1));
s.push("key", new ValueWrapper(2));
s.push("key", new ValueWrapper(1));
s.push("key", new ValueWrapper(1));
assertNotNull(s.pop("key"));
assertNotNull(s.pop("key"));
assertNotNull(s.pop("key"));
assertNotNull(s.pop("key"));
}
@Test
void testPushThrowsWhenNullValuesGiven() {
ObjectMultistack s = new ObjectMultistack();
assertThrows(NullPointerException.class, () -> s.push("key", null));
assertThrows(NullPointerException.class, () -> s.push(null, new ValueWrapper(3)));
assertThrows(NullPointerException.class, () -> s.push(null, null));
}
@Test
void testPushDoesntThrowWhenNullIsWrapped() {
ObjectMultistack s = new ObjectMultistack();
s.push("key", new ValueWrapper(null));
}
@Test
void testPeek() {
ObjectMultistack s = new ObjectMultistack();
ValueWrapper v = new ValueWrapper(1);
s.push("key", v);
assertEquals(v, s.peek("key"));
}
@Test
void testPeekDoesntRemoveTheElement() {
ObjectMultistack s = new ObjectMultistack();
ValueWrapper v = new ValueWrapper(1);
s.push("key", v);
assertEquals(v, s.peek("key"));
assertEquals(v, s.peek("key"));
assertEquals(v, s.peek("key"));
}
@Test
void testPeekThrowsWhenEmpty() {
ObjectMultistack s = new ObjectMultistack();
assertThrows(EmptyStackException.class, () -> s.peek("wut"));
}
@Test
void testIsEmpty() {
ObjectMultistack s = new ObjectMultistack();
s.push("key", new ValueWrapper(1));
assertTrue(s.isEmpty("a"));
assertTrue(s.isEmpty("b"));
assertTrue(s.isEmpty("aea ofuhsdfilh assadf"));
assertFalse(s.isEmpty("key"));
}
@Test
void testIsEmptyAfterTheStackGotEmpty() {
ObjectMultistack s = new ObjectMultistack();
s.push("key", new ValueWrapper(1));
assertFalse(s.isEmpty("key"));
s.pop("key");
assertTrue(s.isEmpty("key"));
}
@Test
void testIsEmptyDoesntChangeStacks() {
ObjectMultistack s = new ObjectMultistack();
ValueWrapper v = new ValueWrapper(1);
s.push("key", v);
assertFalse(s.isEmpty("key"));
assertFalse(s.isEmpty("key"));
assertEquals(v, s.pop("key"));
;
assertTrue(s.isEmpty("key"));
assertTrue(s.isEmpty("key"));
}
@Test
void testIsEmptyThrowsWhenAskedForKeyNull() {
ObjectMultistack s = new ObjectMultistack();
assertThrows(NullPointerException.class, () -> s.isEmpty(null));
}
@Test
void testPop() {
ObjectMultistack s = new ObjectMultistack();
ValueWrapper v = new ValueWrapper(3);
s.push("key", v);
assertEquals(v, s.pop("key"));
}
@Test
void testPoppingMultipleElements() {
ObjectMultistack s = new ObjectMultistack();
ValueWrapper v1 = new ValueWrapper(1);
ValueWrapper v2 = new ValueWrapper(2);
ValueWrapper v3 = new ValueWrapper(34);
ValueWrapper v4 = new ValueWrapper(44);
s.push("key", v1);
s.push("key", v2);
s.push("key", v3);
s.push("key", v4);
s.push("key1", v4);
s.push("key1", v4);
assertEquals(v4, s.pop("key"));
assertEquals(v3, s.pop("key"));
assertEquals(v2, s.pop("key"));
assertEquals(v1, s.pop("key"));
assertEquals(v4, s.pop("key1"));
assertEquals(v4, s.pop("key1"));
}
@Test
void testPopThrowsWhenEmpty() {
ObjectMultistack s = new ObjectMultistack();
assertThrows(EmptyStackException.class, () -> s.pop("wut"));
}
@Test
void testComplicatedWorkflowWithMultistack() {
ObjectMultistack s = new ObjectMultistack();
ValueWrapper v1 = new ValueWrapper(1);
ValueWrapper v2 = new ValueWrapper(2);
ValueWrapper v3 = new ValueWrapper(3);
s.push("key1", v1);
s.push("key1", v2);
s.push("key1", v3);
s.push("key2", v3);
s.push("key2", v3);
s.push("key2", v3);
assertEquals(v3, s.peek("key1"));
assertEquals(v3, s.pop("key1"));
assertFalse(s.isEmpty("key1"));
assertEquals(v2, s.peek("key1"));
assertEquals(v2, s.pop("key1"));
assertFalse(s.isEmpty("key1"));
assertEquals(v1, s.peek("key1"));
assertEquals(v1, s.pop("key1"));
assertTrue(s.isEmpty("key1"));
assertEquals(v3, s.peek("key2"));
assertEquals(v3, s.pop("key2"));
assertFalse(s.isEmpty("key2"));
assertEquals(v3, s.peek("key2"));
assertEquals(v3, s.pop("key2"));
assertFalse(s.isEmpty("key2"));
assertEquals(v3, s.peek("key2"));
assertEquals(v3, s.pop("key2"));
assertTrue(s.isEmpty("key2"));
}
}
| 5,690 | 0.672056 | 0.652021 | 242 | 22.512396 | 18.942547 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.07438 | false | false | 0 |
837407db0ece7141a0dcd8d834306d324a2920da | 38,139,309,610,947 | d8cb289a5c80089595fc5428c18d329c2e31e0dd | /week-7/lab/MyPoint.java | 1ac7693965781526f911ed3559f5b3fc5c212935 | []
| no_license | NickParker68/tc3-csci165-main | https://github.com/NickParker68/tc3-csci165-main | b2a8996f639df1ceb15ace90e6820dc21b34af02 | 9bb5dde0ef4854c0946fd098133920e65091ac01 | refs/heads/master | 2020-12-20T02:50:49.424000 | 2020-05-04T06:40:42 | 2020-05-04T06:40:42 | 235,938,489 | 0 | 0 | null | true | 2020-01-24T04:20:16 | 2020-01-24T04:20:16 | 2020-01-22T15:57:06 | 2020-01-22T15:57:04 | 573 | 0 | 0 | 0 | null | false | false |
public class MyPoint {
int x = 0;
int y = 0;
int[] XY = new int[2];
MyPoint() {} //no argument constructor
MyPoint(int x, int y){
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void setXY(int x, int y) {
this.x = x;
this.y = y;
}
public int[] getXY() {
int[] XY = {x, y};
return XY;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
public double distance(int x2, int y2) {
int x1 = x;
int y1 = y;
return Math.sqrt(((y2 - y1) * (y2 - y1)) + ((x2 - x1) * (x2 - x1)));
}
public double distance(MyPoint another) {
int x1 = x;
int y1 = y;
int x2 = another.getX();
int y2 = another.getY();
return Math.sqrt((y2 - y1) * (y2 - y1) + (x2 -x1) * (x2 - x1));
}
public double distance() {
int x1 = x;
int y1 = y;
int x2 = 0;
int y2 = 0;
return Math.sqrt((y2 - y1) * (y2 - y1) + (x2 -x1) * (x2 - x1));
}
}
| UTF-8 | Java | 1,064 | java | MyPoint.java | Java | []
| null | []
|
public class MyPoint {
int x = 0;
int y = 0;
int[] XY = new int[2];
MyPoint() {} //no argument constructor
MyPoint(int x, int y){
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void setXY(int x, int y) {
this.x = x;
this.y = y;
}
public int[] getXY() {
int[] XY = {x, y};
return XY;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
public double distance(int x2, int y2) {
int x1 = x;
int y1 = y;
return Math.sqrt(((y2 - y1) * (y2 - y1)) + ((x2 - x1) * (x2 - x1)));
}
public double distance(MyPoint another) {
int x1 = x;
int y1 = y;
int x2 = another.getX();
int y2 = another.getY();
return Math.sqrt((y2 - y1) * (y2 - y1) + (x2 -x1) * (x2 - x1));
}
public double distance() {
int x1 = x;
int y1 = y;
int x2 = 0;
int y2 = 0;
return Math.sqrt((y2 - y1) * (y2 - y1) + (x2 -x1) * (x2 - x1));
}
}
| 1,064 | 0.504699 | 0.466165 | 74 | 13.351352 | 15.619143 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.675676 | false | false | 0 |
a7316aa8672b49de166eb223f67ad2f271ab6302 | 25,486,335,994,361 | 72b957878edcba12b26149d3c742edd9f018e17e | /compiler-studio-core/src/main/java/org/xteam/cs/model/Project.java | 0c4c04e77b53701a51982f7b297f99622b88f7c6 | []
| no_license | madbrain/compiler-studio | https://github.com/madbrain/compiler-studio | 505d66c3574adbee28331d4684004bf95a7115d2 | 543d14f2cb7c7b87c9d9da035f9bdf37fe5ddfd9 | refs/heads/master | 2021-01-02T08:34:20.271000 | 2015-02-15T14:42:51 | 2015-02-15T14:42:51 | 30,828,974 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.xteam.cs.model;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class Project {
private File file;
private boolean isDirty;
private List<ProjectResource> resources = new ArrayList<ProjectResource>();
private ProjectProperties properties = new ProjectProperties();
private List<IProjectListener> listeners = new ArrayList<IProjectListener>();
private ProjectManager manager;
public Project(ProjectManager projectManager) {
this.manager = projectManager;
}
public File getFile() {
return file;
}
public boolean isDirty() {
return isDirty;
}
public List<ProjectResource> getResources() {
return resources;
}
public <T extends ProjectResource> List<T> getResources(Class<T> cls) {
List<T> res = new ArrayList<T>();
for (ProjectResource r : resources) {
if (r.getClass().equals(cls))
res.add((T)r);
}
return res;
}
public void saveAs(File file) {
if (manager.saveProject(this, file)) {
this.file = file;
this.isDirty = false;
fireEvent(new ProjectEvent(this, ProjectEvent.CHANGE_STATE));
}
}
public void save() {
if (manager.saveProject(this, file)) {
this.isDirty = false;
fireEvent(new ProjectEvent(this, ProjectEvent.CHANGE_STATE));
}
}
public void reset() {
clear();
fireEvent(new ProjectEvent(this, ProjectEvent.CHANGE_STRUCTURE));
}
public void propertyChanged() {
isDirty = true;
fireEvent(new ProjectEvent(this, ProjectEvent.CHANGE_PROPERTIES));
}
public void clear() {
resources.clear();
isDirty = false;
properties = new ProjectProperties();
}
public void open(File file) {
if (manager.loadProject(this, file)) {
this.file = file;
this.isDirty = false;
fireEvent(new ProjectEvent(this, ProjectEvent.CHANGE_STRUCTURE));
}
}
public void addFile(File elementFile) {
for (ProjectResource f : resources) {
if (f instanceof FileResource && ((FileResource)f).getFile().equals(elementFile))
return;
}
ProjectResource newFile = manager.createResource(this, elementFile);
if (newFile != null) {
resources.add(newFile);
isDirty = true;
fireEvent(new ProjectEvent(this, ProjectEvent.ADD_FILE, newFile));
}
}
public void addProjectListener(IProjectListener l) {
this.listeners.add(l);
}
public void removeProjectListener(IProjectListener l) {
this.listeners.remove(l);
}
private void fireEvent(ProjectEvent event) {
for (IProjectListener l : listeners) {
l.projectChanged(event);
}
}
public ProjectResource getResource(String filename) {
for (ProjectResource res : resources) {
if (res.getPath().equals(filename)) {
return res;
}
}
return null;
}
public void setProperties(Properties properties) {
this.properties.fillFrom(properties);
}
public ProjectProperties getProperties() {
return properties;
}
public void generate(IProgressMonitor monitor) {
manager.generateProject(this, monitor);
}
public void finishBuilding() {
fireEvent(new ProjectEvent(this, ProjectEvent.END_BUILD));
}
public <T> List<T> getMarks(Class<T> cls) {
List<T> marks = new ArrayList<T>();
for (ProjectResource res : resources) {
marks.addAll(res.getMarks(cls));
}
return marks;
}
public File makeAbsolute(File f) {
if (f.isAbsolute())
return f;
return new File(getFile().getParentFile(), f.getPath());
}
@Override
public String toString() {
return file == null ? "<unamed>" : file.getName();
}
}
| UTF-8 | Java | 3,486 | java | Project.java | Java | []
| null | []
| package org.xteam.cs.model;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class Project {
private File file;
private boolean isDirty;
private List<ProjectResource> resources = new ArrayList<ProjectResource>();
private ProjectProperties properties = new ProjectProperties();
private List<IProjectListener> listeners = new ArrayList<IProjectListener>();
private ProjectManager manager;
public Project(ProjectManager projectManager) {
this.manager = projectManager;
}
public File getFile() {
return file;
}
public boolean isDirty() {
return isDirty;
}
public List<ProjectResource> getResources() {
return resources;
}
public <T extends ProjectResource> List<T> getResources(Class<T> cls) {
List<T> res = new ArrayList<T>();
for (ProjectResource r : resources) {
if (r.getClass().equals(cls))
res.add((T)r);
}
return res;
}
public void saveAs(File file) {
if (manager.saveProject(this, file)) {
this.file = file;
this.isDirty = false;
fireEvent(new ProjectEvent(this, ProjectEvent.CHANGE_STATE));
}
}
public void save() {
if (manager.saveProject(this, file)) {
this.isDirty = false;
fireEvent(new ProjectEvent(this, ProjectEvent.CHANGE_STATE));
}
}
public void reset() {
clear();
fireEvent(new ProjectEvent(this, ProjectEvent.CHANGE_STRUCTURE));
}
public void propertyChanged() {
isDirty = true;
fireEvent(new ProjectEvent(this, ProjectEvent.CHANGE_PROPERTIES));
}
public void clear() {
resources.clear();
isDirty = false;
properties = new ProjectProperties();
}
public void open(File file) {
if (manager.loadProject(this, file)) {
this.file = file;
this.isDirty = false;
fireEvent(new ProjectEvent(this, ProjectEvent.CHANGE_STRUCTURE));
}
}
public void addFile(File elementFile) {
for (ProjectResource f : resources) {
if (f instanceof FileResource && ((FileResource)f).getFile().equals(elementFile))
return;
}
ProjectResource newFile = manager.createResource(this, elementFile);
if (newFile != null) {
resources.add(newFile);
isDirty = true;
fireEvent(new ProjectEvent(this, ProjectEvent.ADD_FILE, newFile));
}
}
public void addProjectListener(IProjectListener l) {
this.listeners.add(l);
}
public void removeProjectListener(IProjectListener l) {
this.listeners.remove(l);
}
private void fireEvent(ProjectEvent event) {
for (IProjectListener l : listeners) {
l.projectChanged(event);
}
}
public ProjectResource getResource(String filename) {
for (ProjectResource res : resources) {
if (res.getPath().equals(filename)) {
return res;
}
}
return null;
}
public void setProperties(Properties properties) {
this.properties.fillFrom(properties);
}
public ProjectProperties getProperties() {
return properties;
}
public void generate(IProgressMonitor monitor) {
manager.generateProject(this, monitor);
}
public void finishBuilding() {
fireEvent(new ProjectEvent(this, ProjectEvent.END_BUILD));
}
public <T> List<T> getMarks(Class<T> cls) {
List<T> marks = new ArrayList<T>();
for (ProjectResource res : resources) {
marks.addAll(res.getMarks(cls));
}
return marks;
}
public File makeAbsolute(File f) {
if (f.isAbsolute())
return f;
return new File(getFile().getParentFile(), f.getPath());
}
@Override
public String toString() {
return file == null ? "<unamed>" : file.getName();
}
}
| 3,486 | 0.703672 | 0.703672 | 153 | 21.784313 | 21.749897 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.888889 | false | false | 0 |
4319234225c17e49dbad48a58a9d97a6e3264742 | 31,069,793,465,189 | 2b56e48ad662ea55f717ac51b3214f4878e79148 | /src/src/LinkedStack.java | 3e99e56474c53a601d8d11f8ab85979c273b736a | []
| no_license | deepfriedbrain1/dataStructures | https://github.com/deepfriedbrain1/dataStructures | 5dd4020c40cb6aeead3644dbf5ddf33c93b78e12 | fc3d9129055f38606d90d8fb89513f05199bf543 | refs/heads/master | 2020-03-22T11:13:00.812000 | 2019-05-18T11:43:07 | 2019-05-18T11:43:07 | 139,955,944 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package src;
import java.util.EmptyStackException;
/**
*
* @author Alberto Fernandez Saucedo
* @param <T>
*/
public final class LinkedStack<T> implements StackInterface<T>
{
private Node head;
public LinkedStack()
{
head = null;
}//end default constructor
@Override
public void push(T newEntry) {
head = new Node(newEntry, head);
}//end push
@Override
public T pop() {
T top = peek();
assert head != null;
head = head.getNextNode();
return top;
}//end pop
@Override
public T peek() {
if(isEmpty())
throw new EmptyStackException();
else
return head.getData();
}//end peek
@Override
public boolean isEmpty() {
return head != null;
}//end isEmpty
@Override
public void clear() {
head = null;
}//end clear
private class Node
{
private T data;
private Node next;
public Node(T data)
{
this(data, null);
}
public Node(T data, Node next)
{
this.data = data;
this.next = next;
}
private T getData(){
return data;
}
private void setData(T anEntry){
data = anEntry;
}
private Node getNextNode(){
return next;
}
private void setNextNode(Node next)
{
this.next = next;
}
}//end Node
}//end LinkedStack
| UTF-8 | Java | 1,606 | java | LinkedStack.java | Java | [
{
"context": " java.util.EmptyStackException;\n\n/**\n *\n * @author Alberto Fernandez Saucedo\n * @param <T>\n */\npublic final class LinkedStack<",
"end": 97,
"score": 0.9998739361763,
"start": 72,
"tag": "NAME",
"value": "Alberto Fernandez Saucedo"
}
]
| null | []
|
package src;
import java.util.EmptyStackException;
/**
*
* @author <NAME>
* @param <T>
*/
public final class LinkedStack<T> implements StackInterface<T>
{
private Node head;
public LinkedStack()
{
head = null;
}//end default constructor
@Override
public void push(T newEntry) {
head = new Node(newEntry, head);
}//end push
@Override
public T pop() {
T top = peek();
assert head != null;
head = head.getNextNode();
return top;
}//end pop
@Override
public T peek() {
if(isEmpty())
throw new EmptyStackException();
else
return head.getData();
}//end peek
@Override
public boolean isEmpty() {
return head != null;
}//end isEmpty
@Override
public void clear() {
head = null;
}//end clear
private class Node
{
private T data;
private Node next;
public Node(T data)
{
this(data, null);
}
public Node(T data, Node next)
{
this.data = data;
this.next = next;
}
private T getData(){
return data;
}
private void setData(T anEntry){
data = anEntry;
}
private Node getNextNode(){
return next;
}
private void setNextNode(Node next)
{
this.next = next;
}
}//end Node
}//end LinkedStack
| 1,587 | 0.482565 | 0.482565 | 86 | 17.66279 | 12.657023 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.290698 | false | false | 0 |
e89de3fa72e671955dd53663feead7e1fb62ab87 | 37,898,791,445,249 | a49758dc125940df0294f9aa8f73f3476d3d23ee | /src/main/java/com/bakery/model/ProductCategory.java | 38399249d16d0e8ffad1c4eaaa83e75dde6f5a91 | []
| no_license | Pawan08082000/Bakery-backend | https://github.com/Pawan08082000/Bakery-backend | bbf0c68c23d8317b2dcf6d314b013d733de49c9c | 7398f73a309bf14586bc86ef1be97f76daa3e617 | refs/heads/master | 2023-07-13T08:39:32.820000 | 2021-08-29T00:38:46 | 2021-08-29T00:38:46 | 400,916,777 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bakery.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
@Document
public class ProductCategory {
@Id
private String id;
@Field
private String name;
@Field
private double maxRewardPoint;
}
| UTF-8 | Java | 473 | java | ProductCategory.java | Java | []
| null | []
| package com.bakery.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
@Document
public class ProductCategory {
@Id
private String id;
@Field
private String name;
@Field
private double maxRewardPoint;
}
| 473 | 0.813953 | 0.813953 | 25 | 17.92 | 17.979811 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.68 | false | false | 0 |
c09022ecea16d0f47a788bfb91f6a4e8636314aa | 39,548,058,882,192 | 3ad04bed43dd2de34f4a6f53028a834e0854139f | /src/propLlibreria/Interficie/VistaGestioAfegirLlibre.java | d6d48363233d5bb766b3ea99c3eaf0ebef7fd037 | []
| no_license | alicenara/prop | https://github.com/alicenara/prop | 01bdc65d59eba602abca890fe99c928d74af0e36 | c50ee94c20a156d8928dd24aa906e33aeff80b25 | refs/heads/master | 2021-01-22T17:53:16.790000 | 2014-06-08T17:17:54 | 2014-06-08T17:17:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package propLlibreria.Interficie;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.ListModel;
/**
*
* @author towerthousand
*/
public class VistaGestioAfegirLlibre extends javax.swing.JPanel {
/**
* Creates new form VistaGestióAfegirEstanteria
*/
public VistaGestioAfegirLlibre() {
initComponents();
}
public void resetFields() {
inputISBN.setText("");
inputAutor.setText("");
inputEditorial.setText("");
inputTitol.setText("");
spinAny.setValue(2000);
spinEdicio.setValue(1);
ArrayList<ArrayList<String> > tematiques = CtrlInterficie.seleccionaAllTematiques();
String[] model = new String[tematiques.size()];
javax.swing.DefaultListModel m = new javax.swing.DefaultListModel();
for(int i = 0; i < tematiques.size(); ++i) {
model[i] = tematiques.get(i).get(0);
m.addElement(tematiques.get(i).get(0));
}
comboTematicaPrincipal.setModel(new javax.swing.DefaultComboBoxModel(model));
listSecundaries.setModel(m);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
inputAutor = new javax.swing.JTextField();
labelAutor = new javax.swing.JLabel();
inputTitol = new javax.swing.JTextField();
labelTitol = new javax.swing.JLabel();
labelEdicio = new javax.swing.JLabel();
labelTematica = new javax.swing.JLabel();
spinEdicio = new javax.swing.JSpinner();
comboTematicaPrincipal = new javax.swing.JComboBox();
labelAny = new javax.swing.JLabel();
labelNom = new javax.swing.JLabel();
inputISBN = new javax.swing.JTextField();
labelEditorial = new javax.swing.JLabel();
inputEditorial = new javax.swing.JTextField();
spinAny = new javax.swing.JSpinner();
botoAfegir = new javax.swing.JToggleButton();
jScrollPane1 = new javax.swing.JScrollPane();
listSecundaries = new javax.swing.JList();
labelSecundaries = new javax.swing.JLabel();
setBackground(new java.awt.Color(212, 220, 245));
setMaximumSize(new java.awt.Dimension(476, 405));
setMinimumSize(new java.awt.Dimension(476, 405));
setPreferredSize(new java.awt.Dimension(476, 405));
jPanel1.setBackground(new java.awt.Color(212, 220, 245));
labelAutor.setText("Autor");
labelTitol.setText("Títol");
labelEdicio.setText("Edició");
labelTematica.setText("Temàtica");
spinEdicio.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));
spinEdicio.setMaximumSize(new java.awt.Dimension(10, 33));
spinEdicio.setMinimumSize(new java.awt.Dimension(10, 33));
spinEdicio.setPreferredSize(new java.awt.Dimension(10, 33));
labelAny.setText("Any");
labelNom.setText("ISBN");
labelEditorial.setText("Editorial");
spinAny.setModel(new javax.swing.SpinnerNumberModel(2000, 0, 2015, 1));
spinAny.setMaximumSize(new java.awt.Dimension(10, 33));
spinAny.setMinimumSize(new java.awt.Dimension(10, 33));
spinAny.setPreferredSize(new java.awt.Dimension(10, 33));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(labelTematica)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(comboTematicaPrincipal, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(labelEdicio, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE)
.addComponent(labelAny, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(29, 29, 29)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(spinAny, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(spinEdicio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(labelEditorial, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelAutor, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelTitol, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelNom, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(inputISBN)
.addComponent(inputEditorial, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(inputAutor, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(inputTitol, javax.swing.GroupLayout.Alignment.TRAILING))))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelNom)
.addComponent(inputISBN, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelTitol)
.addComponent(inputTitol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelAutor)
.addComponent(inputAutor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelEditorial)
.addComponent(inputEditorial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelEdicio)
.addComponent(spinEdicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelAny)
.addComponent(spinAny, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelTematica)
.addComponent(comboTematicaPrincipal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
botoAfegir.setText("Crear");
botoAfegir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botoAfegirActionPerformed(evt);
}
});
listSecundaries.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPane1.setViewportView(listSecundaries);
labelSecundaries.setText("Temàtiques secundàries");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(botoAfegir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(labelSecundaries, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35))
.addComponent(jScrollPane1))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(labelSecundaries, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(botoAfegir)
.addContainerGap(87, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void botoAfegirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botoAfegirActionPerformed
String autor = inputAutor.getText();
String isbn = inputISBN.getText();
String editorial = inputEditorial.getText();
String titol = inputTitol.getText();
int any = (Integer) spinAny.getValue();
int edicio = (Integer) spinEdicio.getValue();
String tprincipal = (String) comboTematicaPrincipal.getModel().getSelectedItem();
ListModel m = listSecundaries.getModel();
ArrayList<String> sec = new ArrayList<String>();
for(int i = 0; i < m.getSize(); ++i)
if(listSecundaries.isSelectedIndex(i))
sec.add((String)m.getElementAt(i));
try {
CtrlInterficie.crearLlibre(isbn, titol, autor, editorial, any, edicio, tprincipal);
for(int i = 0; i < sec.size(); ++i) CtrlInterficie.afegirTSecundaria(titol, autor, any, sec.get(i));
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error al inserir.\nCodi d'error: " + e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
return;
}
JOptionPane.showMessageDialog(null, "Afegit correctament","Info",JOptionPane.INFORMATION_MESSAGE);
}//GEN-LAST:event_botoAfegirActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JToggleButton botoAfegir;
private javax.swing.JComboBox comboTematicaPrincipal;
private javax.swing.JTextField inputAutor;
private javax.swing.JTextField inputEditorial;
private javax.swing.JTextField inputISBN;
private javax.swing.JTextField inputTitol;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel labelAny;
private javax.swing.JLabel labelAutor;
private javax.swing.JLabel labelEdicio;
private javax.swing.JLabel labelEditorial;
private javax.swing.JLabel labelNom;
private javax.swing.JLabel labelSecundaries;
private javax.swing.JLabel labelTematica;
private javax.swing.JLabel labelTitol;
private javax.swing.JList listSecundaries;
private javax.swing.JSpinner spinAny;
private javax.swing.JSpinner spinEdicio;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 15,559 | java | VistaGestioAfegirLlibre.java | Java | [
{
"context": ";\nimport javax.swing.ListModel;\n\n/**\n *\n * @author towerthousand\n */\npublic class VistaGestioAfegirLlibre extends ",
"end": 343,
"score": 0.9964650273323059,
"start": 330,
"tag": "USERNAME",
"value": "towerthousand"
}
]
| null | []
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package propLlibreria.Interficie;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.ListModel;
/**
*
* @author towerthousand
*/
public class VistaGestioAfegirLlibre extends javax.swing.JPanel {
/**
* Creates new form VistaGestióAfegirEstanteria
*/
public VistaGestioAfegirLlibre() {
initComponents();
}
public void resetFields() {
inputISBN.setText("");
inputAutor.setText("");
inputEditorial.setText("");
inputTitol.setText("");
spinAny.setValue(2000);
spinEdicio.setValue(1);
ArrayList<ArrayList<String> > tematiques = CtrlInterficie.seleccionaAllTematiques();
String[] model = new String[tematiques.size()];
javax.swing.DefaultListModel m = new javax.swing.DefaultListModel();
for(int i = 0; i < tematiques.size(); ++i) {
model[i] = tematiques.get(i).get(0);
m.addElement(tematiques.get(i).get(0));
}
comboTematicaPrincipal.setModel(new javax.swing.DefaultComboBoxModel(model));
listSecundaries.setModel(m);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
inputAutor = new javax.swing.JTextField();
labelAutor = new javax.swing.JLabel();
inputTitol = new javax.swing.JTextField();
labelTitol = new javax.swing.JLabel();
labelEdicio = new javax.swing.JLabel();
labelTematica = new javax.swing.JLabel();
spinEdicio = new javax.swing.JSpinner();
comboTematicaPrincipal = new javax.swing.JComboBox();
labelAny = new javax.swing.JLabel();
labelNom = new javax.swing.JLabel();
inputISBN = new javax.swing.JTextField();
labelEditorial = new javax.swing.JLabel();
inputEditorial = new javax.swing.JTextField();
spinAny = new javax.swing.JSpinner();
botoAfegir = new javax.swing.JToggleButton();
jScrollPane1 = new javax.swing.JScrollPane();
listSecundaries = new javax.swing.JList();
labelSecundaries = new javax.swing.JLabel();
setBackground(new java.awt.Color(212, 220, 245));
setMaximumSize(new java.awt.Dimension(476, 405));
setMinimumSize(new java.awt.Dimension(476, 405));
setPreferredSize(new java.awt.Dimension(476, 405));
jPanel1.setBackground(new java.awt.Color(212, 220, 245));
labelAutor.setText("Autor");
labelTitol.setText("Títol");
labelEdicio.setText("Edició");
labelTematica.setText("Temàtica");
spinEdicio.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));
spinEdicio.setMaximumSize(new java.awt.Dimension(10, 33));
spinEdicio.setMinimumSize(new java.awt.Dimension(10, 33));
spinEdicio.setPreferredSize(new java.awt.Dimension(10, 33));
labelAny.setText("Any");
labelNom.setText("ISBN");
labelEditorial.setText("Editorial");
spinAny.setModel(new javax.swing.SpinnerNumberModel(2000, 0, 2015, 1));
spinAny.setMaximumSize(new java.awt.Dimension(10, 33));
spinAny.setMinimumSize(new java.awt.Dimension(10, 33));
spinAny.setPreferredSize(new java.awt.Dimension(10, 33));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(labelTematica)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(comboTematicaPrincipal, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(labelEdicio, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE)
.addComponent(labelAny, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(29, 29, 29)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(spinAny, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(spinEdicio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(labelEditorial, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelAutor, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelTitol, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelNom, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(inputISBN)
.addComponent(inputEditorial, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(inputAutor, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(inputTitol, javax.swing.GroupLayout.Alignment.TRAILING))))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelNom)
.addComponent(inputISBN, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelTitol)
.addComponent(inputTitol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelAutor)
.addComponent(inputAutor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelEditorial)
.addComponent(inputEditorial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelEdicio)
.addComponent(spinEdicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelAny)
.addComponent(spinAny, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelTematica)
.addComponent(comboTematicaPrincipal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
botoAfegir.setText("Crear");
botoAfegir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botoAfegirActionPerformed(evt);
}
});
listSecundaries.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPane1.setViewportView(listSecundaries);
labelSecundaries.setText("Temàtiques secundàries");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(botoAfegir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(labelSecundaries, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35))
.addComponent(jScrollPane1))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(labelSecundaries, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(6, 6, 6)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(botoAfegir)
.addContainerGap(87, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void botoAfegirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botoAfegirActionPerformed
String autor = inputAutor.getText();
String isbn = inputISBN.getText();
String editorial = inputEditorial.getText();
String titol = inputTitol.getText();
int any = (Integer) spinAny.getValue();
int edicio = (Integer) spinEdicio.getValue();
String tprincipal = (String) comboTematicaPrincipal.getModel().getSelectedItem();
ListModel m = listSecundaries.getModel();
ArrayList<String> sec = new ArrayList<String>();
for(int i = 0; i < m.getSize(); ++i)
if(listSecundaries.isSelectedIndex(i))
sec.add((String)m.getElementAt(i));
try {
CtrlInterficie.crearLlibre(isbn, titol, autor, editorial, any, edicio, tprincipal);
for(int i = 0; i < sec.size(); ++i) CtrlInterficie.afegirTSecundaria(titol, autor, any, sec.get(i));
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error al inserir.\nCodi d'error: " + e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
return;
}
JOptionPane.showMessageDialog(null, "Afegit correctament","Info",JOptionPane.INFORMATION_MESSAGE);
}//GEN-LAST:event_botoAfegirActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JToggleButton botoAfegir;
private javax.swing.JComboBox comboTematicaPrincipal;
private javax.swing.JTextField inputAutor;
private javax.swing.JTextField inputEditorial;
private javax.swing.JTextField inputISBN;
private javax.swing.JTextField inputTitol;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel labelAny;
private javax.swing.JLabel labelAutor;
private javax.swing.JLabel labelEdicio;
private javax.swing.JLabel labelEditorial;
private javax.swing.JLabel labelNom;
private javax.swing.JLabel labelSecundaries;
private javax.swing.JLabel labelTematica;
private javax.swing.JLabel labelTitol;
private javax.swing.JList listSecundaries;
private javax.swing.JSpinner spinAny;
private javax.swing.JSpinner spinEdicio;
// End of variables declaration//GEN-END:variables
}
| 15,559 | 0.660644 | 0.650421 | 265 | 57.690567 | 41.66346 | 177 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.89434 | false | false | 0 |
6e4c600c46f90a0d0924d051570567c6cfd8b793 | 9,715,216,049,281 | 096b07ae52cf32b24d2f7369c933635cd06ef04f | /airport-security-control/airport-security-control/src/main/java/Main/SimulationEmployee/SupervisorWorkspaceSupervisor.java | d268c68f69c8a891e87476a0445d724652d48cd8 | []
| no_license | FabMaster2000/Sicherheitskontrolle | https://github.com/FabMaster2000/Sicherheitskontrolle | fbb74ef612072729eb3291dfaffc752dc521925e | a480d1f23aeb4f93377e92ef679bf7daa251723d | refs/heads/main | 2023-04-02T18:12:18.198000 | 2021-04-07T09:44:09 | 2021-04-07T09:44:09 | 319,064,579 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Main.SimulationEmployee;
import Main.Employee.IDCard;
import Main.Employee.Supervisor;
import Main.Employee.Pin;
import Main.Workspaces.SupervisorWorkspace;
import java.time.LocalDate;
public class SupervisorWorkspaceSupervisor extends Supervisor {
private SupervisorWorkspace workspace;
public SupervisorWorkspaceSupervisor(int id, String name, LocalDate birthDate, IDCard idCard, boolean isSenior, boolean isExecutive, SupervisorWorkspace workspace) {
super(id, name, birthDate, idCard, isSenior, isExecutive);
this.workspace = workspace;
}
public boolean unlockBaggageScanner(Pin enteredPin) {
return getWorkspace().unlockBaggageScanner(this, getIDCard(), enteredPin);
}
public boolean pressButtonStartBaggageScanner() {
return getWorkspace().onButtonStartBaggageScannerClicked(this);
}
public boolean pressButtonShutdownBaggageScanner() {
return getWorkspace().onButtonShutdownBaggageScannerClicked(this);
}
public SupervisorWorkspace getWorkspace() {
return workspace;
}
}
| UTF-8 | Java | 1,121 | java | SupervisorWorkspaceSupervisor.java | Java | []
| null | []
| package Main.SimulationEmployee;
import Main.Employee.IDCard;
import Main.Employee.Supervisor;
import Main.Employee.Pin;
import Main.Workspaces.SupervisorWorkspace;
import java.time.LocalDate;
public class SupervisorWorkspaceSupervisor extends Supervisor {
private SupervisorWorkspace workspace;
public SupervisorWorkspaceSupervisor(int id, String name, LocalDate birthDate, IDCard idCard, boolean isSenior, boolean isExecutive, SupervisorWorkspace workspace) {
super(id, name, birthDate, idCard, isSenior, isExecutive);
this.workspace = workspace;
}
public boolean unlockBaggageScanner(Pin enteredPin) {
return getWorkspace().unlockBaggageScanner(this, getIDCard(), enteredPin);
}
public boolean pressButtonStartBaggageScanner() {
return getWorkspace().onButtonStartBaggageScannerClicked(this);
}
public boolean pressButtonShutdownBaggageScanner() {
return getWorkspace().onButtonShutdownBaggageScannerClicked(this);
}
public SupervisorWorkspace getWorkspace() {
return workspace;
}
}
| 1,121 | 0.737734 | 0.737734 | 34 | 30.970589 | 35.435513 | 169 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.764706 | false | false | 0 |
559ae50e0d1f1a3c8a580d37fcebc722fb059acb | 6,708,738,945,813 | d5695b673b24807f922543b3316d75ace0d1a398 | /src/Controllers/BirthdayController.java | 8594b8961fdd685afc5e688bec141b6578cb33ad | []
| no_license | Cosmin2108/PAO_Project | https://github.com/Cosmin2108/PAO_Project | e2ebddfadab0dca46900600b06903b58fda2d47d | e6f6e9c82cceb5f79f038b1e4b2ad33320775b8f | refs/heads/master | 2021-05-18T00:40:28.197000 | 2020-06-10T16:49:20 | 2020-06-10T16:49:20 | 251,028,031 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Controllers;
import DB.DbContext;
import agenda.Birthday;
import java.sql.SQLException;
import java.util.ArrayList;
public class BirthdayController {
private DbContext context = DbContext.getInstance();
public BirthdayController() {
}
public ArrayList<Birthday> getBirthdays() {
ArrayList<Birthday> birthdays = context.getBirthdays();
return birthdays;
}
public void addBirthday(Birthday event) {
context.addBirthday(event);
}
public void deleteBirthday(Birthday element) {
context.deleteBirthday(element);
}
public void editBirthday(Birthday event){
context.editBirthday(event);
}
}
| UTF-8 | Java | 685 | java | BirthdayController.java | Java | []
| null | []
| package Controllers;
import DB.DbContext;
import agenda.Birthday;
import java.sql.SQLException;
import java.util.ArrayList;
public class BirthdayController {
private DbContext context = DbContext.getInstance();
public BirthdayController() {
}
public ArrayList<Birthday> getBirthdays() {
ArrayList<Birthday> birthdays = context.getBirthdays();
return birthdays;
}
public void addBirthday(Birthday event) {
context.addBirthday(event);
}
public void deleteBirthday(Birthday element) {
context.deleteBirthday(element);
}
public void editBirthday(Birthday event){
context.editBirthday(event);
}
}
| 685 | 0.69635 | 0.69635 | 32 | 20.40625 | 19.754524 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.34375 | false | false | 0 |
631b7778d3e135e908cd644093df12ab9a9ffc6a | 18,777,597,048,235 | 9fcb62e90379771bb02b3e70112c2e981df13a3a | /src/Test.java | d6b800828541ff0a8a880c11f6e845a22347ca58 | []
| no_license | rprockchick/CoreJava | https://github.com/rprockchick/CoreJava | d73a5e059e925d469fad0cb6a9f1809aa214c298 | af1e4e082a89639f1e20a7b2b5a618d9296afb2c | refs/heads/master | 2020-03-31T10:56:11.172000 | 2018-11-12T20:17:39 | 2018-11-12T20:17:39 | 152,156,046 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Test{
int a,b;
Test(int i,int j){
a = i;
b = j;
}
boolean equalTo(Test o){
if(o.a == a && o.b == b) return true;
else return false;
}
} | UTF-8 | Java | 146 | java | Test.java | Java | []
| null | []
| class Test{
int a,b;
Test(int i,int j){
a = i;
b = j;
}
boolean equalTo(Test o){
if(o.a == a && o.b == b) return true;
else return false;
}
} | 146 | 0.561644 | 0.561644 | 16 | 8.1875 | 10.548808 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false | 0 |
b0a3aeb5e0ee5a0be0477de7cbe0ea1d3ca4bf14 | 841,813,621,638 | ec35dd0c5e707844970328fb24a2dbc8b1faf38a | /DSAArena/String/akash1.java | b965fca01aa321054ef70c26e77b0ddcb972a7cc | []
| no_license | agentmishra/DSATopicWise | https://github.com/agentmishra/DSATopicWise | 6ce07f819f75312ec6b4b19d4b142c4e2eb7c81b | 9e6ae2432f908cf7ba5810aeefc11d05f38a47a7 | refs/heads/main | 2023-06-11T18:57:07.582000 | 2021-07-03T07:46:23 | 2021-07-03T07:46:23 | 456,707,571 | 1 | 1 | null | true | 2022-02-07T23:04:53 | 2022-02-07T23:04:53 | 2021-07-03T07:48:37 | 2021-07-03T07:48:34 | 149 | 0 | 0 | 0 | null | false | false | import java.util.*;
class Test
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
int res=0;
for(int i=0;i<n;i+=2)
res+=a[i];
System.out.println(res);
double res1=Math.sqrt(2);
int r=(int)res1;
if(res1==r)
System.out.println("Yes");
else
System.out.println("No");
}
} | UTF-8 | Java | 498 | java | akash1.java | Java | []
| null | []
| import java.util.*;
class Test
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
int res=0;
for(int i=0;i<n;i+=2)
res+=a[i];
System.out.println(res);
double res1=Math.sqrt(2);
int r=(int)res1;
if(res1==r)
System.out.println("Yes");
else
System.out.println("No");
}
} | 498 | 0.495984 | 0.47992 | 22 | 21.681818 | 11.955928 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.727273 | false | false | 0 |
1d6a3dbada589e39645a91bf87171edc2f0718d2 | 18,330,920,443,534 | 38db341ef4488fe64d714c175aad2486683f5775 | /photos-app-microservices/photos-app-users-service/src/main/java/com/example/photosappusersservice/ui/model/LoginRequestModel.java | ce944bd8f28b5929a97958f0b3c1097d7edddc69 | []
| no_license | sardul3/spr-microservice | https://github.com/sardul3/spr-microservice | 3de0aef1ffaeb518fa8f31dec517a80202c4b906 | 48d47db6fd731d586afa75633373ad2409334140 | refs/heads/master | 2022-09-12T23:53:09.129000 | 2020-04-03T04:07:57 | 2020-04-03T04:07:57 | 250,904,795 | 0 | 0 | null | false | 2022-09-01T23:22:31 | 2020-03-28T22:18:59 | 2020-04-23T17:49:22 | 2022-09-01T23:22:29 | 117 | 0 | 0 | 3 | Java | false | false | package com.example.photosappusersservice.ui.model;
public class LoginRequestModel {
}
| UTF-8 | Java | 88 | java | LoginRequestModel.java | Java | []
| null | []
| package com.example.photosappusersservice.ui.model;
public class LoginRequestModel {
}
| 88 | 0.829545 | 0.829545 | 4 | 21 | 21.575449 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 0 |
53b3635cc706eb8536398d4f9fe82b0afc32c17c | 22,007,412,449,672 | 4d3e819e7d0e7cf69ffe020e7d2f7422deac1a6a | /app/src/main/java/com/udacity/stockhawk/data/StockCursorHelper.java | a78239bb9ba50c84799173be80ed4023cba374b1 | []
| no_license | JarvisMcFace/StockHawk | https://github.com/JarvisMcFace/StockHawk | 7e69c9e2c7585343a1790e9268a6309e0837b67a | 1cf207b3402b23b92935721795a80262d6c98fcf | refs/heads/master | 2021-01-12T09:59:02.662000 | 2017-02-25T04:18:32 | 2017-02-25T04:18:32 | 76,323,021 | 0 | 0 | null | true | 2016-12-13T04:36:46 | 2016-12-13T04:36:45 | 2016-11-26T06:34:15 | 2016-12-06T21:13:06 | 784 | 0 | 0 | 0 | null | null | null | package com.udacity.stockhawk.data;
import android.database.Cursor;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.udacity.stockhawk.fragment.StockChartDetailsFragment;
import com.udacity.stockhawk.to.StockTO;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import yahoofinance.histquotes.HistoricalQuote;
/**
* Created by David on 2/7/17.
*/
public class StockCursorHelper {
public static List<StockTO> retrieveAllStocks(Cursor cursor) {
List<StockTO> stockTOs = new ArrayList<StockTO>();
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast() && cursor.getCount() > 0) {
StockTO stockTO = getStockData(cursor);
if (stockTO != null) {
stockTOs.add(stockTO);
}
cursor.moveToNext();
}
cursor.close();
}
return stockTOs;
}
private static StockTO getStockData(Cursor cursor) {
final int symbolIndex = cursor.getColumnIndex(QuoteContract.Quote.COLUMN_SYMBOL);
final int priceIndex = cursor.getColumnIndex(QuoteContract.Quote.COLUMN_PRICE);
final int nameIndex = cursor.getColumnIndex(QuoteContract.Quote.COLUMN_NAME);
final int historyIndex = cursor.getColumnIndex(QuoteContract.Quote.COLUMN_HISTORY);
final int lastUpdateIndex = cursor.getColumnIndex(QuoteContract.Quote.COLUMN_LAST_UPDATED);
final int priceChangeIndex = cursor.getColumnIndex(QuoteContract.Quote.COLUMN_ABSOLUTE_CHANGE);
try {
String symbol = cursor.getString(symbolIndex);
String price = cursor.getString(priceIndex);
String name = cursor.getString(nameIndex);
String history = cursor.getString(historyIndex);
String lastUpdate = cursor.getString(lastUpdateIndex);
String priceChange = cursor.getString(priceChangeIndex);
Gson gson = new Gson();
Type listOfTestObject = new TypeToken<List<HistoricalQuote>>() {
}.getType();
List<HistoricalQuote> stockHistoryTOs = gson.fromJson(history, listOfTestObject);
Date date = new Date();
date.setTime(Long.valueOf(lastUpdate));
StockTO stockTO = new StockTO();
stockTO.setSymbol(symbol);
stockTO.setName(name);
stockTO.setPrice(Float.valueOf(price));
stockTO.setHistory(stockHistoryTOs);
stockTO.setLastUpdated(date);
stockTO.setChange(Float.parseFloat(priceChange));
return stockTO;
} catch (Exception ex) {
Log.d(StockChartDetailsFragment.class.getSimpleName(), "StockSymbolCursorHelper getStockHistoryTO: ");
return null;
}
}
}
| UTF-8 | Java | 2,911 | java | StockCursorHelper.java | Java | [
{
"context": "nce.histquotes.HistoricalQuote;\n\n/**\n * Created by David on 2/7/17.\n */\n\npublic class StockCursorHelper {\n",
"end": 451,
"score": 0.565054178237915,
"start": 446,
"tag": "NAME",
"value": "David"
}
]
| null | []
| package com.udacity.stockhawk.data;
import android.database.Cursor;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.udacity.stockhawk.fragment.StockChartDetailsFragment;
import com.udacity.stockhawk.to.StockTO;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import yahoofinance.histquotes.HistoricalQuote;
/**
* Created by David on 2/7/17.
*/
public class StockCursorHelper {
public static List<StockTO> retrieveAllStocks(Cursor cursor) {
List<StockTO> stockTOs = new ArrayList<StockTO>();
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast() && cursor.getCount() > 0) {
StockTO stockTO = getStockData(cursor);
if (stockTO != null) {
stockTOs.add(stockTO);
}
cursor.moveToNext();
}
cursor.close();
}
return stockTOs;
}
private static StockTO getStockData(Cursor cursor) {
final int symbolIndex = cursor.getColumnIndex(QuoteContract.Quote.COLUMN_SYMBOL);
final int priceIndex = cursor.getColumnIndex(QuoteContract.Quote.COLUMN_PRICE);
final int nameIndex = cursor.getColumnIndex(QuoteContract.Quote.COLUMN_NAME);
final int historyIndex = cursor.getColumnIndex(QuoteContract.Quote.COLUMN_HISTORY);
final int lastUpdateIndex = cursor.getColumnIndex(QuoteContract.Quote.COLUMN_LAST_UPDATED);
final int priceChangeIndex = cursor.getColumnIndex(QuoteContract.Quote.COLUMN_ABSOLUTE_CHANGE);
try {
String symbol = cursor.getString(symbolIndex);
String price = cursor.getString(priceIndex);
String name = cursor.getString(nameIndex);
String history = cursor.getString(historyIndex);
String lastUpdate = cursor.getString(lastUpdateIndex);
String priceChange = cursor.getString(priceChangeIndex);
Gson gson = new Gson();
Type listOfTestObject = new TypeToken<List<HistoricalQuote>>() {
}.getType();
List<HistoricalQuote> stockHistoryTOs = gson.fromJson(history, listOfTestObject);
Date date = new Date();
date.setTime(Long.valueOf(lastUpdate));
StockTO stockTO = new StockTO();
stockTO.setSymbol(symbol);
stockTO.setName(name);
stockTO.setPrice(Float.valueOf(price));
stockTO.setHistory(stockHistoryTOs);
stockTO.setLastUpdated(date);
stockTO.setChange(Float.parseFloat(priceChange));
return stockTO;
} catch (Exception ex) {
Log.d(StockChartDetailsFragment.class.getSimpleName(), "StockSymbolCursorHelper getStockHistoryTO: ");
return null;
}
}
}
| 2,911 | 0.650292 | 0.648574 | 84 | 33.654762 | 29.527023 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 0 |
a7b43f61a9f878f448be58709f9d73aaf0973ea2 | 34,359,746,192 | 01664b9f956eab7ee7746bf7e4760cb6cbf84776 | /src/main/java/cz/elk/bsctest/Start.java | 7824dbca36e8ddc282bc3bb0f1d0cbad264ed7d4 | []
| no_license | karelkrema/bsc-test | https://github.com/karelkrema/bsc-test | 88ac23d3a95e62099a0da1f31a08a8efbfffb30c | 51a8355b4bfd57a08ca50062ecaf65962786614a | refs/heads/master | 2021-01-10T09:40:30.663000 | 2016-01-11T10:23:41 | 2016-01-11T10:23:41 | 43,636,416 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cz.elk.bsctest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import cz.elk.bsctest.io.CurrencyTransactionReader;
/** Yes, I made it into BSC */
public class Start {
public static void main(final String[] args) throws FileNotFoundException {
final AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext("cz.elk.bsctest");
final CurrencyTransactionReader txReader = ctx.getBean(CurrencyTransactionReader.class);
// Process input file, if parameter was given
if(args.length > 0) {
final File file = new File(args[0]);
if((file != null) && file.exists() && file.isFile()) {
txReader.readAndProcessCommands(new FileInputStream(file));
}
}
txReader.readAndProcessCommands(System.in);
System.exit(0); // TODO terminate running scheduler more elegantly
}
}
| UTF-8 | Java | 989 | java | Start.java | Java | []
| null | []
| package cz.elk.bsctest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import cz.elk.bsctest.io.CurrencyTransactionReader;
/** Yes, I made it into BSC */
public class Start {
public static void main(final String[] args) throws FileNotFoundException {
final AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext("cz.elk.bsctest");
final CurrencyTransactionReader txReader = ctx.getBean(CurrencyTransactionReader.class);
// Process input file, if parameter was given
if(args.length > 0) {
final File file = new File(args[0]);
if((file != null) && file.exists() && file.isFile()) {
txReader.readAndProcessCommands(new FileInputStream(file));
}
}
txReader.readAndProcessCommands(System.in);
System.exit(0); // TODO terminate running scheduler more elegantly
}
}
| 989 | 0.733064 | 0.73003 | 31 | 30.903225 | 31.685303 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.032258 | false | false | 0 |
87ed325189f69339671094e061dd2fa5a5f4a1d3 | 17,772,574,678,121 | ae5050b2303511fee63862ec0ff3d882cf8edfab | /app/src/main/java/com/example/zrouter/App.java | c8353b758016660813ce2f38bdb9303376d436d1 | []
| no_license | qingdaofu1/ZRouter | https://github.com/qingdaofu1/ZRouter | ea089003d0624cb00bd924e766ae71b94c6d9c7e | d3ade88282d367d8e55e8768bc0003a5c44a26c9 | refs/heads/master | 2022-11-14T05:05:54.682000 | 2020-06-28T15:20:51 | 2020-06-28T15:21:09 | 275,608,949 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.zrouter;
import android.app.Application;
import com.example.myzrouter.ZRouter;
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
ZRouter.init(this);
}
}
| UTF-8 | Java | 246 | java | App.java | Java | []
| null | []
| package com.example.zrouter;
import android.app.Application;
import com.example.myzrouter.ZRouter;
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
ZRouter.init(this);
}
}
| 246 | 0.686992 | 0.686992 | 13 | 17.923077 | 14.451305 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 0 |
148e297faba837b45b023fdbaaecf8cb89f2dd5b | 20,882,130,998,233 | 09a99d675faa63cc9e993c74d6f8edd24202abab | /src/main/java/com/dr/leo/etl/controller/LogRestServer.java | 429355f6b9ac5fa429c5565da632db88b5a497f6 | []
| no_license | CCweixiao/leo-fast-kettle | https://github.com/CCweixiao/leo-fast-kettle | b635256c8d4c6afbd230dc3955fc0a3089b6d517 | 300454bb01297163d20467b950e847555cd907d4 | refs/heads/master | 2020-06-08T15:21:12.524000 | 2019-06-22T15:44:46 | 2019-06-22T15:44:46 | 193,250,974 | 0 | 1 | null | false | 2020-07-01T23:33:37 | 2019-06-22T15:44:17 | 2019-06-22T15:44:54 | 2020-07-01T23:33:35 | 32 | 0 | 1 | 1 | Java | false | false | package com.dr.leo.etl.controller;
import com.dr.leo.etl.common.ResponseRestResult;
import com.dr.leo.etl.util.FileUtil;
import com.dr.leo.etl.util.HdfsUtil;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author leo.jie (weixiao.me@aliyun.com)
* @version 1.0
* @organization DataReal
* @website https://www.jlpyyf.com
* @date 2019-06-22 18:36
* @since 1.0
*/
@RestController
@RequestMapping("/leo/etl/api/log")
public class LogRestServer extends BaseRestController {
@GetMapping("/detail/{jobId}")
public ResponseRestResult logDetail(@PathVariable int jobId) {
List<String> logContent = HdfsUtil.read("/test/error4.log");
return success(logContent);
}
@GetMapping("/detailLocal/{jobId}")
public ResponseRestResult logDetailLocal(@PathVariable int jobId, @RequestParam String filePath) {
String logContent = FileUtil.read(filePath);
return success(logContent);
}
@GetMapping("/write")
public ResponseRestResult write(@RequestParam String filePath) {
FileUtil.write(filePath, "19/06/22 19:00:39 INFO DispatcherServlet: FrameworkServlet " +
"'dispatcherServlet': initialization completed in 34 ms 结束!");
return success();
}
}
| UTF-8 | Java | 1,274 | java | LogRestServer.java | Java | [
{
"context": "otation.*;\n\nimport java.util.List;\n\n/**\n * @author leo.jie (weixiao.me@aliyun.com)\n * @version 1.0\n * @organ",
"end": 256,
"score": 0.9997345805168152,
"start": 249,
"tag": "NAME",
"value": "leo.jie"
},
{
"context": "\n\nimport java.util.List;\n\n/**\n * @author leo.jie (weixiao.me@aliyun.com)\n * @version 1.0\n * @organization DataReal\n * @we",
"end": 279,
"score": 0.9999335408210754,
"start": 258,
"tag": "EMAIL",
"value": "weixiao.me@aliyun.com"
}
]
| null | []
| package com.dr.leo.etl.controller;
import com.dr.leo.etl.common.ResponseRestResult;
import com.dr.leo.etl.util.FileUtil;
import com.dr.leo.etl.util.HdfsUtil;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author leo.jie (<EMAIL>)
* @version 1.0
* @organization DataReal
* @website https://www.jlpyyf.com
* @date 2019-06-22 18:36
* @since 1.0
*/
@RestController
@RequestMapping("/leo/etl/api/log")
public class LogRestServer extends BaseRestController {
@GetMapping("/detail/{jobId}")
public ResponseRestResult logDetail(@PathVariable int jobId) {
List<String> logContent = HdfsUtil.read("/test/error4.log");
return success(logContent);
}
@GetMapping("/detailLocal/{jobId}")
public ResponseRestResult logDetailLocal(@PathVariable int jobId, @RequestParam String filePath) {
String logContent = FileUtil.read(filePath);
return success(logContent);
}
@GetMapping("/write")
public ResponseRestResult write(@RequestParam String filePath) {
FileUtil.write(filePath, "19/06/22 19:00:39 INFO DispatcherServlet: FrameworkServlet " +
"'dispatcherServlet': initialization completed in 34 ms 结束!");
return success();
}
}
| 1,260 | 0.704259 | 0.679811 | 39 | 31.512821 | 26.66494 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.358974 | false | false | 0 |
c628ae81919e880dc408cecf2fee57aefa747fab | 20,882,131,001,508 | 29197bee635164ef2e4584abddd67211f1a21759 | /spring-boot-data/spring-data-mybatis-plus-mysql/src/test/java/com/asa/dem/spring/boot/vwe/service/dao/BlogDaoTest.java | c282fe7f728ee95ca824b2275efacb29a3c8c119 | []
| no_license | GitHubsteven/spring-in-action2.0 | https://github.com/GitHubsteven/spring-in-action2.0 | 7bbd8ac92c03800131aacb58a8f60c98b9ebf750 | 606901dfa0a26123eef2999313122597cc1c04e2 | refs/heads/master | 2023-08-09T19:42:12.229000 | 2023-08-03T08:07:31 | 2023-08-03T08:07:31 | 204,603,363 | 0 | 0 | null | false | 2023-08-03T08:08:08 | 2019-08-27T02:32:31 | 2021-12-09T14:00:31 | 2023-08-03T08:08:07 | 640 | 0 | 0 | 3 | Java | false | false | package com.asa.dem.spring.boot.vwe.service.dao;
import com.asa.dem.spring.boot.vwe.bean.BlogTreeBean;
import com.asa.dem.spring.boot.vwe.dao.BlogDao;
import com.asa.dem.spring.boot.vwe.service.BaseServiceTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author rongbin.xie
* @version 1.0.0
* @date 2020/10/19
* @description
* @copyright COPYRIGHT © 2014 - 2020 VOYAGE ONE GROUP INC. ALL RIGHTS RESERVED.
**/
public class BlogDaoTest extends BaseServiceTest {
@Autowired
private BlogDao blogDao;
@Test
public void test() {
BlogTreeBean result = blogDao.blogTree(11);
System.out.println(result.getComments());
}
}
| UTF-8 | Java | 708 | java | BlogDaoTest.java | Java | [
{
"context": "eans.factory.annotation.Autowired;\n\n/**\n * @author rongbin.xie\n * @version 1.0.0\n * @date 2020/10/19\n * @descrip",
"end": 325,
"score": 0.8808274269104004,
"start": 314,
"tag": "USERNAME",
"value": "rongbin.xie"
}
]
| null | []
| package com.asa.dem.spring.boot.vwe.service.dao;
import com.asa.dem.spring.boot.vwe.bean.BlogTreeBean;
import com.asa.dem.spring.boot.vwe.dao.BlogDao;
import com.asa.dem.spring.boot.vwe.service.BaseServiceTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author rongbin.xie
* @version 1.0.0
* @date 2020/10/19
* @description
* @copyright COPYRIGHT © 2014 - 2020 VOYAGE ONE GROUP INC. ALL RIGHTS RESERVED.
**/
public class BlogDaoTest extends BaseServiceTest {
@Autowired
private BlogDao blogDao;
@Test
public void test() {
BlogTreeBean result = blogDao.blogTree(11);
System.out.println(result.getComments());
}
}
| 708 | 0.725601 | 0.695898 | 25 | 27.280001 | 23.216408 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.36 | false | false | 0 |
811d47699db734cb7399ffa73faa3ffc281d7f1c | 17,858,474,028,527 | 2fa824fff3cc5a1fb9b6fbec3e6d7b548733a801 | /dust-core/src/main/java/se/l4/dust/api/expression/AbstractDynamicProperty.java | 2bcf2d1364d01e904f2eb68e51d0db3b39798754 | [
"Apache-2.0"
]
| permissive | LevelFourAB/dust | https://github.com/LevelFourAB/dust | 85ea551d4d0520eec2845d975c95f31ed44b103c | 27537385912338f9be8de9366369371c5064969d | refs/heads/master | 2023-03-16T15:54:02.872000 | 2019-03-24T19:01:54 | 2019-03-24T19:01:54 | 486,214 | 3 | 2 | Apache-2.0 | false | 2020-12-10T05:45:20 | 2010-01-24T11:41:22 | 2019-03-24T19:04:49 | 2020-12-10T05:45:17 | 1,900 | 7 | 2 | 10 | Java | false | false | package se.l4.dust.api.expression;
/**
* Abstract implementation of {@link DynamicProperty}.
*
* @author Andreas Holstenson
*
*/
public abstract class AbstractDynamicProperty<T>
implements DynamicProperty<T>
{
@Override
public boolean needsContext()
{
return true;
}
@Override
public DynamicProperty getProperty(ExpressionEncounter encounter, String name)
{
return null;
}
@Override
public DynamicMethod getMethod(ExpressionEncounter encounter, String name, Class... parameters)
{
return null;
}
}
| UTF-8 | Java | 525 | java | AbstractDynamicProperty.java | Java | [
{
"context": "entation of {@link DynamicProperty}.\n *\n * @author Andreas Holstenson\n *\n */\npublic abstract class AbstractDynamicPrope",
"end": 127,
"score": 0.9997166395187378,
"start": 109,
"tag": "NAME",
"value": "Andreas Holstenson"
}
]
| null | []
| package se.l4.dust.api.expression;
/**
* Abstract implementation of {@link DynamicProperty}.
*
* @author <NAME>
*
*/
public abstract class AbstractDynamicProperty<T>
implements DynamicProperty<T>
{
@Override
public boolean needsContext()
{
return true;
}
@Override
public DynamicProperty getProperty(ExpressionEncounter encounter, String name)
{
return null;
}
@Override
public DynamicMethod getMethod(ExpressionEncounter encounter, String name, Class... parameters)
{
return null;
}
}
| 513 | 0.748571 | 0.746667 | 29 | 17.103449 | 24.162302 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.896552 | false | false | 0 |
53db0268aed2101ca8bc99a29fe8691e99c2aaf5 | 5,695,126,645,721 | b1d771b7ac995703f4f31dd1cb5126cc616ec4df | /src/com/video/domain/User.java | 6030bf8f1fec4f6a0f8092c8c9cf286887d71340 | []
| no_license | eolanir/M8 | https://github.com/eolanir/M8 | d3d0e3e9f812dfff2dad57796ab5b9c6cad30dc0 | 65f0799ee8dc16761be975c1aec001fed6e6b89f | refs/heads/master | 2023-06-01T20:45:07.222000 | 2021-06-22T08:52:49 | 2021-06-22T08:52:49 | 379,203,465 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.video.domain;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
public class User {
protected String name;
protected String lastname;
protected Date register;
protected String password;
protected GregorianCalendar calendar;
protected List<Video> videos = new ArrayList<Video>();
public User(String name, String lastname, String password) {
this.name = name;
this.lastname = lastname;
this.password = password;
calendar = new GregorianCalendar();
this.register = calendar.getTime();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Date getRegister() {
return register;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void addVideo(Video video) {
videos.add(video);
}
public List<Video> getVideos(){
return videos;
}
}
| UTF-8 | Java | 1,117 | java | User.java | Java | [
{
"context": "ame;\n\t\tthis.lastname = lastname;\n\t\tthis.password = password;\n\t\tcalendar = new GregorianCalendar();\n\t\tthis.reg",
"end": 497,
"score": 0.9943320751190186,
"start": 489,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "d setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\t\n\tpublic void addVideo(Video video) {\n\t\tvide",
"end": 992,
"score": 0.9965556263923645,
"start": 984,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package com.video.domain;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
public class User {
protected String name;
protected String lastname;
protected Date register;
protected String password;
protected GregorianCalendar calendar;
protected List<Video> videos = new ArrayList<Video>();
public User(String name, String lastname, String password) {
this.name = name;
this.lastname = lastname;
this.password = <PASSWORD>;
calendar = new GregorianCalendar();
this.register = calendar.getTime();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Date getRegister() {
return register;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public void addVideo(Video video) {
videos.add(video);
}
public List<Video> getVideos(){
return videos;
}
}
| 1,121 | 0.722471 | 0.722471 | 60 | 17.616667 | 15.724813 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.4 | false | false | 0 |
6a536f40bc2c7a880e0e0bc931b6ed8041c2f4bf | 20,933,670,611,844 | 5ec8377fe0168af7387c060b5e7fc11abd0b7af6 | /src/main/java/com/myleetcode/bucket_sort/sort_characters_by_frequency/SortCharactersByFrequency.java | 721e41ea2f31e9351b4963d2c7b63a4e1a4ab27c | []
| no_license | arnabs542/leetcode-35 | https://github.com/arnabs542/leetcode-35 | 18c84e18434e41dd7881efe0b942472879a6ccd4 | 492bdfe1b6532dfbcfbc3e7b073e3729184241a4 | refs/heads/master | 2022-12-15T08:13:02.469000 | 2020-09-11T23:07:52 | 2020-09-11T23:07:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.myleetcode.bucket_sort.sort_characters_by_frequency;
public class SortCharactersByFrequency {
/**
* 451. Sort Characters By Frequency
* Medium
*
* 663
*
* 58
*
* Favorite
*
* Share
* Given a string, sort it in decreasing order based on the frequency of characters.
*
* Example 1:
*
* Input:
* "tree"
*
* Output:
* "eert"
*
* Explanation:
* 'e' appears twice while 'r' and 't' both appear once.
* So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
* Example 2:
*
* Input:
* "cccaaa"
*
* Output:
* "cccaaa"
*
* Explanation:
* Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
* Note that "cacaca" is incorrect, as the same characters must be together.
* Example 3:
*
* Input:
* "Aabb"
*
* Output:
* "bbAa"
*
* Explanation:
* "bbaA" is also a valid answer, but "Aabb" is incorrect.
* Note that 'A' and 'a' are treated as two different characters.
*/
/**
* Hash Table
* Heap
* Bucket Sort
*/
/**
* Bloomberg
* |
* 8
*
* Uber
* |
* 4
*
* Expedia
* |
* 3
*
* Amazon
* |
* 2
*
* Microsoft
* |
* 2
*/
}
| UTF-8 | Java | 1,429 | java | SortCharactersByFrequency.java | Java | []
| null | []
| package com.myleetcode.bucket_sort.sort_characters_by_frequency;
public class SortCharactersByFrequency {
/**
* 451. Sort Characters By Frequency
* Medium
*
* 663
*
* 58
*
* Favorite
*
* Share
* Given a string, sort it in decreasing order based on the frequency of characters.
*
* Example 1:
*
* Input:
* "tree"
*
* Output:
* "eert"
*
* Explanation:
* 'e' appears twice while 'r' and 't' both appear once.
* So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
* Example 2:
*
* Input:
* "cccaaa"
*
* Output:
* "cccaaa"
*
* Explanation:
* Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
* Note that "cacaca" is incorrect, as the same characters must be together.
* Example 3:
*
* Input:
* "Aabb"
*
* Output:
* "bbAa"
*
* Explanation:
* "bbaA" is also a valid answer, but "Aabb" is incorrect.
* Note that 'A' and 'a' are treated as two different characters.
*/
/**
* Hash Table
* Heap
* Bucket Sort
*/
/**
* Bloomberg
* |
* 8
*
* Uber
* |
* 4
*
* Expedia
* |
* 3
*
* Amazon
* |
* 2
*
* Microsoft
* |
* 2
*/
}
| 1,429 | 0.477257 | 0.46606 | 79 | 17.088608 | 20.531662 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.126582 | false | false | 0 |
3cd6826cb1ada564cdefd6019d45a428de2c198a | 6,133,213,309,130 | 98ffbe64080f098b73bf27fb4635846985277a2b | /src/main/java/com/example/wbdvsp20astefanifinalprojectserver/repositories/InviteRepository.java | 8a2f9799057376d8a58f0bbbaaa7991c7bf5a2b6 | []
| no_license | stefamy/final-project-java-server | https://github.com/stefamy/final-project-java-server | 57b358e3846ecf4d70273bc3bcd37501896526f3 | 33931a3caedb3d7661bef4cf9fa931e6faf5f8c1 | refs/heads/master | 2023-08-08T23:01:08.778000 | 2020-05-06T00:48:37 | 2020-05-06T00:48:37 | 253,706,533 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.wbdvsp20astefanifinalprojectserver.repositories;
import com.example.wbdvsp20astefanifinalprojectserver.models.Invite;
import com.example.wbdvsp20astefanifinalprojectserver.models.Event;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface InviteRepository extends CrudRepository<Invite, Integer> {
@Query(value = "SELECT * FROM Invite invite", nativeQuery = true)
List<Invite> findAllInvites();
@Query(value ="SELECT * FROM Invite invite WHERE event_id=:eventId", nativeQuery = true)
public List<Invite> findAllInvitesForEvent(@Param("eventId") Integer eventId);
@Query(value = "SELECT * FROM Invite invite WHERE id=:id", nativeQuery = true)
public Invite findInviteById(@Param("id") Integer id);
@Query(value = "SELECT * FROM Invite invite WHERE guest_id=:userId", nativeQuery = true)
public List<Invite> findInvitesByGuestId(@Param("userId") Integer userId);
@Query(value = "SELECT * FROM Invite invite WHERE guest_id=:userId AND response='Yes'", nativeQuery = true)
public List<Invite> findAcceptedInvitesByGuestId(@Param("userId") Integer userId);
}
| UTF-8 | Java | 1,344 | java | InviteRepository.java | Java | []
| null | []
| package com.example.wbdvsp20astefanifinalprojectserver.repositories;
import com.example.wbdvsp20astefanifinalprojectserver.models.Invite;
import com.example.wbdvsp20astefanifinalprojectserver.models.Event;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface InviteRepository extends CrudRepository<Invite, Integer> {
@Query(value = "SELECT * FROM Invite invite", nativeQuery = true)
List<Invite> findAllInvites();
@Query(value ="SELECT * FROM Invite invite WHERE event_id=:eventId", nativeQuery = true)
public List<Invite> findAllInvitesForEvent(@Param("eventId") Integer eventId);
@Query(value = "SELECT * FROM Invite invite WHERE id=:id", nativeQuery = true)
public Invite findInviteById(@Param("id") Integer id);
@Query(value = "SELECT * FROM Invite invite WHERE guest_id=:userId", nativeQuery = true)
public List<Invite> findInvitesByGuestId(@Param("userId") Integer userId);
@Query(value = "SELECT * FROM Invite invite WHERE guest_id=:userId AND response='Yes'", nativeQuery = true)
public List<Invite> findAcceptedInvitesByGuestId(@Param("userId") Integer userId);
}
| 1,344 | 0.77381 | 0.769345 | 31 | 42.290321 | 36.624683 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.612903 | false | false | 0 |
0fe800ed3c26d98baa0111197457dc0c7e4f592c | 9,457,517,995,713 | 93229ce4a0853d80cee7702c505543bbd2add9ab | /src/main/java/com/darian/schoolmanager/teacher/DTO/request/ClassesCourseTeacherGetAllSearchRequest.java | 4d2f242e88c7d90974fe58cdc25b309257d9be3e | []
| no_license | Darian1996/school-manager | https://github.com/Darian1996/school-manager | f740b5d3b6ab1e9e16961b2e3afbb78ad687e20d | e61c31482683d259ce93c633280809ad10e332e2 | refs/heads/master | 2023-03-21T15:46:10.209000 | 2021-03-18T18:14:10 | 2021-03-18T18:14:10 | 314,790,246 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.darian.schoolmanager.teacher.DTO.request;
import com.darian.schoolmanager.common.modle.BasePageRequest;
import lombok.Data;
/***
*
*
* @author <a href="mailto:1934849492@qq.com">Darian</a>
* @date 2020/10/11 1:33
*/
@Data
public class ClassesCourseTeacherGetAllSearchRequest extends BasePageRequest {
private Long id;
private Long classesId;
private Long courseId;
private Long teacherId;
}
| UTF-8 | Java | 431 | java | ClassesCourseTeacherGetAllSearchRequest.java | Java | [
{
"context": "mbok.Data;\n\n/***\n *\n *\n * @author <a href=\"mailto:1934849492@qq.com\">Darian</a> \n * @date 2020/10/11 1:33\n */\n@Data\n",
"end": 193,
"score": 0.9999069571495056,
"start": 176,
"tag": "EMAIL",
"value": "1934849492@qq.com"
},
{
"context": "\n *\n * @author <a href=\"mailto:1934849492@qq.com\">Darian</a> \n * @date 2020/10/11 1:33\n */\n@Data\npublic c",
"end": 201,
"score": 0.9986286759376526,
"start": 195,
"tag": "NAME",
"value": "Darian"
}
]
| null | []
| package com.darian.schoolmanager.teacher.DTO.request;
import com.darian.schoolmanager.common.modle.BasePageRequest;
import lombok.Data;
/***
*
*
* @author <a href="mailto:<EMAIL>">Darian</a>
* @date 2020/10/11 1:33
*/
@Data
public class ClassesCourseTeacherGetAllSearchRequest extends BasePageRequest {
private Long id;
private Long classesId;
private Long courseId;
private Long teacherId;
}
| 421 | 0.737819 | 0.689095 | 21 | 19.523809 | 23.337317 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 0 |
3b042266670505f19b790c65770e196c22394093 | 27,762,668,644,701 | a8e1f52311fe470dc7fbce720b498cf4dcdc1df3 | /src/com/jeradmeisner/sickdroid/utils/enumerations/ApiCommands.java | 50cebcc53e8443d5b2c3f77414e42d8bf4139098 | []
| no_license | jeradM/sickdroid | https://github.com/jeradM/sickdroid | ba736b2faa81540f29c59802fc86fe306ff0fa53 | e901e3142470f6d6469173b93d23fae0eefb845d | refs/heads/master | 2021-01-22T04:33:26.617000 | 2013-07-06T20:29:21 | 2013-07-06T20:29:21 | 38,391,325 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jeradmeisner.sickdroid.utils.enumerations;
public enum ApiCommands {
SHOWS("shows"),
SHOW("show&tvdbid=%s"),
BANNER("show.getbanner&tvdbid=%s"),
POSTER("show.getposter&tvdbid=%s"),
HISTORY("history&limit=%s&type=%s"),
SEASONLIST("show.seasonlist&tvdbid=%s"),
EPISODE("episode&tvdbid=%s&season=%s&episode=%s"),
EPISODE_SEARCH("episode.search&tvdbid=%s&season=%s&episode=%s"),
FUTURE("future");
private String cmdString;
private ApiCommands(String cmdString)
{
this.cmdString = cmdString;
}
public String toString()
{
return cmdString;
}
} | UTF-8 | Java | 634 | java | ApiCommands.java | Java | [
{
"context": "package com.jeradmeisner.sickdroid.utils.enumerations;\n\npublic enum ApiCom",
"end": 24,
"score": 0.9513447880744934,
"start": 12,
"tag": "USERNAME",
"value": "jeradmeisner"
}
]
| null | []
| package com.jeradmeisner.sickdroid.utils.enumerations;
public enum ApiCommands {
SHOWS("shows"),
SHOW("show&tvdbid=%s"),
BANNER("show.getbanner&tvdbid=%s"),
POSTER("show.getposter&tvdbid=%s"),
HISTORY("history&limit=%s&type=%s"),
SEASONLIST("show.seasonlist&tvdbid=%s"),
EPISODE("episode&tvdbid=%s&season=%s&episode=%s"),
EPISODE_SEARCH("episode.search&tvdbid=%s&season=%s&episode=%s"),
FUTURE("future");
private String cmdString;
private ApiCommands(String cmdString)
{
this.cmdString = cmdString;
}
public String toString()
{
return cmdString;
}
} | 634 | 0.646688 | 0.646688 | 26 | 23.423077 | 19.789612 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 0 |
f2f5e6cf6846bbd0b511a9602430e6726ee435b8 | 33,139,967,702,904 | 58caaadb314acdff29c23633741895f1aee462c4 | /server/com.dexels.navajo.resource.http/src/com/dexels/navajo/resource/http/HttpResource.java | a0583c662efe41b2f2b087f8cbd5bf56401bfdd6 | []
| no_license | mvdhorst/navajo | https://github.com/mvdhorst/navajo | 5c26314cc5a9a4ecb337d81604e941f9239ea9f2 | 21e1ed205d5995ae7aa3bdc645124885448bf867 | refs/heads/master | 2021-01-10T22:28:23.051000 | 2015-02-27T08:48:52 | 2015-02-27T08:48:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dexels.navajo.resource.http;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.concurrent.Future;
public interface HttpResource {
public InputStream call() throws MalformedURLException, IOException;
public InputStream call(OutputStream os) throws MalformedURLException, IOException;
public Future<InputStream> callAsync();
public Future<InputStream> callAsync(OutputStream os);
public String getURL();
}
| UTF-8 | Java | 514 | java | HttpResource.java | Java | []
| null | []
| package com.dexels.navajo.resource.http;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.concurrent.Future;
public interface HttpResource {
public InputStream call() throws MalformedURLException, IOException;
public InputStream call(OutputStream os) throws MalformedURLException, IOException;
public Future<InputStream> callAsync();
public Future<InputStream> callAsync(OutputStream os);
public String getURL();
}
| 514 | 0.822957 | 0.822957 | 15 | 33.266666 | 22.936047 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.2 | false | false | 0 |
5953096c770bd667111c3aee261ce03ce221808f | 33,139,967,700,121 | bdcbf6ecf514e99174dfc2248bdddfcfea29d618 | /frontend/modules/DBModule/src/objects/Permission.java | 161a95aeefe6f56eddf0a147e4736d48f7180105 | []
| no_license | bmiddag/car-sharing | https://github.com/bmiddag/car-sharing | 08ad8450be0606346d14b8a8611ef16e320145fb | 2dbafec40cbacf11329ec5ee48fd4d1bf9340341 | refs/heads/master | 2021-01-11T01:14:34.195000 | 2016-10-12T20:16:37 | 2016-10-12T20:16:37 | 70,732,283 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package objects;
import java.util.EnumMap;
/**
* A permission in the system. I.e. block users
*/
public class Permission extends DataObject {
public enum Field implements DataField {
ID(Integer.class, true, false),
NAME(String.class);
private final boolean stamp;
private final boolean key;
private final Class type;
private Field(Class type, boolean key, boolean stamp) {
this.type = type;
this.key = key;
this.stamp = stamp;
}
private Field(Class type) {
this.type = type;
this.key = false;
this.stamp = false;
}
@Override
public Class getType() {
return type;
}
@Override
public boolean isKey() {
return key;
}
@Override
public boolean isStamp() {
return stamp;
}
}
/**
*
* @param id the id generated by the db
* @param name the name of the role
*/
public Permission(Integer id, String name) {
super(new EnumMap<>(Field.class));
data.put(Field.ID, id);
data.put(Field.NAME, name);
}
/**
*
* @return the id assigned by the db
*/
public Integer getId() {
return (Integer) data.get(Field.ID);
}
/**
*
* @return the name of the role
*/
public String getName() {
return (String) data.get(Field.NAME);
}
/**
*
* @param name the name of the role
*/
public void setName(String name) {
data.put(Field.NAME, name);
}
}
| UTF-8 | Java | 1,447 | java | Permission.java | Java | []
| null | []
| package objects;
import java.util.EnumMap;
/**
* A permission in the system. I.e. block users
*/
public class Permission extends DataObject {
public enum Field implements DataField {
ID(Integer.class, true, false),
NAME(String.class);
private final boolean stamp;
private final boolean key;
private final Class type;
private Field(Class type, boolean key, boolean stamp) {
this.type = type;
this.key = key;
this.stamp = stamp;
}
private Field(Class type) {
this.type = type;
this.key = false;
this.stamp = false;
}
@Override
public Class getType() {
return type;
}
@Override
public boolean isKey() {
return key;
}
@Override
public boolean isStamp() {
return stamp;
}
}
/**
*
* @param id the id generated by the db
* @param name the name of the role
*/
public Permission(Integer id, String name) {
super(new EnumMap<>(Field.class));
data.put(Field.ID, id);
data.put(Field.NAME, name);
}
/**
*
* @return the id assigned by the db
*/
public Integer getId() {
return (Integer) data.get(Field.ID);
}
/**
*
* @return the name of the role
*/
public String getName() {
return (String) data.get(Field.NAME);
}
/**
*
* @param name the name of the role
*/
public void setName(String name) {
data.put(Field.NAME, name);
}
}
| 1,447 | 0.590878 | 0.590878 | 85 | 16.023529 | 15.64682 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 0 |
062fe687bf25e7c2ea6d89de9a6edabc6210240b | 6,433,861,061,549 | 500934481bd99d0c6ee59add9e7c3ba43d1e459d | /core/src/main/java/nl/weeaboo/vn/impl/scene/AnimatedRenderable.java | cb713f8f67b6b456e889809ac7342999017b4778 | [
"Apache-2.0"
]
| permissive | anonl/nvlist | https://github.com/anonl/nvlist | c60c1cf92eb91e0441385f2db1a66992e3653be3 | 235b251c0896c9fb568398012a4316f2f4177fd9 | refs/heads/master | 2023-08-24T01:00:05.582000 | 2023-07-29T11:31:12 | 2023-07-29T11:31:12 | 39,298,591 | 26 | 5 | NOASSERTION | false | 2023-09-09T07:54:45 | 2015-07-18T13:07:58 | 2023-05-27T17:13:27 | 2023-09-09T07:54:44 | 130,820 | 23 | 1 | 9 | Java | false | false | package nl.weeaboo.vn.impl.scene;
import nl.weeaboo.common.Area2D;
import nl.weeaboo.vn.core.IAnimation;
import nl.weeaboo.vn.core.IEventListener;
import nl.weeaboo.vn.impl.core.Animation;
import nl.weeaboo.vn.render.IDrawBuffer;
import nl.weeaboo.vn.scene.IDrawable;
import nl.weeaboo.vn.scene.IRenderable;
/**
* Base implementation for classes implementing both {@link IRenderable} and {@link IAnimation}.
*/
public abstract class AnimatedRenderable extends AbstractRenderable implements IAnimation {
private static final long serialVersionUID = SceneImpl.serialVersionUID;
private final Animation animation;
private boolean prepared;
protected AnimatedRenderable(double duration) {
animation = new Animation(duration);
}
@Override
public void onAttached(IEventListener cl) {
super.onAttached(cl);
checkedPrepare();
}
@Override
public void onDetached(IEventListener cl) {
super.onDetached(cl);
checkedDispose();
}
@Override
public void update() {
super.update();
if (!isFinished()) {
animation.update();
checkedPrepare();
updateResources();
if (isFinished()) {
onFinished();
}
}
}
private void checkedPrepare() {
if (!prepared) {
prepareResources();
prepared = true;
}
}
private void checkedDispose() {
if (prepared) {
disposeResources();
prepared = false;
}
}
protected void onFinished() {
}
protected void prepareResources() {
}
protected void updateResources() {
}
protected void disposeResources() {
}
@Override
public boolean isFinished() {
return animation.isFinished();
}
/**
* @see Animation#getNormalizedTime()
*/
public final double getNormalizedTime() {
return animation.getNormalizedTime();
}
/**
* @see Animation#getTime()
*/
public final double getTime() {
return animation.getTime();
}
/**
* @see Animation#setTime(double)
*/
public void setTime(double newTime) {
animation.setTime(newTime);
}
/**
* @see Animation#getDuration()
*/
public double getDuration() {
return animation.getDuration();
}
@Override
public void setSpeed(double s) {
animation.setSpeed(s);
}
@Override
protected final void render(IDrawBuffer drawBuffer, IDrawable parent, Area2D bounds) {
if (isFinished()) {
renderEnd(drawBuffer, parent, bounds);
} else if (getNormalizedTime() <= 0) {
renderStart(drawBuffer, parent, bounds);
} else {
checkedRenderIntermediate(drawBuffer, parent, bounds);
}
}
private void checkedRenderIntermediate(IDrawBuffer drawBuffer, IDrawable parent, Area2D bounds) {
checkedPrepare();
renderIntermediate(drawBuffer, parent, bounds);
}
protected void renderStart(IDrawBuffer drawBuffer, IDrawable parent, Area2D bounds) {
checkedRenderIntermediate(drawBuffer, parent, bounds);
}
protected abstract void renderIntermediate(IDrawBuffer drawBuffer, IDrawable parent, Area2D bounds);
protected void renderEnd(IDrawBuffer drawBuffer, IDrawable parent, Area2D bounds) {
checkedRenderIntermediate(drawBuffer, parent, bounds);
}
}
| UTF-8 | Java | 3,497 | java | AnimatedRenderable.java | Java | []
| null | []
| package nl.weeaboo.vn.impl.scene;
import nl.weeaboo.common.Area2D;
import nl.weeaboo.vn.core.IAnimation;
import nl.weeaboo.vn.core.IEventListener;
import nl.weeaboo.vn.impl.core.Animation;
import nl.weeaboo.vn.render.IDrawBuffer;
import nl.weeaboo.vn.scene.IDrawable;
import nl.weeaboo.vn.scene.IRenderable;
/**
* Base implementation for classes implementing both {@link IRenderable} and {@link IAnimation}.
*/
public abstract class AnimatedRenderable extends AbstractRenderable implements IAnimation {
private static final long serialVersionUID = SceneImpl.serialVersionUID;
private final Animation animation;
private boolean prepared;
protected AnimatedRenderable(double duration) {
animation = new Animation(duration);
}
@Override
public void onAttached(IEventListener cl) {
super.onAttached(cl);
checkedPrepare();
}
@Override
public void onDetached(IEventListener cl) {
super.onDetached(cl);
checkedDispose();
}
@Override
public void update() {
super.update();
if (!isFinished()) {
animation.update();
checkedPrepare();
updateResources();
if (isFinished()) {
onFinished();
}
}
}
private void checkedPrepare() {
if (!prepared) {
prepareResources();
prepared = true;
}
}
private void checkedDispose() {
if (prepared) {
disposeResources();
prepared = false;
}
}
protected void onFinished() {
}
protected void prepareResources() {
}
protected void updateResources() {
}
protected void disposeResources() {
}
@Override
public boolean isFinished() {
return animation.isFinished();
}
/**
* @see Animation#getNormalizedTime()
*/
public final double getNormalizedTime() {
return animation.getNormalizedTime();
}
/**
* @see Animation#getTime()
*/
public final double getTime() {
return animation.getTime();
}
/**
* @see Animation#setTime(double)
*/
public void setTime(double newTime) {
animation.setTime(newTime);
}
/**
* @see Animation#getDuration()
*/
public double getDuration() {
return animation.getDuration();
}
@Override
public void setSpeed(double s) {
animation.setSpeed(s);
}
@Override
protected final void render(IDrawBuffer drawBuffer, IDrawable parent, Area2D bounds) {
if (isFinished()) {
renderEnd(drawBuffer, parent, bounds);
} else if (getNormalizedTime() <= 0) {
renderStart(drawBuffer, parent, bounds);
} else {
checkedRenderIntermediate(drawBuffer, parent, bounds);
}
}
private void checkedRenderIntermediate(IDrawBuffer drawBuffer, IDrawable parent, Area2D bounds) {
checkedPrepare();
renderIntermediate(drawBuffer, parent, bounds);
}
protected void renderStart(IDrawBuffer drawBuffer, IDrawable parent, Area2D bounds) {
checkedRenderIntermediate(drawBuffer, parent, bounds);
}
protected abstract void renderIntermediate(IDrawBuffer drawBuffer, IDrawable parent, Area2D bounds);
protected void renderEnd(IDrawBuffer drawBuffer, IDrawable parent, Area2D bounds) {
checkedRenderIntermediate(drawBuffer, parent, bounds);
}
}
| 3,497 | 0.629969 | 0.627967 | 147 | 22.789116 | 23.991278 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.414966 | false | false | 0 |
556a13ae28b520084946f61e22b2e831c4c9c484 | 6,433,861,062,987 | 693894c0937958320c7852241007106572aec0e2 | /too.base/src/too/util/function/ObjIntPredicate.java | 8b471fb8d02f887d7500dce3ef25974101b85e32 | []
| no_license | ituke/too | https://github.com/ituke/too | 44829228270ec7adeff9a7a2a37891ba94a41a95 | 9d017af32ae2769e14eece8811457cc392be1931 | refs/heads/master | 2017-12-17T20:36:48.300000 | 2017-11-13T07:51:28 | 2017-11-13T07:51:28 | 77,191,670 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package too.util.function;
@FunctionalInterface
public interface ObjIntPredicate<G> {
boolean test(G v1, int v2);
}
| UTF-8 | Java | 121 | java | ObjIntPredicate.java | Java | []
| null | []
| package too.util.function;
@FunctionalInterface
public interface ObjIntPredicate<G> {
boolean test(G v1, int v2);
}
| 121 | 0.752066 | 0.735537 | 6 | 19.166666 | 14.158821 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 0 |
acb4b2ad93ae4fdb534837aaa1299e5d765123bc | 3,968,549,836,904 | 1f785f9ea300ae0fcc96efb2e70253345e285dec | /src/main/java/org/okaria/util/R.java | 7b879187fd483f1f23165633e8999ba67cf172ab | []
| no_license | salemebo/okaria | https://github.com/salemebo/okaria | 242de8bcfa174a6c15344fe2b8adbd1a99f7d615 | 8ea7355f514f0da6a56c4dba9921600b5cf7ead8 | refs/heads/master | 2020-03-21T13:52:47.375000 | 2020-03-15T08:38:22 | 2020-03-15T08:38:22 | 138,629,771 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.okaria.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.log.concurrent.Log;
public class R {
public static char sprtr = File.separatorChar;
public static String app_name = "okaria";
public static String code_name = "و";
public static String UserHome = System.getProperty("user.home");
public static String DownloadsPath = UserHome + sprtr + "Downloads" + sprtr + app_name + sprtr;
public static String ConfigPath = UserHome + sprtr + ".config" + sprtr + app_name + sprtr;
public static String CachePath = UserHome + sprtr + ".cache" + sprtr + app_name + sprtr;
public static String ConfigJsonFile;
public static String LockFile = CachePath + sprtr + "lock";
public static String TempDir = "/tmp/";
static {
String cacheFolder = "";
if (PlatformUtil.isWin7OrLater()) {
cacheFolder = UserHome + sprtr + "AppData" + sprtr + "Roaming" + sprtr + app_name + sprtr;
CachePath = cacheFolder + "cache" + sprtr;
ConfigPath = cacheFolder + "config" + sprtr;
} else if (PlatformUtil.isWindows()) {
cacheFolder = UserHome + sprtr + "Application Data" + sprtr + app_name + sprtr;
TempDir = cacheFolder + "temp";
CachePath = cacheFolder + "cache" + sprtr;
ConfigPath = cacheFolder + "config" + sprtr;
} else if (PlatformUtil.isMac()) { // Library/Application Support/
cacheFolder = UserHome + sprtr + "Library" + sprtr + "Application Support" + sprtr + app_name + sprtr;
TempDir = UserHome + "/Library/Caches/TemporaryItems/";
CachePath = cacheFolder + "cache" + sprtr;
ConfigPath = cacheFolder + "config" + sprtr;
}
LockFile = CachePath + sprtr + "lock";
ConfigJsonFile = ConfigPath + "config.json";
;
}
/* ========================================================================= */
/* ========================== Resources Methods Init ======================= */
/**
* use <System.currentTimeMillis()> as timeMapId
*
* @return string represent a
*/
public static String getConfigDirectory() {
return ConfigPath;
}
public static String getConfigPath(String filename) {
filename = ConfigPath + filename;
// mkParentDir(filename);
return filename;
}
public static File getConfigFile(String filename) {
return new File(getConfigPath(filename));
}
public static String getCompleteFile(String filename) {
return getCompleteDir() + filename;
}
public static String getNewDownload(String name) {
return ConfigPath + "download" + sprtr + name;
}
public static String getCompleteDir() {
return ConfigPath + "complete" + sprtr;
}
public static String NewCacheDir() {
return getNewCacheDir(System.currentTimeMillis());
}
public static String getNewCacheDir(long timeMapId) {
return CachePath + timeMapId + sprtr;
}
public static String getCacheFile(String filename) {
return CachePath + filename;
}
public static String getNewCacheDir(String dirname) {
return CachePath + dirname + sprtr;
}
public static String NewCacheFile(String filename) {
return CreateCacheFile(System.currentTimeMillis(), filename);
}
public static String CreateCacheFile(long timeMapId, String filename) {
filename = CachePath + timeMapId + "-" + filename;
mkParentDir(filename);
return filename;
}
public static String getDownloadsFile() {
return DownloadsPath;
}
public static String getDownloadsFile(String filename) {
filename = DownloadsPath + filename;
mkParentDir(filename);
return filename;
}
public static void InitDirs() {
File creator = new File(ConfigPath);
mkdir(creator);
creator = new File(CachePath);
mkdir(creator);
}
public static void MK_DIRS(String creator) {
mkdir(new File(creator));
}
public static void mkdir(File creator) {
try {
creator.mkdirs();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void mkParentDir(String creator) {
mkParentDir(new File(creator));
}
public static void mkParentDir(File creator) {
try {
creator.getParentFile().mkdirs();
} catch (Exception e) {
e.printStackTrace();
}
}
/* ========================================================================= */
/* ======================== Resources Methods onSave ======================= */
public static void DeleteTemp() {
File temp = new File(ConfigPath);
try {
delete(temp);
} catch (IOException e) {
System.out.println("Can't delete Files");
e.printStackTrace();
}
}
public static void delete(File file) throws IOException {
if (file.isDirectory()) {
// directory is empty, then delete it
if (file.list().length == 0) {
file.delete();
// System.out.println("Delete Directory : "+ file.getAbsolutePath());
} else {
// list all the directory contents
String files[] = file.list();
for (String temp : files) {
// construct the file structure
File fileDelete = new File(file, temp);
// recursive delete
delete(fileDelete);
}
// check the directory again, if empty then delete it
if (file.list().length == 0) {
file.delete();
}
}
} else {
// if file, then delete it
file.delete();
}
}
public static void openProcess(String str) {
List<String> list = new ArrayList<String>();
if (PlatformUtil.isLinux()) {
list.add("xdg-open");
list.add(str);
} else if (PlatformUtil.isWindows()) {
list.add("start");
list.add(str);
} else if (PlatformUtil.isMac()) {
list.add("open");
list.add(str);
}
ProcessBuilder builder = new ProcessBuilder(list);
try {
builder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String CurrentDirectory() {
return System.getProperty("user.dir") + File.separatorChar;
}
/**
*
* @return
*/
public static String getCurrentDirectory() {
String path = System.getProperty("user.dir") + File.separatorChar;
System.out.println(path);
try {
System.getSecurityManager().checkWrite(path+"test");
Log.info(R.class, "set default directory to [" + path + " ].");
return path;
} catch (Exception e) {
e.printStackTrace();
Log.info(R.class, "set default directory to [" + getDownloadsFile() + " ].");
return getDownloadsFile();
}
}
}
| UTF-8 | Java | 6,479 | java | R.java | Java | []
| null | []
| package org.okaria.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.log.concurrent.Log;
public class R {
public static char sprtr = File.separatorChar;
public static String app_name = "okaria";
public static String code_name = "و";
public static String UserHome = System.getProperty("user.home");
public static String DownloadsPath = UserHome + sprtr + "Downloads" + sprtr + app_name + sprtr;
public static String ConfigPath = UserHome + sprtr + ".config" + sprtr + app_name + sprtr;
public static String CachePath = UserHome + sprtr + ".cache" + sprtr + app_name + sprtr;
public static String ConfigJsonFile;
public static String LockFile = CachePath + sprtr + "lock";
public static String TempDir = "/tmp/";
static {
String cacheFolder = "";
if (PlatformUtil.isWin7OrLater()) {
cacheFolder = UserHome + sprtr + "AppData" + sprtr + "Roaming" + sprtr + app_name + sprtr;
CachePath = cacheFolder + "cache" + sprtr;
ConfigPath = cacheFolder + "config" + sprtr;
} else if (PlatformUtil.isWindows()) {
cacheFolder = UserHome + sprtr + "Application Data" + sprtr + app_name + sprtr;
TempDir = cacheFolder + "temp";
CachePath = cacheFolder + "cache" + sprtr;
ConfigPath = cacheFolder + "config" + sprtr;
} else if (PlatformUtil.isMac()) { // Library/Application Support/
cacheFolder = UserHome + sprtr + "Library" + sprtr + "Application Support" + sprtr + app_name + sprtr;
TempDir = UserHome + "/Library/Caches/TemporaryItems/";
CachePath = cacheFolder + "cache" + sprtr;
ConfigPath = cacheFolder + "config" + sprtr;
}
LockFile = CachePath + sprtr + "lock";
ConfigJsonFile = ConfigPath + "config.json";
;
}
/* ========================================================================= */
/* ========================== Resources Methods Init ======================= */
/**
* use <System.currentTimeMillis()> as timeMapId
*
* @return string represent a
*/
public static String getConfigDirectory() {
return ConfigPath;
}
public static String getConfigPath(String filename) {
filename = ConfigPath + filename;
// mkParentDir(filename);
return filename;
}
public static File getConfigFile(String filename) {
return new File(getConfigPath(filename));
}
public static String getCompleteFile(String filename) {
return getCompleteDir() + filename;
}
public static String getNewDownload(String name) {
return ConfigPath + "download" + sprtr + name;
}
public static String getCompleteDir() {
return ConfigPath + "complete" + sprtr;
}
public static String NewCacheDir() {
return getNewCacheDir(System.currentTimeMillis());
}
public static String getNewCacheDir(long timeMapId) {
return CachePath + timeMapId + sprtr;
}
public static String getCacheFile(String filename) {
return CachePath + filename;
}
public static String getNewCacheDir(String dirname) {
return CachePath + dirname + sprtr;
}
public static String NewCacheFile(String filename) {
return CreateCacheFile(System.currentTimeMillis(), filename);
}
public static String CreateCacheFile(long timeMapId, String filename) {
filename = CachePath + timeMapId + "-" + filename;
mkParentDir(filename);
return filename;
}
public static String getDownloadsFile() {
return DownloadsPath;
}
public static String getDownloadsFile(String filename) {
filename = DownloadsPath + filename;
mkParentDir(filename);
return filename;
}
public static void InitDirs() {
File creator = new File(ConfigPath);
mkdir(creator);
creator = new File(CachePath);
mkdir(creator);
}
public static void MK_DIRS(String creator) {
mkdir(new File(creator));
}
public static void mkdir(File creator) {
try {
creator.mkdirs();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void mkParentDir(String creator) {
mkParentDir(new File(creator));
}
public static void mkParentDir(File creator) {
try {
creator.getParentFile().mkdirs();
} catch (Exception e) {
e.printStackTrace();
}
}
/* ========================================================================= */
/* ======================== Resources Methods onSave ======================= */
public static void DeleteTemp() {
File temp = new File(ConfigPath);
try {
delete(temp);
} catch (IOException e) {
System.out.println("Can't delete Files");
e.printStackTrace();
}
}
public static void delete(File file) throws IOException {
if (file.isDirectory()) {
// directory is empty, then delete it
if (file.list().length == 0) {
file.delete();
// System.out.println("Delete Directory : "+ file.getAbsolutePath());
} else {
// list all the directory contents
String files[] = file.list();
for (String temp : files) {
// construct the file structure
File fileDelete = new File(file, temp);
// recursive delete
delete(fileDelete);
}
// check the directory again, if empty then delete it
if (file.list().length == 0) {
file.delete();
}
}
} else {
// if file, then delete it
file.delete();
}
}
public static void openProcess(String str) {
List<String> list = new ArrayList<String>();
if (PlatformUtil.isLinux()) {
list.add("xdg-open");
list.add(str);
} else if (PlatformUtil.isWindows()) {
list.add("start");
list.add(str);
} else if (PlatformUtil.isMac()) {
list.add("open");
list.add(str);
}
ProcessBuilder builder = new ProcessBuilder(list);
try {
builder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String CurrentDirectory() {
return System.getProperty("user.dir") + File.separatorChar;
}
/**
*
* @return
*/
public static String getCurrentDirectory() {
String path = System.getProperty("user.dir") + File.separatorChar;
System.out.println(path);
try {
System.getSecurityManager().checkWrite(path+"test");
Log.info(R.class, "set default directory to [" + path + " ].");
return path;
} catch (Exception e) {
e.printStackTrace();
Log.info(R.class, "set default directory to [" + getDownloadsFile() + " ].");
return getDownloadsFile();
}
}
}
| 6,479 | 0.62581 | 0.625347 | 237 | 25.333334 | 24.123159 | 105 | false | false | 0 | 0 | 0 | 0 | 73 | 0.022538 | 2.050633 | false | false | 0 |
f4e75eaf97413ea28d6fd520faf972073591d6f3 | 3,298,534,935,448 | 411143aef6059b55ee45a93c3c44cf98b84dc132 | /module-dynamic-load/src/main/java/yunnex/mdl/ModuleMetrics.java | 8b37328e89b17355ebce6a48e117bb4ea5eb692b | []
| no_license | awang12345/module-dynamic-load | https://github.com/awang12345/module-dynamic-load | 215934f18190fee8a878b7c2f26aa1307a67bd1f | 054ff0943a4a3ba8505518c8cd00508cf9072a80 | refs/heads/master | 2020-03-17T20:06:16.596000 | 2018-05-18T02:52:33 | 2018-05-18T02:52:33 | 133,893,313 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package yunnex.mdl;
/**
* 模块运行的一些指标信息
*
* @author jingyiwang
* @date 2018年3月26日
*/
public interface ModuleMetrics {
/**
* 模块运行过程处理请求次数
*
* @return
* @date 2018年3月26日
* @author jiangyiwang
*/
int getTotalProcessCount();
/**
* 模块运行时处理异常次数
*
* @return
* @date 2018年3月26日
* @author jiangyiwang
*/
int getErrorProcessCount();
/**
* 获取运行时间
*
* @return
* @date 2018年3月26日
* @author jiangyiwang
*/
long getRuntime();
}
| UTF-8 | Java | 640 | java | ModuleMetrics.java | Java | [
{
"context": "age yunnex.mdl;\n\n/**\n * 模块运行的一些指标信息\n * \n * @author jingyiwang\n * @date 2018年3月26日\n */\npublic interface ModuleMe",
"end": 65,
"score": 0.9979667663574219,
"start": 55,
"tag": "USERNAME",
"value": "jingyiwang"
},
{
"context": " * @return\n * @date 2018年3月26日\n * @author jiangyiwang\n */\n int getTotalProcessCount();\n\n /**\n",
"end": 224,
"score": 0.9990357160568237,
"start": 213,
"tag": "USERNAME",
"value": "jiangyiwang"
},
{
"context": " * @return\n * @date 2018年3月26日\n * @author jiangyiwang\n */\n int getErrorProcessCount();\n\n /**\n",
"end": 365,
"score": 0.99933922290802,
"start": 354,
"tag": "USERNAME",
"value": "jiangyiwang"
},
{
"context": " * @return\n * @date 2018年3月26日\n * @author jiangyiwang\n */\n long getRuntime();\n\n}\n",
"end": 501,
"score": 0.9975708723068237,
"start": 490,
"tag": "USERNAME",
"value": "jiangyiwang"
}
]
| null | []
| package yunnex.mdl;
/**
* 模块运行的一些指标信息
*
* @author jingyiwang
* @date 2018年3月26日
*/
public interface ModuleMetrics {
/**
* 模块运行过程处理请求次数
*
* @return
* @date 2018年3月26日
* @author jiangyiwang
*/
int getTotalProcessCount();
/**
* 模块运行时处理异常次数
*
* @return
* @date 2018年3月26日
* @author jiangyiwang
*/
int getErrorProcessCount();
/**
* 获取运行时间
*
* @return
* @date 2018年3月26日
* @author jiangyiwang
*/
long getRuntime();
}
| 640 | 0.531716 | 0.479478 | 38 | 13.105263 | 9.933435 | 32 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.105263 | false | false | 0 |
23c90e2c2241e5e399f663847857b82f2e8b839b | 16,329,465,702,771 | 230268429f860a744774a9728d5ad04b60518ef0 | /final-framework-testng/src/com/training/pom/DeleteiconPOM.java | dd58a1fe918042029d9c5abe8b97a2a55fab18a6 | []
| no_license | VamanamurthyJonnadula/SeleniumProject | https://github.com/VamanamurthyJonnadula/SeleniumProject | 40b74718ff5ab849743e1b37f4ce49b8d8332a15 | ead7cbbfb247337ad2b28ee20f9e8bde20d75ad1 | refs/heads/master | 2022-07-16T14:25:27.068000 | 2019-09-30T08:52:23 | 2019-09-30T08:52:23 | 205,354,425 | 0 | 0 | null | false | 2022-06-29T17:36:58 | 2019-08-30T09:53:24 | 2019-09-30T08:52:46 | 2022-06-29T17:36:57 | 160 | 0 | 0 | 9 | Java | false | false | package com.training.pom;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class DeleteiconPOM {private WebDriver driver;
public DeleteiconPOM (WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
@FindBy(css ="#\\31 3 > td:nth-child(6) > a:nth-child(5) > img")
private WebElement DeleteiconPOM;
public void DeleteiconPOM()
{
this.DeleteiconPOM.click();
}
}
| UTF-8 | Java | 592 | java | DeleteiconPOM.java | Java | []
| null | []
| package com.training.pom;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class DeleteiconPOM {private WebDriver driver;
public DeleteiconPOM (WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
@FindBy(css ="#\\31 3 > td:nth-child(6) > a:nth-child(5) > img")
private WebElement DeleteiconPOM;
public void DeleteiconPOM()
{
this.DeleteiconPOM.click();
}
}
| 592 | 0.680743 | 0.672297 | 27 | 19.481482 | 20.651196 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.185185 | false | false | 0 |
562753c044459c29bbd884a93086c971bc5bfedb | 21,337,397,584,924 | c82229cf5b2cf3e26a0c5cfa34e9302546bf936c | /src/com/parlour/business/presentation/wrapper/ResultItem.java | 3c960258afcfa11585863aab196271b96d69ff75 | []
| no_license | d-biswas/ParlourApp | https://github.com/d-biswas/ParlourApp | a1d108d8b04c3cb4d0454999ee5b72fa70fa8006 | e9fa49a4ff53a74e738bd32aa17c7e502321f190 | refs/heads/master | 2021-01-24T06:22:08.011000 | 2014-01-22T15:02:34 | 2014-01-22T15:02:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.parlour.business.presentation.wrapper;
import java.io.Serializable;
/**
*
* @author DEB
*
*/
public interface ResultItem extends Serializable{
public int CATEGORY_TYPE = 1001;
public int SUBCATEGORY_TYPE = 2001;
public int SERVICE_TYPE = 3001;
public Object getItem();
public int getItemType();
}
| UTF-8 | Java | 328 | java | ResultItem.java | Java | [
{
"context": "\n\nimport java.io.Serializable;\n\n/**\n * \n * @author DEB\n *\n */\npublic interface ResultItem extends Serial",
"end": 104,
"score": 0.9983689785003662,
"start": 101,
"tag": "USERNAME",
"value": "DEB"
}
]
| null | []
| package com.parlour.business.presentation.wrapper;
import java.io.Serializable;
/**
*
* @author DEB
*
*/
public interface ResultItem extends Serializable{
public int CATEGORY_TYPE = 1001;
public int SUBCATEGORY_TYPE = 2001;
public int SERVICE_TYPE = 3001;
public Object getItem();
public int getItemType();
}
| 328 | 0.722561 | 0.685976 | 20 | 15.4 | 17.150511 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 0 |
b4cb9f67898bfa77d46baf134541fdd355ab44e9 | 5,394,478,979,213 | 2db0e8b9e5de48863fc5c7c4057989ebdd947430 | /src/main/java/com/der/abstractFactory/version3/SqlServerFactory.java | 2fb5c76fc829d43d89d9225db86daa370b0bfc80 | []
| no_license | DERDRAGON/design-pattern-learning | https://github.com/DERDRAGON/design-pattern-learning | 8bd33d8053bc6af7e97458e4fe7b5626e7d233fb | 2298b7b3246f9c5e20333ac1f013d4022080782e | refs/heads/master | 2021-07-13T02:01:46.036000 | 2020-03-26T06:13:51 | 2020-03-26T06:13:51 | 208,223,308 | 0 | 0 | null | false | 2020-10-13T16:00:07 | 2019-09-13T08:16:54 | 2020-03-26T06:14:09 | 2020-10-13T16:00:05 | 83 | 0 | 0 | 1 | Java | false | false | package com.der.abstractFactory.version3;
import com.der.abstractFactory.version2.IUser;
import com.der.abstractFactory.version2.SqlServerUser;
/**
* @ClassName SqlServerFactory
* @Desctiption TODO
* @Author 曹世龙
* @Date 2019/7/6 18:18
* @Version 1.0
**/
public class SqlServerFactory implements IFactory {
@Override
public IUser createUser() {
return new SqlServerUser();
}
@Override
public IDepartment createDept() {
return new SqlServerDepartment();
}
}
| UTF-8 | Java | 512 | java | SqlServerFactory.java | Java | [
{
"context": "e SqlServerFactory\n * @Desctiption TODO\n * @Author 曹世龙\n * @Date 2019/7/6 18:18\n * @Version 1.0\n **/\npubl",
"end": 216,
"score": 0.9997900724411011,
"start": 213,
"tag": "NAME",
"value": "曹世龙"
}
]
| null | []
| package com.der.abstractFactory.version3;
import com.der.abstractFactory.version2.IUser;
import com.der.abstractFactory.version2.SqlServerUser;
/**
* @ClassName SqlServerFactory
* @Desctiption TODO
* @Author 曹世龙
* @Date 2019/7/6 18:18
* @Version 1.0
**/
public class SqlServerFactory implements IFactory {
@Override
public IUser createUser() {
return new SqlServerUser();
}
@Override
public IDepartment createDept() {
return new SqlServerDepartment();
}
}
| 512 | 0.701581 | 0.671937 | 24 | 20.083334 | 17.717497 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.208333 | false | false | 0 |
f87d91ed879a134116ff5f13edcaaba0fb6b6e1f | 16,750,372,515,763 | 40022c12287789b58959c81daf5a3427b7e359dc | /src/main/java/xenoteo/com/github/ConslatorApplication.java | 38d9f1f71aced179c06207e6a7f4200f709a793d | [
"MIT"
]
| permissive | xenoteo/Conslator | https://github.com/xenoteo/Conslator | 2bbe03ed20902d4614c815c4e007d4aa3317c1c0 | 0cbccfc3b2b082d1b3be5e069455ade599bf7937 | refs/heads/main | 2023-06-07T07:06:47.323000 | 2021-06-21T10:25:06 | 2021-06-21T10:25:06 | 358,002,796 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package xenoteo.com.github;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
/**
* The Conslator application.
*/
@SpringBootApplication
public class ConslatorApplication {
public static void main(String[] args) {
SpringApplication.run(ConslatorApplication.class, args);
}
@Bean
public CommandLineRunner runConsoleApp(ConsoleApplication consoleApp){
return args -> consoleApp.run();
}
}
| UTF-8 | Java | 603 | java | ConslatorApplication.java | Java | []
| null | []
| package xenoteo.com.github;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
/**
* The Conslator application.
*/
@SpringBootApplication
public class ConslatorApplication {
public static void main(String[] args) {
SpringApplication.run(ConslatorApplication.class, args);
}
@Bean
public CommandLineRunner runConsoleApp(ConsoleApplication consoleApp){
return args -> consoleApp.run();
}
}
| 603 | 0.771144 | 0.771144 | 23 | 25.217392 | 24.791227 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.347826 | false | false | 0 |
5b7778b4b1aac34c0be25d7f87f406e4a677e102 | 16,750,372,512,906 | 451709e6462c9d0a1f648c8f780298dd52e3bfb4 | /project/staffmanager/src/com/chinasoft/sms/index/dao/StaffDAOImpl.java | a52ff00b1eeee52119f887ba52ac2018ae24c0d5 | []
| no_license | forsunchao/forsunchao | https://github.com/forsunchao/forsunchao | acec1606e9550f66e2eac36c6f0ee7b8a4589778 | 75ff7c7be27b8babbc03b2d3e500b9bcf2cf3753 | refs/heads/master | 2021-01-02T22:43:51.809000 | 2013-05-28T12:36:31 | 2013-05-28T12:36:31 | 34,045,525 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chinasoft.sms.index.dao;
import java.util.ArrayList;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.chinasoft.sms.check.pojo.Basicinfo;
public class StaffDAOImpl extends HibernateDaoSupport implements IStaffDAO {
/**
* 根据用户角色查询合同到期
*/
public List<String> query(Basicinfo bi)
{
// 获取角色
List<String> nameList = new ArrayList<String>();
long role = bi.getRole().longValue();
if (role == 0)
{
return nameList;
}
if (role == 1 || role == 2||role==3)// 经理,人事部查询所有合同到期
{
nameList = this
.getHibernateTemplate()
.find(
"select ci.basicinfo.nameId from Compactinfo ci where to_char(ci.outDate,'YYYY-MM')=to_char(SYSDATE,'YYYY-MM')");
}
if (role == 3)
{
nameList = this
.getHibernateTemplate()
.find(
"select ci.basicinfo.nameId from Compactinfo ci where to_char(ci.outDate,'YYYY-MM')=to_char(SYSDATE,'YYYY-MM') and ci.basicinfo.nameId='"
+ bi.getNameId() + "'");
// 普通员工查询自己有没有到期
}
/*
* List<Compactinfo> ci = this.getHibernateTemplate().find("from
* Compactinfo ci where ci.basicinfo.nameId='" + name_id + "' and
* ci.basicinfo.password='" + password + "'");
*/
// int length=ci.size();
//
// for(int index=0;index<length;index++){
//
// ci.get(index);
// }
//
/*
* if (ci != null) { DateFormat df= new SimpleDateFormat("yyyy-MM");
* //System.out.println(String.valueOf(ci.get(0).getOutDate())); return
* String.valueOf(df.format(ci.get(0).getOutDate()));
* }
*/
return nameList;
}
public List<String> querystaffdate(Basicinfo bi)
{
List<String> namedate = new ArrayList<String>();
namedate=this.getHibernateTemplate().find("select name from Basicinfo where to_char(birthday,'MM-DD')=to_char(SYSDATE,'MM-DD')");
// TODO Auto-generated method stub
return namedate;
}
}
| GB18030 | Java | 2,091 | java | StaffDAOImpl.java | Java | []
| null | []
| package com.chinasoft.sms.index.dao;
import java.util.ArrayList;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.chinasoft.sms.check.pojo.Basicinfo;
public class StaffDAOImpl extends HibernateDaoSupport implements IStaffDAO {
/**
* 根据用户角色查询合同到期
*/
public List<String> query(Basicinfo bi)
{
// 获取角色
List<String> nameList = new ArrayList<String>();
long role = bi.getRole().longValue();
if (role == 0)
{
return nameList;
}
if (role == 1 || role == 2||role==3)// 经理,人事部查询所有合同到期
{
nameList = this
.getHibernateTemplate()
.find(
"select ci.basicinfo.nameId from Compactinfo ci where to_char(ci.outDate,'YYYY-MM')=to_char(SYSDATE,'YYYY-MM')");
}
if (role == 3)
{
nameList = this
.getHibernateTemplate()
.find(
"select ci.basicinfo.nameId from Compactinfo ci where to_char(ci.outDate,'YYYY-MM')=to_char(SYSDATE,'YYYY-MM') and ci.basicinfo.nameId='"
+ bi.getNameId() + "'");
// 普通员工查询自己有没有到期
}
/*
* List<Compactinfo> ci = this.getHibernateTemplate().find("from
* Compactinfo ci where ci.basicinfo.nameId='" + name_id + "' and
* ci.basicinfo.password='" + password + "'");
*/
// int length=ci.size();
//
// for(int index=0;index<length;index++){
//
// ci.get(index);
// }
//
/*
* if (ci != null) { DateFormat df= new SimpleDateFormat("yyyy-MM");
* //System.out.println(String.valueOf(ci.get(0).getOutDate())); return
* String.valueOf(df.format(ci.get(0).getOutDate()));
* }
*/
return nameList;
}
public List<String> querystaffdate(Basicinfo bi)
{
List<String> namedate = new ArrayList<String>();
namedate=this.getHibernateTemplate().find("select name from Basicinfo where to_char(birthday,'MM-DD')=to_char(SYSDATE,'MM-DD')");
// TODO Auto-generated method stub
return namedate;
}
}
| 2,091 | 0.614464 | 0.609975 | 78 | 23.705128 | 31.280005 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.307692 | false | false | 0 |
247c665a7a87aca6e6653a4674744b6bb551101e | 11,665,131,233,658 | 2f4a058ab684068be5af77fea0bf07665b675ac0 | /utils/com/facebook/graphql/GraphQlQueryTimelineNavAppSectionsConnection$TimelineNavAppSectionsConnectionField.java | 5ad4cc130001423e9e2e12b4ac68a1f53b973257 | []
| no_license | cengizgoren/facebook_apk_crack | https://github.com/cengizgoren/facebook_apk_crack | ee812a57c746df3c28fb1f9263ae77190f08d8d2 | a112d30542b9f0bfcf17de0b3a09c6e6cfe1273b | refs/heads/master | 2021-05-26T14:44:04.092000 | 2013-01-16T08:39:00 | 2013-01-16T08:39:00 | 8,321,708 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.facebook.graphql;
public final class GraphQlQueryTimelineNavAppSectionsConnection$TimelineNavAppSectionsConnectionField extends GraphQlQueryBaseObjectImpl.FieldImpl
{
GraphQlQueryTimelineNavAppSectionsConnection$TimelineNavAppSectionsConnectionField(String paramString)
{
super("TimelineNavAppSectionsConnection", paramString);
}
GraphQlQueryTimelineNavAppSectionsConnection$TimelineNavAppSectionsConnectionField(String paramString, GraphQlQueryBaseObject paramGraphQlQueryBaseObject)
{
super("TimelineNavAppSectionsConnection", paramString, null, paramGraphQlQueryBaseObject);
}
}
/* Location: /data1/software/apk2java/dex2jar-0.0.9.12/secondary-1.dex_dex2jar.jar
* Qualified Name: com.facebook.graphql.GraphQlQueryTimelineNavAppSectionsConnection.TimelineNavAppSectionsConnectionField
* JD-Core Version: 0.6.2
*/ | UTF-8 | Java | 869 | java | GraphQlQueryTimelineNavAppSectionsConnection$TimelineNavAppSectionsConnectionField.java | Java | []
| null | []
| package com.facebook.graphql;
public final class GraphQlQueryTimelineNavAppSectionsConnection$TimelineNavAppSectionsConnectionField extends GraphQlQueryBaseObjectImpl.FieldImpl
{
GraphQlQueryTimelineNavAppSectionsConnection$TimelineNavAppSectionsConnectionField(String paramString)
{
super("TimelineNavAppSectionsConnection", paramString);
}
GraphQlQueryTimelineNavAppSectionsConnection$TimelineNavAppSectionsConnectionField(String paramString, GraphQlQueryBaseObject paramGraphQlQueryBaseObject)
{
super("TimelineNavAppSectionsConnection", paramString, null, paramGraphQlQueryBaseObject);
}
}
/* Location: /data1/software/apk2java/dex2jar-0.0.9.12/secondary-1.dex_dex2jar.jar
* Qualified Name: com.facebook.graphql.GraphQlQueryTimelineNavAppSectionsConnection.TimelineNavAppSectionsConnectionField
* JD-Core Version: 0.6.2
*/ | 869 | 0.837745 | 0.822785 | 19 | 44.789474 | 54.618851 | 156 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421053 | false | false | 0 |
f93c1dbe986006ff259d1d575a7c83b7561f82ea | 13,993,003,506,650 | c3b9312e6100ef5dc4233395e5e97955aeabdf63 | /Relacion4CreandoBDHibernate/src/principal/Principal.java | c99473e11a20cf6545f49515f4d0f2f08048469f | []
| no_license | Riosfen/2DAM-Programacion | https://github.com/Riosfen/2DAM-Programacion | 71cb51effee88ae857e3b048143ec24ab1101095 | eae47a30a4f44b77c2a6bc09ca089c84f683c85f | refs/heads/master | 2021-01-11T04:43:20.252000 | 2017-02-12T23:49:19 | 2017-02-12T23:49:19 | 71,108,502 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package principal;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import persistencia.Pelicula;
public class Principal {
public static void main(String[] args) {
SessionFactory factoria;
Configuration configuracion = new Configuration();
configuracion.configure();
ServiceRegistry servicio = new ServiceRegistryBuilder().applySettings(configuracion.getProperties()).buildServiceRegistry();
factoria = configuracion.buildSessionFactory(servicio);
Session sesion = factoria.openSession();
sesion.beginTransaction(); // TODO error no se ha podido abrir la conexion
sesion.save();
sesion.getTransaction().commit();
sesion.close();
}
}
| UTF-8 | Java | 871 | java | Principal.java | Java | []
| null | []
| package principal;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import persistencia.Pelicula;
public class Principal {
public static void main(String[] args) {
SessionFactory factoria;
Configuration configuracion = new Configuration();
configuracion.configure();
ServiceRegistry servicio = new ServiceRegistryBuilder().applySettings(configuracion.getProperties()).buildServiceRegistry();
factoria = configuracion.buildSessionFactory(servicio);
Session sesion = factoria.openSession();
sesion.beginTransaction(); // TODO error no se ha podido abrir la conexion
sesion.save();
sesion.getTransaction().commit();
sesion.close();
}
}
| 871 | 0.743972 | 0.743972 | 34 | 23.617647 | 27.371103 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5 | false | false | 0 |
7b480cf582cd3c072535a9555f2f43b7a9115949 | 19,774,029,448,722 | 3e155c71613615efb122a85d3bc25ae592281fb9 | /app/src/main/java/com/example/mingwei_countbook/NegativeValueException.java | a3ea500076ff0807b1571c165be1c9e990e4b636 | []
| no_license | mingweiarthurli/mingwei-CountBook | https://github.com/mingweiarthurli/mingwei-CountBook | e3f8d4eeee79c29837e28327b1d19370567a9150 | 8604210a60d849f3d7910fe34aef8cb6d174bd5a | refs/heads/master | 2021-07-22T01:02:33.312000 | 2017-11-01T00:58:00 | 2017-11-01T00:58:00 | 105,582,505 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.mingwei_countbook;
/**
* Exception created for negative value violation.
*/
public class NegativeValueException extends Exception {
}
| UTF-8 | Java | 158 | java | NegativeValueException.java | Java | []
| null | []
| package com.example.mingwei_countbook;
/**
* Exception created for negative value violation.
*/
public class NegativeValueException extends Exception {
}
| 158 | 0.778481 | 0.778481 | 8 | 18.75 | 22.845951 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.125 | false | false | 0 |
718cbe957ba5781d087df9d2737cc2890eae249b | 25,237,227,876,231 | 49ad2a9f3fddf24268a60edd7ef2971052ac9316 | /src/main/java/com/mindfire/bicyclesharing/dto/RateGroupDTO.java | 14a50e7735e311ec0e386a18704b97610229e584 | []
| no_license | kirankumarsingh/cycle_rental | https://github.com/kirankumarsingh/cycle_rental | cf234a7368123729cf430da69476c8f08fd6111d | 88b176e5ac732667683c2d57f4c9ca9b473a4433 | refs/heads/master | 2019-05-16T12:24:27.851000 | 2016-06-08T10:45:02 | 2016-06-08T10:45:02 | 52,769,829 | 2 | 1 | null | false | 2016-06-08T10:45:02 | 2016-02-29T06:37:16 | 2016-04-20T13:10:17 | 2016-06-08T10:45:02 | 12,068 | 1 | 1 | 0 | null | null | null | /*
* Copyright 2016 Mindfire Solutions
*
* 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.mindfire.bicyclesharing.dto;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import org.springframework.format.annotation.NumberFormat;
/**
* RateGroupDTO class is used for taking data from add new rate group view.
*
* @author mindfire
* @version 1.0
* @since 10/03/2016
*/
public class RateGroupDTO {
@NotNull @NumberFormat
@Min(0) @Max(100)
private Double discount;
@NotNull @Length(min=2,max=25)
private String groupType;
@NotNull @Length(min=2,max=10)
private String effectiveFrom;
/**
* @return the discount
*/
public Double getDiscount() {
return discount;
}
/**
* @param discount
* the discount to set
*/
public void setDiscount(Double discount) {
this.discount = discount;
}
/**
* @return the groupType
*/
public String getGroupType() {
return groupType;
}
/**
* @param groupType
* the groupType to set
*/
public void setGroupType(String groupType) {
this.groupType = groupType;
}
/**
* @return the effectiveFrom
*/
public String getEffectiveFrom() {
return effectiveFrom;
}
/**
* @param effectiveFrom
* the effectiveFrom to set
*/
public void setEffectiveFrom(String effectiveFrom) {
this.effectiveFrom = effectiveFrom;
}
}
| UTF-8 | Java | 2,000 | java | RateGroupDTO.java | Java | [
{
"context": " data from add new rate group view.\n * \n * @author mindfire\n * @version 1.0\n * @since 10/03/2016\n */\npublic c",
"end": 988,
"score": 0.9997127652168274,
"start": 980,
"tag": "USERNAME",
"value": "mindfire"
}
]
| null | []
| /*
* Copyright 2016 Mindfire Solutions
*
* 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.mindfire.bicyclesharing.dto;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import org.springframework.format.annotation.NumberFormat;
/**
* RateGroupDTO class is used for taking data from add new rate group view.
*
* @author mindfire
* @version 1.0
* @since 10/03/2016
*/
public class RateGroupDTO {
@NotNull @NumberFormat
@Min(0) @Max(100)
private Double discount;
@NotNull @Length(min=2,max=25)
private String groupType;
@NotNull @Length(min=2,max=10)
private String effectiveFrom;
/**
* @return the discount
*/
public Double getDiscount() {
return discount;
}
/**
* @param discount
* the discount to set
*/
public void setDiscount(Double discount) {
this.discount = discount;
}
/**
* @return the groupType
*/
public String getGroupType() {
return groupType;
}
/**
* @param groupType
* the groupType to set
*/
public void setGroupType(String groupType) {
this.groupType = groupType;
}
/**
* @return the effectiveFrom
*/
public String getEffectiveFrom() {
return effectiveFrom;
}
/**
* @param effectiveFrom
* the effectiveFrom to set
*/
public void setEffectiveFrom(String effectiveFrom) {
this.effectiveFrom = effectiveFrom;
}
}
| 2,000 | 0.707 | 0.693 | 89 | 21.47191 | 21.364725 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.876405 | false | false | 0 |
24b05178a18196224c8fee8fabe3de5d608a6751 | 1,778,116,490,267 | fd608bab7d91c9f6b879c6b2f4ef86f552564ee9 | /chemistry-opencmis-client/chemistry-opencmis-client-bindings/src/main/java/org/apache/chemistry/opencmis/client/bindings/cache/CacheLevel.java | b7c26f05fa4065aef8c0327c838f9b9f23dffc5d | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
]
| permissive | apache/chemistry-opencmis | https://github.com/apache/chemistry-opencmis | 3c113ff9f1ff33e91f49bd70dd30ffc4c3870eef | 9e49c685af9044a64cde0ab111792d74e914f4f2 | refs/heads/trunk | 2023-07-02T16:16:27.193000 | 2019-05-24T11:46:36 | 2019-05-24T11:46:36 | 3,216,014 | 48 | 66 | null | false | 2021-02-24T15:29:15 | 2012-01-19T08:00:11 | 2021-01-28T16:29:20 | 2019-05-24T12:45:44 | 15,587 | 39 | 51 | 4 | Java | false | false | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.chemistry.opencmis.client.bindings.cache;
import java.io.Serializable;
import java.util.Map;
/**
* Interface for a level of an hierarchical cache.
*
* @see Cache
*/
public interface CacheLevel extends Serializable {
/**
* Initialize the cache level.
*
* @param parameters
* level parameters
*/
void initialize(Map<String, String> parameters);
/**
* Adds an object to the cache level.
*
* @param value
* the object
* @param key
* the key at this level
*/
void put(Object value, String key);
/**
* Retrieves an object from the cache level.
*
* @param key
* the key at this cache level
* @return the object or <code>null</code> if the object doesn't exist
*/
Object get(String key);
/**
* Removes an object from this cache level.
*
* @param key
* the key at this cache level
*/
void remove(String key);
}
| UTF-8 | Java | 1,844 | java | CacheLevel.java | Java | []
| null | []
| /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.chemistry.opencmis.client.bindings.cache;
import java.io.Serializable;
import java.util.Map;
/**
* Interface for a level of an hierarchical cache.
*
* @see Cache
*/
public interface CacheLevel extends Serializable {
/**
* Initialize the cache level.
*
* @param parameters
* level parameters
*/
void initialize(Map<String, String> parameters);
/**
* Adds an object to the cache level.
*
* @param value
* the object
* @param key
* the key at this level
*/
void put(Object value, String key);
/**
* Retrieves an object from the cache level.
*
* @param key
* the key at this cache level
* @return the object or <code>null</code> if the object doesn't exist
*/
Object get(String key);
/**
* Removes an object from this cache level.
*
* @param key
* the key at this cache level
*/
void remove(String key);
}
| 1,844 | 0.64859 | 0.646421 | 65 | 27.36923 | 23.124126 | 74 | true | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.215385 | false | false | 0 |
4ca7cc4d24893ba8dfbdf401fa52d33da30482b1 | 2,379,411,929,983 | c82b3ff9dee68bd8eee8b4d7cd0bf97552ceb092 | /Watten/src/com/mpp/watten/cards/Suit.java | 81ed513cdc44a75dee4f00cf6fc44d85a2e2d7f5 | []
| no_license | Piiit/watten | https://github.com/Piiit/watten | 23a244f758712d1770f52309fc518e3ce1ffb817 | ca0ac9693e1f21fc3175ddb1db3fba13790711a1 | refs/heads/master | 2016-08-03T16:44:40.549000 | 2014-06-10T09:58:54 | 2014-06-10T09:58:54 | 32,858,272 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mpp.watten.cards;
public enum Suit {
BELLS(0), HEARTS(1), ACORNS(2), LEAVES(3);
private final int index;
Suit(int index) {
this.index = index;
}
public int getIndex() {
return index;
}
public static Suit get(int index) {
return Suit.values()[index];
}
}
| UTF-8 | Java | 304 | java | Suit.java | Java | []
| null | []
| package com.mpp.watten.cards;
public enum Suit {
BELLS(0), HEARTS(1), ACORNS(2), LEAVES(3);
private final int index;
Suit(int index) {
this.index = index;
}
public int getIndex() {
return index;
}
public static Suit get(int index) {
return Suit.values()[index];
}
}
| 304 | 0.615132 | 0.601974 | 19 | 14 | 13.935944 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.210526 | false | false | 0 |
bee7bb091ec0149ca713fa4706d0b8eca8d3f71a | 39,195,871,573,218 | add37d74bac37efa055b02ea69ff75eca8cfaccf | /src/main/java/bean/ResultBean.java | 4ffcdbf4e8178da35b579b1696e9efa7da325403 | []
| no_license | fengsigaoju/school-demo | https://github.com/fengsigaoju/school-demo | c6c5128df8e373ff450040fdb33f6c1efaec9eed | 31ddfc6929e03db780829b0c209fd4dee157f8af | refs/heads/master | 2021-04-28T02:20:22.753000 | 2018-02-21T06:25:59 | 2018-02-21T06:25:59 | 122,300,253 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bean;
public class ResultBean {
/**
* 温度
*/
private String temperature;
/**
* 二氧化碳
*/
private String carbonDioxide;
/**
* 光照
*/
private String illumination;
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
public String getCarbonDioxide() {
return carbonDioxide;
}
public void setCarbonDioxide(String carbonDioxide) {
this.carbonDioxide = carbonDioxide;
}
public String getIllumination() {
return illumination;
}
public void setIllumination(String illumination) {
this.illumination = illumination;
}
}
| UTF-8 | Java | 775 | java | ResultBean.java | Java | []
| null | []
| package bean;
public class ResultBean {
/**
* 温度
*/
private String temperature;
/**
* 二氧化碳
*/
private String carbonDioxide;
/**
* 光照
*/
private String illumination;
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
public String getCarbonDioxide() {
return carbonDioxide;
}
public void setCarbonDioxide(String carbonDioxide) {
this.carbonDioxide = carbonDioxide;
}
public String getIllumination() {
return illumination;
}
public void setIllumination(String illumination) {
this.illumination = illumination;
}
}
| 775 | 0.610013 | 0.610013 | 43 | 16.651163 | 17.349867 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.232558 | false | false | 0 |
cf3137c86a9aba520ccadaf27f3a352acfbeb9ee | 39,041,252,761,414 | d012909895f15d8346f02fa007d08f2291087a98 | /reef-io/src/main/java/com/microsoft/reef/io/network/util/Utils.java | bc448d16c0e42863d9b9a00cfcb8b3ec5bdfcd0c | [
"Apache-2.0"
]
| permissive | ICtest333/REEF | https://github.com/ICtest333/REEF | a7bae7f124285b0ebad40f20ecdea342cdc80a13 | 1b27051156516f0bf9e4ca885b4752dd47c844b9 | refs/heads/master | 2021-01-18T03:46:20.341000 | 2014-07-23T01:09:01 | 2014-07-23T01:09:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright (C) 2014 Microsoft Corporation
*
* 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.microsoft.reef.io.network.util;
import java.io.Serializable;
import java.net.Inet4Address;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import com.google.protobuf.ByteString;
import com.microsoft.reef.io.network.proto.ReefNetworkGroupCommProtos.GroupCommMessage;
import com.microsoft.reef.io.network.proto.ReefNetworkGroupCommProtos.GroupCommMessage.Type;
import com.microsoft.reef.io.network.proto.ReefNetworkGroupCommProtos.GroupMessageBody;
import com.microsoft.wake.ComparableIdentifier;
import com.microsoft.wake.Identifier;
import com.microsoft.wake.IdentifierFactory;
public class Utils {
private static final String DELIMITER = "-";
/**
* TODO: Merge with parseListCmp() into one generic implementation.
*/
public static List<Identifier> parseList(
final String ids, final IdentifierFactory factory) {
final List<Identifier> result = new ArrayList<>();
for (final String token : ids.split(DELIMITER)) {
result.add(factory.getNewInstance(token.trim()));
}
return result;
}
/**
* TODO: Merge with parseList() into one generic implementation.
*/
public static List<ComparableIdentifier> parseListCmp(
final String ids, final IdentifierFactory factory) {
final List<ComparableIdentifier> result = new ArrayList<>();
for (final String token : ids.split(DELIMITER)) {
result.add((ComparableIdentifier) factory.getNewInstance(token.trim()));
}
return result;
}
public static String listToString(final List<ComparableIdentifier> ids) {
return StringUtils.join(ids, DELIMITER);
}
public static List<Integer> createUniformCounts(final int elemSize, final int childSize) {
final int remainder = elemSize % childSize;
final int quotient = elemSize / childSize;
final ArrayList<Integer> result = new ArrayList<>(childSize);
result.addAll(Collections.nCopies(remainder, quotient + 1));
result.addAll(Collections.nCopies(childSize - remainder, quotient));
return Collections.unmodifiableList(result);
}
public final static class Pair<T1, T2> implements Serializable {
public final T1 first;
public final T2 second;
private String pairStr = null;
public Pair(final T1 first, final T2 second) {
this.first = first;
this.second = second;
}
@Override
public String toString() {
if (this.pairStr == null) {
this.pairStr = "(" + this.first + "," + this.second + ")";
}
return this.pairStr;
}
}
private static class AddressComparator implements Comparator<Inet4Address> {
@Override
public int compare(final Inet4Address aa, final Inet4Address ba) {
final byte[] a = aa.getAddress();
final byte[] b = ba.getAddress();
// local subnet comes after all else.
if (a[0] == 127 && b[0] != 127) {
return 1;
}
if (a[0] != 127 && b[0] == 127) {
return -1;
}
for (int i = 0; i < 4; i++) {
if (a[i] < b[i]) {
return -1;
}
if (a[i] > b[i]) {
return 1;
}
}
return 0;
}
}
public static GroupCommMessage bldGCM(
final Type msgType, final Identifier from, final Identifier to, final byte[]... elements) {
final GroupCommMessage.Builder GCMBuilder = GroupCommMessage.newBuilder()
.setType(msgType)
.setSrcid(from.toString())
.setDestid(to.toString());
final GroupMessageBody.Builder bodyBuilder = GroupMessageBody.newBuilder();
for (final byte[] element : elements) {
bodyBuilder.setData(ByteString.copyFrom(element));
GCMBuilder.addMsgs(bodyBuilder.build());
}
return GCMBuilder.build();
}
}
| UTF-8 | Java | 4,418 | java | Utils.java | Java | []
| null | []
| /**
* Copyright (C) 2014 Microsoft Corporation
*
* 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.microsoft.reef.io.network.util;
import java.io.Serializable;
import java.net.Inet4Address;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import com.google.protobuf.ByteString;
import com.microsoft.reef.io.network.proto.ReefNetworkGroupCommProtos.GroupCommMessage;
import com.microsoft.reef.io.network.proto.ReefNetworkGroupCommProtos.GroupCommMessage.Type;
import com.microsoft.reef.io.network.proto.ReefNetworkGroupCommProtos.GroupMessageBody;
import com.microsoft.wake.ComparableIdentifier;
import com.microsoft.wake.Identifier;
import com.microsoft.wake.IdentifierFactory;
public class Utils {
private static final String DELIMITER = "-";
/**
* TODO: Merge with parseListCmp() into one generic implementation.
*/
public static List<Identifier> parseList(
final String ids, final IdentifierFactory factory) {
final List<Identifier> result = new ArrayList<>();
for (final String token : ids.split(DELIMITER)) {
result.add(factory.getNewInstance(token.trim()));
}
return result;
}
/**
* TODO: Merge with parseList() into one generic implementation.
*/
public static List<ComparableIdentifier> parseListCmp(
final String ids, final IdentifierFactory factory) {
final List<ComparableIdentifier> result = new ArrayList<>();
for (final String token : ids.split(DELIMITER)) {
result.add((ComparableIdentifier) factory.getNewInstance(token.trim()));
}
return result;
}
public static String listToString(final List<ComparableIdentifier> ids) {
return StringUtils.join(ids, DELIMITER);
}
public static List<Integer> createUniformCounts(final int elemSize, final int childSize) {
final int remainder = elemSize % childSize;
final int quotient = elemSize / childSize;
final ArrayList<Integer> result = new ArrayList<>(childSize);
result.addAll(Collections.nCopies(remainder, quotient + 1));
result.addAll(Collections.nCopies(childSize - remainder, quotient));
return Collections.unmodifiableList(result);
}
public final static class Pair<T1, T2> implements Serializable {
public final T1 first;
public final T2 second;
private String pairStr = null;
public Pair(final T1 first, final T2 second) {
this.first = first;
this.second = second;
}
@Override
public String toString() {
if (this.pairStr == null) {
this.pairStr = "(" + this.first + "," + this.second + ")";
}
return this.pairStr;
}
}
private static class AddressComparator implements Comparator<Inet4Address> {
@Override
public int compare(final Inet4Address aa, final Inet4Address ba) {
final byte[] a = aa.getAddress();
final byte[] b = ba.getAddress();
// local subnet comes after all else.
if (a[0] == 127 && b[0] != 127) {
return 1;
}
if (a[0] != 127 && b[0] == 127) {
return -1;
}
for (int i = 0; i < 4; i++) {
if (a[i] < b[i]) {
return -1;
}
if (a[i] > b[i]) {
return 1;
}
}
return 0;
}
}
public static GroupCommMessage bldGCM(
final Type msgType, final Identifier from, final Identifier to, final byte[]... elements) {
final GroupCommMessage.Builder GCMBuilder = GroupCommMessage.newBuilder()
.setType(msgType)
.setSrcid(from.toString())
.setDestid(to.toString());
final GroupMessageBody.Builder bodyBuilder = GroupMessageBody.newBuilder();
for (final byte[] element : elements) {
bodyBuilder.setData(ByteString.copyFrom(element));
GCMBuilder.addMsgs(bodyBuilder.build());
}
return GCMBuilder.build();
}
}
| 4,418 | 0.686962 | 0.677456 | 138 | 31.014492 | 26.961859 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.492754 | false | false | 0 |
67a0a0db4e0c895a05b2e0b0eb3138c2450f8bab | 25,451,976,261,820 | a7cc15fa378b7c73847117d7fe722dacd71bac18 | /SampleGeometryApp2/src/com/js/delaunay/DelaunayDriver.java | 2a45470668da1e1ea88ea9b0734aa28ac98c1c18 | []
| no_license | jpsember/geometry | https://github.com/jpsember/geometry | a280230441cc0e986728964cb618be8efffacb9c | fd71ec1a03769016ee53ca24502de9a9523db830 | refs/heads/master | 2020-05-31T11:24:37.397000 | 2015-03-29T19:38:41 | 2015-03-29T19:38:41 | 23,127,895 | 6 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.js.delaunay;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import android.graphics.Color;
import com.js.basic.GeometryException;
import com.js.basic.MyMath;
import com.js.basic.Point;
import com.js.basic.Rect;
import com.js.geometry.*;
import com.js.geometryapp.Algorithm;
import com.js.geometryapp.AlgorithmInput;
import com.js.geometryapp.AlgorithmOptions;
import com.js.geometryapp.widget.ComboBoxWidget;
import static com.js.basic.Tools.*;
public class DelaunayDriver implements Algorithm {
private static final String BGND_ELEMENT_MESH = "50:mesh";
private static final String BGND_ELEMENT_VORONOI_CELLS = "60";
private static final String USE_EDITOR_POINTS = "Use editor points";
@Override
public String getAlgorithmName() {
return "Delaunay Triangulation";
}
@Override
public void prepareOptions(AlgorithmOptions options) {
mOptions = options;
mOptions.addSlider("Seed", "min", 1, "max", 300);
mOptions.addCheckBox("Small initial mesh", "value", true);
mOptions.addCheckBox("Random disc", "value", false);
mOptions.addCheckBox("Deletions", "value", true);
mOptions.addCheckBox("Delete all");
mOptions.addCheckBox("Voronoi cells", "value", true);
mOptions.addSlider("Attempts", "min", 1, "max", 5);
ComboBoxWidget w = mOptions.addComboBox("Pattern");
w.addItem("Random");
w.addItem("Circle");
w.prepare();
mOptions.addSlider("Points", "min", 1, "max", 250, "value", 25);
mOptions.addCheckBox(Delaunay.DETAIL_SWAPS, "value", true);
mOptions.addCheckBox(Delaunay.DETAIL_FIND_TRIANGLE, "value", true);
mOptions.addCheckBox(Delaunay.DETAIL_TRIANGULATE_HOLE, "value", false);
mOptions.addCheckBox(USE_EDITOR_POINTS);
}
@Override
public void run(final AlgorithmStepper s, AlgorithmInput input) {
mEditorPoints = input.points;
mPointBounds = new Rect(50, 50, 900, 900);
mMesh = new Mesh();
mRandom = new Random(mOptions.getIntValue("Seed"));
boolean deleteAll = mOptions.getBooleanValue("Delete all");
boolean withDeletions = deleteAll
|| mOptions.getBooleanValue("Deletions");
s.addLayer(BGND_ELEMENT_MESH, mMesh);
Rect delaunayBounds = null;
if (mOptions.getBooleanValue("Small initial mesh")) {
delaunayBounds = new Rect(mPointBounds);
delaunayBounds.inset(-10, -10);
}
mDelaunay = new Delaunay(mMesh, delaunayBounds, s);
if (s.bigStep())
s.show("Initial triangulation");
List<Point> inputPoints = new ArrayList();
if (mOptions.getBooleanValue(USE_EDITOR_POINTS)) {
for (Point pt : mEditorPoints) {
if (mPointBounds.contains(pt))
inputPoints.add(pt);
}
} else {
constructRandomPoints(inputPoints);
}
if (inputPoints.isEmpty())
GeometryException.raise("no points");
mVertices = new ArrayList();
for (Point pt : inputPoints) {
int attempt = 0;
while (true) {
try {
mVertices.add(mDelaunay.add(pt));
break;
} catch (GeometryException e) {
attempt++;
pr("Problem adding " + pt + ", attempt #" + attempt);
if (s.step())
s.show("Problem adding " + pt + ", attempt #" + attempt);
if (attempt >= mOptions.getIntValue("Attempts")) {
pr("Failed several attempts at insertion");
throw e;
}
MyMath.perturb(mRandom, pt);
}
}
if (withDeletions) {
// Once in a while, remove a series of points
if (mRandom.nextInt(3) == 0) {
int rem = Math.min(mVertices.size(), mRandom.nextInt(5));
while (rem-- > 0) {
removeArbitraryVertex();
}
}
}
}
if (deleteAll) {
while (!mVertices.isEmpty())
removeArbitraryVertex();
s.setDoneMessage("Removed all vertices");
} else if (mOptions.getBooleanValue("Voronoi cells")) {
s.addLayer(BGND_ELEMENT_VORONOI_CELLS, new Renderable() {
@Override
public void render(AlgorithmStepper s) {
s.setLineWidth(2);
s.setColor(Color.argb(0x80, 0x20, 0x80, 0x20));
for (int i = 0; i < mDelaunay.nSites(); i++) {
Vertex v = mDelaunay.site(i);
s.render(v);
Polygon p = mDelaunay.constructVoronoiPolygon(i);
s.render(p);
}
}
});
s.setDoneMessage("Voronoi cells");
}
}
private void constructRandomPoints(List<Point> points) {
int numPoints = mOptions.getIntValue("Points");
ComboBoxWidget w = mOptions.getWidget("Pattern");
String pattern = (String) w.getSelectedKey();
for (int i = 0; i < numPoints; i++) {
Point pt;
if (pattern.equals("Circle")) {
Point center = mPointBounds.midPoint();
if (i == numPoints - 1)
pt = center;
else
pt = MyMath.pointOnCircle(center, (i * MyMath.PI * 2)
/ (numPoints - 1), .49f * mPointBounds.minDim());
MyMath.perturb(mRandom, pt);
} else {
if (mOptions.getBooleanValue("Random disc")) {
pt = MyMath.randomPointInDisc(mRandom,
mPointBounds.midPoint(), mPointBounds.minDim() / 2);
} else
pt = new Point(mPointBounds.x + mRandom.nextFloat()
* mPointBounds.width, mPointBounds.y
+ mRandom.nextFloat() * mPointBounds.height);
}
points.add(pt);
}
}
private void removeArbitraryVertex() {
Vertex v = removeAndFill(mVertices, mRandom.nextInt(mVertices.size()));
mDelaunay.remove(v);
}
private AlgorithmOptions mOptions;
private Mesh mMesh;
private Delaunay mDelaunay;
private Random mRandom;
private List<Vertex> mVertices;
private Rect mPointBounds;
private Point[] mEditorPoints;
}
| UTF-8 | Java | 5,411 | java | DelaunayDriver.java | Java | []
| null | []
| package com.js.delaunay;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import android.graphics.Color;
import com.js.basic.GeometryException;
import com.js.basic.MyMath;
import com.js.basic.Point;
import com.js.basic.Rect;
import com.js.geometry.*;
import com.js.geometryapp.Algorithm;
import com.js.geometryapp.AlgorithmInput;
import com.js.geometryapp.AlgorithmOptions;
import com.js.geometryapp.widget.ComboBoxWidget;
import static com.js.basic.Tools.*;
public class DelaunayDriver implements Algorithm {
private static final String BGND_ELEMENT_MESH = "50:mesh";
private static final String BGND_ELEMENT_VORONOI_CELLS = "60";
private static final String USE_EDITOR_POINTS = "Use editor points";
@Override
public String getAlgorithmName() {
return "Delaunay Triangulation";
}
@Override
public void prepareOptions(AlgorithmOptions options) {
mOptions = options;
mOptions.addSlider("Seed", "min", 1, "max", 300);
mOptions.addCheckBox("Small initial mesh", "value", true);
mOptions.addCheckBox("Random disc", "value", false);
mOptions.addCheckBox("Deletions", "value", true);
mOptions.addCheckBox("Delete all");
mOptions.addCheckBox("Voronoi cells", "value", true);
mOptions.addSlider("Attempts", "min", 1, "max", 5);
ComboBoxWidget w = mOptions.addComboBox("Pattern");
w.addItem("Random");
w.addItem("Circle");
w.prepare();
mOptions.addSlider("Points", "min", 1, "max", 250, "value", 25);
mOptions.addCheckBox(Delaunay.DETAIL_SWAPS, "value", true);
mOptions.addCheckBox(Delaunay.DETAIL_FIND_TRIANGLE, "value", true);
mOptions.addCheckBox(Delaunay.DETAIL_TRIANGULATE_HOLE, "value", false);
mOptions.addCheckBox(USE_EDITOR_POINTS);
}
@Override
public void run(final AlgorithmStepper s, AlgorithmInput input) {
mEditorPoints = input.points;
mPointBounds = new Rect(50, 50, 900, 900);
mMesh = new Mesh();
mRandom = new Random(mOptions.getIntValue("Seed"));
boolean deleteAll = mOptions.getBooleanValue("Delete all");
boolean withDeletions = deleteAll
|| mOptions.getBooleanValue("Deletions");
s.addLayer(BGND_ELEMENT_MESH, mMesh);
Rect delaunayBounds = null;
if (mOptions.getBooleanValue("Small initial mesh")) {
delaunayBounds = new Rect(mPointBounds);
delaunayBounds.inset(-10, -10);
}
mDelaunay = new Delaunay(mMesh, delaunayBounds, s);
if (s.bigStep())
s.show("Initial triangulation");
List<Point> inputPoints = new ArrayList();
if (mOptions.getBooleanValue(USE_EDITOR_POINTS)) {
for (Point pt : mEditorPoints) {
if (mPointBounds.contains(pt))
inputPoints.add(pt);
}
} else {
constructRandomPoints(inputPoints);
}
if (inputPoints.isEmpty())
GeometryException.raise("no points");
mVertices = new ArrayList();
for (Point pt : inputPoints) {
int attempt = 0;
while (true) {
try {
mVertices.add(mDelaunay.add(pt));
break;
} catch (GeometryException e) {
attempt++;
pr("Problem adding " + pt + ", attempt #" + attempt);
if (s.step())
s.show("Problem adding " + pt + ", attempt #" + attempt);
if (attempt >= mOptions.getIntValue("Attempts")) {
pr("Failed several attempts at insertion");
throw e;
}
MyMath.perturb(mRandom, pt);
}
}
if (withDeletions) {
// Once in a while, remove a series of points
if (mRandom.nextInt(3) == 0) {
int rem = Math.min(mVertices.size(), mRandom.nextInt(5));
while (rem-- > 0) {
removeArbitraryVertex();
}
}
}
}
if (deleteAll) {
while (!mVertices.isEmpty())
removeArbitraryVertex();
s.setDoneMessage("Removed all vertices");
} else if (mOptions.getBooleanValue("Voronoi cells")) {
s.addLayer(BGND_ELEMENT_VORONOI_CELLS, new Renderable() {
@Override
public void render(AlgorithmStepper s) {
s.setLineWidth(2);
s.setColor(Color.argb(0x80, 0x20, 0x80, 0x20));
for (int i = 0; i < mDelaunay.nSites(); i++) {
Vertex v = mDelaunay.site(i);
s.render(v);
Polygon p = mDelaunay.constructVoronoiPolygon(i);
s.render(p);
}
}
});
s.setDoneMessage("Voronoi cells");
}
}
private void constructRandomPoints(List<Point> points) {
int numPoints = mOptions.getIntValue("Points");
ComboBoxWidget w = mOptions.getWidget("Pattern");
String pattern = (String) w.getSelectedKey();
for (int i = 0; i < numPoints; i++) {
Point pt;
if (pattern.equals("Circle")) {
Point center = mPointBounds.midPoint();
if (i == numPoints - 1)
pt = center;
else
pt = MyMath.pointOnCircle(center, (i * MyMath.PI * 2)
/ (numPoints - 1), .49f * mPointBounds.minDim());
MyMath.perturb(mRandom, pt);
} else {
if (mOptions.getBooleanValue("Random disc")) {
pt = MyMath.randomPointInDisc(mRandom,
mPointBounds.midPoint(), mPointBounds.minDim() / 2);
} else
pt = new Point(mPointBounds.x + mRandom.nextFloat()
* mPointBounds.width, mPointBounds.y
+ mRandom.nextFloat() * mPointBounds.height);
}
points.add(pt);
}
}
private void removeArbitraryVertex() {
Vertex v = removeAndFill(mVertices, mRandom.nextInt(mVertices.size()));
mDelaunay.remove(v);
}
private AlgorithmOptions mOptions;
private Mesh mMesh;
private Delaunay mDelaunay;
private Random mRandom;
private List<Vertex> mVertices;
private Rect mPointBounds;
private Point[] mEditorPoints;
}
| 5,411 | 0.678802 | 0.668453 | 181 | 28.895027 | 20.761339 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.198895 | false | false | 0 |
3d791f80bc4fcf6adb6f70e67beb1dfff48e2450 | 26,302,379,784,124 | 571df90e3ea18bab7be094651b0cac299ccf451b | /src/View/DataGudangClient.java | d342ca04c1ebf48070e8bfd1dfa8d56695eb8bf8 | []
| no_license | mari4rossa/Inventaris_Gudang_RMI | https://github.com/mari4rossa/Inventaris_Gudang_RMI | e56d756a6a402cf8a78b4f29b7a12607fe023d32 | 1011f0022182bf777181686b3114800477e5bb6a | refs/heads/master | 2023-04-06T12:35:08.023000 | 2021-04-07T04:38:20 | 2021-04-07T04:38:20 | 355,038,476 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package View;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import Model.GudangModel;
/**
*
* @author Matius Andreatna
*/
public class DataGudangClient extends javax.swing.JFrame {
/**
* Creates new form DataGudangClient
*/
private Service.AllService serv = null;
public DataGudangClient() throws NotBoundException, MalformedURLException, RemoteException {
initComponents();
serv = (Service.AllService) Naming.lookup("rmi://localhost:1234/allService");
setLocationRelativeTo(null);
showTable(serv.loadGudang());
}
public void resizeColumnWidth(JTable table) {
final TableColumnModel columnModel = table.getColumnModel();
for (int column = 0; column < table.getColumnCount(); column++) {
int width = 15; // Min width
for (int row = 0; row < table.getRowCount(); row++) {
TableCellRenderer renderer = table.getCellRenderer(row, column);
Component comp = table.prepareRenderer(renderer, row, column);
width = Math.max(comp.getPreferredSize().width +1 , width);
}
if(width > 300)
width=300;
columnModel.getColumn(column).setPreferredWidth(width);
}
columnModel.getColumn(2).setPreferredWidth(100);
}
public void showTable(List<String[]> dataTabel){
DefaultTableModel model = new DefaultTableModel();
List<String[]> result = dataTabel;
String[] columnsName = {"ID", "Lokasi Gudang", "ID Admin"};
String[][] data = new String[result.size()][3];
int idx = 0;
for (String[] row : result) {
data[idx] = row;
idx += 1;
}
tabelGudang.setModel(new DefaultTableModel(data, columnsName));
resizeColumnWidth(tabelGudang);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane2 = new javax.swing.JScrollPane();
tabelGudang = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
txtIdGudang = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
txtLokasi = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
txtIdAdmin = new javax.swing.JTextField();
btnDelete = new javax.swing.JButton();
btnSubmit = new javax.swing.JButton();
btnUpdate = new javax.swing.JButton();
btnBack = new javax.swing.JButton();
btnLogout = new javax.swing.JButton();
boxSort = new javax.swing.JComboBox<>();
jLabel8 = new javax.swing.JLabel();
txtCari = new javax.swing.JTextField();
btnCari = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
tabelGudang.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
tabelGudang.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
jScrollPane2.setViewportView(tabelGudang);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel1.setText("DATA GUDANG");
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("DAFTAR GUDANG");
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setText("INPUT GUDANG");
txtIdGudang.setEditable(false);
txtIdGudang.setBackground(new java.awt.Color(153, 153, 153));
jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel4.setText("ID GUDANG");
jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel5.setText("LOKASI ");
jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel6.setText("ID ADMIN");
btnDelete.setText("DELETE");
btnDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDeleteActionPerformed(evt);
}
});
btnSubmit.setText("SUBMIT");
btnSubmit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSubmitActionPerformed(evt);
}
});
btnUpdate.setText("UPDATE");
btnUpdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnUpdateActionPerformed(evt);
}
});
btnBack.setText("<BACK");
btnBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBackActionPerformed(evt);
}
});
btnLogout.setText("LOGOUT");
btnLogout.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLogoutActionPerformed(evt);
}
});
boxSort.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "ID", "Lokasi", "ID Admin" }));
boxSort.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
boxSortActionPerformed(evt);
}
});
jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel8.setText("Urutkan berdasar");
btnCari.setText("Cari");
btnCari.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCariActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(265, 265, 265)
.addComponent(jLabel1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(47, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 85, Short.MAX_VALUE)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(txtIdAdmin, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
.addComponent(txtLokasi, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtIdGudang, javax.swing.GroupLayout.Alignment.LEADING)))
.addGroup(layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(btnDelete)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnSubmit)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnUpdate))))
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 419, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(btnBack)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnLogout)))
.addContainerGap())
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 349, Short.MAX_VALUE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(boxSort, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(txtCari, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnCari)
.addGap(3, 3, 3)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txtIdGudang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(14, 14, 14)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(txtLokasi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(14, 14, 14)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(txtIdAdmin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(56, 56, 56)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnSubmit)
.addComponent(btnUpdate)
.addComponent(btnDelete)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnLogout)
.addComponent(btnBack))
.addGap(209, 209, 209))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(73, 73, 73)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnCari)
.addComponent(txtCari, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(boxSort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8))
.addContainerGap(407, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
// TODO add your handling code here:
GudangModel id = new GudangModel();
id.setId(txtIdGudang.getText());
//deleteData(id);
}//GEN-LAST:event_btnDeleteActionPerformed
private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSubmitActionPerformed
// TODO add your handling code here:
String id;
try {
id = serv.idGudang();
GudangModel bM = new GudangModel();
txtIdGudang.setText(id);
String nama = txtLokasi.getText();
String idAdmin = txtIdAdmin.getText();
bM.setId(id);
bM.setLokasi(nama);
bM.setId_admin(idAdmin);
//insertData(bM);
} catch (RemoteException ex) {
Logger.getLogger(DataGudangClient.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnSubmitActionPerformed
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
// TODO add your handling code here:
String id = txtIdGudang.getText();
String lokasi = txtLokasi.getText();
String idAdmin = txtIdAdmin.getText();
GudangModel data = new GudangModel();
data.setId(id);
data.setLokasi(lokasi);
data.setId_admin(idAdmin);
//updateData(data);
}//GEN-LAST:event_btnUpdateActionPerformed
private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed
try {
// TODO add your handling code here:
this.dispose();
HomeClient Home = new HomeClient();
Home.setVisible(true);
} catch (NotBoundException ex) {
Logger.getLogger(DataGudangClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(DataGudangClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (RemoteException ex) {
Logger.getLogger(DataGudangClient.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnBackActionPerformed
private void btnLogoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLogoutActionPerformed
// TODO add your handling code here:
int selectedOption = JOptionPane.showConfirmDialog(null,
"Apakah Anda ingin keluar?",
"LOGOUT",
JOptionPane.YES_NO_OPTION);
if (selectedOption == JOptionPane.YES_OPTION) {
try {
this.dispose();
LoginUserClient loginUserClient = new LoginUserClient();
loginUserClient.setVisible(true);
} catch (NotBoundException ex) {
Logger.getLogger(HomeClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(HomeClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (RemoteException ex) {
Logger.getLogger(HomeClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_btnLogoutActionPerformed
private void boxSortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boxSortActionPerformed
try {
// TODO add your handling code here:
String selectedItem = String.valueOf(boxSort.getSelectedItem());
List <String[]> result = serv.sortGudang(selectedItem);
DefaultTableModel model = new DefaultTableModel();
String[] columnsName = {"ID", "Nama", "Ukuran", "Harga"};
String[][] data = new String[result.size()][4];
int idx = 0;
for (String[] row : result) {
data[idx] = row;
idx += 1;
}
tabelGudang.setModel(new DefaultTableModel(data, columnsName));
resizeColumnWidth(tabelGudang);
} catch (RemoteException ex) {
Logger.getLogger(DataGudangClient.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_boxSortActionPerformed
private void btnCariActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCariActionPerformed
// TODO add your handling code here:
String cariGudang = txtCari.getText();
//cariData(cariBrg);
}//GEN-LAST:event_btnCariActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DataGudangClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DataGudangClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DataGudangClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DataGudangClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new DataGudangClient().setVisible(true);
} catch (NotBoundException ex) {
Logger.getLogger(DataGudangClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(DataGudangClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (RemoteException ex) {
Logger.getLogger(DataGudangClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox<String> boxSort;
private javax.swing.JButton btnBack;
private javax.swing.JButton btnCari;
private javax.swing.JButton btnDelete;
private javax.swing.JButton btnLogout;
private javax.swing.JButton btnSubmit;
private javax.swing.JButton btnUpdate;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel8;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable tabelGudang;
private javax.swing.JTextField txtCari;
private javax.swing.JTextField txtIdAdmin;
private javax.swing.JTextField txtIdGudang;
private javax.swing.JTextField txtLokasi;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 23,508 | java | DataGudangClient.java | Java | [
{
"context": "odel;\nimport Model.GudangModel;\n\n/**\n *\n * @author Matius Andreatna\n */\npublic class DataGudangClient extends javax.s",
"end": 804,
"score": 0.9998493194580078,
"start": 788,
"tag": "NAME",
"value": "Matius Andreatna"
}
]
| null | []
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package View;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import Model.GudangModel;
/**
*
* @author <NAME>
*/
public class DataGudangClient extends javax.swing.JFrame {
/**
* Creates new form DataGudangClient
*/
private Service.AllService serv = null;
public DataGudangClient() throws NotBoundException, MalformedURLException, RemoteException {
initComponents();
serv = (Service.AllService) Naming.lookup("rmi://localhost:1234/allService");
setLocationRelativeTo(null);
showTable(serv.loadGudang());
}
public void resizeColumnWidth(JTable table) {
final TableColumnModel columnModel = table.getColumnModel();
for (int column = 0; column < table.getColumnCount(); column++) {
int width = 15; // Min width
for (int row = 0; row < table.getRowCount(); row++) {
TableCellRenderer renderer = table.getCellRenderer(row, column);
Component comp = table.prepareRenderer(renderer, row, column);
width = Math.max(comp.getPreferredSize().width +1 , width);
}
if(width > 300)
width=300;
columnModel.getColumn(column).setPreferredWidth(width);
}
columnModel.getColumn(2).setPreferredWidth(100);
}
public void showTable(List<String[]> dataTabel){
DefaultTableModel model = new DefaultTableModel();
List<String[]> result = dataTabel;
String[] columnsName = {"ID", "Lokasi Gudang", "ID Admin"};
String[][] data = new String[result.size()][3];
int idx = 0;
for (String[] row : result) {
data[idx] = row;
idx += 1;
}
tabelGudang.setModel(new DefaultTableModel(data, columnsName));
resizeColumnWidth(tabelGudang);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane2 = new javax.swing.JScrollPane();
tabelGudang = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
txtIdGudang = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
txtLokasi = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
txtIdAdmin = new javax.swing.JTextField();
btnDelete = new javax.swing.JButton();
btnSubmit = new javax.swing.JButton();
btnUpdate = new javax.swing.JButton();
btnBack = new javax.swing.JButton();
btnLogout = new javax.swing.JButton();
boxSort = new javax.swing.JComboBox<>();
jLabel8 = new javax.swing.JLabel();
txtCari = new javax.swing.JTextField();
btnCari = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
tabelGudang.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
tabelGudang.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
jScrollPane2.setViewportView(tabelGudang);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel1.setText("DATA GUDANG");
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("DAFTAR GUDANG");
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setText("INPUT GUDANG");
txtIdGudang.setEditable(false);
txtIdGudang.setBackground(new java.awt.Color(153, 153, 153));
jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel4.setText("ID GUDANG");
jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel5.setText("LOKASI ");
jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel6.setText("ID ADMIN");
btnDelete.setText("DELETE");
btnDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDeleteActionPerformed(evt);
}
});
btnSubmit.setText("SUBMIT");
btnSubmit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSubmitActionPerformed(evt);
}
});
btnUpdate.setText("UPDATE");
btnUpdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnUpdateActionPerformed(evt);
}
});
btnBack.setText("<BACK");
btnBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBackActionPerformed(evt);
}
});
btnLogout.setText("LOGOUT");
btnLogout.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLogoutActionPerformed(evt);
}
});
boxSort.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "ID", "Lokasi", "ID Admin" }));
boxSort.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
boxSortActionPerformed(evt);
}
});
jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel8.setText("Urutkan berdasar");
btnCari.setText("Cari");
btnCari.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCariActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(265, 265, 265)
.addComponent(jLabel1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(47, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 85, Short.MAX_VALUE)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(txtIdAdmin, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
.addComponent(txtLokasi, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtIdGudang, javax.swing.GroupLayout.Alignment.LEADING)))
.addGroup(layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(btnDelete)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnSubmit)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnUpdate))))
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 419, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(btnBack)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnLogout)))
.addContainerGap())
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 349, Short.MAX_VALUE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(boxSort, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(txtCari, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnCari)
.addGap(3, 3, 3)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txtIdGudang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(14, 14, 14)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(txtLokasi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(14, 14, 14)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(txtIdAdmin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(56, 56, 56)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnSubmit)
.addComponent(btnUpdate)
.addComponent(btnDelete)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnLogout)
.addComponent(btnBack))
.addGap(209, 209, 209))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(73, 73, 73)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnCari)
.addComponent(txtCari, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(boxSort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8))
.addContainerGap(407, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
// TODO add your handling code here:
GudangModel id = new GudangModel();
id.setId(txtIdGudang.getText());
//deleteData(id);
}//GEN-LAST:event_btnDeleteActionPerformed
private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSubmitActionPerformed
// TODO add your handling code here:
String id;
try {
id = serv.idGudang();
GudangModel bM = new GudangModel();
txtIdGudang.setText(id);
String nama = txtLokasi.getText();
String idAdmin = txtIdAdmin.getText();
bM.setId(id);
bM.setLokasi(nama);
bM.setId_admin(idAdmin);
//insertData(bM);
} catch (RemoteException ex) {
Logger.getLogger(DataGudangClient.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnSubmitActionPerformed
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
// TODO add your handling code here:
String id = txtIdGudang.getText();
String lokasi = txtLokasi.getText();
String idAdmin = txtIdAdmin.getText();
GudangModel data = new GudangModel();
data.setId(id);
data.setLokasi(lokasi);
data.setId_admin(idAdmin);
//updateData(data);
}//GEN-LAST:event_btnUpdateActionPerformed
private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed
try {
// TODO add your handling code here:
this.dispose();
HomeClient Home = new HomeClient();
Home.setVisible(true);
} catch (NotBoundException ex) {
Logger.getLogger(DataGudangClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(DataGudangClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (RemoteException ex) {
Logger.getLogger(DataGudangClient.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnBackActionPerformed
private void btnLogoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLogoutActionPerformed
// TODO add your handling code here:
int selectedOption = JOptionPane.showConfirmDialog(null,
"Apakah Anda ingin keluar?",
"LOGOUT",
JOptionPane.YES_NO_OPTION);
if (selectedOption == JOptionPane.YES_OPTION) {
try {
this.dispose();
LoginUserClient loginUserClient = new LoginUserClient();
loginUserClient.setVisible(true);
} catch (NotBoundException ex) {
Logger.getLogger(HomeClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(HomeClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (RemoteException ex) {
Logger.getLogger(HomeClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_btnLogoutActionPerformed
private void boxSortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boxSortActionPerformed
try {
// TODO add your handling code here:
String selectedItem = String.valueOf(boxSort.getSelectedItem());
List <String[]> result = serv.sortGudang(selectedItem);
DefaultTableModel model = new DefaultTableModel();
String[] columnsName = {"ID", "Nama", "Ukuran", "Harga"};
String[][] data = new String[result.size()][4];
int idx = 0;
for (String[] row : result) {
data[idx] = row;
idx += 1;
}
tabelGudang.setModel(new DefaultTableModel(data, columnsName));
resizeColumnWidth(tabelGudang);
} catch (RemoteException ex) {
Logger.getLogger(DataGudangClient.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_boxSortActionPerformed
private void btnCariActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCariActionPerformed
// TODO add your handling code here:
String cariGudang = txtCari.getText();
//cariData(cariBrg);
}//GEN-LAST:event_btnCariActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DataGudangClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DataGudangClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DataGudangClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DataGudangClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new DataGudangClient().setVisible(true);
} catch (NotBoundException ex) {
Logger.getLogger(DataGudangClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(DataGudangClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (RemoteException ex) {
Logger.getLogger(DataGudangClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox<String> boxSort;
private javax.swing.JButton btnBack;
private javax.swing.JButton btnCari;
private javax.swing.JButton btnDelete;
private javax.swing.JButton btnLogout;
private javax.swing.JButton btnSubmit;
private javax.swing.JButton btnUpdate;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel8;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable tabelGudang;
private javax.swing.JTextField txtCari;
private javax.swing.JTextField txtIdAdmin;
private javax.swing.JTextField txtIdGudang;
private javax.swing.JTextField txtLokasi;
// End of variables declaration//GEN-END:variables
}
| 23,498 | 0.62332 | 0.615493 | 475 | 48.490528 | 37.401398 | 186 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.713684 | false | false | 0 |
98d9c3ab813f6ff5451a769f449b70e43d2c6b3a | 36,636,071,071,609 | c08d1635052e88ce6764cf4bdbb54c8f6aae3895 | /gzf/zflow4a_WDIT/src/main/java/com/bizduo/zflow/util/FileUtil.java | b99a0a9cc0162ddf632546c388bc476eccd51b68 | []
| no_license | pengchengming/myCode | https://github.com/pengchengming/myCode | 09f020369895b4ff2bddca411fff8f94abb54142 | 5a738056c6abb64ef8148263d368000183b3c774 | refs/heads/master | 2020-03-22T02:59:51.899000 | 2019-02-15T07:00:18 | 2019-02-15T07:00:18 | 139,406,872 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bizduo.zflow.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
public class FileUtil {
/**
* 加载属性文件
* @param filePath 文件路径
* @return
*/
public static Properties loadProps(String filePath){
Properties dbProps = new Properties();
try {
InputStream is = new FileInputStream(filePath);
dbProps.load(is);
} catch (Exception e) {
e.printStackTrace();
}
return dbProps;
}
/**
* 读取配置文件
* @param props 配置文件
* @param key
* @return
*/
public static String getString(Properties properties,String key){
return properties.getProperty(key);
}
public static void saveFile(String path,String center){
// FileToUploadRecord fileUploadRecord =new FileToUploadRecord();
RandomAccessFile raf = null;
Boolean isfoundRecord=false;
try {
File uploadRecord = new File(path);
FileUtil.createFile(uploadRecord,path);
/*System.out.println(uploadRecord.getParentFile());
if(!uploadRecord.exists()){
uploadRecord.createNewFile();
}*/
raf = new RandomAccessFile(uploadRecord, "rw");
if(!isfoundRecord){
FileWriter fw = new FileWriter(uploadRecord);
fw.write(center);
fw.flush();
fw.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(raf!=null){
raf.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void saveFile(String path, MultipartFile file, String filename){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String realPath = path + File.separator + "upload" + File.separator + sdf.format(new Date());
File dir = new File(realPath);
if(dir.exists()) {
dir.mkdirs();
}
//这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的
try {
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, filename + ".xlsx"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param args
*/
@SuppressWarnings("unused")
public static String getMD5(String path) {
StringBuilder sb = new StringBuilder();
byte[] size = null;
StringBuilder noAlgorithm=new StringBuilder("无法使用MD5算法,这可能是你的JAVA虚拟机版本太低");
StringBuilder fileNotFound=new StringBuilder("未能找到文件,请重新定位文件路径");
StringBuilder IOerror=new StringBuilder("文件输入流错误");
try {
MessageDigest md5=MessageDigest.getInstance("MD5");//生成MD5类的实例
File file = new File(path); //创建文件实例,设置路径为方法参数
FileInputStream fs = new FileInputStream(file);
BufferedInputStream bi = new BufferedInputStream(fs);
ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] b = new byte[bi.available()]; //定义字节数组b大小为文件的不受阻塞的可访问字节数
int i;
//将文件以字节方式读到数组b中
while ((i = bi.read(b, 0, b.length)) != -1)
{
}
md5.update(b);//执行MD5算法
for (byte by : md5.digest())
{
sb.append(String.format("%02X", by));//将生成的字节MD5值转换成字符串
}
bo.close();
bi.close();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
return noAlgorithm.toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return fileNotFound.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
return IOerror.toString();
}
return sb.toString();//返回MD5值
}
/***
* 读取文件夹下所有文件
* @param path
* @param importDateLong
* @return
*/
public static List<String> traverseFolder(String path,Long importDateLong,List<String> filePathNames) {
boolean isAll=true;
if(importDateLong!=null)
isAll=false;
File file = new File(path);
if (file.exists()) {
File[] files = file.listFiles();
if (files.length == 0) {
System.out.println("文件夹是空的!");
} else {
for (File file2 : files) {
if (file2.isDirectory()) {
System.out.println("文件夹:" + file2.getAbsolutePath());
traverseFolder(file2.getAbsolutePath(),importDateLong,filePathNames);
} else {
boolean isdownload=false;
if(isAll)
isdownload=true;
else if(file2.lastModified() > importDateLong){
isdownload=true;
}
if(isdownload){
String filePath= file2.getAbsolutePath();
String filePathName= filePath.substring(filePath.lastIndexOf("upload")-1);
filePathNames.add(filePathName);
System.out.println("文件:" + file2.getAbsolutePath());
}
}
}
}
} else {
System.out.println("文件不存在!");
}
return filePathNames;
}
/**
* 下载远程文件并保存到本地
* @param remoteFilePath 远程文件路径
* @param localFilePath 本地文件路径
*/
public static boolean downloadFile(String remoteFilePath, String localFilePath)
{
URL urlfile = null;
HttpURLConnection httpUrl = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
boolean issuccess=true;
try
{
urlfile = new URL(remoteFilePath);
httpUrl = (HttpURLConnection)urlfile.openConnection();
httpUrl.connect();
bis = new BufferedInputStream(httpUrl.getInputStream());
//如果链接成功成功 创建本地目录
File f = new File(localFilePath);
boolean isExist= createFile(f,localFilePath);
if(!isExist){
issuccess=false;
}
bos = new BufferedOutputStream(new FileOutputStream(f));
int len = 2048;
byte[] b = new byte[len];
while ((len = bis.read(b)) != -1)
{
bos.write(b, 0, len);
}
bos.flush();
bis.close();
httpUrl.disconnect();
}
catch (Exception e)
{
issuccess=false;
e.printStackTrace();
}
finally
{
try
{
if(bis!=null)
bis.close();
if(bos!=null)
bos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return issuccess;
}
public static boolean createFile(File file,String destFileName) {
// File file = new File(destFileName);
if(file.exists()) {
System.out.println("创建单个文件" + destFileName + "失败,目标文件已存在!");
return false;
}
if (destFileName.endsWith(File.separator)) {
System.out.println("创建单个文件" + destFileName + "失败,目标文件不能为目录!");
return false;
}
//判断目标文件所在的目录是否存在
if(!file.getParentFile().exists()) {
//如果目标文件所在的目录不存在,则创建父目录
System.out.println("目标文件所在目录不存在,准备创建它!");
if(!file.getParentFile().mkdirs()) {
System.out.println("创建目标文件所在目录失败!");
return false;
}
}
//创建目标文件
try {
if (file.createNewFile()) {
System.out.println("创建单个文件" + destFileName + "成功!");
return true;
} else {
System.out.println("创建单个文件" + destFileName + "失败!");
return false;
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("创建单个文件" + destFileName + "失败!" + e.getMessage());
return false;
}
}
}
| UTF-8 | Java | 9,780 | java | FileUtil.java | Java | []
| null | []
| package com.bizduo.zflow.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
public class FileUtil {
/**
* 加载属性文件
* @param filePath 文件路径
* @return
*/
public static Properties loadProps(String filePath){
Properties dbProps = new Properties();
try {
InputStream is = new FileInputStream(filePath);
dbProps.load(is);
} catch (Exception e) {
e.printStackTrace();
}
return dbProps;
}
/**
* 读取配置文件
* @param props 配置文件
* @param key
* @return
*/
public static String getString(Properties properties,String key){
return properties.getProperty(key);
}
public static void saveFile(String path,String center){
// FileToUploadRecord fileUploadRecord =new FileToUploadRecord();
RandomAccessFile raf = null;
Boolean isfoundRecord=false;
try {
File uploadRecord = new File(path);
FileUtil.createFile(uploadRecord,path);
/*System.out.println(uploadRecord.getParentFile());
if(!uploadRecord.exists()){
uploadRecord.createNewFile();
}*/
raf = new RandomAccessFile(uploadRecord, "rw");
if(!isfoundRecord){
FileWriter fw = new FileWriter(uploadRecord);
fw.write(center);
fw.flush();
fw.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(raf!=null){
raf.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void saveFile(String path, MultipartFile file, String filename){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String realPath = path + File.separator + "upload" + File.separator + sdf.format(new Date());
File dir = new File(realPath);
if(dir.exists()) {
dir.mkdirs();
}
//这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的
try {
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, filename + ".xlsx"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param args
*/
@SuppressWarnings("unused")
public static String getMD5(String path) {
StringBuilder sb = new StringBuilder();
byte[] size = null;
StringBuilder noAlgorithm=new StringBuilder("无法使用MD5算法,这可能是你的JAVA虚拟机版本太低");
StringBuilder fileNotFound=new StringBuilder("未能找到文件,请重新定位文件路径");
StringBuilder IOerror=new StringBuilder("文件输入流错误");
try {
MessageDigest md5=MessageDigest.getInstance("MD5");//生成MD5类的实例
File file = new File(path); //创建文件实例,设置路径为方法参数
FileInputStream fs = new FileInputStream(file);
BufferedInputStream bi = new BufferedInputStream(fs);
ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] b = new byte[bi.available()]; //定义字节数组b大小为文件的不受阻塞的可访问字节数
int i;
//将文件以字节方式读到数组b中
while ((i = bi.read(b, 0, b.length)) != -1)
{
}
md5.update(b);//执行MD5算法
for (byte by : md5.digest())
{
sb.append(String.format("%02X", by));//将生成的字节MD5值转换成字符串
}
bo.close();
bi.close();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
return noAlgorithm.toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return fileNotFound.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
return IOerror.toString();
}
return sb.toString();//返回MD5值
}
/***
* 读取文件夹下所有文件
* @param path
* @param importDateLong
* @return
*/
public static List<String> traverseFolder(String path,Long importDateLong,List<String> filePathNames) {
boolean isAll=true;
if(importDateLong!=null)
isAll=false;
File file = new File(path);
if (file.exists()) {
File[] files = file.listFiles();
if (files.length == 0) {
System.out.println("文件夹是空的!");
} else {
for (File file2 : files) {
if (file2.isDirectory()) {
System.out.println("文件夹:" + file2.getAbsolutePath());
traverseFolder(file2.getAbsolutePath(),importDateLong,filePathNames);
} else {
boolean isdownload=false;
if(isAll)
isdownload=true;
else if(file2.lastModified() > importDateLong){
isdownload=true;
}
if(isdownload){
String filePath= file2.getAbsolutePath();
String filePathName= filePath.substring(filePath.lastIndexOf("upload")-1);
filePathNames.add(filePathName);
System.out.println("文件:" + file2.getAbsolutePath());
}
}
}
}
} else {
System.out.println("文件不存在!");
}
return filePathNames;
}
/**
* 下载远程文件并保存到本地
* @param remoteFilePath 远程文件路径
* @param localFilePath 本地文件路径
*/
public static boolean downloadFile(String remoteFilePath, String localFilePath)
{
URL urlfile = null;
HttpURLConnection httpUrl = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
boolean issuccess=true;
try
{
urlfile = new URL(remoteFilePath);
httpUrl = (HttpURLConnection)urlfile.openConnection();
httpUrl.connect();
bis = new BufferedInputStream(httpUrl.getInputStream());
//如果链接成功成功 创建本地目录
File f = new File(localFilePath);
boolean isExist= createFile(f,localFilePath);
if(!isExist){
issuccess=false;
}
bos = new BufferedOutputStream(new FileOutputStream(f));
int len = 2048;
byte[] b = new byte[len];
while ((len = bis.read(b)) != -1)
{
bos.write(b, 0, len);
}
bos.flush();
bis.close();
httpUrl.disconnect();
}
catch (Exception e)
{
issuccess=false;
e.printStackTrace();
}
finally
{
try
{
if(bis!=null)
bis.close();
if(bos!=null)
bos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return issuccess;
}
public static boolean createFile(File file,String destFileName) {
// File file = new File(destFileName);
if(file.exists()) {
System.out.println("创建单个文件" + destFileName + "失败,目标文件已存在!");
return false;
}
if (destFileName.endsWith(File.separator)) {
System.out.println("创建单个文件" + destFileName + "失败,目标文件不能为目录!");
return false;
}
//判断目标文件所在的目录是否存在
if(!file.getParentFile().exists()) {
//如果目标文件所在的目录不存在,则创建父目录
System.out.println("目标文件所在目录不存在,准备创建它!");
if(!file.getParentFile().mkdirs()) {
System.out.println("创建目标文件所在目录失败!");
return false;
}
}
//创建目标文件
try {
if (file.createNewFile()) {
System.out.println("创建单个文件" + destFileName + "成功!");
return true;
} else {
System.out.println("创建单个文件" + destFileName + "失败!");
return false;
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("创建单个文件" + destFileName + "失败!" + e.getMessage());
return false;
}
}
}
| 9,780 | 0.539725 | 0.536507 | 279 | 31.301075 | 22.135191 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.057348 | false | false | 0 |
1c4f957ae7c54883ad409b363e671305ead7661c | 13,494,787,310,558 | 2108d4cdb1722cf9b4b5ceab2da5a56972c5847f | /net/minecraft/src/mod_SAPI.java | 76dc7c7e806ac4c9f0abfc74afa96db3a38681dd | []
| no_license | chorman0773/Aether-mod | https://github.com/chorman0773/Aether-mod | 9ea92cd4ced39f2e0992fa0075b9d8fddcde2e98 | 785c7fbc76e27b5e544aa8b091b448544f51de4d | refs/heads/master | 2021-01-17T08:46:37.297000 | 2013-10-23T15:23:58 | 2013-10-23T15:23:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode fieldsfirst
package net.minecraft.src;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import net.minecraft.client.Minecraft;
// Referenced classes of package net.minecraft.src:
// BaseMod, INBT, SAPI, ModLoader,
// DungeonLoot, ItemStack, Item, PlayerBaseSAPI,
// PlayerAPI, GuiLockDifficulty, World, WorldInfo,
// GuiAchievements, GuiAchievementsPages, StatFileWriter, GameSettings,
// NBTTagCompound, CompressedStreamTools, SaveHandler, GuiScreen,
// ISaveHandler
public class mod_SAPI extends BaseMod
implements INBT
{
private static World worldObj;
protected static int lockDifficulty = -1;
private static int counter = 0;
public mod_SAPI()
{
}
public String getVersion()
{
return "r11";
}
public void load()
{
ModLoader.SetInGameHook(this, true, true);
ModLoader.SetInGUIHook(this, true, false);
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[329])));
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[265]), 1, 4));
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[297])));
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[296]), 1, 4));
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[289]), 1, 4));
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[287]), 1, 4));
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[325])));
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[322])), 0.01F);
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[331]), 1, 4), 0.5F);
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[2256])), 0.05F);
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[2257])), 0.05F);
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[351], 1, 3)));
SAPI.Dungeon.addMob("Skeleton");
SAPI.Dungeon.addMob("Zombie", 2.0F);
SAPI.Dungeon.addMob("Spider");
SAPI.NBT.add(this);
PlayerAPI.register("Dimension API", net.minecraft.src.PlayerBaseSAPI.class);
}
public boolean OnTickInGame(float f, Minecraft minecraft)
{
if(counter == 1)
{
counter = 0;
minecraft.displayGuiScreen(new GuiLockDifficulty(minecraft.theWorld));
}
tick(minecraft);
if(!minecraft.theWorld.multiplayerWorld)
{
if(minecraft.theWorld != worldObj)
{
if(worldObj != null)
{
saveNBT(worldObj);
}
if(minecraft.thePlayer != null)
{
loadNBT(minecraft.theWorld);
}
worldObj = minecraft.theWorld;
}
if(worldObj != null && worldObj.worldInfo.getWorldTime() % (long)worldObj.autosavePeriod == 0L)
{
saveNBT(worldObj);
}
}
return true;
}
public boolean OnTickInGUI(float f, Minecraft minecraft, GuiScreen guiscreen)
{
if(guiscreen != null && guiscreen.getClass() == (net.minecraft.src.GuiAchievements.class))
{
try
{
minecraft.displayGuiScreen(new GuiAchievementsPages((StatFileWriter)ModLoader.getPrivateValue(net.minecraft.src.GuiAchievements.class, (GuiAchievements)guiscreen, "x")));
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
tick(minecraft);
worldObj = null;
return true;
}
public void tick(Minecraft minecraft)
{
lockDifficulty(minecraft);
}
public static void updateShouldLock(World world)
{
if(world == null)
{
lockDifficulty = -1;
}
}
public static void lockDifficulty(Minecraft minecraft)
{
if(lockDifficulty == -1)
{
return;
} else
{
minecraft.gameSettings.difficulty = lockDifficulty;
return;
}
}
public static void saveNBT(World world)
{
try
{
File file = GetWorldSaveLocation(world);
ArrayList arraylist = SAPI.NBT.getList();
File file1;
NBTTagCompound nbttagcompound;
for(Iterator iterator = arraylist.iterator(); iterator.hasNext(); CompressedStreamTools.writeGzippedCompoundToOutputStream(nbttagcompound, new FileOutputStream(file1)))
{
INBT inbt = (INBT)iterator.next();
file1 = new File(file, inbt.iNBTFilename());
if(!file1.exists())
{
CompressedStreamTools.writeGzippedCompoundToOutputStream(new NBTTagCompound(), new FileOutputStream(file1));
}
nbttagcompound = CompressedStreamTools.loadGzippedCompoundFromOutputStream(new FileInputStream(file1));
inbt.iNBTSave(nbttagcompound);
}
}
catch(Exception exception)
{
exception.printStackTrace();
}
updateShouldLock(world);
}
public static void loadNBT(World world)
{
try
{
File file = GetWorldSaveLocation(world);
ArrayList arraylist = SAPI.NBT.getList();
INBT inbt;
NBTTagCompound nbttagcompound;
for(Iterator iterator = arraylist.iterator(); iterator.hasNext(); inbt.iNBTLoad(nbttagcompound))
{
inbt = (INBT)iterator.next();
File file1 = new File(file, inbt.iNBTFilename());
if(!file1.exists())
{
CompressedStreamTools.writeGzippedCompoundToOutputStream(new NBTTagCompound(), new FileOutputStream(file1));
}
nbttagcompound = CompressedStreamTools.loadGzippedCompoundFromOutputStream(new FileInputStream(file1));
}
}
catch(Exception exception)
{
exception.printStackTrace();
}
updateShouldLock(world);
if(!SAPI.LockDifficulty.listLockingMods().isEmpty() && lockDifficulty == -1)
{
counter = 1;
}
}
public static File GetWorldSaveLocation(World world)
{
return GetWorldSaveLocation(world.saveHandler);
}
public static File GetWorldSaveLocation(ISaveHandler isavehandler)
{
return (isavehandler instanceof SaveHandler) ? ((SaveHandler)isavehandler).getSaveDirectory() : null;
}
public String iNBTFilename()
{
return "SAPI.dat";
}
public void iNBTSave(NBTTagCompound nbttagcompound)
{
nbttagcompound.setInteger("LockDifficulty", lockDifficulty);
}
public void iNBTLoad(NBTTagCompound nbttagcompound)
{
lockDifficulty = -1;
if(nbttagcompound.hasKey("LockDifficulty"))
{
lockDifficulty = nbttagcompound.getInteger("LockDifficulty");
}
}
}
| UTF-8 | Java | 7,483 | java | mod_SAPI.java | Java | [
{
"context": "// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.kpdus.com/jad.html\n",
"end": 61,
"score": 0.9996446371078491,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
]
| null | []
| // Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode fieldsfirst
package net.minecraft.src;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import net.minecraft.client.Minecraft;
// Referenced classes of package net.minecraft.src:
// BaseMod, INBT, SAPI, ModLoader,
// DungeonLoot, ItemStack, Item, PlayerBaseSAPI,
// PlayerAPI, GuiLockDifficulty, World, WorldInfo,
// GuiAchievements, GuiAchievementsPages, StatFileWriter, GameSettings,
// NBTTagCompound, CompressedStreamTools, SaveHandler, GuiScreen,
// ISaveHandler
public class mod_SAPI extends BaseMod
implements INBT
{
private static World worldObj;
protected static int lockDifficulty = -1;
private static int counter = 0;
public mod_SAPI()
{
}
public String getVersion()
{
return "r11";
}
public void load()
{
ModLoader.SetInGameHook(this, true, true);
ModLoader.SetInGUIHook(this, true, false);
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[329])));
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[265]), 1, 4));
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[297])));
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[296]), 1, 4));
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[289]), 1, 4));
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[287]), 1, 4));
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[325])));
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[322])), 0.01F);
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[331]), 1, 4), 0.5F);
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[2256])), 0.05F);
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[2257])), 0.05F);
SAPI.Dungeon.addDungeonLoot(new DungeonLoot(new ItemStack(Item.itemsList[351], 1, 3)));
SAPI.Dungeon.addMob("Skeleton");
SAPI.Dungeon.addMob("Zombie", 2.0F);
SAPI.Dungeon.addMob("Spider");
SAPI.NBT.add(this);
PlayerAPI.register("Dimension API", net.minecraft.src.PlayerBaseSAPI.class);
}
public boolean OnTickInGame(float f, Minecraft minecraft)
{
if(counter == 1)
{
counter = 0;
minecraft.displayGuiScreen(new GuiLockDifficulty(minecraft.theWorld));
}
tick(minecraft);
if(!minecraft.theWorld.multiplayerWorld)
{
if(minecraft.theWorld != worldObj)
{
if(worldObj != null)
{
saveNBT(worldObj);
}
if(minecraft.thePlayer != null)
{
loadNBT(minecraft.theWorld);
}
worldObj = minecraft.theWorld;
}
if(worldObj != null && worldObj.worldInfo.getWorldTime() % (long)worldObj.autosavePeriod == 0L)
{
saveNBT(worldObj);
}
}
return true;
}
public boolean OnTickInGUI(float f, Minecraft minecraft, GuiScreen guiscreen)
{
if(guiscreen != null && guiscreen.getClass() == (net.minecraft.src.GuiAchievements.class))
{
try
{
minecraft.displayGuiScreen(new GuiAchievementsPages((StatFileWriter)ModLoader.getPrivateValue(net.minecraft.src.GuiAchievements.class, (GuiAchievements)guiscreen, "x")));
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
tick(minecraft);
worldObj = null;
return true;
}
public void tick(Minecraft minecraft)
{
lockDifficulty(minecraft);
}
public static void updateShouldLock(World world)
{
if(world == null)
{
lockDifficulty = -1;
}
}
public static void lockDifficulty(Minecraft minecraft)
{
if(lockDifficulty == -1)
{
return;
} else
{
minecraft.gameSettings.difficulty = lockDifficulty;
return;
}
}
public static void saveNBT(World world)
{
try
{
File file = GetWorldSaveLocation(world);
ArrayList arraylist = SAPI.NBT.getList();
File file1;
NBTTagCompound nbttagcompound;
for(Iterator iterator = arraylist.iterator(); iterator.hasNext(); CompressedStreamTools.writeGzippedCompoundToOutputStream(nbttagcompound, new FileOutputStream(file1)))
{
INBT inbt = (INBT)iterator.next();
file1 = new File(file, inbt.iNBTFilename());
if(!file1.exists())
{
CompressedStreamTools.writeGzippedCompoundToOutputStream(new NBTTagCompound(), new FileOutputStream(file1));
}
nbttagcompound = CompressedStreamTools.loadGzippedCompoundFromOutputStream(new FileInputStream(file1));
inbt.iNBTSave(nbttagcompound);
}
}
catch(Exception exception)
{
exception.printStackTrace();
}
updateShouldLock(world);
}
public static void loadNBT(World world)
{
try
{
File file = GetWorldSaveLocation(world);
ArrayList arraylist = SAPI.NBT.getList();
INBT inbt;
NBTTagCompound nbttagcompound;
for(Iterator iterator = arraylist.iterator(); iterator.hasNext(); inbt.iNBTLoad(nbttagcompound))
{
inbt = (INBT)iterator.next();
File file1 = new File(file, inbt.iNBTFilename());
if(!file1.exists())
{
CompressedStreamTools.writeGzippedCompoundToOutputStream(new NBTTagCompound(), new FileOutputStream(file1));
}
nbttagcompound = CompressedStreamTools.loadGzippedCompoundFromOutputStream(new FileInputStream(file1));
}
}
catch(Exception exception)
{
exception.printStackTrace();
}
updateShouldLock(world);
if(!SAPI.LockDifficulty.listLockingMods().isEmpty() && lockDifficulty == -1)
{
counter = 1;
}
}
public static File GetWorldSaveLocation(World world)
{
return GetWorldSaveLocation(world.saveHandler);
}
public static File GetWorldSaveLocation(ISaveHandler isavehandler)
{
return (isavehandler instanceof SaveHandler) ? ((SaveHandler)isavehandler).getSaveDirectory() : null;
}
public String iNBTFilename()
{
return "SAPI.dat";
}
public void iNBTSave(NBTTagCompound nbttagcompound)
{
nbttagcompound.setInteger("LockDifficulty", lockDifficulty);
}
public void iNBTLoad(NBTTagCompound nbttagcompound)
{
lockDifficulty = -1;
if(nbttagcompound.hasKey("LockDifficulty"))
{
lockDifficulty = nbttagcompound.getInteger("LockDifficulty");
}
}
}
| 7,473 | 0.604704 | 0.592276 | 221 | 32.85973 | 33.877918 | 186 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.59276 | false | false | 0 |
bc9123debd2541c3de4b43167dc9d100c9dc7be6 | 35,656,818,534,639 | 932884fadae5fbe39e230d9938f5a66a5c34ee6e | /Server.java | dd96204293f46083cbb1320618a87f5000abdf8c | []
| no_license | tristo7/PG1TST | https://github.com/tristo7/PG1TST | a35f9f546a93b5b663329f05bc5b06320da37de1 | 143c504d9df41770b715d86f6d10cd8bc4c7f778 | refs/heads/master | 2021-05-03T17:44:42.611000 | 2015-09-26T16:02:58 | 2015-09-26T16:02:58 | 42,969,288 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Server.java
*
* This creates the buffer and the producer and consumer threads.
*
* @author Greg Gagne, Peter Galvin, Avi Silberschatz
* @version 1.0 - July 15, 1999
* Copyright 2000 by Greg Gagne, Peter Galvin, Avi Silberschatz
* Applied Operating Systems Concepts - John Wiley and Sons, Inc.
*/
/*
Name: Tristin Terry
Date: 9/29/2015
Description:
Alter the given templates to do the following:
-Have 2 separate groups of producers and consumers.
-Producers will generate random int from 9000 to 50000
-Consumers will take that int and determine if it is prime or not.
-Producers and Consumers sleep randomly from 3 to 5 seconds.
*/
public class Server
{
public static void main(String args[]) {
//Create 2 bounded buffers to separate the two sets of
//producers and consumers.
BoundedBuffer room1 = new BoundedBuffer();
BoundedBuffer room2 = new BoundedBuffer();
//Create Producer and Consumer threads.
//Group 1:
Producer John = new Producer(room1, "John");
Consumer Mary = new Consumer(room1, "Mary");
//Group 2:
Producer Liz = new Producer(room2, "Liz");
Consumer Bert = new Consumer(room2, "Bert");
//Start threads
//Group 1:
John.start();
Mary.start();
//Group 2:
Liz.start();
Bert.start();
}//main
}//class | UTF-8 | Java | 1,401 | java | Server.java | Java | [
{
"context": "d the producer and consumer threads.\n *\n * @author Greg Gagne, Peter Galvin, Avi Silberschatz\n * @version 1.0 -",
"end": 112,
"score": 0.9998946785926819,
"start": 102,
"tag": "NAME",
"value": "Greg Gagne"
},
{
"context": "er and consumer threads.\n *\n * @author Greg Gagne, Peter Galvin, Avi Silberschatz\n * @version 1.0 - July 15, 1999",
"end": 126,
"score": 0.9998577237129211,
"start": 114,
"tag": "NAME",
"value": "Peter Galvin"
},
{
"context": "r threads.\n *\n * @author Greg Gagne, Peter Galvin, Avi Silberschatz\n * @version 1.0 - July 15, 1999\n * Copyright 2000",
"end": 144,
"score": 0.9998810887336731,
"start": 128,
"tag": "NAME",
"value": "Avi Silberschatz"
},
{
"context": " @version 1.0 - July 15, 1999\n * Copyright 2000 by Greg Gagne, Peter Galvin, Avi Silberschatz\n * Applied Operat",
"end": 208,
"score": 0.9998986721038818,
"start": 198,
"tag": "NAME",
"value": "Greg Gagne"
},
{
"context": "0 - July 15, 1999\n * Copyright 2000 by Greg Gagne, Peter Galvin, Avi Silberschatz\n * Applied Operating Systems Co",
"end": 222,
"score": 0.9998688697814941,
"start": 210,
"tag": "NAME",
"value": "Peter Galvin"
},
{
"context": "999\n * Copyright 2000 by Greg Gagne, Peter Galvin, Avi Silberschatz\n * Applied Operating Systems Concepts - John Wile",
"end": 240,
"score": 0.9998767971992493,
"start": 224,
"tag": "NAME",
"value": "Avi Silberschatz"
},
{
"context": "epts - John Wiley and Sons, Inc.\n */\n \n /*\n\tName: Tristin Terry\n\tDate: 9/29/2015\n\tDescription:\n\t\tAlter the given ",
"end": 338,
"score": 0.9998782277107239,
"start": 325,
"tag": "NAME",
"value": "Tristin Terry"
},
{
"context": "p 1:\n \t\tProducer John = new Producer(room1, \"John\");\n \t\tConsumer Mary = new Consumer(room1, \"M",
"end": 1028,
"score": 0.9993557333946228,
"start": 1024,
"tag": "NAME",
"value": "John"
},
{
"context": "hn = new Producer(room1, \"John\");\n \t\tConsumer Mary = new Consumer(room1, \"Mary\");\n \t\t\n ",
"end": 1050,
"score": 0.9032113552093506,
"start": 1049,
"tag": "NAME",
"value": "M"
},
{
"context": "n\");\n \t\tConsumer Mary = new Consumer(room1, \"Mary\");\n \t\t\n \t\t//Group 2:\n \t\tProducer L",
"end": 1081,
"score": 0.9986518025398254,
"start": 1077,
"tag": "NAME",
"value": "Mary"
},
{
"context": "up 2:\n \t\tProducer Liz = new Producer(room2, \"Liz\");\n \t\tConsumer Bert = new Consumer(room2, \"B",
"end": 1160,
"score": 0.9974414706230164,
"start": 1157,
"tag": "NAME",
"value": "Liz"
},
{
"context": "z\");\n \t\tConsumer Bert = new Consumer(room2, \"Bert\");\n \t\t\n \t\t//Start threads\n\t\t\t\n\t\t\t//Grou",
"end": 1213,
"score": 0.9988422393798828,
"start": 1209,
"tag": "NAME",
"value": "Bert"
}
]
| null | []
| /**
* Server.java
*
* This creates the buffer and the producer and consumer threads.
*
* @author <NAME>, <NAME>, <NAME>
* @version 1.0 - July 15, 1999
* Copyright 2000 by <NAME>, <NAME>, <NAME>
* Applied Operating Systems Concepts - John Wiley and Sons, Inc.
*/
/*
Name: <NAME>
Date: 9/29/2015
Description:
Alter the given templates to do the following:
-Have 2 separate groups of producers and consumers.
-Producers will generate random int from 9000 to 50000
-Consumers will take that int and determine if it is prime or not.
-Producers and Consumers sleep randomly from 3 to 5 seconds.
*/
public class Server
{
public static void main(String args[]) {
//Create 2 bounded buffers to separate the two sets of
//producers and consumers.
BoundedBuffer room1 = new BoundedBuffer();
BoundedBuffer room2 = new BoundedBuffer();
//Create Producer and Consumer threads.
//Group 1:
Producer John = new Producer(room1, "John");
Consumer Mary = new Consumer(room1, "Mary");
//Group 2:
Producer Liz = new Producer(room2, "Liz");
Consumer Bert = new Consumer(room2, "Bert");
//Start threads
//Group 1:
John.start();
Mary.start();
//Group 2:
Liz.start();
Bert.start();
}//main
}//class | 1,354 | 0.64454 | 0.614561 | 51 | 26.490196 | 22.157522 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.803922 | false | false | 0 |
0ede388939f056f12200fc9c5bd7fc318b9155f7 | 38,809,324,530,412 | 8b4eed04c78ec8b173e5ac8a1b719b2e498cedcc | /src/com/mxgraph/yeli/service/RanqiEnumSensorModeService.java | 10508f18b79f6223ac7c160ff9f7c7c6c97cc92e | []
| no_license | kkkf1190/new-GoldHouse | https://github.com/kkkf1190/new-GoldHouse | f0f9b5c38d59886a7cb2ffdc6ccf5a78d2907c42 | 5104c924bf86c9bddc893d784f1c2e6b280ffe35 | refs/heads/master | 2016-09-05T09:54:50.285000 | 2014-11-20T03:36:38 | 2014-11-20T03:36:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mxgraph.yeli.service;
import generate.Service;
import generate.ServiceAdapter;
import java.io.Serializable;
import com.mxgraph.examples.swing.JDBC.JDBCService;
import com.mxgraph.model.mxCell;
import com.mxgraph.model.mxICell;
import com.mxgraph.swing.mxGraphComponent;
public class RanqiEnumSensorModeService extends ServiceAdapter{
@Override
public void setValue(mxICell cell, mxGraphComponent component) {
// TODO Auto-generated method stub
mxCell task = (mxCell)cell;
JDBCService service = new JDBCService();
service.getCellValue(task,component);
}
@Override
public void invoke(mxGraphComponent graphComponent, mxICell cell,
Object[] objects) {
setValue(cell, graphComponent);
}
}
| UTF-8 | Java | 727 | java | RanqiEnumSensorModeService.java | Java | []
| null | []
| package com.mxgraph.yeli.service;
import generate.Service;
import generate.ServiceAdapter;
import java.io.Serializable;
import com.mxgraph.examples.swing.JDBC.JDBCService;
import com.mxgraph.model.mxCell;
import com.mxgraph.model.mxICell;
import com.mxgraph.swing.mxGraphComponent;
public class RanqiEnumSensorModeService extends ServiceAdapter{
@Override
public void setValue(mxICell cell, mxGraphComponent component) {
// TODO Auto-generated method stub
mxCell task = (mxCell)cell;
JDBCService service = new JDBCService();
service.getCellValue(task,component);
}
@Override
public void invoke(mxGraphComponent graphComponent, mxICell cell,
Object[] objects) {
setValue(cell, graphComponent);
}
}
| 727 | 0.786795 | 0.786795 | 31 | 22.451612 | 21.266115 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.225806 | false | false | 0 |
f4b466c7f972313443ef0c7e24c2c44b4c923c3f | 35,811,437,362,747 | fa20bb300daa5f912baab2e6df9af86922d5fbae | /sz.java | a65a0c0fd7815f6bdcae6d382b477956dd3cf9a4 | []
| no_license | booleantrue1/JavaCodes | https://github.com/booleantrue1/JavaCodes | 4ef8314b6f2ae5599383ea3104c0b0d0a4c5bbc1 | 8e5524a8f31dc68329186e16d1ffdb63d2bf8e22 | refs/heads/master | 2021-01-01T04:58:02.861000 | 2016-05-12T23:21:18 | 2016-05-12T23:21:18 | 58,675,851 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.*;
class j
{
public static void main(String a[])throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int i=0,n=0;
String s=b.readLine();
n=Integer.parseInt(b.readLine());
String d[]={"January","February","March","April","May","June","July","August","September","October","November","December"};
for(i=0;i<12;i++)
{
if(d[i].equals(s))
{
System.out.print(d[((n%12)+i)%12]);
System.exit(0);
}
}
}
} | UTF-8 | Java | 449 | java | sz.java | Java | []
| null | []
| import java.io.*;
class j
{
public static void main(String a[])throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int i=0,n=0;
String s=b.readLine();
n=Integer.parseInt(b.readLine());
String d[]={"January","February","March","April","May","June","July","August","September","October","November","December"};
for(i=0;i<12;i++)
{
if(d[i].equals(s))
{
System.out.print(d[((n%12)+i)%12]);
System.exit(0);
}
}
}
} | 449 | 0.674833 | 0.652561 | 20 | 21.5 | 29.764912 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.1 | false | false | 0 |
a735d78ce4e1748b490bd3ade74dc2eec42ca3a7 | 566,935,709,797 | 82285f7736b33ec47260893d0ddb4b5cf8550671 | /src/pacoteClassesUsuario/RepositorioUsuariosArray.java | 53e20d0384cb5cba26695bfc1d4028bc9ae508b5 | []
| no_license | melissafalcao/ProjectIP | https://github.com/melissafalcao/ProjectIP | 9f77c7bb59524f726c04742f093dccf7ca6e938c | 671b3cfcdb14c616c133a34b5756e6d32839dbae | refs/heads/master | 2021-03-22T05:17:34.391000 | 2017-11-28T19:29:02 | 2017-11-28T19:29:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pacoteClassesUsuario;
import pacoteExcecoes.UJCException;
import pacoteExcecoes.UNCException;
/**
* "classe colecao de dados array"
* classe que contem um array de usuarios e metodos da interface implementada
*
* @author Gabriel
*
*/
public class RepositorioUsuariosArray implements RepositorioUsuarios {
private Usuario[] usuarios;
private int indice;
public RepositorioUsuariosArray() {
usuarios = new Usuario[100];
indice = 0;
}
@Override
public void inserir(Usuario usuario) throws UJCException {
if (!this.existe(usuario.getNick()) && this.indice < this.usuarios.length - 1) {
this.usuarios[indice] = usuario;
this.indice++;
} else {
throw new UJCException();
}
}
@Override
public void remover(String nomeUsuario) throws UNCException {
boolean encontrou = false;
for (int i = 0; i <= indice && !encontrou; i++) {
if (this.usuarios[i].getNick().equals(nomeUsuario)) {
for (int k = i; k <= indice - 1; k++) {
this.usuarios[k] = this.usuarios[k + 1];
}
encontrou = true;
indice--;
}
}
if (!encontrou) {
throw new UNCException();
}
}
@Override
public void atualizar(Usuario usuario) throws UNCException {
int i = this.procurar(usuario.getNick());
this.usuarios[i] = usuario;
}
@Override
public boolean existe(String nomeUsuario) {
boolean encontrou = false;
for (int i = 0; i < indice && !encontrou; i++) {
if (this.usuarios[i].getNick().equals(nomeUsuario)) {
encontrou = true;
}
}
return encontrou;
}
public int procurar(String nomeUsuario) throws UNCException {
int indicee = 0;
boolean encontrou = false;
for (int i = 0; i <= indice && !encontrou; i++) {
if (this.usuarios[i].getNick().equals(nomeUsuario)) {
encontrou = true;
indicee = i;
}
}
if (!encontrou) {
throw new UNCException();
}
return indicee;
}
public Usuario procurarUsuario(String nomeUsuario) throws UNCException {
int indicee = 0;
boolean encontrou = false;
for (int i = 0; i <= indice && !encontrou; i++) {
if (this.usuarios[i].getNick().equals(nomeUsuario)) {
encontrou = true;
indicee = i;
}
}
if (!encontrou) {
throw new UNCException();
}
return this.usuarios[indicee];
}
}
| UTF-8 | Java | 2,241 | java | RepositorioUsuariosArray.java | Java | [
{
"context": "e metodos da interface implementada\n * \n * @author Gabriel\n *\n */\npublic class RepositorioUsuariosArray impl",
"end": 243,
"score": 0.9990652203559875,
"start": 236,
"tag": "NAME",
"value": "Gabriel"
},
{
"context": "+) {\n\t\t\tif (this.usuarios[i].getNick().equals(nomeUsuario)) {\n\t\t\t\tencontrou = true;\n\t\t\t\tindicee = i;\n\t\t\t}\n\t",
"end": 1742,
"score": 0.6974397301673889,
"start": 1735,
"tag": "USERNAME",
"value": "Usuario"
},
{
"context": "; i++) {\n\t\t\tif (this.usuarios[i].getNick().equals(nomeUsuario)) {\n\t\t\t\tencontrou = true;\n\t\t\t\tindicee = i;\n\t\t\t}\n\t",
"end": 2096,
"score": 0.8819884657859802,
"start": 2085,
"tag": "USERNAME",
"value": "nomeUsuario"
}
]
| null | []
| package pacoteClassesUsuario;
import pacoteExcecoes.UJCException;
import pacoteExcecoes.UNCException;
/**
* "classe colecao de dados array"
* classe que contem um array de usuarios e metodos da interface implementada
*
* @author Gabriel
*
*/
public class RepositorioUsuariosArray implements RepositorioUsuarios {
private Usuario[] usuarios;
private int indice;
public RepositorioUsuariosArray() {
usuarios = new Usuario[100];
indice = 0;
}
@Override
public void inserir(Usuario usuario) throws UJCException {
if (!this.existe(usuario.getNick()) && this.indice < this.usuarios.length - 1) {
this.usuarios[indice] = usuario;
this.indice++;
} else {
throw new UJCException();
}
}
@Override
public void remover(String nomeUsuario) throws UNCException {
boolean encontrou = false;
for (int i = 0; i <= indice && !encontrou; i++) {
if (this.usuarios[i].getNick().equals(nomeUsuario)) {
for (int k = i; k <= indice - 1; k++) {
this.usuarios[k] = this.usuarios[k + 1];
}
encontrou = true;
indice--;
}
}
if (!encontrou) {
throw new UNCException();
}
}
@Override
public void atualizar(Usuario usuario) throws UNCException {
int i = this.procurar(usuario.getNick());
this.usuarios[i] = usuario;
}
@Override
public boolean existe(String nomeUsuario) {
boolean encontrou = false;
for (int i = 0; i < indice && !encontrou; i++) {
if (this.usuarios[i].getNick().equals(nomeUsuario)) {
encontrou = true;
}
}
return encontrou;
}
public int procurar(String nomeUsuario) throws UNCException {
int indicee = 0;
boolean encontrou = false;
for (int i = 0; i <= indice && !encontrou; i++) {
if (this.usuarios[i].getNick().equals(nomeUsuario)) {
encontrou = true;
indicee = i;
}
}
if (!encontrou) {
throw new UNCException();
}
return indicee;
}
public Usuario procurarUsuario(String nomeUsuario) throws UNCException {
int indicee = 0;
boolean encontrou = false;
for (int i = 0; i <= indice && !encontrou; i++) {
if (this.usuarios[i].getNick().equals(nomeUsuario)) {
encontrou = true;
indicee = i;
}
}
if (!encontrou) {
throw new UNCException();
}
return this.usuarios[indicee];
}
}
| 2,241 | 0.659081 | 0.65328 | 98 | 21.867348 | 21.447914 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.102041 | false | false | 0 |
3fa895ff7937cd81fd7e578d462eb0ae929e1a95 | 28,948,079,594,936 | 646d1f0ee62c160a2a6cbc0d552c5b2619d9407c | /google/gae/holidaybot/src/com/ise_web/holidaybot/CallbackServlet.java | 0661c5540fbbf70ea09f84bc48bea90bc25c12ba | []
| no_license | isystk/sample | https://github.com/isystk/sample | 57d6b6e767fc271c63e8e115490d39a7d6e162b2 | 2fc1514df04503d62b51626ac6c57cf6ad44d320 | refs/heads/master | 2016-08-07T04:22:54.558000 | 2015-09-05T09:16:36 | 2015-09-05T09:16:36 | 41,955,379 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* プロジェクト名:holidaybot
* ファイル名:CallbackServlet.java
* 作成日:2011/11/03
* 作成者:ise
* Copyright (C) 2010-2011 ISE INC. All rights reserved.
*/
package com.ise_web.holidaybot;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
/**
* TwitterからOAuth認証のコールバックを受け取る
* @author ise
*/
public class CallbackServlet extends HttpServlet {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
/**
* Logger
*/
private static final Logger log = Logger.getLogger(CallbackServlet.class.getName());
/**
* GET処理
*/
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//セッションからtwitterオブジェクトとRequestTokenの取出
String botname = (String)req.getSession().getAttribute("botname");
Twitter twitter = (Twitter) req.getSession().getAttribute("twitter");
RequestToken requestToken = (RequestToken) req.getSession().getAttribute("requestToken");
String verifier = req.getParameter("oauth_verifier");
try {
log.info("twitter:["+twitter+"]/requestToken:["+requestToken+"]/verifier:["+verifier+"]");
if (twitter == null || requestToken == null || verifier == null) {
log.info("認証失敗");
resp.sendRedirect(req.getContextPath()+ "/");
return;
}
//AccessTokenの取得
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
//TokenオブジェクトにAccessToken/Secretと「bot name」を格納しGAE上に保存
if(accessToken != null){
Token token = new Token();
token.setAccessToken(accessToken.getToken());
token.setAccessSecret(accessToken.getTokenSecret());
token.setBotName(botname);
token.setScreenName(twitter.getScreenName());
// ユーザーのアクセストークンをデータストアに保存する。
BotUtil.putUser(ApplicationConst.BOT_NAME, token);
log.info("認証完了 screenName:["+twitter.getScreenName()+"]/AccessToken:["+token.getAccessToken()+"]/AccessSecret:["+token.getAccessSecret()+"]");
}
req.getSession().removeAttribute("twitter");
req.getSession().removeAttribute("requestToken");
req.getSession().removeAttribute("botname");
resp.sendRedirect(req.getContextPath()+ "/");
} catch (TwitterException e) {
log.info(e.getMessage());
}
}
}
| UTF-8 | Java | 3,078 | java | CallbackServlet.java | Java | [
{
"context": "名:CallbackServlet.java\r\n * 作成日:2011/11/03\r\n * 作成者:ise\r\n * Copyright (C) 2010-2011 ISE INC. All rights r",
"end": 83,
"score": 0.7686871886253357,
"start": 80,
"tag": "USERNAME",
"value": "ise"
},
{
"context": "\r\n/**\r\n * TwitterからOAuth認証のコールバックを受け取る\r\n * @author ise\r\n */\r\npublic class CallbackServlet extends HttpSe",
"end": 575,
"score": 0.9991425275802612,
"start": 572,
"tag": "USERNAME",
"value": "ise"
},
{
"context": "TokenSecret());\r\n token.setBotName(botname);\r\n token.setScreenName(twitter.ge",
"end": 2147,
"score": 0.9033291339874268,
"start": 2140,
"tag": "USERNAME",
"value": "botname"
}
]
| null | []
| /* プロジェクト名:holidaybot
* ファイル名:CallbackServlet.java
* 作成日:2011/11/03
* 作成者:ise
* Copyright (C) 2010-2011 ISE INC. All rights reserved.
*/
package com.ise_web.holidaybot;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
/**
* TwitterからOAuth認証のコールバックを受け取る
* @author ise
*/
public class CallbackServlet extends HttpServlet {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
/**
* Logger
*/
private static final Logger log = Logger.getLogger(CallbackServlet.class.getName());
/**
* GET処理
*/
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//セッションからtwitterオブジェクトとRequestTokenの取出
String botname = (String)req.getSession().getAttribute("botname");
Twitter twitter = (Twitter) req.getSession().getAttribute("twitter");
RequestToken requestToken = (RequestToken) req.getSession().getAttribute("requestToken");
String verifier = req.getParameter("oauth_verifier");
try {
log.info("twitter:["+twitter+"]/requestToken:["+requestToken+"]/verifier:["+verifier+"]");
if (twitter == null || requestToken == null || verifier == null) {
log.info("認証失敗");
resp.sendRedirect(req.getContextPath()+ "/");
return;
}
//AccessTokenの取得
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
//TokenオブジェクトにAccessToken/Secretと「bot name」を格納しGAE上に保存
if(accessToken != null){
Token token = new Token();
token.setAccessToken(accessToken.getToken());
token.setAccessSecret(accessToken.getTokenSecret());
token.setBotName(botname);
token.setScreenName(twitter.getScreenName());
// ユーザーのアクセストークンをデータストアに保存する。
BotUtil.putUser(ApplicationConst.BOT_NAME, token);
log.info("認証完了 screenName:["+twitter.getScreenName()+"]/AccessToken:["+token.getAccessToken()+"]/AccessSecret:["+token.getAccessSecret()+"]");
}
req.getSession().removeAttribute("twitter");
req.getSession().removeAttribute("requestToken");
req.getSession().removeAttribute("botname");
resp.sendRedirect(req.getContextPath()+ "/");
} catch (TwitterException e) {
log.info(e.getMessage());
}
}
}
| 3,078 | 0.619131 | 0.611773 | 86 | 31.16279 | 31.272568 | 158 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.465116 | false | false | 0 |
77a4d434ff37f2ea267533e7253e69495d345c14 | 10,075,993,301,869 | 4d3f6a244bc2e10bdb8fe9fe4d134da813e217a9 | /5.0/FTPConfig/src/com/asiainfo/service/BasicService.java | c176ebf2bc466264ff32f03f390f05e0454f0344 | [
"Apache-2.0"
]
| permissive | xiaomozhang/ESBApp | https://github.com/xiaomozhang/ESBApp | 231ed6c6de75513aad04a9ce758cddac1e0cc58f | 47178277add93c3e736162302e0e6599320e5e07 | refs/heads/master | 2016-08-08T20:33:48.352000 | 2015-11-22T05:43:48 | 2015-11-22T05:43:48 | 46,249,109 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.asiainfo.service;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.asiainfo.been.ChoosServerUser;
import com.asiainfo.been.FTPUser;
import com.asiainfo.been.SerchComponent;
import com.asiainfo.been.UserConfig;
import com.asiainfo.been.queryFComponent;
import com.cattsoft.framework.exception.AppException;
import com.cattsoft.framework.exception.SysException;
/**
*
* @author zhangyufei
* 操作对基础的service类
*/
public interface BasicService {
@SuppressWarnings("rawtypes")
public List getUserInfo();
public List<FTPUser> validateUser() throws SysException,AppException;
public List<SerchComponent> serChCompoentConfigData(int page,int pageSize)throws SysException,AppException;
public List<ChoosServerUser> queryUserData(int page,int pageSize,String userName)throws SysException,AppException;
public List<queryFComponent> busFFileTypeData()throws SysException,AppException;
public List<UserConfig> busFileTypeData()throws SysException,AppException;
public List<queryFComponent> queryFGatherCycle()throws SysException,AppException;
public List<UserConfig> queryGatherCycle()throws SysException,AppException;
public int getTotalCount(String tableName)throws SysException,AppException;
public int getFTotalCount(String tableName)throws SysException,AppException;
public int getUserDataCount(String userName)throws SysException,AppException;
public int saveComponet(String orgId,String orgName,String componentName)throws SysException,AppException;
public int checkComponentName(String componentName)throws SysException,AppException;
public int checkOrgName(String orgId,String orgName)throws SysException,AppException;
public int checkUserName(String userName)throws SysException,AppException;
public int checkUserPasswd(String userPasswd)throws SysException,AppException;
public int checkServerName(String serverName)throws SysException,AppException;
public int addUsers(HttpServletRequest request)throws SysException,AppException;
public List<UserConfig> sercheUserData(String componentId)throws SysException,AppException;
public List<SerchComponent> fuzzyQueryComponet(int page,int pageSize,String comPonentName)throws SysException,AppException;
public int getComponentTotalCount(String componentName)throws SysException,AppException;
public String checkgcNameFCronExpressionIsNull(String gcName,String cronExpression)throws SysException,AppException;
public String checkgcNameCronExpressionIsNull(String gcName,String cronExpression)throws SysException,AppException;
public int insertCronFExpression(String gcName,String cronExpression)throws SysException,AppException;
public int insertCronExpression(String gcName,String cronExpression)throws SysException,AppException;
public String checkFBusFileIsNull(String fileTypeName,String fileSufix)throws SysException,AppException;
public String checkBusFileIsNull(String fileTypeName,String fileSufix)throws SysException,AppException;
public int insertFBusFile(String fileTypeName,String fileSufix)throws SysException,AppException;
public int insertBusFile(String fileTypeName,String fileSufix)throws SysException,AppException;
public int checkBusName(String busName)throws SysException,AppException;
//added by bgp 20150316
public int checkBusinessName(String busName)throws SysException,AppException;
public String checkBusCode(Map<String,String> argData)throws SysException,AppException,UnsupportedEncodingException;
public String getMaxBusCode()throws SysException,AppException;
public String saveUserConfigData(List<UserConfig> userConfigList,Map<String,Object> session)throws SysException,AppException;
public String remoteCreateUser(HttpServletRequest request)throws SysException,AppException;
public String remoteCreateDirector(HttpServletRequest request)throws SysException,AppException;
public List<queryFComponent> queryFcomponetValue()throws SysException,AppException;
public List<queryFComponent> queryFTPOrgId()throws SysException,AppException;
public String createFTPComponetId(String orgId,String orgName,String componetName)throws SysException,AppException;
public String checkUserExistence(String componentId)throws SysException,AppException;
public String queryRemoteUserConfig(String componentId)throws SysException,AppException;
public String updateUserPasswd(String oldPass,String userName,String newPassWord)throws SysException,AppException;
public String checkBusCodeRepeat(Map<String, String> param)throws SysException,AppException;
}
| UTF-8 | Java | 4,821 | java | BasicService.java | Java | [
{
"context": "mework.exception.SysException;\n\n/**\n * \n * @author zhangyufei\n * 操作对基础的service类\n */\npublic interface BasicServi",
"end": 503,
"score": 0.9993165731430054,
"start": 493,
"tag": "USERNAME",
"value": "zhangyufei"
},
{
"context": "SysException,AppException;\n \n //added by bgp 20150316\n public int checkBusinessName(Strin",
"end": 3465,
"score": 0.7359660267829895,
"start": 3462,
"tag": "USERNAME",
"value": "bgp"
},
{
"context": "blic String updateUserPasswd(String oldPass,String userName,String newPassWord)throws SysException,AppExcepti",
"end": 4640,
"score": 0.9111172556877136,
"start": 4632,
"tag": "USERNAME",
"value": "userName"
}
]
| null | []
| package com.asiainfo.service;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.asiainfo.been.ChoosServerUser;
import com.asiainfo.been.FTPUser;
import com.asiainfo.been.SerchComponent;
import com.asiainfo.been.UserConfig;
import com.asiainfo.been.queryFComponent;
import com.cattsoft.framework.exception.AppException;
import com.cattsoft.framework.exception.SysException;
/**
*
* @author zhangyufei
* 操作对基础的service类
*/
public interface BasicService {
@SuppressWarnings("rawtypes")
public List getUserInfo();
public List<FTPUser> validateUser() throws SysException,AppException;
public List<SerchComponent> serChCompoentConfigData(int page,int pageSize)throws SysException,AppException;
public List<ChoosServerUser> queryUserData(int page,int pageSize,String userName)throws SysException,AppException;
public List<queryFComponent> busFFileTypeData()throws SysException,AppException;
public List<UserConfig> busFileTypeData()throws SysException,AppException;
public List<queryFComponent> queryFGatherCycle()throws SysException,AppException;
public List<UserConfig> queryGatherCycle()throws SysException,AppException;
public int getTotalCount(String tableName)throws SysException,AppException;
public int getFTotalCount(String tableName)throws SysException,AppException;
public int getUserDataCount(String userName)throws SysException,AppException;
public int saveComponet(String orgId,String orgName,String componentName)throws SysException,AppException;
public int checkComponentName(String componentName)throws SysException,AppException;
public int checkOrgName(String orgId,String orgName)throws SysException,AppException;
public int checkUserName(String userName)throws SysException,AppException;
public int checkUserPasswd(String userPasswd)throws SysException,AppException;
public int checkServerName(String serverName)throws SysException,AppException;
public int addUsers(HttpServletRequest request)throws SysException,AppException;
public List<UserConfig> sercheUserData(String componentId)throws SysException,AppException;
public List<SerchComponent> fuzzyQueryComponet(int page,int pageSize,String comPonentName)throws SysException,AppException;
public int getComponentTotalCount(String componentName)throws SysException,AppException;
public String checkgcNameFCronExpressionIsNull(String gcName,String cronExpression)throws SysException,AppException;
public String checkgcNameCronExpressionIsNull(String gcName,String cronExpression)throws SysException,AppException;
public int insertCronFExpression(String gcName,String cronExpression)throws SysException,AppException;
public int insertCronExpression(String gcName,String cronExpression)throws SysException,AppException;
public String checkFBusFileIsNull(String fileTypeName,String fileSufix)throws SysException,AppException;
public String checkBusFileIsNull(String fileTypeName,String fileSufix)throws SysException,AppException;
public int insertFBusFile(String fileTypeName,String fileSufix)throws SysException,AppException;
public int insertBusFile(String fileTypeName,String fileSufix)throws SysException,AppException;
public int checkBusName(String busName)throws SysException,AppException;
//added by bgp 20150316
public int checkBusinessName(String busName)throws SysException,AppException;
public String checkBusCode(Map<String,String> argData)throws SysException,AppException,UnsupportedEncodingException;
public String getMaxBusCode()throws SysException,AppException;
public String saveUserConfigData(List<UserConfig> userConfigList,Map<String,Object> session)throws SysException,AppException;
public String remoteCreateUser(HttpServletRequest request)throws SysException,AppException;
public String remoteCreateDirector(HttpServletRequest request)throws SysException,AppException;
public List<queryFComponent> queryFcomponetValue()throws SysException,AppException;
public List<queryFComponent> queryFTPOrgId()throws SysException,AppException;
public String createFTPComponetId(String orgId,String orgName,String componetName)throws SysException,AppException;
public String checkUserExistence(String componentId)throws SysException,AppException;
public String queryRemoteUserConfig(String componentId)throws SysException,AppException;
public String updateUserPasswd(String oldPass,String userName,String newPassWord)throws SysException,AppException;
public String checkBusCodeRepeat(Map<String, String> param)throws SysException,AppException;
}
| 4,821 | 0.822342 | 0.820678 | 71 | 66.704224 | 40.472351 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.84507 | false | false | 0 |
37935e81accb0f59501615fd96b243a4095b6c43 | 10,746,008,199,257 | 933eb1866043dc2421b4783740a466f9563d311d | /src/main/java/com/sso/repository/master/ContributionTypeRepository.java | aff9ecf66a63d9eba794b0290243f3c108f44da3 | []
| no_license | memoriad/sso_m40_online | https://github.com/memoriad/sso_m40_online | 99b94aa3f3a803a3fbbfa27ae681c8c2dacbd179 | 0338730d3f86ad8e884ec003f5b18d0fa3cf2e39 | refs/heads/master | 2018-02-08T13:10:38.096000 | 2017-07-13T07:32:01 | 2017-07-13T07:32:01 | 94,699,761 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sso.repository.master;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.repository.JpaRepository;
import com.sso.entity.master.ContributionType;
import java.util.Collection;
public interface ContributionTypeRepository extends JpaRepository<ContributionType, Long> {
Collection<ContributionType> findContributionTypesByCttStatusEquals(String cttStatus);
@Cacheable("contributionTypeRepo")
ContributionType findByCttId(Long id);
}
| UTF-8 | Java | 501 | java | ContributionTypeRepository.java | Java | []
| null | []
| package com.sso.repository.master;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.repository.JpaRepository;
import com.sso.entity.master.ContributionType;
import java.util.Collection;
public interface ContributionTypeRepository extends JpaRepository<ContributionType, Long> {
Collection<ContributionType> findContributionTypesByCttStatusEquals(String cttStatus);
@Cacheable("contributionTypeRepo")
ContributionType findByCttId(Long id);
}
| 501 | 0.832335 | 0.832335 | 16 | 30.3125 | 31.206408 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 0 |
e55e0ffc703aaaa7003b451aec6a18b82c00ca29 | 4,801,773,474,279 | 8d87ec1f8ef6ae8488418b8170c5c8e9a0ab0965 | /src/gazillionSongs/SongCollection.java | 84ed7cc5c57ba707f10d4c5285b247b2736a07df | []
| no_license | NewportCS/gazillionsongs-matt-ketk | https://github.com/NewportCS/gazillionsongs-matt-ketk | f7c887ed02f4080f2722356ad32dd07751831017 | 7f975912c8bbe6f9c756ef0ab257bf61c9288161 | refs/heads/master | 2020-03-07T11:06:24.803000 | 2018-06-03T20:44:23 | 2018-06-03T20:44:23 | 127,447,792 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gazillionSongs;
import java.util.*;
import java.io.*;
public class SongCollection {
private ArrayList<Song> collection;
private boolean isSorted;
public SongCollection() {
this.collection = new ArrayList<Song>();
this.isSorted = false;
}
public void addSong(String line) {
this.isSorted = false;
String[] lineEntries = line.split("\t");
this.collection.add(new Song(Integer.parseInt(lineEntries[0]), Integer.parseInt(lineEntries[1]), lineEntries[2],
lineEntries[3]));
}
public int getSize() {
return this.collection.size();
}
public void selectionSort(String field) {
int minIndex;
Song temp;
if (field.equals("year") || field.equals("rank") || field.equals("artist") || field.equals("title")) {
for (int i = 0; i < this.collection.size() - 1; i++) {
minIndex = i;
for (int j = i + 1; j < this.collection.size(); j++) {
if (this.collection.get(j).compareTo(this.collection.get(minIndex), field) < 0) {
minIndex = j;
}
}
temp = this.collection.get(i);
this.collection.set(i, this.collection.get(minIndex));
this.collection.set(minIndex, temp);
}
} else {
throw new IllegalArgumentException();
}
}
private void merge(String field, int from, int mid, int to, Song[] temp) {
int i = from;
int j = mid + 1;
int k = from;
while (i <= mid && j <= to) {
if (this.collection.get(i).compareTo(this.collection.get(j), field) < 0) {
temp[k] = this.collection.get(i);
i++;
} else {
temp[k] = this.collection.get(j);
j++;
}
k++;
}
while (i <= mid) {
temp[k] = this.collection.get(i);
i++;
k++;
}
while (j <= to) {
temp[k] = this.collection.get(j);
j++;
k++;
}
for (k = from; k <= to; k++) {
this.collection.set(k, temp[k]);
}
}
private void mergeSortX(String field, int from, int to, Song[] temp) {
int mid;
if (from < to) {
mid = (from + to) / 2;
mergeSortX(field, from, mid, temp);
mergeSortX(field, mid + 1, to, temp);
merge(field, from, mid, to, temp);
}
}
public void mergeSort(String field) {
int n;
if (field.equals("year") || field.equals("rank") || field.equals("artist") || field.equals("title")) {
n = this.collection.size();
mergeSortX(field, 0, n - 1, new Song[n]);
} else {;
throw new IllegalArgumentException();
}
}
public void insertionSort(String field) {
Song song;
int possibleIndex;
if (field.equals("year") || field.equals("rank") || field.equals("artist") || field.equals("title")) {
for (int i = 1; i < this.collection.size(); i++) {
song = this.collection.get(i);
possibleIndex = i;
while (possibleIndex > 0 && song.compareTo(this.collection.get(possibleIndex - 1), field) < 0) {
this.collection.set(possibleIndex, this.collection.get(possibleIndex - 1));
possibleIndex--;
}
this.collection.set(possibleIndex, song);
}
} else {
throw new IllegalArgumentException();
}
}
public void printSongs(PrintStream output) {
Song song;
for (int i = 0; i < this.collection.size(); i++) {
song = this.collection.get(i);
output.print(song.getYear() + "\t" + song.getRank() + "\t" + song.getArtist() + "\t" + song.getTitle());
output.println();
}
// output.print(song.getYear() + "\t" + song.getRank() + "\t" + song.getArtist()
// + "\t" + song.getTitle());
// System.out.println("done; printed this many songs: " +
// this.collection.size());
// output.print(song.getYear() + "\t" + song.getRank() + "\t" + song.getArtist() + "\t" + song.getTitle());
// System.out.println("done; printed this many songs: " + this.collection.size());
}
} | UTF-8 | Java | 3,758 | java | SongCollection.java | Java | []
| null | []
| package gazillionSongs;
import java.util.*;
import java.io.*;
public class SongCollection {
private ArrayList<Song> collection;
private boolean isSorted;
public SongCollection() {
this.collection = new ArrayList<Song>();
this.isSorted = false;
}
public void addSong(String line) {
this.isSorted = false;
String[] lineEntries = line.split("\t");
this.collection.add(new Song(Integer.parseInt(lineEntries[0]), Integer.parseInt(lineEntries[1]), lineEntries[2],
lineEntries[3]));
}
public int getSize() {
return this.collection.size();
}
public void selectionSort(String field) {
int minIndex;
Song temp;
if (field.equals("year") || field.equals("rank") || field.equals("artist") || field.equals("title")) {
for (int i = 0; i < this.collection.size() - 1; i++) {
minIndex = i;
for (int j = i + 1; j < this.collection.size(); j++) {
if (this.collection.get(j).compareTo(this.collection.get(minIndex), field) < 0) {
minIndex = j;
}
}
temp = this.collection.get(i);
this.collection.set(i, this.collection.get(minIndex));
this.collection.set(minIndex, temp);
}
} else {
throw new IllegalArgumentException();
}
}
private void merge(String field, int from, int mid, int to, Song[] temp) {
int i = from;
int j = mid + 1;
int k = from;
while (i <= mid && j <= to) {
if (this.collection.get(i).compareTo(this.collection.get(j), field) < 0) {
temp[k] = this.collection.get(i);
i++;
} else {
temp[k] = this.collection.get(j);
j++;
}
k++;
}
while (i <= mid) {
temp[k] = this.collection.get(i);
i++;
k++;
}
while (j <= to) {
temp[k] = this.collection.get(j);
j++;
k++;
}
for (k = from; k <= to; k++) {
this.collection.set(k, temp[k]);
}
}
private void mergeSortX(String field, int from, int to, Song[] temp) {
int mid;
if (from < to) {
mid = (from + to) / 2;
mergeSortX(field, from, mid, temp);
mergeSortX(field, mid + 1, to, temp);
merge(field, from, mid, to, temp);
}
}
public void mergeSort(String field) {
int n;
if (field.equals("year") || field.equals("rank") || field.equals("artist") || field.equals("title")) {
n = this.collection.size();
mergeSortX(field, 0, n - 1, new Song[n]);
} else {;
throw new IllegalArgumentException();
}
}
public void insertionSort(String field) {
Song song;
int possibleIndex;
if (field.equals("year") || field.equals("rank") || field.equals("artist") || field.equals("title")) {
for (int i = 1; i < this.collection.size(); i++) {
song = this.collection.get(i);
possibleIndex = i;
while (possibleIndex > 0 && song.compareTo(this.collection.get(possibleIndex - 1), field) < 0) {
this.collection.set(possibleIndex, this.collection.get(possibleIndex - 1));
possibleIndex--;
}
this.collection.set(possibleIndex, song);
}
} else {
throw new IllegalArgumentException();
}
}
public void printSongs(PrintStream output) {
Song song;
for (int i = 0; i < this.collection.size(); i++) {
song = this.collection.get(i);
output.print(song.getYear() + "\t" + song.getRank() + "\t" + song.getArtist() + "\t" + song.getTitle());
output.println();
}
// output.print(song.getYear() + "\t" + song.getRank() + "\t" + song.getArtist()
// + "\t" + song.getTitle());
// System.out.println("done; printed this many songs: " +
// this.collection.size());
// output.print(song.getYear() + "\t" + song.getRank() + "\t" + song.getArtist() + "\t" + song.getTitle());
// System.out.println("done; printed this many songs: " + this.collection.size());
}
} | 3,758 | 0.591272 | 0.58595 | 128 | 27.40625 | 28.160933 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.140625 | false | false | 0 |
83bac2cc92353ebd068b712e20cc81aba52f955d | 24,592,982,767,592 | c9d71153bf606b7b54092d7c837614165f2a4b3d | /mosquito-api/src/main/java/com/eussence/mosquito/api/parser/ContentParser.java | 0772137020729e53629721f98ffc3bce4a061dcd | [
"Apache-2.0",
"CC-BY-SA-4.0"
]
| permissive | ernest-kiwele/mosquito | https://github.com/ernest-kiwele/mosquito | aeb8ae100d8926a7bd898799a0b551de2f493b9d | c8e393afbecaff02c255e075de531b43b495dbd0 | refs/heads/master | 2021-06-04T14:33:04.678000 | 2020-12-10T11:50:57 | 2020-12-10T11:50:57 | 136,289,564 | 0 | 0 | Apache-2.0 | false | 2020-05-16T10:45:57 | 2018-06-06T07:23:32 | 2020-05-16T10:45:14 | 2020-05-16T10:45:11 | 76 | 0 | 0 | 0 | Java | false | false | /**
* Copyright 2018 eussence.com and contributors
* 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.eussence.mosquito.api.parser;
import java.io.File;
import java.io.FileInputStream;
import java.util.Objects;
import java.util.Set;
import javax.ws.rs.core.MediaType;
import org.apache.tika.Tika;
import org.apache.tika.io.IOUtils;
import com.eussence.mosquito.api.exception.CheckedExecutable;
import com.eussence.mosquito.api.exception.MosquitoException;
/**
* Content parsing utilities
*
* @author Ernest Kiwele
*/
public class ContentParser {
public static final long MEMORY_SIZE_THRESHOLD = 1024 * 1024;
private static Tika tika = new Tika();
private static Set<String> TEXT_FORMATS = Set.of(MediaType.APPLICATION_JSON, MediaType.APPLICATION_SVG_XML,
MediaType.APPLICATION_XHTML_XML, MediaType.APPLICATION_XML, MediaType.TEXT_HTML, MediaType.TEXT_PLAIN,
MediaType.TEXT_XML);
private ContentParser() {
}
public static Object parseFileEntity(String path) {
var file = new File(Objects.requireNonNull(path));
if (!file.exists()) {
throw new MosquitoException("No file found at " + path);
}
if (file.length() > MEMORY_SIZE_THRESHOLD) {
return CheckedExecutable.wrap(() -> new FileInputStream(file));
}
if (isTextContent(fileMediaType(file))) {
return readToText(file);
}
return CheckedExecutable.wrap(() -> new FileInputStream(file));
}
public static String fileMediaType(String path) {
return fileMediaType(new File(path));
}
public static String fileMediaType(File file) {
return CheckedExecutable.wrap(() -> tika.detect(file));
}
public static String readToText(File path) {
return CheckedExecutable.wrap(() -> IOUtils.toString(new FileInputStream(path)));
}
public static boolean isTextContent(String mediaType) {
String ct = Objects.requireNonNull(mediaType);
return ct.startsWith("text/") || TEXT_FORMATS.contains(ct);
}
}
| UTF-8 | Java | 2,425 | java | ContentParser.java | Java | [
{
"context": ";\n\n/**\n * Content parsing utilities\n * \n * @author Ernest Kiwele\n */\npublic class ContentParser {\n\tpublic static f",
"end": 1041,
"score": 0.9996196627616882,
"start": 1028,
"tag": "NAME",
"value": "Ernest Kiwele"
}
]
| null | []
| /**
* Copyright 2018 eussence.com and contributors
* 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.eussence.mosquito.api.parser;
import java.io.File;
import java.io.FileInputStream;
import java.util.Objects;
import java.util.Set;
import javax.ws.rs.core.MediaType;
import org.apache.tika.Tika;
import org.apache.tika.io.IOUtils;
import com.eussence.mosquito.api.exception.CheckedExecutable;
import com.eussence.mosquito.api.exception.MosquitoException;
/**
* Content parsing utilities
*
* @author <NAME>
*/
public class ContentParser {
public static final long MEMORY_SIZE_THRESHOLD = 1024 * 1024;
private static Tika tika = new Tika();
private static Set<String> TEXT_FORMATS = Set.of(MediaType.APPLICATION_JSON, MediaType.APPLICATION_SVG_XML,
MediaType.APPLICATION_XHTML_XML, MediaType.APPLICATION_XML, MediaType.TEXT_HTML, MediaType.TEXT_PLAIN,
MediaType.TEXT_XML);
private ContentParser() {
}
public static Object parseFileEntity(String path) {
var file = new File(Objects.requireNonNull(path));
if (!file.exists()) {
throw new MosquitoException("No file found at " + path);
}
if (file.length() > MEMORY_SIZE_THRESHOLD) {
return CheckedExecutable.wrap(() -> new FileInputStream(file));
}
if (isTextContent(fileMediaType(file))) {
return readToText(file);
}
return CheckedExecutable.wrap(() -> new FileInputStream(file));
}
public static String fileMediaType(String path) {
return fileMediaType(new File(path));
}
public static String fileMediaType(File file) {
return CheckedExecutable.wrap(() -> tika.detect(file));
}
public static String readToText(File path) {
return CheckedExecutable.wrap(() -> IOUtils.toString(new FileInputStream(path)));
}
public static boolean isTextContent(String mediaType) {
String ct = Objects.requireNonNull(mediaType);
return ct.startsWith("text/") || TEXT_FORMATS.contains(ct);
}
}
| 2,418 | 0.74433 | 0.737732 | 81 | 28.938272 | 28.270451 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.135803 | false | false | 0 |
73b4f2089b9fc8c75869276d5bbeee2186dde3f6 | 33,105,607,948,171 | 1c5fd654b46d3fb018032dc11aa17552b64b191c | /spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/tunnel/client/package-info.java | f1a40006936459989c9a5012629523beabedb3c1 | [
"Apache-2.0"
]
| permissive | yangfancoming/spring-boot-build | https://github.com/yangfancoming/spring-boot-build | 6ce9b97b105e401a4016ae4b75964ef93beeb9f1 | 3d4b8cbb8fea3e68617490609a68ded8f034bc67 | refs/heads/master | 2023-01-07T11:10:28.181000 | 2021-06-21T11:46:46 | 2021-06-21T11:46:46 | 193,871,877 | 0 | 0 | Apache-2.0 | false | 2022-12-27T14:52:46 | 2019-06-26T09:19:40 | 2021-06-21T11:46:55 | 2022-12-27T14:52:43 | 4,403 | 0 | 0 | 45 | Java | false | false |
/**
* Client side TCP tunnel support.
*/
package org.springframework.boot.devtools.tunnel.client;
| UTF-8 | Java | 102 | java | package-info.java | Java | []
| null | []
|
/**
* Client side TCP tunnel support.
*/
package org.springframework.boot.devtools.tunnel.client;
| 102 | 0.735294 | 0.735294 | 4 | 24 | 22.394196 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 0 |
a9b0ae93954590597c5e50445d7387fa4433e45e | 31,430,570,703,583 | 0fb3f1140a6c02cafcd01137aa08bde91ab7560d | /TSL756_Selenium/src/util/Grid.java | c7029b238a81a6c8af130b39676c15932fd36c06 | []
| no_license | ShreyashMarotkar/TSL756 | https://github.com/ShreyashMarotkar/TSL756 | f0a3e0a124fdc5e4423d7fc9bfc0da2ff2e0bdad | 3fcff4271b6c6344549edc5c9405558a88fce1ea | refs/heads/master | 2020-04-29T06:45:13.583000 | 2019-03-16T05:07:40 | 2019-03-16T05:07:40 | 175,928,311 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package util;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.net.URL;
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
//import org.openqa.selenium.remote.DesiredCapabilties;
public class Grid {
@Test
public void f() throws Exception{
DesiredCapabilities dc=DesiredCapabilities.chrome();
dc.setPlatform(Platform.WINDOWS);
dc.setBrowserName("chrome");
WebDriver driver=new RemoteWebDriver(new URL("http://192.168.100.134:27258/wd/hub"),dc);
driver.get("https://www.seleniumhq.org/");
Assert.assertEquals(driver.getTitle(),"Selenium - Web Browser Automation" );
driver.quit();
}
}
| UTF-8 | Java | 762 | java | Grid.java | Java | [
{
"context": "Driver driver=new RemoteWebDriver(new URL(\"http://192.168.100.134:27258/wd/hub\"),dc);\n\t driver.get(\"https://www.se",
"end": 588,
"score": 0.9997044801712036,
"start": 573,
"tag": "IP_ADDRESS",
"value": "192.168.100.134"
}
]
| null | []
| package util;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.net.URL;
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
//import org.openqa.selenium.remote.DesiredCapabilties;
public class Grid {
@Test
public void f() throws Exception{
DesiredCapabilities dc=DesiredCapabilities.chrome();
dc.setPlatform(Platform.WINDOWS);
dc.setBrowserName("chrome");
WebDriver driver=new RemoteWebDriver(new URL("http://192.168.100.134:27258/wd/hub"),dc);
driver.get("https://www.seleniumhq.org/");
Assert.assertEquals(driver.getTitle(),"Selenium - Web Browser Automation" );
driver.quit();
}
}
| 762 | 0.751969 | 0.729659 | 25 | 29.48 | 24.196066 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.12 | false | false | 0 |
f063c14db99c44d8f5f426bccd28bff9106a2957 | 15,169,824,522,280 | 6f0904b38259a7c69e982290676bdad3537c7e51 | /Assignment1_4.java | c72ea7f7e872c339dd556a9a31861d7ac27a64d3 | []
| no_license | zsebastian1/ACD_JAVAB_Session_1_Assignment_4 | https://github.com/zsebastian1/ACD_JAVAB_Session_1_Assignment_4 | 74c78a583470d2240898584d3c776579e2f6f393 | 2b28a0f7caebae6f972e286d24683a846b65897c | refs/heads/master | 2020-07-01T05:47:56.287000 | 2019-08-07T14:21:29 | 2019-08-07T14:21:29 | 201,065,431 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ACADAssignments;
import java.util.Scanner;
public class Assignment1_4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your value for byte");
byte b = input.nextByte();
System.out.println("Enter your value for short");
short s = input.nextShort();
int i = b + s;
long l = s + i;
float f = i + l;
double d = l + f;
System.out.println("The added sums of each value are as follows: \n The value for int is: " + i + "\n The value for long is: " + l + "\n The value for float is: " + f + "\n The value for double is: " + d);
}
}
| UTF-8 | Java | 652 | java | Assignment1_4.java | Java | []
| null | []
| package ACADAssignments;
import java.util.Scanner;
public class Assignment1_4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your value for byte");
byte b = input.nextByte();
System.out.println("Enter your value for short");
short s = input.nextShort();
int i = b + s;
long l = s + i;
float f = i + l;
double d = l + f;
System.out.println("The added sums of each value are as follows: \n The value for int is: " + i + "\n The value for long is: " + l + "\n The value for float is: " + f + "\n The value for double is: " + d);
}
}
| 652 | 0.610429 | 0.607362 | 23 | 26.347826 | 41.840908 | 207 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.826087 | false | false | 0 |
8b326ccb68dba65bc8b4f8f079270f3ea7e07f88 | 15,281,493,673,402 | 00a86073680db2ffbde7958f6fcd2864b938982c | /xxyms/xxysm-service/src/test/java/net/happystudy/xxyms/test/service/TestDaoTest.java | c41e1552cf276850e8601d190dc5beb94f46277f | []
| no_license | 201206030/xxyms | https://github.com/201206030/xxyms | 00b87729e79d548447ac51619fb9fefb95f8508b | c0cddfdf3006980b09be8fbbeb6f5af7e8312163 | refs/heads/master | 2020-12-03T00:14:49.190000 | 2017-07-04T10:32:57 | 2017-07-04T10:32:57 | 96,003,365 | 5 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.happystudy.xxyms.test.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.testng.annotations.Test;
import net.happystudy.xxyms.test.dao.XxymsTestDao;
import net.happystudy.xxyms.test.domain.XxymsTest;
@ContextConfiguration(locations={"classpath*:/spring-context.xml","classpath*:/spring-mybatis.xml"})
public class TestDaoTest extends AbstractTestNGSpringContextTests{
@Autowired
private XxymsTestDao xxymsTestDao;
@Test
public void testInsert(){
XxymsTest test = new XxymsTest();
test.setTestName("test11");
xxymsTestDao.insert(test);
System.out.println(test.getTestId());
test = new XxymsTest();
test.setTestName("test21");
xxymsTestDao.insert(test);
System.out.println(test.getTestId());
test = new XxymsTest();
test.setTestName("test131");
xxymsTestDao.insert(test);
System.out.println(test.getTestId());
test = new XxymsTest();
test.setTestName("test14");
xxymsTestDao.insert(test);
System.out.println(test.getTestId());
test = new XxymsTest();
test.setTestName("test15");
xxymsTestDao.insert(test);
System.out.println(test.getTestId());
}
@Test
public void testFindAll(){
List<XxymsTest> xxymsTests = xxymsTestDao.findAll();
for(XxymsTest xxymsTest : xxymsTests){
System.out.println(xxymsTest.getTestId()+":"+xxymsTest.getTestName());
}
}
@Test
public void testInsertList(){
XxymsTest test1 = new XxymsTest();
test1.setTestName("test100");
XxymsTest test2 = new XxymsTest();
test2.setTestName("test20e1");
XxymsTest test3 = new XxymsTest();
test3.setTestName("test20ww1");
XxymsTest test4 = new XxymsTest();
test4.setTestName("test201d");
XxymsTest test5 = new XxymsTest();
test5.setTestName("test621");
List<XxymsTest> list = new ArrayList<XxymsTest>();
list.add(test1);
list.add(test2);
list.add(test3);
list.add(test4);
list.add(test5);
System.out.println(xxymsTestDao.insertList(list));
System.out.println(list.get(0).getTestId());
System.out.println(list.get(4).getTestId());
}
}
| UTF-8 | Java | 2,709 | java | TestDaoTest.java | Java | []
| null | []
| package net.happystudy.xxyms.test.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.testng.annotations.Test;
import net.happystudy.xxyms.test.dao.XxymsTestDao;
import net.happystudy.xxyms.test.domain.XxymsTest;
@ContextConfiguration(locations={"classpath*:/spring-context.xml","classpath*:/spring-mybatis.xml"})
public class TestDaoTest extends AbstractTestNGSpringContextTests{
@Autowired
private XxymsTestDao xxymsTestDao;
@Test
public void testInsert(){
XxymsTest test = new XxymsTest();
test.setTestName("test11");
xxymsTestDao.insert(test);
System.out.println(test.getTestId());
test = new XxymsTest();
test.setTestName("test21");
xxymsTestDao.insert(test);
System.out.println(test.getTestId());
test = new XxymsTest();
test.setTestName("test131");
xxymsTestDao.insert(test);
System.out.println(test.getTestId());
test = new XxymsTest();
test.setTestName("test14");
xxymsTestDao.insert(test);
System.out.println(test.getTestId());
test = new XxymsTest();
test.setTestName("test15");
xxymsTestDao.insert(test);
System.out.println(test.getTestId());
}
@Test
public void testFindAll(){
List<XxymsTest> xxymsTests = xxymsTestDao.findAll();
for(XxymsTest xxymsTest : xxymsTests){
System.out.println(xxymsTest.getTestId()+":"+xxymsTest.getTestName());
}
}
@Test
public void testInsertList(){
XxymsTest test1 = new XxymsTest();
test1.setTestName("test100");
XxymsTest test2 = new XxymsTest();
test2.setTestName("test20e1");
XxymsTest test3 = new XxymsTest();
test3.setTestName("test20ww1");
XxymsTest test4 = new XxymsTest();
test4.setTestName("test201d");
XxymsTest test5 = new XxymsTest();
test5.setTestName("test621");
List<XxymsTest> list = new ArrayList<XxymsTest>();
list.add(test1);
list.add(test2);
list.add(test3);
list.add(test4);
list.add(test5);
System.out.println(xxymsTestDao.insertList(list));
System.out.println(list.get(0).getTestId());
System.out.println(list.get(4).getTestId());
}
}
| 2,709 | 0.646364 | 0.630491 | 75 | 34.119999 | 21.548679 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.706667 | false | false | 0 |
ed271f7d53c799566f2339077e49e7b7b9a9bace | 18,339,510,385,789 | ac9cbc19251a31fd53709b7d26f2a22a8dd76fbc | /src/main/java/life/majiang/community/wx/ClickButton.java | c4f47da0f5e35254ff77a7a3f9c268f7395790ca | []
| no_license | loveqq317/community | https://github.com/loveqq317/community | c067942fbf2524b0b097c6343079670b067ca1a2 | d8e659fbf48adf2d08de084ef9a443382ca3eb7f | refs/heads/master | 2022-06-24T11:56:01.351000 | 2020-03-30T12:48:53 | 2020-03-30T12:48:53 | 248,909,441 | 0 | 0 | null | false | 2022-02-01T01:01:32 | 2020-03-21T04:56:24 | 2020-03-30T12:49:10 | 2022-02-01T01:01:30 | 647 | 0 | 0 | 2 | Java | false | false | package life.majiang.community.wx;
import lombok.Data;
/**
* @ClassName ClickButton
* @Description TODO
* @Author Q
* @Date 2020/3/25 1:08 下午
* @Version 1.0
**/
@Data
public class ClickButton extends AbstractButton{
private String type="click";
private String key;
public ClickButton(String name, String key) {
super(name);
this.key = key;
}
}
| UTF-8 | Java | 390 | java | ClickButton.java | Java | [
{
"context": "ssName ClickButton\n * @Description TODO\n * @Author Q\n * @Date 2020/3/25 1:08 下午\n * @Version 1.0\n **/\n@",
"end": 120,
"score": 0.8240835666656494,
"start": 119,
"tag": "NAME",
"value": "Q"
}
]
| null | []
| package life.majiang.community.wx;
import lombok.Data;
/**
* @ClassName ClickButton
* @Description TODO
* @Author Q
* @Date 2020/3/25 1:08 下午
* @Version 1.0
**/
@Data
public class ClickButton extends AbstractButton{
private String type="click";
private String key;
public ClickButton(String name, String key) {
super(name);
this.key = key;
}
}
| 390 | 0.65285 | 0.621762 | 21 | 17.380953 | 14.805006 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 0 |
e89fd87d5d8b28bbca0c5935b483c78105968f99 | 24,498,493,517,222 | 84a592c29b82328657c3961d09e60fe7cefc6b7e | /src/main/java/house/BeiKeConstants.java | 2ba7da2879e4d12bd0920eb316fa5ef00c0f4258 | []
| no_license | legend91325/house | https://github.com/legend91325/house | a7d03b6b7f50214ebc3e226080a1abee5bc8e455 | f778c2bdc43f45d00a603e7c83c5ce64da2dcf99 | refs/heads/master | 2022-09-25T23:15:45.749000 | 2019-08-19T07:52:39 | 2019-08-19T07:52:39 | 203,123,477 | 3 | 0 | null | false | 2022-09-01T23:11:43 | 2019-08-19T07:43:39 | 2021-06-18T05:36:21 | 2022-09-01T23:11:41 | 20 | 2 | 0 | 4 | Java | false | false | package house;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Legend91325 on 2019/6/27.
*/
public class BeiKeConstants {
public static final String house_东城="东城";
public static final String house_西城="西城";
public static final String house_朝阳="朝阳";
public static final String house_海淀="海淀";
public static final String house_丰台="丰台";
public static final String house_石景山="石景山";
public static final String house_亦庄开发区="亦庄开发区";
public static final String house_通州="通州";
public static final String house_大兴="大兴";
public static final String house_顺义="顺义";
public static final String house_房山="房山";
public static final String house_门头沟="门头沟";
public static final String house_昌平="昌平";
public static final String room_一室 = "l1";
public static final String room_二室 = "l2";
public static final String room_三室 = "l3";
public static final String room_四室 = "l4";
public static final String room_五室及以上 = "l5";
public static final String feature_必看好房 = "tt9";
public static final String feature_满五 = "mw1";
public static final String feature_满两年 = "ty1";
public static final String feature_近地铁 = "su1";
public static final String feature_七日新上 = "tt2";
public static final String feature_随时看房 = "tt4";
public static final String feature_VR房源 = "tt8";
public static final String 朝向_朝东 = "f1";
public static final String 朝向_朝南= "f2";
public static final String 朝向_朝西 = "f3";
public static final String 朝向_朝北 = "f4";
public static final String 朝向_南北 = "f5";
public static final String 楼层_底楼层 = "lc1";
public static final String 楼层_中楼层 = "lc2";
public static final String 楼层_高楼层 = "lc3";
public static final String 楼龄_5年以内 = "y1";
public static final String 楼龄_10年以内 = "y2";
public static final String 楼龄_15年以内 = "y3";
public static final String 楼龄_20年以内 = "y4";
public static final String 楼龄_20年以上 = "y5";
public static final String 装修_精装修 = "de1";
public static final String 装修_普通装修 = "de2";
public static final String 装修_毛坯房 = "de3";
public static final String 用途_普通住宅 = "sf1";
public static final String 用途_商业类 = "sf2";
public static final String 用途_别墅 = "sf3";
public static final String 用途_四合院 = "sf4";
public static final String 用途_车位 = "sf6";
public static final String 用途_其他 = "sf5";
public static final String 电梯_有电梯 = "ie2";
public static final String 电梯_无电梯 = "ie1";
public static final String 供暖_集体供暖 = "hy1";
public static final String 供暖_自供暖 = "hy2";
public static final String 房屋权属_商品房 = "dp1";
public static final String 房屋权属_公房 = "dp2";
public static final String 房屋权属_经济适用房 = "dp3";
public static final String 房屋权属_其他 = "dp4";
public static final String 房屋建筑结构_塔楼 = "bt1";
public static final String 房屋建筑结构_板楼 = "bt2";
public static final String 房屋建筑结构_板塔结合 = "bt3";
public static final Map<String,String> postionMap = new HashMap<String,String>(){{
put("东城","dongcheng");
put("西城","xicheng");
put("朝阳","chaoyang");
put("海淀","haidian");
put("丰台","fengtai");
put("石景山","shijingshan");
put("亦庄开发区","yizhuangkaifaqu");
put("通州","tongzhou");
put("大兴","daxing");
put("顺义","shunyi");
put("昌平","changping");
put("房山","fangshan");
put("门头沟","mentougou");
}};
}
| UTF-8 | Java | 4,049 | java | BeiKeConstants.java | Java | [
{
"context": ".HashMap;\nimport java.util.Map;\n\n/**\n * Created by Legend91325 on 2019/6/27.\n */\npublic class BeiKeConstants {\n\n",
"end": 94,
"score": 0.9991564154624939,
"start": 83,
"tag": "USERNAME",
"value": "Legend91325"
}
]
| null | []
| package house;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Legend91325 on 2019/6/27.
*/
public class BeiKeConstants {
public static final String house_东城="东城";
public static final String house_西城="西城";
public static final String house_朝阳="朝阳";
public static final String house_海淀="海淀";
public static final String house_丰台="丰台";
public static final String house_石景山="石景山";
public static final String house_亦庄开发区="亦庄开发区";
public static final String house_通州="通州";
public static final String house_大兴="大兴";
public static final String house_顺义="顺义";
public static final String house_房山="房山";
public static final String house_门头沟="门头沟";
public static final String house_昌平="昌平";
public static final String room_一室 = "l1";
public static final String room_二室 = "l2";
public static final String room_三室 = "l3";
public static final String room_四室 = "l4";
public static final String room_五室及以上 = "l5";
public static final String feature_必看好房 = "tt9";
public static final String feature_满五 = "mw1";
public static final String feature_满两年 = "ty1";
public static final String feature_近地铁 = "su1";
public static final String feature_七日新上 = "tt2";
public static final String feature_随时看房 = "tt4";
public static final String feature_VR房源 = "tt8";
public static final String 朝向_朝东 = "f1";
public static final String 朝向_朝南= "f2";
public static final String 朝向_朝西 = "f3";
public static final String 朝向_朝北 = "f4";
public static final String 朝向_南北 = "f5";
public static final String 楼层_底楼层 = "lc1";
public static final String 楼层_中楼层 = "lc2";
public static final String 楼层_高楼层 = "lc3";
public static final String 楼龄_5年以内 = "y1";
public static final String 楼龄_10年以内 = "y2";
public static final String 楼龄_15年以内 = "y3";
public static final String 楼龄_20年以内 = "y4";
public static final String 楼龄_20年以上 = "y5";
public static final String 装修_精装修 = "de1";
public static final String 装修_普通装修 = "de2";
public static final String 装修_毛坯房 = "de3";
public static final String 用途_普通住宅 = "sf1";
public static final String 用途_商业类 = "sf2";
public static final String 用途_别墅 = "sf3";
public static final String 用途_四合院 = "sf4";
public static final String 用途_车位 = "sf6";
public static final String 用途_其他 = "sf5";
public static final String 电梯_有电梯 = "ie2";
public static final String 电梯_无电梯 = "ie1";
public static final String 供暖_集体供暖 = "hy1";
public static final String 供暖_自供暖 = "hy2";
public static final String 房屋权属_商品房 = "dp1";
public static final String 房屋权属_公房 = "dp2";
public static final String 房屋权属_经济适用房 = "dp3";
public static final String 房屋权属_其他 = "dp4";
public static final String 房屋建筑结构_塔楼 = "bt1";
public static final String 房屋建筑结构_板楼 = "bt2";
public static final String 房屋建筑结构_板塔结合 = "bt3";
public static final Map<String,String> postionMap = new HashMap<String,String>(){{
put("东城","dongcheng");
put("西城","xicheng");
put("朝阳","chaoyang");
put("海淀","haidian");
put("丰台","fengtai");
put("石景山","shijingshan");
put("亦庄开发区","yizhuangkaifaqu");
put("通州","tongzhou");
put("大兴","daxing");
put("顺义","shunyi");
put("昌平","changping");
put("房山","fangshan");
put("门头沟","mentougou");
}};
}
| 4,049 | 0.647162 | 0.627948 | 100 | 33.349998 | 19.856171 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.9 | false | false | 0 |
b4508fc58cac8d010af1f544ce23484d23ae8e74 | 7,756,710,993,459 | caa05d82a3e0cf84ae664e18c37e5ca1cb85fd95 | /JAVA/src/kr/co/ch/day06/homework/Icecream.java | 10859cf41429f8d616d0e74f2e63258a38b0b5d3 | []
| no_license | park-cheonho/Polytech_JAVA | https://github.com/park-cheonho/Polytech_JAVA | 060e56783a3d18eb47e1b8b82db6ae011aee4cc6 | ea52df76f151ce68e6c44bc8c245c443bcadbb45 | refs/heads/master | 2022-11-09T18:59:26.770000 | 2020-06-23T23:40:57 | 2020-06-23T23:40:57 | 266,079,918 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kr.co.ch.day06.homework;
import java.util.Scanner;
/*
* 어제 과 제 아 이 스 크 림 구 하 는 코 드 에 메 소 드 를 추 가 해서 작 성 해 보 세요
* 과제를 정확하게 이해했는지 걱정입니다..ㅠ 빨리 코로나가 끝나고 대면수업을 하고 싶네요 ㅠㅠ
* 조금 막막하네요 ㅠ
*/
public class Icecream {
String productName; // 상품 이름
String productPrice; // 상품 가격
/**
* 아이스크림 구매 정보 반환 메소드
* @param EA
*/
// 지난 아아스크림 과제는 메소드를 만드는 것이 아니라 IcecreamMain에서 값을 입력 받을때 Icecream의 멤버변수를 참조하여 저장?
// 지금 과제는 Icecream에 info라는 메소드를 만들어서 IcecreamMain라는 클래스 외부에서 메소드 호출하기
// 이렇게 하면 어떤 부분이 좋아지는지는 아직 감이 안옵니다.
void info(int EA) {
Scanner sc = new Scanner(System.in);
Icecream[] str = new Icecream[EA]; //str배열을 만들기 입력받은 EA개 크기로
for(int i = 0; i < EA; i++) {
str[i] = new Icecream(); //HomeworkIcecream 클래스 불러옴
System.out.println("*** " + (i+1) + "번째 아이스크림 구매 정보 ***");
System.out.print("아이스크림 명 : ");
str[i].productName = sc.nextLine(); //아이스크림명 저장
System.out.print("아이스크림 가격 : ");
str[i].productPrice = sc.nextLine(); //아이스크림 가격 저장
System.out.println();
}
System.out.println("< 총 " + EA + "개의 아이스크림 구매정보 출력 >");
System.out.println("번호\t 아이스크림명\t 아이스크림가격\t");
for(int i = 0; i < str.length; i++) {
System.out.printf("%2d\t %5s\t\t %7s\t\n", (i+1), str[i].productName, str[i].productPrice);
}
}
}
| UTF-8 | Java | 1,838 | java | Icecream.java | Java | []
| null | []
| package kr.co.ch.day06.homework;
import java.util.Scanner;
/*
* 어제 과 제 아 이 스 크 림 구 하 는 코 드 에 메 소 드 를 추 가 해서 작 성 해 보 세요
* 과제를 정확하게 이해했는지 걱정입니다..ㅠ 빨리 코로나가 끝나고 대면수업을 하고 싶네요 ㅠㅠ
* 조금 막막하네요 ㅠ
*/
public class Icecream {
String productName; // 상품 이름
String productPrice; // 상품 가격
/**
* 아이스크림 구매 정보 반환 메소드
* @param EA
*/
// 지난 아아스크림 과제는 메소드를 만드는 것이 아니라 IcecreamMain에서 값을 입력 받을때 Icecream의 멤버변수를 참조하여 저장?
// 지금 과제는 Icecream에 info라는 메소드를 만들어서 IcecreamMain라는 클래스 외부에서 메소드 호출하기
// 이렇게 하면 어떤 부분이 좋아지는지는 아직 감이 안옵니다.
void info(int EA) {
Scanner sc = new Scanner(System.in);
Icecream[] str = new Icecream[EA]; //str배열을 만들기 입력받은 EA개 크기로
for(int i = 0; i < EA; i++) {
str[i] = new Icecream(); //HomeworkIcecream 클래스 불러옴
System.out.println("*** " + (i+1) + "번째 아이스크림 구매 정보 ***");
System.out.print("아이스크림 명 : ");
str[i].productName = sc.nextLine(); //아이스크림명 저장
System.out.print("아이스크림 가격 : ");
str[i].productPrice = sc.nextLine(); //아이스크림 가격 저장
System.out.println();
}
System.out.println("< 총 " + EA + "개의 아이스크림 구매정보 출력 >");
System.out.println("번호\t 아이스크림명\t 아이스크림가격\t");
for(int i = 0; i < str.length; i++) {
System.out.printf("%2d\t %5s\t\t %7s\t\n", (i+1), str[i].productName, str[i].productPrice);
}
}
}
| 1,838 | 0.616297 | 0.609177 | 45 | 27.066668 | 25.247574 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.8 | false | false | 0 |
4ee4ea2c65adc1a2d0416ec23d18812c8c475585 | 6,485,400,637,834 | 8cb46db06fd60d0a346feb1e0681dac21878118a | /user-8002/src/main/java/com/wolf/cloud/user/mapper/UserMapper.java | 37b14b65fc42ce81f2824b3bd11d7566b011fd6d | []
| no_license | xiaoxiaowAlways/cloud-lean | https://github.com/xiaoxiaowAlways/cloud-lean | 9095498c9fcb1fece19473e79f5081f25a708e2a | 7f4366a17e91125dded31041dd758827225fc719 | refs/heads/master | 2020-03-28T18:43:22.976000 | 2018-09-15T13:35:35 | 2018-09-15T13:35:35 | 148,904,417 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wolf.cloud.user.mapper;
import com.wolf.cloud.api.entities.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
/**
* @author Captain Wolf
* 2018/9/9 17:36
*/
public interface UserMapper {
@Select("select * from user where id = #{userId}")
User selectById(@Param("userId") Integer userId);
@Update("update user set name = #{name} where id = #{userId}")
int updateNameById(@Param("name") String name, @Param("userId") Integer userId);
@Select("select * from user ")
List<User> selectAll();
}
| UTF-8 | Java | 633 | java | UserMapper.java | Java | [
{
"context": "ns.Update;\n\nimport java.util.List;\n\n/**\n * @author Captain Wolf\n * 2018/9/9 17:36\n */\npublic interface UserMapper",
"end": 264,
"score": 0.9998009204864502,
"start": 252,
"tag": "NAME",
"value": "Captain Wolf"
}
]
| null | []
| package com.wolf.cloud.user.mapper;
import com.wolf.cloud.api.entities.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
/**
* @author <NAME>
* 2018/9/9 17:36
*/
public interface UserMapper {
@Select("select * from user where id = #{userId}")
User selectById(@Param("userId") Integer userId);
@Update("update user set name = #{name} where id = #{userId}")
int updateNameById(@Param("name") String name, @Param("userId") Integer userId);
@Select("select * from user ")
List<User> selectAll();
}
| 627 | 0.71564 | 0.699842 | 23 | 26.52174 | 23.128881 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false | 0 |
e3b9f9db2d7a77ca3c568c49e14109a9f5325783 | 17,523,466,619,367 | 5a782728e786b5efa62676ee0acc1f60280d0de7 | /src/main/java/com/sample/coding/exercises/elevator/operation/traversal/ITraversalModeStrategy.java | 9ec4ce28ff859bbc2349037ab61a545e00cbb8b6 | []
| no_license | Manyce400/sample-coding-exercises | https://github.com/Manyce400/sample-coding-exercises | 6c3c1c636b97ef403761f09bd434c127a4a6f1aa | e6696b9306a5ce74e330498ffde60f3c03b47c12 | refs/heads/master | 2020-04-12T17:44:09.095000 | 2019-01-20T01:04:03 | 2019-01-20T01:04:03 | 162,655,229 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sample.coding.exercises.elevator.operation.traversal;
import com.sample.coding.exercises.elevator.model.ElevatorDirectionE;
import com.sample.coding.exercises.elevator.model.ElevatorOperationRequest;
import com.sample.coding.exercises.elevator.model.ElevatorTraversalPath;
import java.util.LinkedList;
/**
* Interface that defines the basic contract for the algorithm that will run an Elevator Mode
*
* @author manyce400
*/
public interface ITraversalModeStrategy {
/**
* Executes algo implementation for an elevator run given instructions.
*
* @param currentElevatorFloor the current floor that the elevator is on when it receives instruction.
* @param elevatorOperationRequest instructions to run a pickup and drop off implementation.
* @return ElevatorTraversalPath returns run results
*/
public ElevatorTraversalPath executeElevatorRun(int currentElevatorFloor, ElevatorOperationRequest elevatorOperationRequest);
default void computePathToDestinationFloor(int startFloor, int destinationFloor, LinkedList<Integer> traversalPath) {
if(destinationFloor > startFloor) {
for(int i = startFloor; i <= destinationFloor; i++) {
traversalPath.add(i);
}
} else if(destinationFloor < startFloor) {
for(int i = startFloor; i >= destinationFloor; i--) {
traversalPath.add(i);
}
} else {
// TODO refactor and have first
// Base case
// Elevator current floor is the same as the pickup floor, no further traversal required.
//traversalPath.add(destinationFloor);
}
}
default ElevatorDirectionE calculateElevatorDirection(ElevatorOperationRequest elevatorOperationRequest) {
int pickupFloor = elevatorOperationRequest.getPickupFloor();
int dropOffFloor = elevatorOperationRequest.getDropOffFloor();
if (pickupFloor < dropOffFloor) {
return ElevatorDirectionE.Up;
}
return ElevatorDirectionE.Down;
}
}
| UTF-8 | Java | 2,084 | java | ITraversalModeStrategy.java | Java | [
{
"context": "rithm that will run an Elevator Mode\n *\n * @author manyce400\n */\npublic interface ITraversalModeStrategy {\n\n\n ",
"end": 438,
"score": 0.9994090795516968,
"start": 429,
"tag": "USERNAME",
"value": "manyce400"
}
]
| null | []
| package com.sample.coding.exercises.elevator.operation.traversal;
import com.sample.coding.exercises.elevator.model.ElevatorDirectionE;
import com.sample.coding.exercises.elevator.model.ElevatorOperationRequest;
import com.sample.coding.exercises.elevator.model.ElevatorTraversalPath;
import java.util.LinkedList;
/**
* Interface that defines the basic contract for the algorithm that will run an Elevator Mode
*
* @author manyce400
*/
public interface ITraversalModeStrategy {
/**
* Executes algo implementation for an elevator run given instructions.
*
* @param currentElevatorFloor the current floor that the elevator is on when it receives instruction.
* @param elevatorOperationRequest instructions to run a pickup and drop off implementation.
* @return ElevatorTraversalPath returns run results
*/
public ElevatorTraversalPath executeElevatorRun(int currentElevatorFloor, ElevatorOperationRequest elevatorOperationRequest);
default void computePathToDestinationFloor(int startFloor, int destinationFloor, LinkedList<Integer> traversalPath) {
if(destinationFloor > startFloor) {
for(int i = startFloor; i <= destinationFloor; i++) {
traversalPath.add(i);
}
} else if(destinationFloor < startFloor) {
for(int i = startFloor; i >= destinationFloor; i--) {
traversalPath.add(i);
}
} else {
// TODO refactor and have first
// Base case
// Elevator current floor is the same as the pickup floor, no further traversal required.
//traversalPath.add(destinationFloor);
}
}
default ElevatorDirectionE calculateElevatorDirection(ElevatorOperationRequest elevatorOperationRequest) {
int pickupFloor = elevatorOperationRequest.getPickupFloor();
int dropOffFloor = elevatorOperationRequest.getDropOffFloor();
if (pickupFloor < dropOffFloor) {
return ElevatorDirectionE.Up;
}
return ElevatorDirectionE.Down;
}
}
| 2,084 | 0.705374 | 0.703935 | 55 | 36.890907 | 36.948452 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.381818 | false | false | 0 |
234dc3335036f1455e7bb008f794edfe3821ffe9 | 17,523,466,615,824 | 25835d4af7e87bc960473582b1e9dc2fda7b4f7d | /common/src/main/java/ds/common/FileStorage.java | b6f22e7e6ee58f96977098d993794e5f66efc577 | []
| no_license | mattrighetti/distributed-job-scheduler | https://github.com/mattrighetti/distributed-job-scheduler | d066817cc68c08925e4ae581155c4ba3a6d36cbd | 9137bddce395971ea60c2f029e02291f7a64794e | refs/heads/master | 2022-12-19T01:45:50.628000 | 2020-09-11T12:53:46 | 2020-09-11T12:53:46 | 252,564,625 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ds.common;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*;
public class FileStorage {
private static final boolean verbose =
System.getenv().containsKey("VERBOSE") && Boolean.parseBoolean(System.getenv("VERBOSE"));
private static final Logger log = LogManager.getLogger(FileStorage.class.getName());
public static <T> void writeObjToFile(T objectToSerialize, String filepath) {
try (
FileOutputStream fileOut = new FileOutputStream(filepath);
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut)
) {
if (verbose) {
log.debug("Writing to file {}", objectToSerialize);
}
objectOut.writeObject(objectToSerialize);
if (verbose) {
log.info("The Object was successfully written to file");
}
} catch (NotSerializableException e) {
log.warn("Could not write {}", objectToSerialize.getClass());
e.printStackTrace();
} catch (FileNotFoundException e) {
log.warn("File was not found");
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public static <T> T readObjFromFile(String filepath) {
T obj = null;
try (
FileInputStream fileIn = new FileInputStream(filepath);
ObjectInputStream objectIn = new ObjectInputStream(fileIn)
) {
obj = (T) objectIn.readObject();
if (verbose) {
log.info("The Object has been read from file");
}
} catch (FileNotFoundException e) {
log.warn("File was not found");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
}
| UTF-8 | Java | 1,911 | java | FileStorage.java | Java | []
| null | []
| package ds.common;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*;
public class FileStorage {
private static final boolean verbose =
System.getenv().containsKey("VERBOSE") && Boolean.parseBoolean(System.getenv("VERBOSE"));
private static final Logger log = LogManager.getLogger(FileStorage.class.getName());
public static <T> void writeObjToFile(T objectToSerialize, String filepath) {
try (
FileOutputStream fileOut = new FileOutputStream(filepath);
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut)
) {
if (verbose) {
log.debug("Writing to file {}", objectToSerialize);
}
objectOut.writeObject(objectToSerialize);
if (verbose) {
log.info("The Object was successfully written to file");
}
} catch (NotSerializableException e) {
log.warn("Could not write {}", objectToSerialize.getClass());
e.printStackTrace();
} catch (FileNotFoundException e) {
log.warn("File was not found");
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public static <T> T readObjFromFile(String filepath) {
T obj = null;
try (
FileInputStream fileIn = new FileInputStream(filepath);
ObjectInputStream objectIn = new ObjectInputStream(fileIn)
) {
obj = (T) objectIn.readObject();
if (verbose) {
log.info("The Object has been read from file");
}
} catch (FileNotFoundException e) {
log.warn("File was not found");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
}
| 1,911 | 0.588697 | 0.58765 | 56 | 33.125 | 27.045637 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.446429 | false | false | 0 |
c4669f9110a3a0d270198fba6ea9fe073d15971d | 15,848,429,364,632 | 262fc48d0477a932a5e8c3f7755ab00782b05e13 | /generate-plugin/src/main/java/com/robintegg/web/plugins/AggregatorPlugin.java | 49c37da1b82519cc477a562046eab4b9c5760696 | []
| no_license | teggr/robintegg | https://github.com/teggr/robintegg | 6fa9ea3b2f69575f7cd6a40276b7c1be4ab48e2c | e15d42e05c01a8c466b0e8fcbd253d9b253b9ae3 | refs/heads/master | 2023-08-08T07:43:53.043000 | 2023-08-02T12:23:13 | 2023-08-02T12:23:13 | 116,415,715 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.robintegg.web.plugins;
import com.robintegg.web.engine.ContentItem;
import com.robintegg.web.engine.ContentModelVisitor;
public interface AggregatorPlugin {
void visit(ContentModelVisitor visitor);
void add(ContentItem contentItem);
}
| UTF-8 | Java | 256 | java | AggregatorPlugin.java | Java | []
| null | []
| package com.robintegg.web.plugins;
import com.robintegg.web.engine.ContentItem;
import com.robintegg.web.engine.ContentModelVisitor;
public interface AggregatorPlugin {
void visit(ContentModelVisitor visitor);
void add(ContentItem contentItem);
}
| 256 | 0.8125 | 0.8125 | 12 | 20.333334 | 20.657255 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 0 |
40e6b2f17afab54c4b19064f1c7a9117f51a0c39 | 14,104,672,643,235 | 995e994052e1af2a841c58691557120e610dd33f | /src/main/java/br/com/sistema/frota/util/Mensagem.java | 529e12bdcdf5765e1c9ed906ed8389eb515631ed | []
| no_license | Luiz10/SistemaFrota | https://github.com/Luiz10/SistemaFrota | ff0c58bfad07f125ccac5c35fc037152d22b9302 | e337ae9fb8db27c0d8483bb1eaf6a3636817f70c | refs/heads/master | 2017-11-11T13:24:13.426000 | 2017-04-10T15:41:25 | 2017-04-10T15:41:25 | 86,862,758 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.sistema.frota.util;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
public class Mensagem implements Serializable {
private static final long serialVersionUID = 1L;
//PASSAGENS DE MENSAGEM DANDO UM RETORNO DE OK
public static void MensagemOK(String msg) {
FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, fm);
}
//PASSAGENS DE MENSAGEM DANDO UM RETORNO DANDO ERROR
public static void MensagemError(String msg) {
FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg,
msg);
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, fm);
}
}
| UTF-8 | Java | 805 | java | Mensagem.java | Java | []
| null | []
| package br.com.sistema.frota.util;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
public class Mensagem implements Serializable {
private static final long serialVersionUID = 1L;
//PASSAGENS DE MENSAGEM DANDO UM RETORNO DE OK
public static void MensagemOK(String msg) {
FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, fm);
}
//PASSAGENS DE MENSAGEM DANDO UM RETORNO DANDO ERROR
public static void MensagemError(String msg) {
FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg,
msg);
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, fm);
}
}
| 805 | 0.749068 | 0.747826 | 26 | 28.961538 | 24.211378 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.576923 | false | false | 0 |
fd40b96f3b384a8969cc21885542f05a142b6d25 | 4,492,535,838,310 | 52bdf7c58fc718c1a017534b0211f4070cd72002 | /RegexMoreExercize/src/SantaSecretHelper.java | 87432c4b0a32636380fff7cc62541efea109e080 | []
| no_license | knaevKMK/Java_Fundsmentals | https://github.com/knaevKMK/Java_Fundsmentals | 08ef75914cb0f3c72db713bf2c839afe1c13e008 | 3768bac72cfdba13a09268c531c3feb8254cb6fd | refs/heads/main | 2023-02-01T04:52:13.089000 | 2020-12-20T20:23:57 | 2020-12-20T20:23:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import com.sun.source.tree.WhileLoopTree;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SantaSecretHelper {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
String read = scanner.nextLine();
while (!"end".equals(read)) {
String decrypt = getIt(n, read);
String name = getName("name", decrypt);
String behavior = getName("behavior", decrypt);
if (behavior.equals("G")) {
System.out.println(name);
}
read = scanner.nextLine();
}
}
private static String getName(String part, String decrypt) {
final String regex = "@(?<name>[A-Za-z]+)" +
"[^@\\-!:>]*" +
"!(?<behavior>[GN])!";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(decrypt);
if (matcher.find()) {
return matcher.group(part);
}
return "not Match";
}
private static String getIt(int n, String read) {
StringBuilder string = new StringBuilder();
for (int i = 0; i < read.length(); i++) {
string.append((char) (read.charAt(i) - n));
}
return string.toString();
}
}
| UTF-8 | Java | 1,378 | java | SantaSecretHelper.java | Java | []
| null | []
| import com.sun.source.tree.WhileLoopTree;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SantaSecretHelper {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
String read = scanner.nextLine();
while (!"end".equals(read)) {
String decrypt = getIt(n, read);
String name = getName("name", decrypt);
String behavior = getName("behavior", decrypt);
if (behavior.equals("G")) {
System.out.println(name);
}
read = scanner.nextLine();
}
}
private static String getName(String part, String decrypt) {
final String regex = "@(?<name>[A-Za-z]+)" +
"[^@\\-!:>]*" +
"!(?<behavior>[GN])!";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(decrypt);
if (matcher.find()) {
return matcher.group(part);
}
return "not Match";
}
private static String getIt(int n, String read) {
StringBuilder string = new StringBuilder();
for (int i = 0; i < read.length(); i++) {
string.append((char) (read.charAt(i) - n));
}
return string.toString();
}
}
| 1,378 | 0.550798 | 0.550073 | 45 | 29.622223 | 20.186121 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 0 |
7250ce2fd34e4bed72bf71df85d73e45a0887598 | 6,073,083,823,891 | 481e2b442a724ddc66e7b6589f1754847d816422 | /Module-1/Labs/Lab1/src/Lab1_Question1.java | d94c536d561d79b8e95c04480b655bdee921d4ed | []
| no_license | hsafari99/Java-Android | https://github.com/hsafari99/Java-Android | 2c9986b82e8d53d25194c0d4523f3a34a82d355f | 1a43458b4a319999911deda4d739d537a7058435 | refs/heads/master | 2020-06-19T07:54:59.387000 | 2019-07-12T20:16:40 | 2019-07-12T20:16:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class lecture_2 {
/*
Write a program to prompt the user to fill out a form with the following fields:
First Name (string)
Last Name (string)
Address (string)
City (string)
Postal Code (string)
Phone number (string)
Age (byte)
earning per hour (float)
Then output the following:
Your name is : (first name and last name)
Your address : (whole address)
Your age is : (age)
Your age in light year
Your earning :
Your earning in 100 years ago: (earning / age)
Your earning in a near future: (earning x 1.7 + age)
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String first_name = new String();
String last_name = new String();
String address = new String();
String city = new String();
String postal_code = new String();
String phone_number = new String();
int age;
float earning;
//getting the user first name after giving a message for entering the first name
System.out.print("Please enter your first name: ");
first_name = sc.nextLine();
//getting the user last name after giving a message for entering the last name
System.out.print("Please enter your last name: ");
last_name = sc.nextLine();
//getting the user address after giving a message for entering the address
System.out.print("Please enter your address: ");
address = sc.nextLine();
//getting the user address after giving a message for entering the city
System.out.print("Please enter the city that you are living: ");
city = sc.nextLine();
//getting the user postal code after giving a message for entering the postal code
System.out.print("Please enter the postal code of where you are living: ");
postal_code = sc.nextLine();
//getting the user phone number after giving a message for entering the phone no.
System.out.print("Please enter You phone number: ");
phone_number = sc.nextLine();
//getting the user phone number after giving a message for entering the age
System.out.print("Please enter your age: ");
age = sc.nextInt();
//getting the user phone number after giving a message for entering the income
System.out.print("Please enter your income: ");
earning = sc.nextFloat();
System.out.format("Your full name is \t: %s%s \n", first_name, last_name);
System.out.format("Your full address is \t: %s, %s, postal code: %s, Tel: %s \n", address, city, postal_code, phone_number);
System.out.format("Your are %d years old.\n", age);
System.out.format("Your income is \t: %s\n", earning);
System.out.println("Your earning in 100 years ago: \t" + (earning/age));
System.out.println("Your earning in a near future: \t" + (Double)((earning * 1.7) + age));
sc.close();
}
}
| UTF-8 | Java | 2,739 | java | Lab1_Question1.java | Java | []
| null | []
| import java.util.Scanner;
public class lecture_2 {
/*
Write a program to prompt the user to fill out a form with the following fields:
First Name (string)
Last Name (string)
Address (string)
City (string)
Postal Code (string)
Phone number (string)
Age (byte)
earning per hour (float)
Then output the following:
Your name is : (first name and last name)
Your address : (whole address)
Your age is : (age)
Your age in light year
Your earning :
Your earning in 100 years ago: (earning / age)
Your earning in a near future: (earning x 1.7 + age)
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String first_name = new String();
String last_name = new String();
String address = new String();
String city = new String();
String postal_code = new String();
String phone_number = new String();
int age;
float earning;
//getting the user first name after giving a message for entering the first name
System.out.print("Please enter your first name: ");
first_name = sc.nextLine();
//getting the user last name after giving a message for entering the last name
System.out.print("Please enter your last name: ");
last_name = sc.nextLine();
//getting the user address after giving a message for entering the address
System.out.print("Please enter your address: ");
address = sc.nextLine();
//getting the user address after giving a message for entering the city
System.out.print("Please enter the city that you are living: ");
city = sc.nextLine();
//getting the user postal code after giving a message for entering the postal code
System.out.print("Please enter the postal code of where you are living: ");
postal_code = sc.nextLine();
//getting the user phone number after giving a message for entering the phone no.
System.out.print("Please enter You phone number: ");
phone_number = sc.nextLine();
//getting the user phone number after giving a message for entering the age
System.out.print("Please enter your age: ");
age = sc.nextInt();
//getting the user phone number after giving a message for entering the income
System.out.print("Please enter your income: ");
earning = sc.nextFloat();
System.out.format("Your full name is \t: %s%s \n", first_name, last_name);
System.out.format("Your full address is \t: %s, %s, postal code: %s, Tel: %s \n", address, city, postal_code, phone_number);
System.out.format("Your are %d years old.\n", age);
System.out.format("Your income is \t: %s\n", earning);
System.out.println("Your earning in 100 years ago: \t" + (earning/age));
System.out.println("Your earning in a near future: \t" + (Double)((earning * 1.7) + age));
sc.close();
}
}
| 2,739 | 0.694779 | 0.690763 | 77 | 34.57143 | 28.62495 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.103896 | false | false | 0 |
dd71a48cbdb30dd8a48e8a8a7e89e8fad6dfcb34 | 7,533,372,682,710 | 656a69190c24152e04ace1ef51365ffe8645ad37 | /src/main/java/com/jojoldu/book/springboot/web/dto/HelloResponseDto.java | 21c59678c9a4ae7ea3d6aa99d312b4131b7f2906 | []
| no_license | azsx92/com.jojoIdu.book | https://github.com/azsx92/com.jojoIdu.book | c4e6f0e0ef50df96d0acb3d939974c9fb1c877d1 | 5d2b53efd23bd6dd3d0757e76972ddbf5e62c88b | refs/heads/master | 2023-08-19T20:24:09.101000 | 2021-10-09T10:29:46 | 2021-10-09T10:29:46 | 364,574,154 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jojoldu.book.springboot.web.dto;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Getter
@RequiredArgsConstructor
public class HelloResponseDto {
private final String name;
private final int amount;
@GetMapping("/hello/dto")
public HelloResponseDto helloDto(@RequestParam("name") String name , @RequestParam("amount") int amount) {
return new HelloResponseDto(name , amount);
}
}
| UTF-8 | Java | 559 | java | HelloResponseDto.java | Java | []
| null | []
| package com.jojoldu.book.springboot.web.dto;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Getter
@RequiredArgsConstructor
public class HelloResponseDto {
private final String name;
private final int amount;
@GetMapping("/hello/dto")
public HelloResponseDto helloDto(@RequestParam("name") String name , @RequestParam("amount") int amount) {
return new HelloResponseDto(name , amount);
}
}
| 559 | 0.767442 | 0.767442 | 21 | 25.619047 | 27.551641 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.47619 | false | false | 0 |
0e711a9d839616d42161794ab9a453ecf26ac204 | 16,698,832,907,189 | 019c1b3267808671f7deb8024ea425cd6039b189 | /src/main/java/gadgetinspector/GadgetChainDiscovery.java | 9f04decfd0aa1a39196f357f8d69957bc8b3c8d3 | [
"MIT"
]
| permissive | threedr3am/gadgetinspector | https://github.com/threedr3am/gadgetinspector | c960ccb79a86e73bc2bff15a9d04d18b07a0bcdf | 528bf5d44ff247113ef73d7d43408280348d6ed6 | refs/heads/master | 2022-04-29T21:15:25.560000 | 2022-03-24T13:22:18 | 2022-03-24T13:43:38 | 197,133,617 | 436 | 59 | null | true | 2019-07-16T06:26:35 | 2019-07-16T06:26:35 | 2019-07-16T06:24:26 | 2018-09-29T04:16:54 | 99 | 0 | 0 | 0 | null | false | false | package gadgetinspector;
import gadgetinspector.config.GIConfig;
import gadgetinspector.config.JavaDeserializationConfig;
import gadgetinspector.data.ClassReference;
import gadgetinspector.data.CustomSlink;
import gadgetinspector.data.DataLoader;
import gadgetinspector.data.GraphCall;
import gadgetinspector.data.InheritanceDeriver;
import gadgetinspector.data.InheritanceMap;
import gadgetinspector.data.MethodReference;
import gadgetinspector.data.MethodReference.Handle;
import gadgetinspector.data.SlinkReference;
import gadgetinspector.data.Source;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GadgetChainDiscovery {
private static final Logger LOGGER = LoggerFactory.getLogger(GadgetChainDiscovery.class);
private final GIConfig config;
public GadgetChainDiscovery(GIConfig config) {
this.config = config;
}
private static List<CustomSlink> customSlinks = new ArrayList<>();
static {
if (!ConfigHelper.slinksFile.isEmpty()) {
try(BufferedReader bufferedReader = Files.newBufferedReader(Paths.get(ConfigHelper.slinksFile))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
String c;
if (!(c = line.split("#")[0].trim()).isEmpty()) {
String[] slinks = c.split(" ");
CustomSlink customSlink = new CustomSlink();
if (slinks.length > 0) {
customSlink.setClassName(slinks[0]);
}
if (slinks.length > 1) {
customSlink.setMethod(slinks[1]);
}
if (slinks.length > 2) {
customSlink.setDesc(slinks[2]);
}
customSlinks.add(customSlink);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void discover(List<Path> pathList) throws Exception {
Map<MethodReference.Handle, MethodReference> methodMap = DataLoader.loadMethods();
InheritanceMap inheritanceMap = InheritanceMap.load();
Map<MethodReference.Handle, Set<MethodReference.Handle>> methodImplMap = InheritanceDeriver
.getAllMethodImplementations(
inheritanceMap, methodMap);
Map<ClassReference.Handle, Set<MethodReference.Handle>> methodsByClass = InheritanceDeriver.getMethodsByClass(methodMap);
final ImplementationFinder implementationFinder = config.getImplementationFinder(
methodMap, methodImplMap, inheritanceMap, methodsByClass);
try (Writer writer = Files.newBufferedWriter(Paths.get("methodimpl.dat"))) {
for (Map.Entry<MethodReference.Handle, Set<MethodReference.Handle>> entry : methodImplMap
.entrySet()) {
writer.write(entry.getKey().getClassReference().getName());
writer.write("\t");
writer.write(entry.getKey().getName());
writer.write("\t");
writer.write(entry.getKey().getDesc());
writer.write("\n");
for (MethodReference.Handle method : entry.getValue()) {
writer.write("\t");
writer.write(method.getClassReference().getName());
writer.write("\t");
writer.write(method.getName());
writer.write("\t");
writer.write(method.getDesc());
writer.write("\n");
}
}
}
Map<MethodReference.Handle, Set<GraphCall>> graphCallMap = new HashMap<>();
for (GraphCall graphCall : DataLoader
.loadData(Paths.get("callgraph.dat"), new GraphCall.Factory())) {
MethodReference.Handle caller = graphCall.getCallerMethod();
if (!graphCallMap.containsKey(caller)) {
Set<GraphCall> graphCalls = new HashSet<>();
graphCalls.add(graphCall);
graphCallMap.put(caller, graphCalls);
} else {
graphCallMap.get(caller).add(graphCall);
}
}
Set<GadgetChainLink> exploredMethods = new HashSet<>();
LinkedList<GadgetChain> methodsToExplore = new LinkedList<>();
LinkedList<GadgetChain> methodsToExploreRepeat = new LinkedList<>();
for (Source source : DataLoader.loadData(Paths.get("sources.dat"), new Source.Factory())) {
GadgetChainLink srcLink = new GadgetChainLink(source.getSourceMethod(),
source.getTaintedArgIndex());
if (exploredMethods.contains(srcLink)) {
continue;
}
methodsToExplore.add(new GadgetChain(Arrays.asList(srcLink)));
exploredMethods.add(srcLink);
}
long iteration = 0;
Set<GadgetChain> discoveredGadgets = new HashSet<>();
while (methodsToExplore.size() > 0) {
if ((iteration % 1000) == 0) {
LOGGER.info("Iteration " + iteration + ", Search space: " + methodsToExplore.size());
}
iteration += 1;
GadgetChain chain = methodsToExplore.pop();
GadgetChainLink lastLink = chain.links.get(chain.links.size() - 1);
//限定链长度
if (chain.links.size() >= ConfigHelper.maxChainLength) {
continue;
}
Set<GraphCall> methodCalls = graphCallMap.get(lastLink.method);
if (methodCalls != null) {
for (GraphCall graphCall : methodCalls) {
//使用污点分析才会进行数据流判断
if (graphCall.getCallerArgIndex() != lastLink.taintedArgIndex
&& ConfigHelper.taintTrack) {
continue;
}
Set<MethodReference.Handle> allImpls = implementationFinder
.getImplementations(graphCall.getTargetMethod());
//todo gadgetinspector bug 没记录继承父类的方法,导致不可能找到
if (allImpls.isEmpty()) {
Set<ClassReference.Handle> parents = inheritanceMap.getSuperClasses(graphCall.getTargetMethod().getClassReference());
if (parents == null)
continue;
for (ClassReference.Handle parent : parents) {
Set<MethodReference.Handle> methods = methodsByClass.get(parent);
//为了解决这个bug,只能反向父类去查找方法,但是目前解决的方式可能会存在记录多个父类方法,但是已初步解决这个问题
if (methods == null)
continue;
for (MethodReference.Handle method : methods) {
if (method.getName().equals(graphCall.getTargetMethod().getName()) && method.getDesc().equals(graphCall.getTargetMethod().getDesc())) {
allImpls.add(method);
}
}
}
}
for (MethodReference.Handle methodImpl : allImpls) {
GadgetChainLink newLink = new GadgetChainLink(methodImpl,
graphCall.getTargetArgIndex());
if (exploredMethods.contains(newLink)) {
if (chain.links.size() <= ConfigHelper.opLevel) {
GadgetChain newChain = new GadgetChain(chain, newLink);
methodsToExploreRepeat.add(newChain);
}
continue;
}
GadgetChain newChain = new GadgetChain(chain, newLink);
if (isSink(methodImpl, graphCall.getTargetArgIndex(), inheritanceMap)) {
discoveredGadgets.add(newChain);
} else {
methodsToExplore.add(newChain);
exploredMethods.add(newLink);
}
}
}
}
}
//链聚合优化
Set<GadgetChain> tmpDiscoveredGadgets = new HashSet<>();
for (GadgetChain gadgetChain : methodsToExploreRepeat) {
GadgetChainLink lastLink = gadgetChain.links.get(gadgetChain.links.size() - 1);
for (GadgetChain discoveredGadgetChain : discoveredGadgets) {
boolean exist = false;
for (GadgetChainLink gadgetChainLink : discoveredGadgetChain.links) {
if (exist) {
gadgetChain = new GadgetChain(gadgetChain, gadgetChainLink);
}
if (lastLink.equals(gadgetChainLink)) {
exist = true;
}
}
if (exist) {
tmpDiscoveredGadgets.add(gadgetChain);
}
}
}
discoveredGadgets.addAll(tmpDiscoveredGadgets);
if (!discoveredGadgets.isEmpty()) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
try (OutputStream outputStream = Files
.newOutputStream(
Paths.get("gadget-result/gadget-chains-" + simpleDateFormat.format(new Date())
+ ".txt"));
Writer writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) {
if (pathList != null) {
writer.write("Using classpath: " + Arrays.toString(pathList.toArray()) + "\n");
}
for (GadgetChain chain : discoveredGadgets) {
printGadgetChain(writer, chain);
}
}
}
LOGGER.info("Found {} gadget chains.", discoveredGadgets.size());
}
private static void printGadgetChain(Writer writer, GadgetChain chain) throws IOException {
writer.write(String.format("%s.%s%s (%d)%n",
chain.links.get(0).method.getClassReference().getName(),
chain.links.get(0).method.getName(),
chain.links.get(0).method.getDesc(),
chain.links.get(0).taintedArgIndex));
for (int i = 1; i < chain.links.size(); i++) {
writer.write(String.format(" %s.%s%s (%d)%n",
chain.links.get(i).method.getClassReference().getName(),
chain.links.get(i).method.getName(),
chain.links.get(i).method.getDesc(),
chain.links.get(i).taintedArgIndex));
}
writer.write("\n");
}
private static class GadgetChain {
private final List<GadgetChainLink> links;
private GadgetChain(List<GadgetChainLink> links) {
this.links = links;
}
private GadgetChain(GadgetChain gadgetChain, GadgetChainLink link) {
List<GadgetChainLink> links = new ArrayList<GadgetChainLink>(gadgetChain.links);
links.add(link);
this.links = links;
}
}
private static class GadgetChainLink {
private final MethodReference.Handle method;
private final int taintedArgIndex;
private GadgetChainLink(MethodReference.Handle method, int taintedArgIndex) {
this.method = method;
this.taintedArgIndex = taintedArgIndex;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GadgetChainLink that = (GadgetChainLink) o;
if (taintedArgIndex != that.taintedArgIndex) {
return false;
}
return method != null ? method.equals(that.method) : that.method == null;
}
@Override
public int hashCode() {
int result = method != null ? method.hashCode() : 0;
result = 31 * result + taintedArgIndex;
return result;
}
}
/**
* Represents a collection of methods in the JDK that we consider to be "interesting". If a gadget
* chain can successfully exercise one of these, it could represent anything as mundade as causing
* the target to make a DNS query to full blown RCE.
*/
// TODO: Parameterize this as a configuration option
private boolean isSink(MethodReference.Handle method, int argIndex,
InheritanceMap inheritanceMap) {
if (!customSlinks.isEmpty()) {
for (CustomSlink customSlink:customSlinks) {
boolean flag = false;
if (customSlink.getClassName() != null)
flag &= customSlink.getClassName().equals(method.getClassReference().getName());
if (customSlink.getMethod() != null)
flag &= customSlink.getMethod().equals(method.getName());
if (customSlink.getDesc() != null)
flag &= customSlink.getDesc().equals(method.getDesc());
if (flag)
return flag;
}
return false;
}
if (config.getName().equals("sqlinject")) {
//SQLInject只能检测注入
return isSQLInjectSink(method, argIndex, inheritanceMap);
}
if (config.getName().equals("hessian")) {
//仅hessian可选BCEL slink
if (ConfigHelper.slinks.contains("BCEL") && BCELSlink(method, argIndex, inheritanceMap)) {
return true;
}
}
//通用slink,不设定slink则全部都挖掘
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("JNDI")) && JNDISlink(method, inheritanceMap)) {
return true;
}
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("CLASSLOADER")) && ClassLoaderlink(method, argIndex, inheritanceMap)) {
return true;
}
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("SSRFAndXXE")) && SSRFAndXXESlink(method, inheritanceMap)) {
return true;
}
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("EXEC")) && EXECSlink(method, argIndex)) {
return true;
}
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("FileIO")) && FileIOSlink(method)) {
return true;
}
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("Reflect")) && ReflectSlink(method, argIndex, inheritanceMap)) {
return true;
}
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("JDBC")) && JDBCSlink(method, argIndex, inheritanceMap)) {
return true;
}
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("EL")) && ELSlink(method, argIndex, inheritanceMap)) {
return true;
}
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("SQLInject")) && isSQLInjectSink(method, argIndex, inheritanceMap)) {
return true;
}
return false;
}
private boolean JDBCSlink(Handle method, int argIndex, InheritanceMap inheritanceMap) {
if (method.getClassReference().getName().equals("javax/sql/DataSource")
&& method.getName().equals("getConnection")) {
return true;
}
return false;
}
private boolean ReflectSlink(Handle method, int argIndex, InheritanceMap inheritanceMap) {
if (method.getClassReference().getName().equals("java/lang/reflect/Method")
&& method.getName().equals("invoke") && argIndex == 0) {
return true;
}
if (method.getClassReference().getName().equals("java/net/URLClassLoader")
&& method.getName().equals("newInstance")) {
return true;
}
if (inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("java/lang/ClassLoader"))
&& method.getName().equals("<init>")) {
return true;
}
// Some groovy-specific sinks
if (method.getClassReference().getName().equals("org/codehaus/groovy/runtime/InvokerHelper")
&& method.getName().equals("invokeMethod") && argIndex == 1) {
return true;
}
if (inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("groovy/lang/MetaClass"))
&& Arrays.asList("invokeMethod", "invokeConstructor", "invokeStaticMethod")
.contains(method.getName())) {
return true;
}
return false;
}
private boolean FileIOSlink(Handle method) {
if (method.getClassReference().getName().equals("java/io/FileInputStream")
&& method.getName().equals("<init>")) {
return true;
}
if (method.getClassReference().getName().equals("java/io/FileOutputStream")
&& method.getName().equals("<init>")) {
return true;
}
if (method.getClassReference().getName().equals("java/nio/file/Files")
&& (method.getName().equals("newInputStream")
|| method.getName().equals("newOutputStream")
|| method.getName().equals("newBufferedReader")
|| method.getName().equals("newBufferedWriter"))) {
return true;
}
if (method.getClassReference().getName().equals("java/net/URL") && method.getName()
.equals("openStream")) {
return true;
}
return false;
}
private boolean dosSlink(Handle method) {
if (method.getClassReference().getName().equals("java/lang/System")
&& method.getName().equals("exit")) {
return true;
}
if (method.getClassReference().getName().equals("java/lang/Shutdown")
&& method.getName().equals("exit")) {
return true;
}
if (method.getClassReference().getName().equals("java/lang/Runtime")
&& method.getName().equals("exit")) {
return true;
}
return false;
}
private boolean EXECSlink(Handle method, int argIndex) {
if (method.getClassReference().getName().equals("java/lang/Runtime")
&& method.getName().equals("exec")) {
return true;
}
if (method.getClassReference().getName().equals("java/lang/ProcessBuilder")
&& method.getName().equals("<init>") && argIndex > 0) {
return true;
}
return false;
}
private boolean BCELSlink(Handle method, int argIndex, InheritanceMap inheritanceMap) {
if (method.getClassReference().getName().equals("java/lang/Class")
&& method.getName().equals("forName")
&& method.getDesc().equals("(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;")) {
return true;
}
return false;
}
private boolean isFastjsonSink(Handle method, int argIndex, InheritanceMap inheritanceMap) {
return false;
}
private boolean SSRFAndXXESlink(Handle method, InheritanceMap inheritanceMap) {
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/xml/parsers/DocumentBuilder"))
)
&& method.getName().equals("parse")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("org/jdom/input/SAXBuilder"))
)
&& method.getName().equals("build")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/xml/parsers/SAXParser"))
)
&& method.getName().equals("parse")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("org/dom4j/io/SAXReader"))
)
&& method.getName().equals("read")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/xml/transform/sax/SAXTransformerFactory"))
)
&& method.getName().equals("newTransformerHandler")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/xml/validation/SchemaFactory"))
)
&& method.getName().equals("newSchema")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/xml/transform/Transformer"))
)
&& method.getName().equals("transform")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/xml/bind/Unmarshaller"))
)
&& method.getName().equals("unmarshal")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/xml/validation/Validator"))
)
&& method.getName().equals("validate")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("org/xml/sax/XMLReader"))
)
&& method.getName().equals("parse")) {
return true;
}
return false;
}
private boolean JNDISlink(Handle method, InheritanceMap inheritanceMap) {
if ((inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("java/rmi/registry/Registry")) ||
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/naming/Context")))
&& method.getName().equals("lookup")) {
return true;
}
return false;
}
private boolean ClassLoaderlink(Handle method, int argIndex, InheritanceMap inheritanceMap) {
if (
inheritanceMap.isSubclassOf(method.getClassReference(), new ClassReference.Handle("java/lang/ClassLoader")) &&
method.getName().equals("loadClass") &&
argIndex == 1
) {
return true;
}
return false;
}
private boolean ELSlink(Handle method, int argIndex, InheritanceMap inheritanceMap) {
if ((inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/validation/ConstraintValidatorContext")) ||
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("org/hibernate/validator/internal/engine/constraintvalidation/ConstraintValidatorContextImpl"))) &&
argIndex == 1 &&
method.getName().equals("buildConstraintViolationWithTemplate")) {
return true;
}
if ((inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("org/springframework/expression/ExpressionParser")) ||
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("org/springframework/expression/spel/standard/SpelExpressionParser"))) &&
argIndex == 1 &&
(method.getName().equals("parseExpression") || method.getName().equals("parseRaw"))) {
return true;
}
if ((inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/el/ELProcessor")) &&
argIndex == 1 && method.getName().equals("eval"))
||
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/el/ExpressionFactory")) &&
argIndex == 2 && method.getName().equals("createValueExpression")) {
return true;
}
return false;
}
private Map<ClassReference.Handle, Set<MethodReference>> slinksMapCache = null;
private boolean isSQLInjectSink(MethodReference.Handle method, int argIndex,
InheritanceMap inheritanceMap) {
if (config.getName().equals("sqlinject")) {
if (slinksMapCache == null) {
Map<ClassReference.Handle, Set<MethodReference>> slinksMap = DataLoader.loadSlinks();
slinksMapCache = slinksMap;
}
if (slinksMapCache.containsKey(method.getClassReference()) &&
slinksMapCache.get(method.getClassReference()).stream()
.filter(methodReference -> methodReference.equals(method)).count() > 0) {
return true;
}
}
if (inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("org/springframework/jdbc/core/StatementCallback")) &&
method.getName().equals("doInStatement")) {
return true;
}
return false;
}
public static void main(String[] args) throws Exception {
GadgetChainDiscovery gadgetChainDiscovery = new GadgetChainDiscovery(
new JavaDeserializationConfig());
gadgetChainDiscovery.discover(null);
}
}
| UTF-8 | Java | 23,524 | java | GadgetChainDiscovery.java | Java | []
| null | []
| package gadgetinspector;
import gadgetinspector.config.GIConfig;
import gadgetinspector.config.JavaDeserializationConfig;
import gadgetinspector.data.ClassReference;
import gadgetinspector.data.CustomSlink;
import gadgetinspector.data.DataLoader;
import gadgetinspector.data.GraphCall;
import gadgetinspector.data.InheritanceDeriver;
import gadgetinspector.data.InheritanceMap;
import gadgetinspector.data.MethodReference;
import gadgetinspector.data.MethodReference.Handle;
import gadgetinspector.data.SlinkReference;
import gadgetinspector.data.Source;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GadgetChainDiscovery {
private static final Logger LOGGER = LoggerFactory.getLogger(GadgetChainDiscovery.class);
private final GIConfig config;
public GadgetChainDiscovery(GIConfig config) {
this.config = config;
}
private static List<CustomSlink> customSlinks = new ArrayList<>();
static {
if (!ConfigHelper.slinksFile.isEmpty()) {
try(BufferedReader bufferedReader = Files.newBufferedReader(Paths.get(ConfigHelper.slinksFile))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
String c;
if (!(c = line.split("#")[0].trim()).isEmpty()) {
String[] slinks = c.split(" ");
CustomSlink customSlink = new CustomSlink();
if (slinks.length > 0) {
customSlink.setClassName(slinks[0]);
}
if (slinks.length > 1) {
customSlink.setMethod(slinks[1]);
}
if (slinks.length > 2) {
customSlink.setDesc(slinks[2]);
}
customSlinks.add(customSlink);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void discover(List<Path> pathList) throws Exception {
Map<MethodReference.Handle, MethodReference> methodMap = DataLoader.loadMethods();
InheritanceMap inheritanceMap = InheritanceMap.load();
Map<MethodReference.Handle, Set<MethodReference.Handle>> methodImplMap = InheritanceDeriver
.getAllMethodImplementations(
inheritanceMap, methodMap);
Map<ClassReference.Handle, Set<MethodReference.Handle>> methodsByClass = InheritanceDeriver.getMethodsByClass(methodMap);
final ImplementationFinder implementationFinder = config.getImplementationFinder(
methodMap, methodImplMap, inheritanceMap, methodsByClass);
try (Writer writer = Files.newBufferedWriter(Paths.get("methodimpl.dat"))) {
for (Map.Entry<MethodReference.Handle, Set<MethodReference.Handle>> entry : methodImplMap
.entrySet()) {
writer.write(entry.getKey().getClassReference().getName());
writer.write("\t");
writer.write(entry.getKey().getName());
writer.write("\t");
writer.write(entry.getKey().getDesc());
writer.write("\n");
for (MethodReference.Handle method : entry.getValue()) {
writer.write("\t");
writer.write(method.getClassReference().getName());
writer.write("\t");
writer.write(method.getName());
writer.write("\t");
writer.write(method.getDesc());
writer.write("\n");
}
}
}
Map<MethodReference.Handle, Set<GraphCall>> graphCallMap = new HashMap<>();
for (GraphCall graphCall : DataLoader
.loadData(Paths.get("callgraph.dat"), new GraphCall.Factory())) {
MethodReference.Handle caller = graphCall.getCallerMethod();
if (!graphCallMap.containsKey(caller)) {
Set<GraphCall> graphCalls = new HashSet<>();
graphCalls.add(graphCall);
graphCallMap.put(caller, graphCalls);
} else {
graphCallMap.get(caller).add(graphCall);
}
}
Set<GadgetChainLink> exploredMethods = new HashSet<>();
LinkedList<GadgetChain> methodsToExplore = new LinkedList<>();
LinkedList<GadgetChain> methodsToExploreRepeat = new LinkedList<>();
for (Source source : DataLoader.loadData(Paths.get("sources.dat"), new Source.Factory())) {
GadgetChainLink srcLink = new GadgetChainLink(source.getSourceMethod(),
source.getTaintedArgIndex());
if (exploredMethods.contains(srcLink)) {
continue;
}
methodsToExplore.add(new GadgetChain(Arrays.asList(srcLink)));
exploredMethods.add(srcLink);
}
long iteration = 0;
Set<GadgetChain> discoveredGadgets = new HashSet<>();
while (methodsToExplore.size() > 0) {
if ((iteration % 1000) == 0) {
LOGGER.info("Iteration " + iteration + ", Search space: " + methodsToExplore.size());
}
iteration += 1;
GadgetChain chain = methodsToExplore.pop();
GadgetChainLink lastLink = chain.links.get(chain.links.size() - 1);
//限定链长度
if (chain.links.size() >= ConfigHelper.maxChainLength) {
continue;
}
Set<GraphCall> methodCalls = graphCallMap.get(lastLink.method);
if (methodCalls != null) {
for (GraphCall graphCall : methodCalls) {
//使用污点分析才会进行数据流判断
if (graphCall.getCallerArgIndex() != lastLink.taintedArgIndex
&& ConfigHelper.taintTrack) {
continue;
}
Set<MethodReference.Handle> allImpls = implementationFinder
.getImplementations(graphCall.getTargetMethod());
//todo gadgetinspector bug 没记录继承父类的方法,导致不可能找到
if (allImpls.isEmpty()) {
Set<ClassReference.Handle> parents = inheritanceMap.getSuperClasses(graphCall.getTargetMethod().getClassReference());
if (parents == null)
continue;
for (ClassReference.Handle parent : parents) {
Set<MethodReference.Handle> methods = methodsByClass.get(parent);
//为了解决这个bug,只能反向父类去查找方法,但是目前解决的方式可能会存在记录多个父类方法,但是已初步解决这个问题
if (methods == null)
continue;
for (MethodReference.Handle method : methods) {
if (method.getName().equals(graphCall.getTargetMethod().getName()) && method.getDesc().equals(graphCall.getTargetMethod().getDesc())) {
allImpls.add(method);
}
}
}
}
for (MethodReference.Handle methodImpl : allImpls) {
GadgetChainLink newLink = new GadgetChainLink(methodImpl,
graphCall.getTargetArgIndex());
if (exploredMethods.contains(newLink)) {
if (chain.links.size() <= ConfigHelper.opLevel) {
GadgetChain newChain = new GadgetChain(chain, newLink);
methodsToExploreRepeat.add(newChain);
}
continue;
}
GadgetChain newChain = new GadgetChain(chain, newLink);
if (isSink(methodImpl, graphCall.getTargetArgIndex(), inheritanceMap)) {
discoveredGadgets.add(newChain);
} else {
methodsToExplore.add(newChain);
exploredMethods.add(newLink);
}
}
}
}
}
//链聚合优化
Set<GadgetChain> tmpDiscoveredGadgets = new HashSet<>();
for (GadgetChain gadgetChain : methodsToExploreRepeat) {
GadgetChainLink lastLink = gadgetChain.links.get(gadgetChain.links.size() - 1);
for (GadgetChain discoveredGadgetChain : discoveredGadgets) {
boolean exist = false;
for (GadgetChainLink gadgetChainLink : discoveredGadgetChain.links) {
if (exist) {
gadgetChain = new GadgetChain(gadgetChain, gadgetChainLink);
}
if (lastLink.equals(gadgetChainLink)) {
exist = true;
}
}
if (exist) {
tmpDiscoveredGadgets.add(gadgetChain);
}
}
}
discoveredGadgets.addAll(tmpDiscoveredGadgets);
if (!discoveredGadgets.isEmpty()) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
try (OutputStream outputStream = Files
.newOutputStream(
Paths.get("gadget-result/gadget-chains-" + simpleDateFormat.format(new Date())
+ ".txt"));
Writer writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) {
if (pathList != null) {
writer.write("Using classpath: " + Arrays.toString(pathList.toArray()) + "\n");
}
for (GadgetChain chain : discoveredGadgets) {
printGadgetChain(writer, chain);
}
}
}
LOGGER.info("Found {} gadget chains.", discoveredGadgets.size());
}
private static void printGadgetChain(Writer writer, GadgetChain chain) throws IOException {
writer.write(String.format("%s.%s%s (%d)%n",
chain.links.get(0).method.getClassReference().getName(),
chain.links.get(0).method.getName(),
chain.links.get(0).method.getDesc(),
chain.links.get(0).taintedArgIndex));
for (int i = 1; i < chain.links.size(); i++) {
writer.write(String.format(" %s.%s%s (%d)%n",
chain.links.get(i).method.getClassReference().getName(),
chain.links.get(i).method.getName(),
chain.links.get(i).method.getDesc(),
chain.links.get(i).taintedArgIndex));
}
writer.write("\n");
}
private static class GadgetChain {
private final List<GadgetChainLink> links;
private GadgetChain(List<GadgetChainLink> links) {
this.links = links;
}
private GadgetChain(GadgetChain gadgetChain, GadgetChainLink link) {
List<GadgetChainLink> links = new ArrayList<GadgetChainLink>(gadgetChain.links);
links.add(link);
this.links = links;
}
}
private static class GadgetChainLink {
private final MethodReference.Handle method;
private final int taintedArgIndex;
private GadgetChainLink(MethodReference.Handle method, int taintedArgIndex) {
this.method = method;
this.taintedArgIndex = taintedArgIndex;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GadgetChainLink that = (GadgetChainLink) o;
if (taintedArgIndex != that.taintedArgIndex) {
return false;
}
return method != null ? method.equals(that.method) : that.method == null;
}
@Override
public int hashCode() {
int result = method != null ? method.hashCode() : 0;
result = 31 * result + taintedArgIndex;
return result;
}
}
/**
* Represents a collection of methods in the JDK that we consider to be "interesting". If a gadget
* chain can successfully exercise one of these, it could represent anything as mundade as causing
* the target to make a DNS query to full blown RCE.
*/
// TODO: Parameterize this as a configuration option
private boolean isSink(MethodReference.Handle method, int argIndex,
InheritanceMap inheritanceMap) {
if (!customSlinks.isEmpty()) {
for (CustomSlink customSlink:customSlinks) {
boolean flag = false;
if (customSlink.getClassName() != null)
flag &= customSlink.getClassName().equals(method.getClassReference().getName());
if (customSlink.getMethod() != null)
flag &= customSlink.getMethod().equals(method.getName());
if (customSlink.getDesc() != null)
flag &= customSlink.getDesc().equals(method.getDesc());
if (flag)
return flag;
}
return false;
}
if (config.getName().equals("sqlinject")) {
//SQLInject只能检测注入
return isSQLInjectSink(method, argIndex, inheritanceMap);
}
if (config.getName().equals("hessian")) {
//仅hessian可选BCEL slink
if (ConfigHelper.slinks.contains("BCEL") && BCELSlink(method, argIndex, inheritanceMap)) {
return true;
}
}
//通用slink,不设定slink则全部都挖掘
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("JNDI")) && JNDISlink(method, inheritanceMap)) {
return true;
}
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("CLASSLOADER")) && ClassLoaderlink(method, argIndex, inheritanceMap)) {
return true;
}
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("SSRFAndXXE")) && SSRFAndXXESlink(method, inheritanceMap)) {
return true;
}
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("EXEC")) && EXECSlink(method, argIndex)) {
return true;
}
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("FileIO")) && FileIOSlink(method)) {
return true;
}
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("Reflect")) && ReflectSlink(method, argIndex, inheritanceMap)) {
return true;
}
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("JDBC")) && JDBCSlink(method, argIndex, inheritanceMap)) {
return true;
}
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("EL")) && ELSlink(method, argIndex, inheritanceMap)) {
return true;
}
if ((ConfigHelper.slinks.isEmpty() || ConfigHelper.slinks.contains("SQLInject")) && isSQLInjectSink(method, argIndex, inheritanceMap)) {
return true;
}
return false;
}
private boolean JDBCSlink(Handle method, int argIndex, InheritanceMap inheritanceMap) {
if (method.getClassReference().getName().equals("javax/sql/DataSource")
&& method.getName().equals("getConnection")) {
return true;
}
return false;
}
private boolean ReflectSlink(Handle method, int argIndex, InheritanceMap inheritanceMap) {
if (method.getClassReference().getName().equals("java/lang/reflect/Method")
&& method.getName().equals("invoke") && argIndex == 0) {
return true;
}
if (method.getClassReference().getName().equals("java/net/URLClassLoader")
&& method.getName().equals("newInstance")) {
return true;
}
if (inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("java/lang/ClassLoader"))
&& method.getName().equals("<init>")) {
return true;
}
// Some groovy-specific sinks
if (method.getClassReference().getName().equals("org/codehaus/groovy/runtime/InvokerHelper")
&& method.getName().equals("invokeMethod") && argIndex == 1) {
return true;
}
if (inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("groovy/lang/MetaClass"))
&& Arrays.asList("invokeMethod", "invokeConstructor", "invokeStaticMethod")
.contains(method.getName())) {
return true;
}
return false;
}
private boolean FileIOSlink(Handle method) {
if (method.getClassReference().getName().equals("java/io/FileInputStream")
&& method.getName().equals("<init>")) {
return true;
}
if (method.getClassReference().getName().equals("java/io/FileOutputStream")
&& method.getName().equals("<init>")) {
return true;
}
if (method.getClassReference().getName().equals("java/nio/file/Files")
&& (method.getName().equals("newInputStream")
|| method.getName().equals("newOutputStream")
|| method.getName().equals("newBufferedReader")
|| method.getName().equals("newBufferedWriter"))) {
return true;
}
if (method.getClassReference().getName().equals("java/net/URL") && method.getName()
.equals("openStream")) {
return true;
}
return false;
}
private boolean dosSlink(Handle method) {
if (method.getClassReference().getName().equals("java/lang/System")
&& method.getName().equals("exit")) {
return true;
}
if (method.getClassReference().getName().equals("java/lang/Shutdown")
&& method.getName().equals("exit")) {
return true;
}
if (method.getClassReference().getName().equals("java/lang/Runtime")
&& method.getName().equals("exit")) {
return true;
}
return false;
}
private boolean EXECSlink(Handle method, int argIndex) {
if (method.getClassReference().getName().equals("java/lang/Runtime")
&& method.getName().equals("exec")) {
return true;
}
if (method.getClassReference().getName().equals("java/lang/ProcessBuilder")
&& method.getName().equals("<init>") && argIndex > 0) {
return true;
}
return false;
}
private boolean BCELSlink(Handle method, int argIndex, InheritanceMap inheritanceMap) {
if (method.getClassReference().getName().equals("java/lang/Class")
&& method.getName().equals("forName")
&& method.getDesc().equals("(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;")) {
return true;
}
return false;
}
private boolean isFastjsonSink(Handle method, int argIndex, InheritanceMap inheritanceMap) {
return false;
}
private boolean SSRFAndXXESlink(Handle method, InheritanceMap inheritanceMap) {
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/xml/parsers/DocumentBuilder"))
)
&& method.getName().equals("parse")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("org/jdom/input/SAXBuilder"))
)
&& method.getName().equals("build")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/xml/parsers/SAXParser"))
)
&& method.getName().equals("parse")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("org/dom4j/io/SAXReader"))
)
&& method.getName().equals("read")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/xml/transform/sax/SAXTransformerFactory"))
)
&& method.getName().equals("newTransformerHandler")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/xml/validation/SchemaFactory"))
)
&& method.getName().equals("newSchema")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/xml/transform/Transformer"))
)
&& method.getName().equals("transform")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/xml/bind/Unmarshaller"))
)
&& method.getName().equals("unmarshal")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/xml/validation/Validator"))
)
&& method.getName().equals("validate")) {
return true;
}
if ((
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("org/xml/sax/XMLReader"))
)
&& method.getName().equals("parse")) {
return true;
}
return false;
}
private boolean JNDISlink(Handle method, InheritanceMap inheritanceMap) {
if ((inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("java/rmi/registry/Registry")) ||
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/naming/Context")))
&& method.getName().equals("lookup")) {
return true;
}
return false;
}
private boolean ClassLoaderlink(Handle method, int argIndex, InheritanceMap inheritanceMap) {
if (
inheritanceMap.isSubclassOf(method.getClassReference(), new ClassReference.Handle("java/lang/ClassLoader")) &&
method.getName().equals("loadClass") &&
argIndex == 1
) {
return true;
}
return false;
}
private boolean ELSlink(Handle method, int argIndex, InheritanceMap inheritanceMap) {
if ((inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/validation/ConstraintValidatorContext")) ||
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("org/hibernate/validator/internal/engine/constraintvalidation/ConstraintValidatorContextImpl"))) &&
argIndex == 1 &&
method.getName().equals("buildConstraintViolationWithTemplate")) {
return true;
}
if ((inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("org/springframework/expression/ExpressionParser")) ||
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("org/springframework/expression/spel/standard/SpelExpressionParser"))) &&
argIndex == 1 &&
(method.getName().equals("parseExpression") || method.getName().equals("parseRaw"))) {
return true;
}
if ((inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/el/ELProcessor")) &&
argIndex == 1 && method.getName().equals("eval"))
||
inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("javax/el/ExpressionFactory")) &&
argIndex == 2 && method.getName().equals("createValueExpression")) {
return true;
}
return false;
}
private Map<ClassReference.Handle, Set<MethodReference>> slinksMapCache = null;
private boolean isSQLInjectSink(MethodReference.Handle method, int argIndex,
InheritanceMap inheritanceMap) {
if (config.getName().equals("sqlinject")) {
if (slinksMapCache == null) {
Map<ClassReference.Handle, Set<MethodReference>> slinksMap = DataLoader.loadSlinks();
slinksMapCache = slinksMap;
}
if (slinksMapCache.containsKey(method.getClassReference()) &&
slinksMapCache.get(method.getClassReference()).stream()
.filter(methodReference -> methodReference.equals(method)).count() > 0) {
return true;
}
}
if (inheritanceMap.isSubclassOf(method.getClassReference(),
new ClassReference.Handle("org/springframework/jdbc/core/StatementCallback")) &&
method.getName().equals("doInStatement")) {
return true;
}
return false;
}
public static void main(String[] args) throws Exception {
GadgetChainDiscovery gadgetChainDiscovery = new GadgetChainDiscovery(
new JavaDeserializationConfig());
gadgetChainDiscovery.discover(null);
}
}
| 23,524 | 0.647059 | 0.645427 | 632 | 35.851265 | 30.988207 | 151 | false | false | 0 | 0 | 0 | 0 | 91 | 0.006698 | 0.536392 | false | false | 0 |
61c7299a61e453952e237604d732062d77fafd97 | 16,698,832,908,718 | 2754fed04a383ad9572e0fa0efb3594d3e48e1c9 | /src/com/neuedu/java05/Person.java | 265d27ac7033beca2c034c3f8136fbb64902fe9e | []
| no_license | liuhoueryu/TestJava | https://github.com/liuhoueryu/TestJava | 4c3b46205f6de4be4dd5cc3d6aab68d523880133 | 52129256311ff488fe940bb7c6c05df9026968c9 | refs/heads/master | 2020-04-27T07:38:42.267000 | 2019-03-06T12:45:40 | 2019-03-06T12:45:40 | 174,142,663 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.neuedu.java05;
public class Person {
//成员变量有默认值 int是0 引用变量为null
//属性私有化 实例变量 instance
private String name = "人";
private String gender = "男";
private int age = 10;
//静态属性
public static int count;
//构造块
{
System.out.println("构造块。。。。");
}
//静态块
static{
System.out.println("静态块。。。。");
}
//提供公有的getter/setter...
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
//数据检查
//if(gender.equals("男") || gender.equals("女")){
if("男".equals(gender)|| "女".equals(gender)){ //字符串常量调用equals方法不会抛出空指针异常
this.gender = gender;
}else{
this.gender = "保密";
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
//数据检查
if(age>=20 & age<=60){
this.age = age;
}else{
this.age = 20; //默认处理
}
}
//输出对象的内容
public void show(){
System.out.println("name=" + this.name + " gender=" + this.gender + " age=" + this.age);
}
//重写toString()
//@Override
//public String toString() {
// return "name=" + this.name + " gender=" + this.gender + " age=" + this.age;
//}
@Override
public String toString() {
return "Person [name=" + name + ", gender=" + gender + ", age=" + age + "]";
}
//无参的构造方法
public Person(){
//System.out.println("无参的构造方法。。。。");
//this.name = "王五";
//this.gender="女";
//this.age=30;
}
//三个参的构造方法
public Person(String name, String gender, int age){
this(name, gender);
System.out.println("三个参的构造方法。。。。");
//this.name = name;
//this.gender = gender;
this.age = age;
count++;
}
//一个参的构造方法
public Person(String name){
System.out.println("一个参的构造方法。。。。");
this.name = name;
}
//两个参的构造方法
public Person(String name, String gender){
this(name);
System.out.println("两个参的构造方法。。。。");
//this.name = name;
this.gender = gender;
}
public static int getCount(){
return count;
}
}
| GB18030 | Java | 2,551 | java | Person.java | Java | [
{
"context": "/属性私有化 实例变量 instance\r\n\tprivate String name = \"人\";\r\n private String gender = \"男\";\r\n private ",
"end": 144,
"score": 0.9931542873382568,
"start": 143,
"tag": "NAME",
"value": "人"
},
{
"context": "tem.out.println(\"无参的构造方法。。。。\");\r\n\t\t//this.name = \"王五\";\r\n\t\t//this.gender=\"女\";\r\n\t\t//this.age=30;\t\t\r\n\t}\r\n",
"end": 1578,
"score": 0.998597264289856,
"start": 1576,
"tag": "NAME",
"value": "王五"
}
]
| null | []
| package com.neuedu.java05;
public class Person {
//成员变量有默认值 int是0 引用变量为null
//属性私有化 实例变量 instance
private String name = "人";
private String gender = "男";
private int age = 10;
//静态属性
public static int count;
//构造块
{
System.out.println("构造块。。。。");
}
//静态块
static{
System.out.println("静态块。。。。");
}
//提供公有的getter/setter...
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
//数据检查
//if(gender.equals("男") || gender.equals("女")){
if("男".equals(gender)|| "女".equals(gender)){ //字符串常量调用equals方法不会抛出空指针异常
this.gender = gender;
}else{
this.gender = "保密";
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
//数据检查
if(age>=20 & age<=60){
this.age = age;
}else{
this.age = 20; //默认处理
}
}
//输出对象的内容
public void show(){
System.out.println("name=" + this.name + " gender=" + this.gender + " age=" + this.age);
}
//重写toString()
//@Override
//public String toString() {
// return "name=" + this.name + " gender=" + this.gender + " age=" + this.age;
//}
@Override
public String toString() {
return "Person [name=" + name + ", gender=" + gender + ", age=" + age + "]";
}
//无参的构造方法
public Person(){
//System.out.println("无参的构造方法。。。。");
//this.name = "王五";
//this.gender="女";
//this.age=30;
}
//三个参的构造方法
public Person(String name, String gender, int age){
this(name, gender);
System.out.println("三个参的构造方法。。。。");
//this.name = name;
//this.gender = gender;
this.age = age;
count++;
}
//一个参的构造方法
public Person(String name){
System.out.println("一个参的构造方法。。。。");
this.name = name;
}
//两个参的构造方法
public Person(String name, String gender){
this(name);
System.out.println("两个参的构造方法。。。。");
//this.name = name;
this.gender = gender;
}
public static int getCount(){
return count;
}
}
| 2,551 | 0.540849 | 0.534916 | 121 | 16.107437 | 17.378054 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.487603 | false | false | 0 |
fa356a808dfe6e09a35d381c1db48b97378e9420 | 15,968,688,406,739 | a60b2073cb988de9e4769fa596ba00c91d514b9c | /app/src/main/java/com/atar/activitys/htmls/AtarCommonWebViewPagerActivity.java | 9ad4b28f7a5856351bb788de774336ac8830a98a | []
| no_license | wgllss/Android-Atar-AS | https://github.com/wgllss/Android-Atar-AS | da9d694834e0acc0439353ada66fa6f4224605ec | 5540446d7da2421d75d21db29147b381a3d95236 | refs/heads/master | 2018-10-29T23:21:32.602000 | 2018-09-05T03:08:22 | 2018-09-05T03:08:22 | 105,000,968 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package com.atar.activitys.htmls;
import android.adapter.FragmentAdapter;
import android.fragment.CommonFragment;
import android.graphics.Color;
import android.os.Bundle;
import android.skin.SkinUtils;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import com.atar.activitys.AtarDropTitleBarActivity;
import com.atar.activitys.R;
import com.atar.adapters.MenuAdapter;
import com.atar.config.HtmlsViewPagerJson;
import com.atar.config.TabMenuItemBean;
import com.atar.fragment.htmls.AtarDynamicFragment;
import com.atar.weex.utils.WeexUtils;
import com.atar.widgets.PagerSlidingTabStrip;
import java.util.ArrayList;
import java.util.List;
/**
* ****************************************************************************************************************************************************************************
* 动态fragment配置activity
*
* @author :Atar
* @createTime:2017-7-24下午5:30:13
* @version:1.0.0
* @modifyTime:
* @modifyAuthor:
* @description: ****************************************************************************************************************************************************************************
*/
public class AtarCommonWebViewPagerActivity extends AtarDropTitleBarActivity implements OnPageChangeListener {
private boolean isExtendsAtarCommonWebViewPagerActivity = true;
protected List<TabMenuItemBean> listMenu = new ArrayList<TabMenuItemBean>();
protected MenuAdapter mMenuAdapter = new MenuAdapter(listMenu);
protected PagerSlidingTabStrip tabs;
protected ViewPager mViewPager;
private List<Fragment> mFragmentList = new ArrayList<Fragment>();
private FragmentAdapter mFragmentPagerAdapter;
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
if (isExtendsAtarCommonWebViewPagerActivity) {
addContentView(R.layout.activity_webview_pager);
}
}
@Override
protected void initControl() {
if (isExtendsAtarCommonWebViewPagerActivity) {
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
}
}
@Override
public void onPageSelected(int arg0) {
if (mMenuAdapter != null) {
mMenuAdapter.setCurrentPostiotn(arg0);
if (tabs != null) {
tabs.notifyDataSetChanged();
}
}
try {
((AtarDynamicFragment) getFragmentList().get(getCurrentItem())).loadWebViewUrl("javascript:onPageSelected('" + arg0 + "')");
} catch (Exception e) {
}
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
public void setExtendsAtarCommonWebViewPagerActivity(boolean isExtendsAtarCommonWebViewPagerActivity) {
this.isExtendsAtarCommonWebViewPagerActivity = isExtendsAtarCommonWebViewPagerActivity;
}
protected void setViewPagerAdapter() {
if (mViewPager != null && getFragmentList() != null && getSupportFragmentManager() != null) {
getFragmentList().get(0).setUserVisibleHint(true);
mFragmentPagerAdapter = new FragmentAdapter(getSupportFragmentManager(), getFragmentList());
mFragmentPagerAdapter.notifyDataSetChanged();
mViewPager.setAdapter(mFragmentPagerAdapter);
mViewPager.setOffscreenPageLimit(getFragmentList().size() > 5 ? 5 : getFragmentList().size());
}
}
/**
* 初始化PagerSlidingTabStrip类容
*
* @author :Atar
* @createTime:2017-7-24下午5:45:11
* @version:1.0.0
* @modifyTime:
* @modifyAuthor:
* @description:
*/
protected void initPagerFragmentVualue(HtmlsViewPagerJson mHtmlsViewPagerJson) {
if (mHtmlsViewPagerJson != null) {
/* 标题start */
if (mHtmlsViewPagerJson.getTITLE() != null && mHtmlsViewPagerJson.getTITLE().length() > 0) {
setActivityTitle(mHtmlsViewPagerJson.getTITLE());
} else {
setTitleBarGone();
}
/* 标题end */
/* 顶部右边部分处理start */
String top_right_img_url = mHtmlsViewPagerJson.getTOP_RIGHT_IMG_URL();
String top_right_txt = mHtmlsViewPagerJson.getTOP_RIGHT_TXT();
if (top_right_txt != null && top_right_txt.length() > 0) {
setTopRightText(top_right_txt);
}
if (top_right_img_url != null && top_right_img_url.length() > 0 && imgCommonTopRight != null) {
imgCommonTopRight.setVisibility(View.VISIBLE);
LoadImageView(top_right_img_url, imgCommonTopRight, 0);
}
/* 顶部右边部分处理end */
listMenu.clear();
for (TabMenuItemBean mTabMenuItemBean : mHtmlsViewPagerJson.getListFragment()) {
listMenu.add(mTabMenuItemBean);
setDynamicFragment(mTabMenuItemBean);
}
getFragmentList().get(0).setUserVisibleHint(true);
mFragmentPagerAdapter = new FragmentAdapter(getSupportFragmentManager(), getFragmentList());
mFragmentPagerAdapter.notifyDataSetChanged();
mViewPager.setAdapter(mFragmentPagerAdapter);
mMenuAdapter.setWebViewPagerActivityTop(true);
mMenuAdapter.setContext(this);
mMenuAdapter.setSkinType(getCurrentSkinType());
tabs.setShouldExpand(mHtmlsViewPagerJson.isShouldExpand());
mMenuAdapter.setCondition(mHtmlsViewPagerJson.isShouldExpand() ? 1 : 0);
if (mHtmlsViewPagerJson.getIndicatorColor() != null && mHtmlsViewPagerJson.getIndicatorColor().length() > 0 && mHtmlsViewPagerJson.getIndicatorColor().contains(",")) {
String[] IndicatorColor = mHtmlsViewPagerJson.getIndicatorColor().split(",");
if (IndicatorColor != null && IndicatorColor.length > 0) {
tabs.setIndicatorColor(Color.parseColor(IndicatorColor[getCurrentSkinType()]));
}
}
if (mHtmlsViewPagerJson.getUnderlineColor() != null && mHtmlsViewPagerJson.getUnderlineColor().length() > 0 && mHtmlsViewPagerJson.getUnderlineColor().contains(",")) {
String[] UnderlineColor = mHtmlsViewPagerJson.getUnderlineColor().split(",");
if (UnderlineColor != null && UnderlineColor.length > 0) {
tabs.setUnderlineColor(Color.parseColor(UnderlineColor[getCurrentSkinType()]));
}
}
tabs.setAdapter(mMenuAdapter, mHtmlsViewPagerJson.isShowDividerLine());
tabs.setViewPager(mViewPager);
mViewPager.setOffscreenPageLimit(getFragmentList().size());
tabs.setOnPageChangeListener(this);
setCurrentItem(0, true);
}
}
/**
* 设置动态fragment
*
* @param mTabMenuItemBean
* @author :Atar
* @createTime:2017-7-24下午5:53:09
* @version:1.0.0
* @modifyTime:
* @modifyAuthor:
* @description:
*/
protected void setDynamicFragment(TabMenuItemBean mTabMenuItemBean) {
if (mTabMenuItemBean.getOnClickInfo() != null) {
String url = mTabMenuItemBean.getOnClickInfo().getClassName();
if (url != null && url.length() > 0 && url.contains("assets/html") && !url.contains("http")) {
url = WeexUtils.WEEX_HOST + url;
mFragmentList.add(AtarDynamicFragment.newInstance(mTabMenuItemBean.getOnClickInfo().getOptionJson(), mTabMenuItemBean.getOnClickInfo().getPULL_TO_REFRESH_MODE(), url));
}
}
}
protected void addFragmentToList(Fragment mFragment) {
mFragmentList.add(mFragment);
}
public int getCurrentItem() {
return mViewPager != null ? mViewPager.getCurrentItem() : 0;
}
public List<Fragment> getFragmentList() {
return mFragmentList;
}
public void setCurrentItem(int position, boolean smoothScroll) {
if (mMenuAdapter != null) {
mMenuAdapter.setCurrentPostiotn(position);
if (tabs != null) {
tabs.notifyDataSetChanged();
}
}
if (mViewPager != null) {
if (position < mFragmentList.size()) {
mViewPager.setCurrentItem(position, smoothScroll);
}
}
}
@Override
public void setActivityTitle(String strTitile) {
super.setActivityTitle(strTitile);
}
/**
* 设置小红点数字
*/
public void setNewInfoNum(int position, int num) {
if (listMenu != null && listMenu.size() > position) {
listMenu.get(position).setInfoNum(num);
if (mMenuAdapter != null) {
mMenuAdapter.notifyDataSetChanged();
if (tabs != null) {
tabs.notifyDataSetChanged();
}
}
}
}
/**
* webview 中 swiper和viewpager 冲突解决
*
* @param disallowIntercept:1:只触发swiper 滑动事件, 0,触发原生viewpager事件
* @author :Atar
* @createTime:2017-10-31上午10:18:06
* @version:1.0.0
* @modifyTime:
* @modifyAuthor: Atar
* @description:
*/
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
if (mViewPager != null) {
mViewPager.requestDisallowInterceptTouchEvent(disallowIntercept);
}
}
@Override
public void ChangeSkin(int skinType) {
super.ChangeSkin(skinType);
// LoadUtil.setBackgroundColor(this, R.array.common_tab_bg_color, skinType, tabs);
if (tabs != null) {
tabs.setIndicatorColor(SkinUtils.getArrayColor(this, R.string.common_tab_line_move_color, skinType));
}
if (tabs != null) {
if (mMenuAdapter != null) {
mMenuAdapter.setSkinType(skinType);
}
tabs.notifyDataSetChanged();
}
if (getFragmentList() != null && getFragmentList().size() > 0) {
for (Fragment fragment : getFragmentList()) {
if (fragment instanceof CommonFragment) {
((CommonFragment) fragment).ChangeSkin(skinType);
}
}
}
}
}
| UTF-8 | Java | 10,532 | java | AtarCommonWebViewPagerActivity.java | Java | [
{
"context": "**********\n * 动态fragment配置activity\n *\n * @author :Atar\n * @createTime:2017-7-24下午5:30:13\n * @version:1.0",
"end": 1000,
"score": 0.9520158171653748,
"start": 996,
"tag": "NAME",
"value": "Atar"
},
{
"context": " 初始化PagerSlidingTabStrip类容\n *\n * @author :Atar\n * @createTime:2017-7-24下午5:45:11\n * @ver",
"end": 3727,
"score": 0.788009524345398,
"start": 3723,
"tag": "NAME",
"value": "Atar"
},
{
"context": " *\n * @param mTabMenuItemBean\n * @author :Atar\n * @createTime:2017-7-24下午5:53:09\n * @ver",
"end": 7080,
"score": 0.9993678331375122,
"start": 7076,
"tag": "NAME",
"value": "Atar"
},
{
"context": "只触发swiper 滑动事件, 0,触发原生viewpager事件\n * @author :Atar\n * @createTime:2017-10-31上午10:18:06\n * @v",
"end": 9217,
"score": 0.9965118765830994,
"start": 9213,
"tag": "NAME",
"value": "Atar"
},
{
"context": "on:1.0.0\n * @modifyTime:\n * @modifyAuthor: Atar\n * @description:\n */\n public void requ",
"end": 9326,
"score": 0.9942003488540649,
"start": 9322,
"tag": "NAME",
"value": "Atar"
}
]
| null | []
| /**
*
*/
package com.atar.activitys.htmls;
import android.adapter.FragmentAdapter;
import android.fragment.CommonFragment;
import android.graphics.Color;
import android.os.Bundle;
import android.skin.SkinUtils;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import com.atar.activitys.AtarDropTitleBarActivity;
import com.atar.activitys.R;
import com.atar.adapters.MenuAdapter;
import com.atar.config.HtmlsViewPagerJson;
import com.atar.config.TabMenuItemBean;
import com.atar.fragment.htmls.AtarDynamicFragment;
import com.atar.weex.utils.WeexUtils;
import com.atar.widgets.PagerSlidingTabStrip;
import java.util.ArrayList;
import java.util.List;
/**
* ****************************************************************************************************************************************************************************
* 动态fragment配置activity
*
* @author :Atar
* @createTime:2017-7-24下午5:30:13
* @version:1.0.0
* @modifyTime:
* @modifyAuthor:
* @description: ****************************************************************************************************************************************************************************
*/
public class AtarCommonWebViewPagerActivity extends AtarDropTitleBarActivity implements OnPageChangeListener {
private boolean isExtendsAtarCommonWebViewPagerActivity = true;
protected List<TabMenuItemBean> listMenu = new ArrayList<TabMenuItemBean>();
protected MenuAdapter mMenuAdapter = new MenuAdapter(listMenu);
protected PagerSlidingTabStrip tabs;
protected ViewPager mViewPager;
private List<Fragment> mFragmentList = new ArrayList<Fragment>();
private FragmentAdapter mFragmentPagerAdapter;
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
if (isExtendsAtarCommonWebViewPagerActivity) {
addContentView(R.layout.activity_webview_pager);
}
}
@Override
protected void initControl() {
if (isExtendsAtarCommonWebViewPagerActivity) {
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
}
}
@Override
public void onPageSelected(int arg0) {
if (mMenuAdapter != null) {
mMenuAdapter.setCurrentPostiotn(arg0);
if (tabs != null) {
tabs.notifyDataSetChanged();
}
}
try {
((AtarDynamicFragment) getFragmentList().get(getCurrentItem())).loadWebViewUrl("javascript:onPageSelected('" + arg0 + "')");
} catch (Exception e) {
}
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
public void setExtendsAtarCommonWebViewPagerActivity(boolean isExtendsAtarCommonWebViewPagerActivity) {
this.isExtendsAtarCommonWebViewPagerActivity = isExtendsAtarCommonWebViewPagerActivity;
}
protected void setViewPagerAdapter() {
if (mViewPager != null && getFragmentList() != null && getSupportFragmentManager() != null) {
getFragmentList().get(0).setUserVisibleHint(true);
mFragmentPagerAdapter = new FragmentAdapter(getSupportFragmentManager(), getFragmentList());
mFragmentPagerAdapter.notifyDataSetChanged();
mViewPager.setAdapter(mFragmentPagerAdapter);
mViewPager.setOffscreenPageLimit(getFragmentList().size() > 5 ? 5 : getFragmentList().size());
}
}
/**
* 初始化PagerSlidingTabStrip类容
*
* @author :Atar
* @createTime:2017-7-24下午5:45:11
* @version:1.0.0
* @modifyTime:
* @modifyAuthor:
* @description:
*/
protected void initPagerFragmentVualue(HtmlsViewPagerJson mHtmlsViewPagerJson) {
if (mHtmlsViewPagerJson != null) {
/* 标题start */
if (mHtmlsViewPagerJson.getTITLE() != null && mHtmlsViewPagerJson.getTITLE().length() > 0) {
setActivityTitle(mHtmlsViewPagerJson.getTITLE());
} else {
setTitleBarGone();
}
/* 标题end */
/* 顶部右边部分处理start */
String top_right_img_url = mHtmlsViewPagerJson.getTOP_RIGHT_IMG_URL();
String top_right_txt = mHtmlsViewPagerJson.getTOP_RIGHT_TXT();
if (top_right_txt != null && top_right_txt.length() > 0) {
setTopRightText(top_right_txt);
}
if (top_right_img_url != null && top_right_img_url.length() > 0 && imgCommonTopRight != null) {
imgCommonTopRight.setVisibility(View.VISIBLE);
LoadImageView(top_right_img_url, imgCommonTopRight, 0);
}
/* 顶部右边部分处理end */
listMenu.clear();
for (TabMenuItemBean mTabMenuItemBean : mHtmlsViewPagerJson.getListFragment()) {
listMenu.add(mTabMenuItemBean);
setDynamicFragment(mTabMenuItemBean);
}
getFragmentList().get(0).setUserVisibleHint(true);
mFragmentPagerAdapter = new FragmentAdapter(getSupportFragmentManager(), getFragmentList());
mFragmentPagerAdapter.notifyDataSetChanged();
mViewPager.setAdapter(mFragmentPagerAdapter);
mMenuAdapter.setWebViewPagerActivityTop(true);
mMenuAdapter.setContext(this);
mMenuAdapter.setSkinType(getCurrentSkinType());
tabs.setShouldExpand(mHtmlsViewPagerJson.isShouldExpand());
mMenuAdapter.setCondition(mHtmlsViewPagerJson.isShouldExpand() ? 1 : 0);
if (mHtmlsViewPagerJson.getIndicatorColor() != null && mHtmlsViewPagerJson.getIndicatorColor().length() > 0 && mHtmlsViewPagerJson.getIndicatorColor().contains(",")) {
String[] IndicatorColor = mHtmlsViewPagerJson.getIndicatorColor().split(",");
if (IndicatorColor != null && IndicatorColor.length > 0) {
tabs.setIndicatorColor(Color.parseColor(IndicatorColor[getCurrentSkinType()]));
}
}
if (mHtmlsViewPagerJson.getUnderlineColor() != null && mHtmlsViewPagerJson.getUnderlineColor().length() > 0 && mHtmlsViewPagerJson.getUnderlineColor().contains(",")) {
String[] UnderlineColor = mHtmlsViewPagerJson.getUnderlineColor().split(",");
if (UnderlineColor != null && UnderlineColor.length > 0) {
tabs.setUnderlineColor(Color.parseColor(UnderlineColor[getCurrentSkinType()]));
}
}
tabs.setAdapter(mMenuAdapter, mHtmlsViewPagerJson.isShowDividerLine());
tabs.setViewPager(mViewPager);
mViewPager.setOffscreenPageLimit(getFragmentList().size());
tabs.setOnPageChangeListener(this);
setCurrentItem(0, true);
}
}
/**
* 设置动态fragment
*
* @param mTabMenuItemBean
* @author :Atar
* @createTime:2017-7-24下午5:53:09
* @version:1.0.0
* @modifyTime:
* @modifyAuthor:
* @description:
*/
protected void setDynamicFragment(TabMenuItemBean mTabMenuItemBean) {
if (mTabMenuItemBean.getOnClickInfo() != null) {
String url = mTabMenuItemBean.getOnClickInfo().getClassName();
if (url != null && url.length() > 0 && url.contains("assets/html") && !url.contains("http")) {
url = WeexUtils.WEEX_HOST + url;
mFragmentList.add(AtarDynamicFragment.newInstance(mTabMenuItemBean.getOnClickInfo().getOptionJson(), mTabMenuItemBean.getOnClickInfo().getPULL_TO_REFRESH_MODE(), url));
}
}
}
protected void addFragmentToList(Fragment mFragment) {
mFragmentList.add(mFragment);
}
public int getCurrentItem() {
return mViewPager != null ? mViewPager.getCurrentItem() : 0;
}
public List<Fragment> getFragmentList() {
return mFragmentList;
}
public void setCurrentItem(int position, boolean smoothScroll) {
if (mMenuAdapter != null) {
mMenuAdapter.setCurrentPostiotn(position);
if (tabs != null) {
tabs.notifyDataSetChanged();
}
}
if (mViewPager != null) {
if (position < mFragmentList.size()) {
mViewPager.setCurrentItem(position, smoothScroll);
}
}
}
@Override
public void setActivityTitle(String strTitile) {
super.setActivityTitle(strTitile);
}
/**
* 设置小红点数字
*/
public void setNewInfoNum(int position, int num) {
if (listMenu != null && listMenu.size() > position) {
listMenu.get(position).setInfoNum(num);
if (mMenuAdapter != null) {
mMenuAdapter.notifyDataSetChanged();
if (tabs != null) {
tabs.notifyDataSetChanged();
}
}
}
}
/**
* webview 中 swiper和viewpager 冲突解决
*
* @param disallowIntercept:1:只触发swiper 滑动事件, 0,触发原生viewpager事件
* @author :Atar
* @createTime:2017-10-31上午10:18:06
* @version:1.0.0
* @modifyTime:
* @modifyAuthor: Atar
* @description:
*/
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
if (mViewPager != null) {
mViewPager.requestDisallowInterceptTouchEvent(disallowIntercept);
}
}
@Override
public void ChangeSkin(int skinType) {
super.ChangeSkin(skinType);
// LoadUtil.setBackgroundColor(this, R.array.common_tab_bg_color, skinType, tabs);
if (tabs != null) {
tabs.setIndicatorColor(SkinUtils.getArrayColor(this, R.string.common_tab_line_move_color, skinType));
}
if (tabs != null) {
if (mMenuAdapter != null) {
mMenuAdapter.setSkinType(skinType);
}
tabs.notifyDataSetChanged();
}
if (getFragmentList() != null && getFragmentList().size() > 0) {
for (Fragment fragment : getFragmentList()) {
if (fragment instanceof CommonFragment) {
((CommonFragment) fragment).ChangeSkin(skinType);
}
}
}
}
}
| 10,532 | 0.608792 | 0.599942 | 273 | 37.080585 | 35.193771 | 189 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.406593 | false | false | 0 |
166dcec816f28231f6ca43ea9a3139f8bf62c395 | 2,370,822,018,635 | ec2e5e1e70179340c49957c22f5dd1b419e68678 | /src/com/westlakestudent/util/WestlakestudentToast.java | c1c64c025115d104d83516b8b32d8f0f7575262c | []
| no_license | westlakestudent/PicWestlakestudent | https://github.com/westlakestudent/PicWestlakestudent | c28f54b88e2c668709bc822ccabb688c8459bb8a | 4fd3898c46117d9452c51ca220a16906d5b78d77 | refs/heads/master | 2021-01-10T19:41:56.013000 | 2014-12-01T06:45:41 | 2014-12-01T06:45:41 | 26,916,113 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.westlakestudent.util;
import android.content.Context;
import android.widget.Toast;
/**
*
* WestlakestudentToast
* @author chendong
* 2014年11月26日 下午5:30:01
* @version 1.0.0
*
*/
public class WestlakestudentToast {
public static void toast(Context context,String msg){
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
}
| UTF-8 | Java | 364 | java | WestlakestudentToast.java | Java | [
{
"context": ".Toast;\n\n/**\n *\n * WestlakestudentToast\n * @author chendong\n * 2014年11月26日 下午5:30:01\n * @version 1.0.0\n *\n */",
"end": 147,
"score": 0.9995842576026917,
"start": 139,
"tag": "USERNAME",
"value": "chendong"
}
]
| null | []
| package com.westlakestudent.util;
import android.content.Context;
import android.widget.Toast;
/**
*
* WestlakestudentToast
* @author chendong
* 2014年11月26日 下午5:30:01
* @version 1.0.0
*
*/
public class WestlakestudentToast {
public static void toast(Context context,String msg){
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
}
| 364 | 0.734463 | 0.689266 | 19 | 17.631578 | 18.091028 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578947 | false | false | 0 |
422a5bfa6478b187d7cfe4b8e811f4e24177f9b8 | 29,953,101,942,564 | 23fb3f1eaafb83a6992a24af871adf4da06f3173 | /src/day_eleven/StudentTest.java | 4a617f7c513969d11de953237d75c4a1048ff63d | []
| no_license | Glsearl/Base | https://github.com/Glsearl/Base | 6f5e61795bb036013def24875d5c83b63eca7e2f | f5cec5a360f5579dd7ff15a3917503e7bf387f7e | refs/heads/master | 2020-04-08T14:52:40.691000 | 2019-08-28T03:04:15 | 2019-08-28T03:04:15 | 144,803,384 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day_eleven;
public class StudentTest {
public static void main(String[] args) throws CloneNotSupportedException {
Student s = new Student("张三", 25);
Student s1 = new Student("李四", 25);
System.out.println(s.hashCode());
System.out.println(s.getClass());
System.out.println(s.equals(s1));
System.out.println(s.toString());
System.out.println("-----------------");
Student s2= (Student) s1.clone();
System.out.println(s1.equals(s2));
System.out.println(s2);
System.out.println("-----------------");
s1.setAge(90);
s1.setName("王二");
System.out.println(s1);
System.out.println(s2);
}
}
| UTF-8 | Java | 733 | java | StudentTest.java | Java | [
{
"context": "ortedException {\n Student s = new Student(\"张三\", 25);\n Student s1 = new Student(\"李四\", 25)",
"end": 162,
"score": 0.9997107982635498,
"start": 160,
"tag": "NAME",
"value": "张三"
},
{
"context": "dent(\"张三\", 25);\n Student s1 = new Student(\"李四\", 25);\n System.out.println(s.hashCode());\n",
"end": 206,
"score": 0.999774694442749,
"start": 204,
"tag": "NAME",
"value": "李四"
},
{
"context": "---\");\n s1.setAge(90);\n s1.setName(\"王二\");\n System.out.println(s1);\n System",
"end": 642,
"score": 0.9997612833976746,
"start": 640,
"tag": "NAME",
"value": "王二"
}
]
| null | []
| package day_eleven;
public class StudentTest {
public static void main(String[] args) throws CloneNotSupportedException {
Student s = new Student("张三", 25);
Student s1 = new Student("李四", 25);
System.out.println(s.hashCode());
System.out.println(s.getClass());
System.out.println(s.equals(s1));
System.out.println(s.toString());
System.out.println("-----------------");
Student s2= (Student) s1.clone();
System.out.println(s1.equals(s2));
System.out.println(s2);
System.out.println("-----------------");
s1.setAge(90);
s1.setName("王二");
System.out.println(s1);
System.out.println(s2);
}
}
| 733 | 0.556172 | 0.532594 | 24 | 29.041666 | 19.671213 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 0 |
4e0b360b184959f4f95691e5b248e0b960ab60a3 | 3,564,822,858,315 | 2de87e95d9cd5aa08bd0ad1a5097516075eb88ae | /LocatorStrategies/src/Alerts.java | 6c4d65def8211b72b9bf5ebc47114aa8f108d08c | []
| no_license | irvingsoto/Automated-Testing | https://github.com/irvingsoto/Automated-Testing | e3d83c1b40d7e4f163bd19d2d9d1c68972e8071f | d95224ad6cb0bd2bc819b33fa8ae0b23ee049de4 | refs/heads/master | 2020-07-20T07:03:41.898000 | 2020-06-20T18:38:50 | 2020-06-20T18:38:50 | 206,595,119 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Alerts {
public static void main(String[] args) {
final TestData data = TestData.TEST_01;
//Initialize Driver
String path = "C:\\Users\\isoto\\Downloads\\chromedriver_win32\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver",path);
WebDriver driver = new ChromeDriver();
//Step 1.- Open app
System.out.println("Step 1.- Open app");
driver.manage().window().maximize();
driver.get(data.getUrl());
driver.findElement(By.linkText("JavaScript Alerts")).click();
//driver.findElement(By.xpath("//*[@id=\"content\"]/div/ul/li[1]/button")).click();
//driver.switchTo().alert().accept();
//driver.findElement(By.xpath("//*[@id=\"content\"]/div/ul/li[2]/button")).click();
//driver.switchTo().alert().dismiss();
driver.findElement(By.xpath("//*[@id=\"content\"]/div/ul/li[3]/button")).click();
driver.switchTo().alert().sendKeys(data.getInput());
driver.switchTo().alert().accept();
driver.quit();
}
}
| UTF-8 | Java | 1,245 | java | Alerts.java | Java | [
{
"context": "alize Driver\r\n String path = \"C:\\\\Users\\\\isoto\\\\Downloads\\\\chromedriver_win32\\\\chromedriver.exe\"",
"end": 318,
"score": 0.5034570693969727,
"start": 315,
"tag": "USERNAME",
"value": "oto"
}
]
| null | []
| import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Alerts {
public static void main(String[] args) {
final TestData data = TestData.TEST_01;
//Initialize Driver
String path = "C:\\Users\\isoto\\Downloads\\chromedriver_win32\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver",path);
WebDriver driver = new ChromeDriver();
//Step 1.- Open app
System.out.println("Step 1.- Open app");
driver.manage().window().maximize();
driver.get(data.getUrl());
driver.findElement(By.linkText("JavaScript Alerts")).click();
//driver.findElement(By.xpath("//*[@id=\"content\"]/div/ul/li[1]/button")).click();
//driver.switchTo().alert().accept();
//driver.findElement(By.xpath("//*[@id=\"content\"]/div/ul/li[2]/button")).click();
//driver.switchTo().alert().dismiss();
driver.findElement(By.xpath("//*[@id=\"content\"]/div/ul/li[3]/button")).click();
driver.switchTo().alert().sendKeys(data.getInput());
driver.switchTo().alert().accept();
driver.quit();
}
}
| 1,245 | 0.594378 | 0.587149 | 38 | 30.710526 | 29.533129 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526316 | false | false | 0 |
78f0ce03eae8846d557cc91d7e4e883a4fc15d31 | 7,842,610,299,367 | 847c23823fa6f672422fe2b8e1fe958927535921 | /src/main/java/lyr/testbot/modules/guild/BadGuildModule.java | 09e69e9b1c94bea5fde24b32fdc09ad7465de0f5 | []
| no_license | Lyrth/DiscordBot-Test | https://github.com/Lyrth/DiscordBot-Test | 1e557c5a1cb4b139ab355bb42bdf0b23671c50c7 | 634f9c18d762cb3c12dde220eec0a33c418b02ca | refs/heads/master | 2022-05-29T04:29:31.263000 | 2022-05-23T15:14:48 | 2022-05-23T15:14:48 | 151,794,415 | 0 | 0 | null | false | 2022-05-20T20:53:20 | 2018-10-06T01:28:52 | 2021-06-07T15:27:06 | 2022-05-20T20:53:20 | 232 | 0 | 0 | 1 | Java | false | false | package lyr.testbot.modules.guild;
import lyr.testbot.annotations.ModuleInfo;
import lyr.testbot.templates.GuildModule;
@ModuleInfo(
desc = "This shouldn't exist."
)
public class BadGuildModule extends GuildModule {
}
| UTF-8 | Java | 225 | java | BadGuildModule.java | Java | []
| null | []
| package lyr.testbot.modules.guild;
import lyr.testbot.annotations.ModuleInfo;
import lyr.testbot.templates.GuildModule;
@ModuleInfo(
desc = "This shouldn't exist."
)
public class BadGuildModule extends GuildModule {
}
| 225 | 0.782222 | 0.782222 | 11 | 19.454546 | 19.401798 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 0 |
f9f70b17f1e4c19b849ca834550fc814f03e354b | 1,477,468,773,298 | fb8b69c51cc95a342e27b3999dd5aa42a59aff73 | /src/main/java/com/softengzone/api/wid/entities/note/NoteRepository.java | e310a9ed6089eb2bbe716de9f53846f94da3613b | [
"MIT"
]
| permissive | softengzone/write-it-down | https://github.com/softengzone/write-it-down | b88c2b571b9f876601c393b861f1f99b49560d8a | 715fb375fdc48fb79877872f99ede5f4986fde1c | refs/heads/master | 2020-03-10T02:13:27.645000 | 2018-05-14T16:07:54 | 2018-05-14T16:07:54 | 129,131,030 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.softengzone.api.wid.entities.note;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface NoteRepository extends JpaRepository<Note, Long> {
@Query("select n from #{#entityName} n where n.subject like %?1%")
List<Note> findAllBySubjectLike(String subject);
@Query("select n from #{#entityName} n where n.subject like %?1% or n.tag like %?1% or n.body like %?1%")
List<Note> findAllByKeyword(String keyword);
}
| UTF-8 | Java | 551 | java | NoteRepository.java | Java | []
| null | []
| package com.softengzone.api.wid.entities.note;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface NoteRepository extends JpaRepository<Note, Long> {
@Query("select n from #{#entityName} n where n.subject like %?1%")
List<Note> findAllBySubjectLike(String subject);
@Query("select n from #{#entityName} n where n.subject like %?1% or n.tag like %?1% or n.body like %?1%")
List<Note> findAllByKeyword(String keyword);
}
| 551 | 0.735027 | 0.727768 | 16 | 32.4375 | 32.536457 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8125 | false | false | 0 |
758180b1759467ac4711d68fb5903b8bfb89e381 | 16,398,185,138,574 | d3071a31fd65ca1c9ede350a903a6b22fd63f625 | /app/src/main/java/com/practice/interfaceexample/AbstractFactoryDesign/Rectangle.java | b88712dd07a1a2a53b888ff2119df72d3230e47f | []
| no_license | UsamaNaseer/designpatterns | https://github.com/UsamaNaseer/designpatterns | dbb67d344a1fcf7f165f5e00695e221926adff8b | 34bf56f5dd264e1dd07c4655b772fb0cbfc2a59a | refs/heads/master | 2021-05-03T17:19:25.803000 | 2018-03-08T08:14:03 | 2018-03-08T08:14:03 | 120,443,843 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.practice.interfaceexample.AbstractFactoryDesign;
import android.util.Log;
/**
* Created by dell on 2/6/2018.
*/
public class Rectangle implements Shape {
@Override
public void draw() {
Log.e("Usama","Square");
}
}
| UTF-8 | Java | 251 | java | Rectangle.java | Java | [
{
"context": "sign;\n\nimport android.util.Log;\n\n/**\n * Created by dell on 2/6/2018.\n */\n\npublic class Rectangle implemen",
"end": 110,
"score": 0.9948968291282654,
"start": 106,
"tag": "USERNAME",
"value": "dell"
}
]
| null | []
| package com.practice.interfaceexample.AbstractFactoryDesign;
import android.util.Log;
/**
* Created by dell on 2/6/2018.
*/
public class Rectangle implements Shape {
@Override
public void draw() {
Log.e("Usama","Square");
}
}
| 251 | 0.669323 | 0.645418 | 14 | 16.928572 | 18.163795 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 0 |
794a5fa62d18420ec262e613a334a91ce615d3ad | 9,474,697,906,629 | 76db54ebc7d1a030e2ba060b6e0dd6602ccfd106 | /Code_For_Study_JSP/JSP_Servlet_MVC/EmpProject_upload/src/cn/xxx/oracle/service/back/IDeptServiceBack.java | e2cb517494eb8a12d4ed9508ddb7d23e3c845616 | []
| no_license | zengge95/javalearning | https://github.com/zengge95/javalearning | 81be111606dc0e7a8929fadbb607779f9ad0c30b | 3405f7c75d79d98646bfb50663e266f7b0e305df | refs/heads/master | 2021-01-21T12:58:01.793000 | 2016-05-16T14:52:21 | 2016-05-16T14:52:21 | 49,569,056 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.mldn.oracle.service.back;
import java.util.List;
import java.util.Set;
import cn.mldn.oracle.vo.Dept;
public interface IDeptServiceBack {
public boolean insert(Dept vo) throws Exception ;
public boolean update(Dept vo) throws Exception ;
/**
* 调用数据的删除操作,本方法要执行两个操作:<br>
* <li>先执行IEmpDAO接口的doRemoveBatchByDeptno()方法,删除掉部门的雇员
* <li>再执行IDeptDAO接口的doRemove()方法,删除掉部门信息
* @param id
* @return
* @throws Exception
*/
public boolean delete(int id) throws Exception ;
/**
* 调用数据的删除操作,本方法要执行两个操作:<br>
* <li>先执行IEmpDAO接口的doRemoveBatchByDeptno()方法,删除掉部门雇员
* <li>再执行IDeptDAO接口的doRemoveBatch()方法,删除掉多个部门信息
* @param ids
* @return
* @throws Exception
*/
public boolean deleteBatch(Set<Integer> ids) throws Exception ;
public List<Dept> list() throws Exception ;
/**
* 查询一个部门的完整信息,本查询要调用如下的操作方法:<br>
* <li>要通过IDeptDAO接口的findByIdDetails()方法统计信息;
* <li>要通过IEmpDAO接口查询所有的雇员数据(分页显示)
* @param id
* @return 如果查询到了部门信息返回对象,如果没有查询到则返回null
* @throws Exception
*/
public Dept show(String column, String keyWord, int currentPage,
int lineSize, int id) throws Exception;
/**
* 查询部门的详细信息,调用IDeptDAO接口的findAllByDetails()方法实现
* @return
* @throws Exception
*/
public List<Dept> listDetails() throws Exception ;
}
| UTF-8 | Java | 1,732 | java | IDeptServiceBack.java | Java | []
| null | []
| package cn.mldn.oracle.service.back;
import java.util.List;
import java.util.Set;
import cn.mldn.oracle.vo.Dept;
public interface IDeptServiceBack {
public boolean insert(Dept vo) throws Exception ;
public boolean update(Dept vo) throws Exception ;
/**
* 调用数据的删除操作,本方法要执行两个操作:<br>
* <li>先执行IEmpDAO接口的doRemoveBatchByDeptno()方法,删除掉部门的雇员
* <li>再执行IDeptDAO接口的doRemove()方法,删除掉部门信息
* @param id
* @return
* @throws Exception
*/
public boolean delete(int id) throws Exception ;
/**
* 调用数据的删除操作,本方法要执行两个操作:<br>
* <li>先执行IEmpDAO接口的doRemoveBatchByDeptno()方法,删除掉部门雇员
* <li>再执行IDeptDAO接口的doRemoveBatch()方法,删除掉多个部门信息
* @param ids
* @return
* @throws Exception
*/
public boolean deleteBatch(Set<Integer> ids) throws Exception ;
public List<Dept> list() throws Exception ;
/**
* 查询一个部门的完整信息,本查询要调用如下的操作方法:<br>
* <li>要通过IDeptDAO接口的findByIdDetails()方法统计信息;
* <li>要通过IEmpDAO接口查询所有的雇员数据(分页显示)
* @param id
* @return 如果查询到了部门信息返回对象,如果没有查询到则返回null
* @throws Exception
*/
public Dept show(String column, String keyWord, int currentPage,
int lineSize, int id) throws Exception;
/**
* 查询部门的详细信息,调用IDeptDAO接口的findAllByDetails()方法实现
* @return
* @throws Exception
*/
public List<Dept> listDetails() throws Exception ;
}
| 1,732 | 0.703364 | 0.703364 | 47 | 25.80851 | 19.689762 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.170213 | false | false | 0 |
598fdedb31c15f134161b4c5de2aab8ffa14cd04 | 33,088,428,089,217 | 4ab88b2db6ef86c4d895f321993e0c8288bdb213 | /src/boids/TestPPSimulator.java | 66fd7c5c685eb4a93738a4d903088649d881d4b4 | []
| no_license | raifer/sma | https://github.com/raifer/sma | 2bf802a0803736e7f320e8e1313582f7a5480a11 | 852dd1cefacf1e562efd1f027fff2d41cda4bacc | refs/heads/master | 2021-08-14T06:00:17.375000 | 2017-11-14T17:53:17 | 2017-11-14T17:53:17 | 107,249,067 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package boids;
import java.awt.Color;
import evenements.EventManager;
import gui.GUISimulator;
public class TestPPSimulator {
public static void main(String[] args) {
int height = 1000;
int width = 1600;
GUISimulator gui = new GUISimulator(width, height, Color.BLACK);
EventManager manager = new EventManager(0);
PredateursProiesSimulator flockSimu = new PredateursProiesSimulator(gui,manager);
gui.setSimulable(flockSimu);
}
}
| UTF-8 | Java | 478 | java | TestPPSimulator.java | Java | []
| null | []
| package boids;
import java.awt.Color;
import evenements.EventManager;
import gui.GUISimulator;
public class TestPPSimulator {
public static void main(String[] args) {
int height = 1000;
int width = 1600;
GUISimulator gui = new GUISimulator(width, height, Color.BLACK);
EventManager manager = new EventManager(0);
PredateursProiesSimulator flockSimu = new PredateursProiesSimulator(gui,manager);
gui.setSimulable(flockSimu);
}
}
| 478 | 0.715481 | 0.696653 | 21 | 20.761906 | 22.971836 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.285714 | false | false | 0 |
80769198ac1c7408e5084cea2086e5e38498e9af | 33,621,004,013,123 | e74faf030f1c3dcdf081fc00befdef667c4bbf4f | /jGo/src/cloud/jgo/jjdom/css/concrete/CSSDefaultRule.java | a5b31d209563093cac94219d4d884b2e7dd3d550 | [
"MIT"
]
| permissive | jWaspSoftware/jGo | https://github.com/jWaspSoftware/jGo | 7ef23faed2cd76e4ca63bc98e08fd12c7e2860fd | 9bdbba5bbaf83914712fdef82088d1d1b4d113b5 | refs/heads/master | 2022-06-05T15:08:12.896000 | 2019-06-17T17:40:42 | 2019-06-17T17:40:42 | 251,272,868 | 0 | 0 | null | false | 2022-05-20T21:31:06 | 2020-03-30T10:31:40 | 2020-03-30T10:34:03 | 2022-05-20T21:31:06 | 2,292 | 0 | 0 | 1 | HTML | false | false | /**
* JGO - A pure Java library,
* its purpose is to make life easier for the programmer.
*
* J - Java
* G - General
* O - Operations
*
* URL Software : https://www.jgo.cloud/
* URL Documentation : https://www.jgo.cloud/docs/
*
* Copyright © 2018 - Marco Martire (www.jgo.cloud)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the MIT License.
*
* You may obtain a copy of License at :
* https://www.jgo.cloud/LICENSE.txt
*
* To collaborate on this project, you need to do it from the software site.
*
*/
package cloud.jgo.jjdom.css.concrete;
import java.util.Iterator;
import java.util.Map;
import cloud.jgo.jjdom.css.CSSPropertyType;
import cloud.jgo.jjdom.css.CSSRule;
/**
*
* @author Martire91<br>
* @see CSSRule
*/
public class CSSDefaultRule extends CSSRule {
/**
*
*/
private static final long serialVersionUID = 1L;
private String selection = null;
private String comment = null;
public CSSDefaultRule(String selection, String comment) {
// TODO Auto-generated constructor stub
this.selection = selection;
this.comment = comment;
}
public CSSDefaultRule(String selection) {
// TODO Auto-generated constructor stub
this.selection = selection;
}
@Override
public String getSelection() {
// TODO Auto-generated method stub
return this.selection;
}
@Override
public String toString() {
// TODO Auto-generated method stub
StringBuffer buffer = new StringBuffer();
if (this.comment != null) {
buffer.append("/*" + "\n\n");
buffer.append(this.comment + "\n\n");
buffer.append("*/" + "\n");
}
buffer.append(selection + "{" + "\n");
Iterator<Map.Entry<CSSPropertyType, String>> iterator = entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<cloud.jgo.jjdom.css.CSSPropertyType, java.lang.String> entry = (Map.Entry<cloud.jgo.jjdom.css.CSSPropertyType, java.lang.String>) iterator
.next();
String cssType = entry.getKey().name().toLowerCase();
String cssValue = entry.getValue();
buffer.append(cssType + ": " + cssValue + ";\n");
}
buffer.append("}");
return buffer.toString();
}
@Override
public String getComment() {
// TODO Auto-generated method stub
return this.comment;
}
}
| WINDOWS-1252 | Java | 2,348 | java | CSSDefaultRule.java | Java | [
{
"context": "s://www.jgo.cloud/docs/\r\n *\r\n * Copyright © 2018 - Marco Martire (www.jgo.cloud)\r\n *\r\n * This program is free soft",
"end": 284,
"score": 0.9998583793640137,
"start": 271,
"tag": "NAME",
"value": "Marco Martire"
},
{
"context": "oud.jgo.jjdom.css.CSSRule;\r\n\r\n/**\r\n * \r\n * @author Martire91<br>\r\n * @see CSSRule\r\n */\r\npublic class CSSDefaul",
"end": 806,
"score": 0.9994990229606628,
"start": 797,
"tag": "USERNAME",
"value": "Martire91"
}
]
| null | []
| /**
* JGO - A pure Java library,
* its purpose is to make life easier for the programmer.
*
* J - Java
* G - General
* O - Operations
*
* URL Software : https://www.jgo.cloud/
* URL Documentation : https://www.jgo.cloud/docs/
*
* Copyright © 2018 - <NAME> (www.jgo.cloud)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the MIT License.
*
* You may obtain a copy of License at :
* https://www.jgo.cloud/LICENSE.txt
*
* To collaborate on this project, you need to do it from the software site.
*
*/
package cloud.jgo.jjdom.css.concrete;
import java.util.Iterator;
import java.util.Map;
import cloud.jgo.jjdom.css.CSSPropertyType;
import cloud.jgo.jjdom.css.CSSRule;
/**
*
* @author Martire91<br>
* @see CSSRule
*/
public class CSSDefaultRule extends CSSRule {
/**
*
*/
private static final long serialVersionUID = 1L;
private String selection = null;
private String comment = null;
public CSSDefaultRule(String selection, String comment) {
// TODO Auto-generated constructor stub
this.selection = selection;
this.comment = comment;
}
public CSSDefaultRule(String selection) {
// TODO Auto-generated constructor stub
this.selection = selection;
}
@Override
public String getSelection() {
// TODO Auto-generated method stub
return this.selection;
}
@Override
public String toString() {
// TODO Auto-generated method stub
StringBuffer buffer = new StringBuffer();
if (this.comment != null) {
buffer.append("/*" + "\n\n");
buffer.append(this.comment + "\n\n");
buffer.append("*/" + "\n");
}
buffer.append(selection + "{" + "\n");
Iterator<Map.Entry<CSSPropertyType, String>> iterator = entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<cloud.jgo.jjdom.css.CSSPropertyType, java.lang.String> entry = (Map.Entry<cloud.jgo.jjdom.css.CSSPropertyType, java.lang.String>) iterator
.next();
String cssType = entry.getKey().name().toLowerCase();
String cssValue = entry.getValue();
buffer.append(cssType + ": " + cssValue + ";\n");
}
buffer.append("}");
return buffer.toString();
}
@Override
public String getComment() {
// TODO Auto-generated method stub
return this.comment;
}
}
| 2,341 | 0.658713 | 0.655731 | 89 | 24.370787 | 24.182537 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.292135 | false | false | 0 |
4182e73169cd63b6b7fa9ac393fa46d43a0fdef7 | 12,309,376,296,992 | 9e4f8d9c7717d6bd20c0a6f724fc355e87d2f666 | /android/java/com/sometrik/framework/FWEventLayout.java | c245a5af902b5222e64892750a2e0a7693952b90 | [
"MIT"
]
| permissive | Sometrik/framework | https://github.com/Sometrik/framework | 071f7e12c9d58f15dad078788b6405ec5440f0a1 | 29d387251cd553aa75f8755adccf94494a9d7367 | refs/heads/master | 2023-02-05T11:31:12.545000 | 2023-02-01T15:07:08 | 2023-02-01T15:07:08 | 44,181,086 | 7 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sometrik.framework;
import com.sometrik.framework.NativeCommand.Selector;
import android.graphics.Bitmap;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
public class FWEventLayout extends FrameLayout implements NativeCommandHandler {
private FrameWork frame;
private ViewStyleManager normalStyle, activeStyle, currentStyle;
public FWEventLayout(FrameWork frameWork, int id) {
super(frameWork);
this.frame = frameWork;
this.setId(id);
final float scale = getContext().getResources().getDisplayMetrics().density;
this.normalStyle = currentStyle = new ViewStyleManager(frame.bitmapCache, scale, true);
this.activeStyle = new ViewStyleManager(frame.bitmapCache, scale, false);
setClickable(true);
setFocusable(false);
final FWEventLayout layout = this;
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (layout.activeStyle.isModified()) {
if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_POINTER_DOWN || event.getAction() == MotionEvent.ACTION_HOVER_ENTER) {
layout.currentStyle = layout.activeStyle;
layout.currentStyle.apply(layout, true);
} else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_POINTER_UP ||
event.getAction() == MotionEvent.ACTION_HOVER_EXIT || event.getAction() == MotionEvent.ACTION_OUTSIDE ||
event.getAction() == MotionEvent.ACTION_CANCEL) {
layout.currentStyle = layout.normalStyle;
layout.currentStyle.apply(layout, true);
}
}
return false;
}
});
}
@Override
public boolean performClick() {
System.out.println("FWEventLayout click");
frame.sendNativeValueEvent(getElementId(), 0, 0);
return super.performClick();
}
@Override
public int getElementId() {
return getId();
}
@Override
public void addChild(final View view) {
addView(view);
}
@Override
public void addOption(int optionId, String text) { }
@Override
public void setValue(String v) { }
@Override
public void setValue(int v) { }
@Override
public void setStyle(Selector selector, String key, String value) {
if (selector == Selector.NORMAL) {
normalStyle.setStyle(key, value);
} else if (selector == Selector.ACTIVE) {
activeStyle.setStyle(key, value);
}
}
@Override
public void applyStyles() {
currentStyle.apply(this);
}
@Override
public void setError(boolean hasError, String errorText) { }
@Override
public void onScreenOrientationChange(boolean isLandscape) {
invalidate();
}
@Override
public void addData(String text, int row, int column, int sheet) { }
@Override
public void setViewVisibility(boolean visibility) {
if (visibility) {
this.setVisibility(VISIBLE);
} else {
this.setVisibility(GONE);
}
}
@Override
public void clear() { }
@Override
public void flush() { }
@Override
public void addColumn(String text, int columnType) { }
@Override
public void reshape(int value, int size) { }
@Override
public void setBitmap(Bitmap bitmap) { }
@Override
public void reshape(int size) { }
@Override
public void deinitialize() { }
@Override
public void addImageUrl(String url, int width, int height) { }
}
| UTF-8 | Java | 3,460 | java | FWEventLayout.java | Java | []
| null | []
| package com.sometrik.framework;
import com.sometrik.framework.NativeCommand.Selector;
import android.graphics.Bitmap;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
public class FWEventLayout extends FrameLayout implements NativeCommandHandler {
private FrameWork frame;
private ViewStyleManager normalStyle, activeStyle, currentStyle;
public FWEventLayout(FrameWork frameWork, int id) {
super(frameWork);
this.frame = frameWork;
this.setId(id);
final float scale = getContext().getResources().getDisplayMetrics().density;
this.normalStyle = currentStyle = new ViewStyleManager(frame.bitmapCache, scale, true);
this.activeStyle = new ViewStyleManager(frame.bitmapCache, scale, false);
setClickable(true);
setFocusable(false);
final FWEventLayout layout = this;
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (layout.activeStyle.isModified()) {
if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_POINTER_DOWN || event.getAction() == MotionEvent.ACTION_HOVER_ENTER) {
layout.currentStyle = layout.activeStyle;
layout.currentStyle.apply(layout, true);
} else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_POINTER_UP ||
event.getAction() == MotionEvent.ACTION_HOVER_EXIT || event.getAction() == MotionEvent.ACTION_OUTSIDE ||
event.getAction() == MotionEvent.ACTION_CANCEL) {
layout.currentStyle = layout.normalStyle;
layout.currentStyle.apply(layout, true);
}
}
return false;
}
});
}
@Override
public boolean performClick() {
System.out.println("FWEventLayout click");
frame.sendNativeValueEvent(getElementId(), 0, 0);
return super.performClick();
}
@Override
public int getElementId() {
return getId();
}
@Override
public void addChild(final View view) {
addView(view);
}
@Override
public void addOption(int optionId, String text) { }
@Override
public void setValue(String v) { }
@Override
public void setValue(int v) { }
@Override
public void setStyle(Selector selector, String key, String value) {
if (selector == Selector.NORMAL) {
normalStyle.setStyle(key, value);
} else if (selector == Selector.ACTIVE) {
activeStyle.setStyle(key, value);
}
}
@Override
public void applyStyles() {
currentStyle.apply(this);
}
@Override
public void setError(boolean hasError, String errorText) { }
@Override
public void onScreenOrientationChange(boolean isLandscape) {
invalidate();
}
@Override
public void addData(String text, int row, int column, int sheet) { }
@Override
public void setViewVisibility(boolean visibility) {
if (visibility) {
this.setVisibility(VISIBLE);
} else {
this.setVisibility(GONE);
}
}
@Override
public void clear() { }
@Override
public void flush() { }
@Override
public void addColumn(String text, int columnType) { }
@Override
public void reshape(int value, int size) { }
@Override
public void setBitmap(Bitmap bitmap) { }
@Override
public void reshape(int size) { }
@Override
public void deinitialize() { }
@Override
public void addImageUrl(String url, int width, int height) { }
}
| 3,460 | 0.68815 | 0.687572 | 132 | 25.212122 | 27.177874 | 163 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.621212 | false | false | 0 |
0942d91a72f693a4ee0546cb1b12cb078fcc378a | 33,749,853,017,440 | d3539d21fb2def3f089a8b222f48647d43232696 | /FactoryMethodPattern/11Proj-FactoryMethodPattern-Problem/src/com/exps/test/NorthCustomer.java | 3f4849ae8f762ac25528c7f0c50f29b600e907cd | []
| no_license | akshaygithub9596/DesignPatterns | https://github.com/akshaygithub9596/DesignPatterns | 7e91b424582c18f722bd5938c1db3fd8104e6e9e | 3c7a1464627ecd7287d57edc108f6602e0a62cc5 | refs/heads/master | 2022-10-05T06:00:38.945000 | 2020-05-21T09:52:52 | 2020-05-21T09:52:52 | 262,452,467 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.exps.test;
import com.exps.bike.BajajBike;
import com.exps.factory.NagpurFactory;
public class NorthCustomer {
public static void main(String[] args) {
BajajBike bike = null;
bike= NagpurFactory.createBike("pulsor");
}
}
| UTF-8 | Java | 256 | java | NorthCustomer.java | Java | []
| null | []
| package com.exps.test;
import com.exps.bike.BajajBike;
import com.exps.factory.NagpurFactory;
public class NorthCustomer {
public static void main(String[] args) {
BajajBike bike = null;
bike= NagpurFactory.createBike("pulsor");
}
}
| 256 | 0.707031 | 0.707031 | 13 | 17.692308 | 16.904184 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.846154 | false | false | 0 |
f03e016390ee040e868c525d042dce14e78bbc2f | 4,415,226,426,219 | 005553bcc8991ccf055f15dcbee3c80926613b7f | /generated/pcftest/DashboardGroup.java | a71b99d6dcf539d8cfb9f86cf73cc748ecbd1e20 | []
| no_license | azanaera/toggle-isbtf | https://github.com/azanaera/toggle-isbtf | 5f14209cd87b98c123fad9af060efbbee1640043 | faf991ec3db2fd1d126bc9b6be1422b819f6cdc8 | refs/heads/master | 2023-01-06T22:20:03.493000 | 2020-11-16T07:04:56 | 2020-11-16T07:04:56 | 313,212,938 | 0 | 0 | null | false | 2020-11-16T08:48:41 | 2020-11-16T06:42:23 | 2020-11-16T07:09:00 | 2020-11-16T08:23:22 | 98,722 | 0 | 0 | 1 | null | false | false | package pcftest;
import gw.lang.SimplePropertyProcessing;
import gw.smoketest.platform.web.ClickableActionElement;
import gw.smoketest.platform.web.MessagesElement;
import gw.smoketest.platform.web.PCFElementId;
import gw.smoketest.platform.web.PCFLocation;
import gw.smoketest.platform.web.ValueElementWithSetAndRefresh;
import gw.testharness.ISmokeTest;
import javax.annotation.processing.Generated;
import pcftest.DashboardGroup.DashboardGroup_UpLink;
import pcftest.DashboardGroup._Paging;
import pcftest.DashboardGroup.__crumb__;
import pcftest.DashboardGroup._msgs;
import pcftest.DashboardGroup.actWizard;
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/dashboard/DashboardGroup.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public class DashboardGroup extends PCFLocation {
public final static String CHECKSUM = "2931de168023a7caca3a349f7d4eccc8";
public DashboardGroup(ISmokeTest helper) {
super(helper, new gw.smoketest.platform.web.PCFElementId("DashboardGroup"));
}
public BlankMenuLinks getBlankMenuLinks() {
return getOrCreateMenuLinksProperty("BlankMenuLinks", "BlankMenuLinks", null, pcftest.BlankMenuLinks.class, null);
}
public DashboardGroup_UpLink getDashboardGroup_UpLink() {
return getOrCreateProperty("DashboardGroup_UpLink", "DashboardGroup_UpLink", null, pcftest.DashboardGroup.DashboardGroup_UpLink.class);
}
public DashboardMenuTree getDashboardMenuTree() {
return getOrCreateProperty("DashboardMenuTree", "DashboardMenuTree", null, pcftest.DashboardMenuTree.class);
}
public DashboardSubGroup getDashboardSubGroup() {
return getOrCreateProperty("DashboardSubGroup", pcftest.DashboardSubGroup.class);
}
public DesktopMenuActions getDesktopMenuActions() {
return getOrCreateProperty("DesktopMenuActions", "DesktopMenuActions", null, pcftest.DesktopMenuActions.class);
}
public TabBar getTabBar() {
return getOrCreateProperty("TabBar", pcftest.TabBar.class);
}
public _Paging get_Paging() {
return getOrCreateProperty("_Paging", "_Paging", null, pcftest.DashboardGroup._Paging.class);
}
public __crumb__ get__crumb__() {
return getOrCreateProperty("__crumb__", "__crumb__", null, pcftest.DashboardGroup.__crumb__.class);
}
public _msgs get_msgs() {
return getOrCreateProperty("_msgs", "_msgs", null, pcftest.DashboardGroup._msgs.class);
}
public actWizard getactWizard() {
return getOrCreateProperty("actWizard", "actWizard", null, pcftest.DashboardGroup.actWizard.class);
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/dashboard/DashboardGroup.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class DashboardGroup_UpLink extends ClickableActionElement {
public DashboardGroup_UpLink(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/dashboard/DashboardGroup.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class _Paging extends ValueElementWithSetAndRefresh {
public _Paging(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/dashboard/DashboardGroup.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class __crumb__ extends ClickableActionElement {
public __crumb__(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/dashboard/DashboardGroup.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class _msgs extends MessagesElement {
public _msgs(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/dashboard/DashboardGroup.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class actWizard extends ClickableActionElement {
public actWizard(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
}
} | UTF-8 | Java | 4,789 | java | DashboardGroup.java | Java | []
| null | []
| package pcftest;
import gw.lang.SimplePropertyProcessing;
import gw.smoketest.platform.web.ClickableActionElement;
import gw.smoketest.platform.web.MessagesElement;
import gw.smoketest.platform.web.PCFElementId;
import gw.smoketest.platform.web.PCFLocation;
import gw.smoketest.platform.web.ValueElementWithSetAndRefresh;
import gw.testharness.ISmokeTest;
import javax.annotation.processing.Generated;
import pcftest.DashboardGroup.DashboardGroup_UpLink;
import pcftest.DashboardGroup._Paging;
import pcftest.DashboardGroup.__crumb__;
import pcftest.DashboardGroup._msgs;
import pcftest.DashboardGroup.actWizard;
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/dashboard/DashboardGroup.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public class DashboardGroup extends PCFLocation {
public final static String CHECKSUM = "2931de168023a7caca3a349f7d4eccc8";
public DashboardGroup(ISmokeTest helper) {
super(helper, new gw.smoketest.platform.web.PCFElementId("DashboardGroup"));
}
public BlankMenuLinks getBlankMenuLinks() {
return getOrCreateMenuLinksProperty("BlankMenuLinks", "BlankMenuLinks", null, pcftest.BlankMenuLinks.class, null);
}
public DashboardGroup_UpLink getDashboardGroup_UpLink() {
return getOrCreateProperty("DashboardGroup_UpLink", "DashboardGroup_UpLink", null, pcftest.DashboardGroup.DashboardGroup_UpLink.class);
}
public DashboardMenuTree getDashboardMenuTree() {
return getOrCreateProperty("DashboardMenuTree", "DashboardMenuTree", null, pcftest.DashboardMenuTree.class);
}
public DashboardSubGroup getDashboardSubGroup() {
return getOrCreateProperty("DashboardSubGroup", pcftest.DashboardSubGroup.class);
}
public DesktopMenuActions getDesktopMenuActions() {
return getOrCreateProperty("DesktopMenuActions", "DesktopMenuActions", null, pcftest.DesktopMenuActions.class);
}
public TabBar getTabBar() {
return getOrCreateProperty("TabBar", pcftest.TabBar.class);
}
public _Paging get_Paging() {
return getOrCreateProperty("_Paging", "_Paging", null, pcftest.DashboardGroup._Paging.class);
}
public __crumb__ get__crumb__() {
return getOrCreateProperty("__crumb__", "__crumb__", null, pcftest.DashboardGroup.__crumb__.class);
}
public _msgs get_msgs() {
return getOrCreateProperty("_msgs", "_msgs", null, pcftest.DashboardGroup._msgs.class);
}
public actWizard getactWizard() {
return getOrCreateProperty("actWizard", "actWizard", null, pcftest.DashboardGroup.actWizard.class);
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/dashboard/DashboardGroup.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class DashboardGroup_UpLink extends ClickableActionElement {
public DashboardGroup_UpLink(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/dashboard/DashboardGroup.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class _Paging extends ValueElementWithSetAndRefresh {
public _Paging(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/dashboard/DashboardGroup.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class __crumb__ extends ClickableActionElement {
public __crumb__(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/dashboard/DashboardGroup.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class _msgs extends MessagesElement {
public _msgs(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/dashboard/DashboardGroup.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class actWizard extends ClickableActionElement {
public actWizard(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
}
} | 4,789 | 0.742117 | 0.738359 | 133 | 35.015038 | 37.72855 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.639098 | false | false | 0 |
ecd3c9a750216c9e61aba6fcefd042866cabc59f | 17,824,114,309,184 | 3481799ed03a011b97a282f6315cca10f8461b05 | /src/main/java/com/ankitgupta/core/App.java | bde7eb0aebdf6cf247e27e192c4d6c8d24313156 | []
| no_license | ankit8898/spring4-mysql | https://github.com/ankit8898/spring4-mysql | fdc2e4f78874241f0d4147e2a6c65eb2481d68b0 | fe2435dc180982c7dde231c0c8293791b896762c | refs/heads/master | 2016-08-06T13:07:47.900000 | 2015-03-03T17:15:00 | 2015-03-03T17:15:00 | 31,610,801 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ankitgupta.core;
/**
* Hello world!
*
*/
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ankitgupta.customer.dao.CustomerDAO;
import com.ankitgupta.customer.model.Customer;
public class App
{
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"Spring-Module.xml");
CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO");
//Customer customer = new Customer(34, "Ankit",28);
//customerDAO.insert(customer);
Customer customer1 = customerDAO.findByCustomerId(34);
System.out.println(customer1);
}
}
| UTF-8 | Java | 732 | java | App.java | Java | [
{
"context": ";\n //Customer customer = new Customer(34, \"Ankit\",28);\n //customerDAO.insert(customer);\n\n ",
"end": 576,
"score": 0.9996767640113831,
"start": 571,
"tag": "NAME",
"value": "Ankit"
}
]
| null | []
| package com.ankitgupta.core;
/**
* Hello world!
*
*/
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ankitgupta.customer.dao.CustomerDAO;
import com.ankitgupta.customer.model.Customer;
public class App
{
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"Spring-Module.xml");
CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO");
//Customer customer = new Customer(34, "Ankit",28);
//customerDAO.insert(customer);
Customer customer1 = customerDAO.findByCustomerId(34);
System.out.println(customer1);
}
}
| 732 | 0.736339 | 0.72541 | 25 | 28.280001 | 26.33404 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52 | false | false | 0 |
c1bb7cba5153259c82a8c235983b2b3a10d38db7 | 20,684,562,555,573 | dcbe17d1c3df35215e81ac503908fa60ad7ac740 | /src/main/java/com/ne0nx3r0/betteralias/config/AliasConfig.java | 9e5d597e772f540fe2e14b8d311de2ec12e26c25 | []
| no_license | plachta11b/BetterAlias | https://github.com/plachta11b/BetterAlias | 6d3abb31c1a44b30efb92b430a82625f938775c5 | cf3d34a823a545b019b593b4fdb73692c0aa589b | refs/heads/master | 2021-01-18T08:56:05.114000 | 2016-08-16T21:02:08 | 2016-08-16T21:02:08 | 30,293,370 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ne0nx3r0.betteralias.config;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import com.ne0nx3r0.betteralias.BetterAlias;
import com.ne0nx3r0.betteralias.alias.Alias;
import com.ne0nx3r0.betteralias.alias.AliasCommand;
import com.ne0nx3r0.betteralias.alias.AliasCommandTypes;
public class AliasConfig {
private final Plugin plugin;
private final File configurationFile;
private static FileConfiguration configuration;
public AliasConfig(final BetterAlias plugin) {
this.plugin = plugin;
this.configurationFile = new File(plugin.getDataFolder(), "aliases.yml");
if (!configurationFile.exists()) {
configurationFile.getParentFile().mkdirs();
copy(plugin.getResource("aliases.yml"), configurationFile);
}
AliasConfig.configuration = YamlConfiguration.loadConfiguration(configurationFile);
}
public void reload() {
AliasConfig.configuration = YamlConfiguration.loadConfiguration(configurationFile);
}
public FileConfiguration getAliasConfiguration() {
return AliasConfig.configuration;
}
public final HashMap<String, Alias> loadAliases() {
HashMap<String, Alias> aliases = new HashMap<String, Alias>();
Set<String> aliasList = AliasConfig.configuration.getKeys(false);
if (aliasList.isEmpty()) {
plugin.getLogger().log(Level.WARNING, "No aliases found in aliases.yml");
return aliases;
}
for (String sAlias : aliasList) {
Alias alias = new Alias(
sAlias,
AliasConfig.configuration.getBoolean(sAlias + ".caseSensitive", false),
AliasConfig.configuration.getString(sAlias + ".permission", null),
AliasConfig.configuration.getString(sAlias + ".priority", null));
for (String sArg : AliasConfig.configuration.getConfigurationSection(sAlias).getKeys(false)) {
List<AliasCommand> commandsList = new ArrayList<AliasCommand>();
if (!sArg.equalsIgnoreCase("permission")
&& !sArg.equalsIgnoreCase("caseSensitive")
&& !sArg.equalsIgnoreCase("priority")) {
int iArg;
if (sArg.equals("*")) {
iArg = -1;
} else {
// TODO This raise error sometime on unknown configuration parameter
iArg = Integer.parseInt(sArg);
}
List<String> sArgLines = new ArrayList<String>();
if (AliasConfig.configuration.isList(sAlias + "." + sArg)) {
sArgLines = AliasConfig.configuration.getStringList(sAlias + "." + sArg);
} else {
sArgLines.add(AliasConfig.configuration.getString(sAlias + "." + sArg));
}
for (String sArgLine : sArgLines) {
AliasCommandTypes type = AliasCommandTypes.PLAYER;
int waitTime = 0;
if (sArgLine.contains(" ")) {
String sType = sArgLine.substring(0, sArgLine.indexOf(" "));
if (sType.equalsIgnoreCase("console")) {
type = AliasCommandTypes.CONSOLE;
sArgLine = sArgLine.substring(sArgLine.indexOf(" ") + 1);
} else if (sType.equalsIgnoreCase("player_as_op")) {
type = AliasCommandTypes.PLAYER_AS_OP;
sArgLine = sArgLine.substring(sArgLine.indexOf(" ") + 1);
} else if (sType.equalsIgnoreCase("reply")) {
type = AliasCommandTypes.REPLY_MESSAGE;
sArgLine = sArgLine.substring(sArgLine.indexOf(" ") + 1);
} else if (sType.equalsIgnoreCase("wait")) {
String[] sArgLineParams = sArgLine.split(" ");
try {
waitTime = Integer.parseInt(sArgLineParams[1]);
} catch (Exception e) {
plugin.getLogger().log(Level.WARNING, "Invalid wait time for command {0} in alias {1}, skipping line",
new Object[]{sArgLine, sAlias});
continue;
}
if (sArgLineParams[2].equalsIgnoreCase("reply")) {
type = AliasCommandTypes.WAIT_THEN_REPLY;
sArgLine = sArgLine.replace(sArgLineParams[0] + " " + sArgLineParams[1] + " " + sArgLineParams[2] + " ", "");
} else if (sArgLineParams[2].equalsIgnoreCase("console")) {
type = AliasCommandTypes.WAIT_THEN_CONSOLE;
sArgLine = sArgLine.replace(sArgLineParams[0] + " " + sArgLineParams[1] + " " + sArgLineParams[2] + " ", "");
} else {
type = AliasCommandTypes.WAIT;
sArgLine = sArgLine.replace(sArgLineParams[0] + " " + sArgLineParams[1] + " ", "");
}
}
}
sArgLine = this.replaceColorCodes(sArgLine);
commandsList.add(new AliasCommand(sArgLine, type, waitTime));
}
alias.setCommandsFor(iArg, commandsList);
}
}
aliases.put(sAlias, alias);
}
return aliases;
}
private String replaceColorCodes(String str) {
for (ChatColor cc : ChatColor.values()) {
str = str.replace("&" + cc.name(), cc.toString());
}
return str;
}
public void copy(InputStream in, File file) {
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 6,932 | java | AliasConfig.java | Java | []
| null | []
| package com.ne0nx3r0.betteralias.config;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import com.ne0nx3r0.betteralias.BetterAlias;
import com.ne0nx3r0.betteralias.alias.Alias;
import com.ne0nx3r0.betteralias.alias.AliasCommand;
import com.ne0nx3r0.betteralias.alias.AliasCommandTypes;
public class AliasConfig {
private final Plugin plugin;
private final File configurationFile;
private static FileConfiguration configuration;
public AliasConfig(final BetterAlias plugin) {
this.plugin = plugin;
this.configurationFile = new File(plugin.getDataFolder(), "aliases.yml");
if (!configurationFile.exists()) {
configurationFile.getParentFile().mkdirs();
copy(plugin.getResource("aliases.yml"), configurationFile);
}
AliasConfig.configuration = YamlConfiguration.loadConfiguration(configurationFile);
}
public void reload() {
AliasConfig.configuration = YamlConfiguration.loadConfiguration(configurationFile);
}
public FileConfiguration getAliasConfiguration() {
return AliasConfig.configuration;
}
public final HashMap<String, Alias> loadAliases() {
HashMap<String, Alias> aliases = new HashMap<String, Alias>();
Set<String> aliasList = AliasConfig.configuration.getKeys(false);
if (aliasList.isEmpty()) {
plugin.getLogger().log(Level.WARNING, "No aliases found in aliases.yml");
return aliases;
}
for (String sAlias : aliasList) {
Alias alias = new Alias(
sAlias,
AliasConfig.configuration.getBoolean(sAlias + ".caseSensitive", false),
AliasConfig.configuration.getString(sAlias + ".permission", null),
AliasConfig.configuration.getString(sAlias + ".priority", null));
for (String sArg : AliasConfig.configuration.getConfigurationSection(sAlias).getKeys(false)) {
List<AliasCommand> commandsList = new ArrayList<AliasCommand>();
if (!sArg.equalsIgnoreCase("permission")
&& !sArg.equalsIgnoreCase("caseSensitive")
&& !sArg.equalsIgnoreCase("priority")) {
int iArg;
if (sArg.equals("*")) {
iArg = -1;
} else {
// TODO This raise error sometime on unknown configuration parameter
iArg = Integer.parseInt(sArg);
}
List<String> sArgLines = new ArrayList<String>();
if (AliasConfig.configuration.isList(sAlias + "." + sArg)) {
sArgLines = AliasConfig.configuration.getStringList(sAlias + "." + sArg);
} else {
sArgLines.add(AliasConfig.configuration.getString(sAlias + "." + sArg));
}
for (String sArgLine : sArgLines) {
AliasCommandTypes type = AliasCommandTypes.PLAYER;
int waitTime = 0;
if (sArgLine.contains(" ")) {
String sType = sArgLine.substring(0, sArgLine.indexOf(" "));
if (sType.equalsIgnoreCase("console")) {
type = AliasCommandTypes.CONSOLE;
sArgLine = sArgLine.substring(sArgLine.indexOf(" ") + 1);
} else if (sType.equalsIgnoreCase("player_as_op")) {
type = AliasCommandTypes.PLAYER_AS_OP;
sArgLine = sArgLine.substring(sArgLine.indexOf(" ") + 1);
} else if (sType.equalsIgnoreCase("reply")) {
type = AliasCommandTypes.REPLY_MESSAGE;
sArgLine = sArgLine.substring(sArgLine.indexOf(" ") + 1);
} else if (sType.equalsIgnoreCase("wait")) {
String[] sArgLineParams = sArgLine.split(" ");
try {
waitTime = Integer.parseInt(sArgLineParams[1]);
} catch (Exception e) {
plugin.getLogger().log(Level.WARNING, "Invalid wait time for command {0} in alias {1}, skipping line",
new Object[]{sArgLine, sAlias});
continue;
}
if (sArgLineParams[2].equalsIgnoreCase("reply")) {
type = AliasCommandTypes.WAIT_THEN_REPLY;
sArgLine = sArgLine.replace(sArgLineParams[0] + " " + sArgLineParams[1] + " " + sArgLineParams[2] + " ", "");
} else if (sArgLineParams[2].equalsIgnoreCase("console")) {
type = AliasCommandTypes.WAIT_THEN_CONSOLE;
sArgLine = sArgLine.replace(sArgLineParams[0] + " " + sArgLineParams[1] + " " + sArgLineParams[2] + " ", "");
} else {
type = AliasCommandTypes.WAIT;
sArgLine = sArgLine.replace(sArgLineParams[0] + " " + sArgLineParams[1] + " ", "");
}
}
}
sArgLine = this.replaceColorCodes(sArgLine);
commandsList.add(new AliasCommand(sArgLine, type, waitTime));
}
alias.setCommandsFor(iArg, commandsList);
}
}
aliases.put(sAlias, alias);
}
return aliases;
}
private String replaceColorCodes(String str) {
for (ChatColor cc : ChatColor.values()) {
str = str.replace("&" + cc.name(), cc.toString());
}
return str;
}
public void copy(InputStream in, File file) {
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 6,932 | 0.518321 | 0.51255 | 179 | 37.726257 | 33.789322 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.564246 | false | false | 0 |
44968e5258971f7ac93f82f6e2893e5bf3d1b61c | 19,576,460,945,996 | d273a07b1bd133acea23539434bbc2aa76379c37 | /Destroscape New/src/game/content/achievement/AchievementExtra.java | 72ed17b34bf51a5eaa0d15ee87c18cdd2ab83c50 | []
| no_license | Destroscape/Server | https://github.com/Destroscape/Server | 7c7f992401a9c275d7793f4db03e34aac878ef00 | 63e0958d4e1d8b7e678fb29dedc7ab6938798280 | refs/heads/master | 2021-01-02T22:39:46.269000 | 2014-12-27T19:36:06 | 2014-12-27T19:36:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package game.content.achievement;
import game.Server;
import game.entity.player.Player;
/**
*
* @author 2012 : 18/08/2011
*
*/
public class AchievementExtra {
public static void addExtra(Player c, int achievement) {
switch (achievement) {
case Achievements.MUNCHER:
c.getPA().addSkillXP(10000, 3);
addItems(c, new int[][] { {386, 50}, {392, 20}, {380, 250}});
c.sendMessage("You're awarded 50 sharks, 20 manta ray and 250 lobsters!");
c.sendMessage("And also 10,000 hitpoints experience!");
break;
case Achievements.POCKETEER:
c.getPA().addSkillXP(60000, 17);
c.sendMessage("You're awarded 60K thieving experience");
break;
case Achievements.GWD_WARRIOR:
c.getPA().addSkillXP(100000, 2);
c.sendMessage("You're awarded 100K strength experience");
break;
case Achievements.GWD_RANGER:
c.getPA().addSkillXP(100000, 4);
c.sendMessage("You're awarded 100K range experience");
break;
case Achievements.GWD_QUEEN:
c.getPA().addSkillXP(100000, 5);
c.sendMessage("You're awarded 100K prayer experience");
break;
case Achievements.GWD_DARKER:
c.getPA().addSkillXP(100000, 1);
c.sendMessage("You're awarded 100K defence experience");
break;
case Achievements.ALCHEMIZER:
c.getPA().addSkillXP(100000, 6);
addItems(c, new int[][] { {554, 3000}, {561, 1000}});
c.sendMessage("You're awarded 3000 fire runes, and 1000 nature runes!");
c.sendMessage("And also 100K magic experience!");
break;
case Achievements.DUNGEONEERER:
c.dTokens += 100000;
c.sendMessage("You're awarded 100K Dungeoneering Tokens.");
break;
default: c.sendMessage("There are no items or experience reward for this achievement."); break;
}
}
private static void addItems(Player c, int[][] items) {
int itemAmount = items.length;
for (int i = 0; i < itemAmount; i++) {
if (c.getItems().freeSlots() < itemAmount) {
Server.itemHandler.createGroundItem(c, items[i][0], c.absX,
c.absY, items[i][1], c.playerId);
} else {
c.getItems().addItem(items[i][0], items[i][1]);
}
}
}
} | UTF-8 | Java | 2,079 | java | AchievementExtra.java | Java | []
| null | []
| package game.content.achievement;
import game.Server;
import game.entity.player.Player;
/**
*
* @author 2012 : 18/08/2011
*
*/
public class AchievementExtra {
public static void addExtra(Player c, int achievement) {
switch (achievement) {
case Achievements.MUNCHER:
c.getPA().addSkillXP(10000, 3);
addItems(c, new int[][] { {386, 50}, {392, 20}, {380, 250}});
c.sendMessage("You're awarded 50 sharks, 20 manta ray and 250 lobsters!");
c.sendMessage("And also 10,000 hitpoints experience!");
break;
case Achievements.POCKETEER:
c.getPA().addSkillXP(60000, 17);
c.sendMessage("You're awarded 60K thieving experience");
break;
case Achievements.GWD_WARRIOR:
c.getPA().addSkillXP(100000, 2);
c.sendMessage("You're awarded 100K strength experience");
break;
case Achievements.GWD_RANGER:
c.getPA().addSkillXP(100000, 4);
c.sendMessage("You're awarded 100K range experience");
break;
case Achievements.GWD_QUEEN:
c.getPA().addSkillXP(100000, 5);
c.sendMessage("You're awarded 100K prayer experience");
break;
case Achievements.GWD_DARKER:
c.getPA().addSkillXP(100000, 1);
c.sendMessage("You're awarded 100K defence experience");
break;
case Achievements.ALCHEMIZER:
c.getPA().addSkillXP(100000, 6);
addItems(c, new int[][] { {554, 3000}, {561, 1000}});
c.sendMessage("You're awarded 3000 fire runes, and 1000 nature runes!");
c.sendMessage("And also 100K magic experience!");
break;
case Achievements.DUNGEONEERER:
c.dTokens += 100000;
c.sendMessage("You're awarded 100K Dungeoneering Tokens.");
break;
default: c.sendMessage("There are no items or experience reward for this achievement."); break;
}
}
private static void addItems(Player c, int[][] items) {
int itemAmount = items.length;
for (int i = 0; i < itemAmount; i++) {
if (c.getItems().freeSlots() < itemAmount) {
Server.itemHandler.createGroundItem(c, items[i][0], c.absX,
c.absY, items[i][1], c.playerId);
} else {
c.getItems().addItem(items[i][0], items[i][1]);
}
}
}
} | 2,079 | 0.677249 | 0.609428 | 67 | 30.044777 | 23.382244 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.104478 | false | false | 0 |
595cded8822a41a9a6a3f6df880e4d5ef02dc7b5 | 32,014,686,252,543 | 46058529be3de9d3188bf1fbb9abe7185ce874b6 | /forms/src/org/riotfamily/forms/resource/Resources.java | 488f3c350d4e6a6e3a9520a0fd3c33480d056931 | [
"Apache-2.0"
]
| permissive | evgeniy-fitsner/riot | https://github.com/evgeniy-fitsner/riot | 6d2cacb80f79cfdddf4d743d8390cbff15d1d881 | 1107e587af0e646599a5b5ed39f422ee524ac88a | refs/heads/9.1.x | 2021-01-12T21:28:56.337000 | 2014-07-17T07:39:38 | 2014-07-17T07:42:51 | 29,406,556 | 0 | 1 | null | true | 2015-01-17T21:38:48 | 2015-01-17T21:38:48 | 2015-01-17T10:31:10 | 2014-12-04T09:30:08 | 24,699 | 0 | 0 | 0 | null | null | null | /* 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.riotfamily.forms.resource;
public final class Resources {
private Resources() {
}
public static final ScriptResource PROTOTYPE =
new ScriptResource("prototype/prototype.js", "Prototype");
public static final ScriptResource SCRIPTACULOUS_EFFECTS =
new ScriptResource("scriptaculous/effects.js", "Effect", PROTOTYPE);
public static final ScriptResource SCRIPTACULOUS_DRAG_DROP =
new ScriptResource("scriptaculous/dragdrop.js", "Droppables",
SCRIPTACULOUS_EFFECTS);
public static final ScriptResource SCRIPTACULOUS_CONTROLS =
new ScriptResource("scriptaculous/controls.js", "Autocompleter",
SCRIPTACULOUS_EFFECTS);
public static final ScriptResource SCRIPTACULOUS_SLIDER =
new ScriptResource("scriptaculous/slider.js", "Control.Slider",
PROTOTYPE);
public static final ScriptResource RIOT_DIALOG =
new ScriptResource("riot/window/dialog.js", "riot.window.Dialog",
PROTOTYPE);
public static final ScriptResource RIOT_UTIL =
new ScriptResource("riot/util.js", "RElement", PROTOTYPE);
public static final ScriptResource RIOT_EFFECTS =
new ScriptResource("riot/effects.js", "Effect.Remove",
SCRIPTACULOUS_EFFECTS);
}
| UTF-8 | Java | 1,762 | java | Resources.java | Java | []
| null | []
| /* 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.riotfamily.forms.resource;
public final class Resources {
private Resources() {
}
public static final ScriptResource PROTOTYPE =
new ScriptResource("prototype/prototype.js", "Prototype");
public static final ScriptResource SCRIPTACULOUS_EFFECTS =
new ScriptResource("scriptaculous/effects.js", "Effect", PROTOTYPE);
public static final ScriptResource SCRIPTACULOUS_DRAG_DROP =
new ScriptResource("scriptaculous/dragdrop.js", "Droppables",
SCRIPTACULOUS_EFFECTS);
public static final ScriptResource SCRIPTACULOUS_CONTROLS =
new ScriptResource("scriptaculous/controls.js", "Autocompleter",
SCRIPTACULOUS_EFFECTS);
public static final ScriptResource SCRIPTACULOUS_SLIDER =
new ScriptResource("scriptaculous/slider.js", "Control.Slider",
PROTOTYPE);
public static final ScriptResource RIOT_DIALOG =
new ScriptResource("riot/window/dialog.js", "riot.window.Dialog",
PROTOTYPE);
public static final ScriptResource RIOT_UTIL =
new ScriptResource("riot/util.js", "RElement", PROTOTYPE);
public static final ScriptResource RIOT_EFFECTS =
new ScriptResource("riot/effects.js", "Effect.Remove",
SCRIPTACULOUS_EFFECTS);
}
| 1,762 | 0.752554 | 0.750284 | 49 | 34.959183 | 27.743694 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.77551 | false | false | 0 |
3625c523accaafa6d3d4b86d0de12cd68480a781 | 2,843,268,388,444 | 8793feadfaf95533663ed2d97362e93bacb7ba1f | /src/main/java/com/wjm/softwareout/system/dao/UserMapper.java | b4a79e23e642782bf777aed3ce44d4f050ba8642 | [
"MIT"
]
| permissive | zhyazhang/softwareout | https://github.com/zhyazhang/softwareout | 04f637b80057cdcbd36c3ca8b91c3ed8d652183c | 758ff124fec919e1af2a3db8ba529a022f32bfd5 | refs/heads/main | 2023-05-31T12:15:56.685000 | 2021-06-15T05:02:51 | 2021-06-15T05:02:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wjm.softwareout.system.dao;
import com.wjm.softwareout.system.entity.User;
import com.wjm.softwareout.system.vo.UserVo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int selectRoleIdByUserID(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
List<User> selectAllUsersByParams(@Param("userVo") UserVo userVo);
/**
* 根据登录名查询用户
*/
User queryUserByLoginName(@Param("loginName") String loginName);
List<User> selectAllUsers();
int updateUserPwd(@Param("newPwd") String newPwd,
@Param("userId") Integer userId);
User selectUserByLoginName(@Param("loginName") String loginname);
int userCount();
} | UTF-8 | Java | 953 | java | UserMapper.java | Java | []
| null | []
| package com.wjm.softwareout.system.dao;
import com.wjm.softwareout.system.entity.User;
import com.wjm.softwareout.system.vo.UserVo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int selectRoleIdByUserID(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
List<User> selectAllUsersByParams(@Param("userVo") UserVo userVo);
/**
* 根据登录名查询用户
*/
User queryUserByLoginName(@Param("loginName") String loginName);
List<User> selectAllUsers();
int updateUserPwd(@Param("newPwd") String newPwd,
@Param("userId") Integer userId);
User selectUserByLoginName(@Param("loginName") String loginname);
int userCount();
} | 953 | 0.712299 | 0.712299 | 41 | 21.829268 | 23.197878 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.463415 | false | false | 0 |
952d5a48be085fe958ba658bc591e4b96fe0d8a6 | 23,141,283,831,536 | cb33636cd37d48ad33df48f2747b2cc657957b57 | /sprintmvc_rule/src/main/java/com/lz_java/controller/RoleController.java | b7598526f2156f98e1be7ae17538b5db7938f2b8 | []
| no_license | Smiler94/learn-java | https://github.com/Smiler94/learn-java | 1ecf8a004054fa46d964ce2f288471abd4305efc | 9c7df6a5c0916a2ad1b1b240b9d1deb3df13eeb5 | refs/heads/master | 2022-12-25T11:50:55.864000 | 2019-12-04T14:29:24 | 2019-12-04T14:29:24 | 135,697,105 | 0 | 0 | null | false | 2022-12-16T08:22:45 | 2018-06-01T09:24:51 | 2019-12-04T14:29:53 | 2022-12-16T08:22:43 | 26,948 | 0 | 0 | 19 | JavaScript | false | false | package com.lz_java.controller;
import com.lz_java.entity.Authority;
import com.lz_java.entity.RoleVO;
import com.lz_java.entity.Role;
import com.lz_java.repository.AuthorityRepository;
import com.lz_java.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Controller
@RequestMapping("/role")
public class RoleController extends BaseController{
@Autowired
private RoleRepository roleRepository;
@Autowired
private AuthorityRepository authorityRepository;
@GetMapping("/add")
public ModelAndView add(HttpServletRequest request) {
ModelAndView modelAndView = getMv(request);
System.out.println(authorityRepository.findAll().iterator());
modelAndView.addObject("list", authorityRepository.findAll().iterator());
modelAndView.setViewName("role/add");
return modelAndView;
}
@PostMapping("add")
public String add(Role role) {
roleRepository.save(role);
return "redirect:/role/index";
}
@GetMapping("/index")
public ModelAndView index(HttpServletRequest request) {
ModelAndView modelAndView = getMv(request);
modelAndView.setViewName("role/index");
return modelAndView;
}
@GetMapping("/getAll")
@ResponseBody
public RoleVO getAll(int page,int limit) {
Pageable pageable = new PageRequest(page-1, limit);
PageImpl pageImpl = roleRepository.findAll(pageable);
List<Role> role = pageImpl.getContent();
RoleVO roleVO = new RoleVO();
roleVO.setData(role);
roleVO.setCount(roleRepository.count());
return roleVO;
}
@GetMapping("findById/{id}")
public ModelAndView findById(@PathVariable(value = "id") String id,HttpServletRequest request) {
ModelAndView modelAndView = getMv(request);
Role role = roleRepository.findById(id);
modelAndView.addObject("role", role);
List<String> myAuths = role.getAuths();
List<Authority> auths = new ArrayList<Authority>();
Iterator<Authority> allAuths = authorityRepository.findAll().iterator();
while(allAuths.hasNext()) {
Authority auth = allAuths.next();
auth.setHas(myAuths.contains(auth.getId()));
auths.add(auth);
}
modelAndView.addObject("auths", auths);
modelAndView.setViewName("role/update");
return modelAndView;
}
}
| UTF-8 | Java | 2,904 | java | RoleController.java | Java | []
| null | []
| package com.lz_java.controller;
import com.lz_java.entity.Authority;
import com.lz_java.entity.RoleVO;
import com.lz_java.entity.Role;
import com.lz_java.repository.AuthorityRepository;
import com.lz_java.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Controller
@RequestMapping("/role")
public class RoleController extends BaseController{
@Autowired
private RoleRepository roleRepository;
@Autowired
private AuthorityRepository authorityRepository;
@GetMapping("/add")
public ModelAndView add(HttpServletRequest request) {
ModelAndView modelAndView = getMv(request);
System.out.println(authorityRepository.findAll().iterator());
modelAndView.addObject("list", authorityRepository.findAll().iterator());
modelAndView.setViewName("role/add");
return modelAndView;
}
@PostMapping("add")
public String add(Role role) {
roleRepository.save(role);
return "redirect:/role/index";
}
@GetMapping("/index")
public ModelAndView index(HttpServletRequest request) {
ModelAndView modelAndView = getMv(request);
modelAndView.setViewName("role/index");
return modelAndView;
}
@GetMapping("/getAll")
@ResponseBody
public RoleVO getAll(int page,int limit) {
Pageable pageable = new PageRequest(page-1, limit);
PageImpl pageImpl = roleRepository.findAll(pageable);
List<Role> role = pageImpl.getContent();
RoleVO roleVO = new RoleVO();
roleVO.setData(role);
roleVO.setCount(roleRepository.count());
return roleVO;
}
@GetMapping("findById/{id}")
public ModelAndView findById(@PathVariable(value = "id") String id,HttpServletRequest request) {
ModelAndView modelAndView = getMv(request);
Role role = roleRepository.findById(id);
modelAndView.addObject("role", role);
List<String> myAuths = role.getAuths();
List<Authority> auths = new ArrayList<Authority>();
Iterator<Authority> allAuths = authorityRepository.findAll().iterator();
while(allAuths.hasNext()) {
Authority auth = allAuths.next();
auth.setHas(myAuths.contains(auth.getId()));
auths.add(auth);
}
modelAndView.addObject("auths", auths);
modelAndView.setViewName("role/update");
return modelAndView;
}
}
| 2,904 | 0.705579 | 0.705234 | 85 | 33.164707 | 22.246136 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.647059 | false | false | 0 |
136fc7a549a8a3aff315bb4f3cdd0b3e0ccc3635 | 6,519,760,413,737 | b6bd6da78e59b027aeff60072c91637b8d78c4dc | /app/src/main/java/com/example/chaithra/pinc/QuestionLoader.java | cd987139e2688722c433c3e2419c0b531562af72 | []
| no_license | chaiths246/Pinc_june | https://github.com/chaiths246/Pinc_june | 07f9d58066c32266e048ac49d79246c656dca3e5 | 9197d90601da4d664a498e95437c561e71f56fe1 | refs/heads/master | 2020-03-19T16:12:18.226000 | 2018-06-09T08:31:23 | 2018-06-09T08:31:23 | 136,705,243 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.chaithra.pinc;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.util.Log;
import com.example.chaithra.pinc.model.Question;
import java.util.ArrayList;
public class QuestionLoader extends AsyncTaskLoader<ArrayList<Question>> {
public static final String LOG_TAG = QuestionLoader.class.getSimpleName();
private String url;
public QuestionLoader(Context context, String url) {
super(context);
this.url = url;
}
@Override
protected void onStartLoading() {
forceLoad();
}
@Override
public ArrayList<Question> loadInBackground() {
if (url == null) {
return null;
}
ArrayList<Question> newslist = Utils.fetchQuestionData(url);
if (newslist.size() == 0) {
Log.d(LOG_TAG, "news list is empty");
}
return newslist;
}
}
| UTF-8 | Java | 908 | java | QuestionLoader.java | Java | []
| null | []
| package com.example.chaithra.pinc;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.util.Log;
import com.example.chaithra.pinc.model.Question;
import java.util.ArrayList;
public class QuestionLoader extends AsyncTaskLoader<ArrayList<Question>> {
public static final String LOG_TAG = QuestionLoader.class.getSimpleName();
private String url;
public QuestionLoader(Context context, String url) {
super(context);
this.url = url;
}
@Override
protected void onStartLoading() {
forceLoad();
}
@Override
public ArrayList<Question> loadInBackground() {
if (url == null) {
return null;
}
ArrayList<Question> newslist = Utils.fetchQuestionData(url);
if (newslist.size() == 0) {
Log.d(LOG_TAG, "news list is empty");
}
return newslist;
}
}
| 908 | 0.655286 | 0.654185 | 34 | 25.705883 | 21.751984 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 0 |
cbdffbfa09a4979e40566b418ee41767b3a5d613 | 8,065,948,627,618 | cf879dcc4163fa272f76962a2e296c1decaef57c | /libandroid/src/com/vnp/core/view/CommonCameraPreview.java | 17d1759841f4c0438cf6c3f547d3d701c38049d0 | []
| no_license | fordream/androidlibraty | https://github.com/fordream/androidlibraty | ae63f59ec0bbfb5553d32af66a23e69a2675f084 | 03693bfc74aa7c696a9f5061d929673702fb07cf | refs/heads/master | 2021-01-14T11:24:55.627000 | 2015-10-23T05:08:00 | 2015-10-23T05:08:00 | 46,546,784 | 0 | 1 | null | true | 2015-11-20T07:33:28 | 2015-11-20T07:33:26 | 2015-05-03T10:57:08 | 2015-10-23T05:08:12 | 55,788 | 0 | 0 | 0 | null | null | null | package com.vnp.core.view;
import java.io.IOException;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
//<uses-permission android:name="android.permission.CAMERA"/>
//<uses-feature android:name="android.hardware.camera" />
//<uses-feature android:name="android.hardware.camera.autofocus" />
//com.vnp.core.view.CommonCameraPreview
public class CommonCameraPreview extends SurfaceView implements
SurfaceHolder.Callback {
public interface TakePictureListener {
public void takeFail();
public void takeSucess(Bitmap bitmap);
}
public CommonCameraPreview(Context context, AttributeSet attrs) {
super(context, attrs);
open();
}
public CommonCameraPreview(Context context) {
super(context);
open();
}
public static Camera isCameraAvailiable() {
Camera object = null;
try {
object = Camera.open();
} catch (Exception e) {
}
return object;
}
private SurfaceHolder holdMe;
private Camera theCamera;
private void open() {
theCamera = isCameraAvailiable();
if (theCamera != null) {
Parameters parameters = theCamera.getParameters();
parameters.setRotation(90);
theCamera.setParameters(parameters);
}
holdMe = getHolder();
holdMe.addCallback(this);
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
try {
theCamera.setPreviewDisplay(surfaceHolder);
theCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
theCamera.setPreviewDisplay(holder);
theCamera.startPreview();
} catch (IOException e) {
}
}
public void takePicture(final TakePictureListener takePictureListener) {
PictureCallback capturedIt = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);
if (bitmap == null) {
takePictureListener.takeFail();
// Toast.makeText(getContext(), "not taken",
// Toast.LENGTH_SHORT).show();
} else {
takePictureListener.takeSucess(bitmap);
// Toast.makeText(getContext(), "taken", Toast.LENGTH_SHORT)
// .show();
}
theCamera.startPreview();
// theCamera.release();
// open();
}
};
if (theCamera != null) {
theCamera.takePicture(null, null, capturedIt);
} else {
takePictureListener.takeFail();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
if (theCamera != null) {
theCamera.stopPreview();
theCamera.release();
theCamera = null;
}
}
} | UTF-8 | Java | 2,930 | java | CommonCameraPreview.java | Java | []
| null | []
| package com.vnp.core.view;
import java.io.IOException;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
//<uses-permission android:name="android.permission.CAMERA"/>
//<uses-feature android:name="android.hardware.camera" />
//<uses-feature android:name="android.hardware.camera.autofocus" />
//com.vnp.core.view.CommonCameraPreview
public class CommonCameraPreview extends SurfaceView implements
SurfaceHolder.Callback {
public interface TakePictureListener {
public void takeFail();
public void takeSucess(Bitmap bitmap);
}
public CommonCameraPreview(Context context, AttributeSet attrs) {
super(context, attrs);
open();
}
public CommonCameraPreview(Context context) {
super(context);
open();
}
public static Camera isCameraAvailiable() {
Camera object = null;
try {
object = Camera.open();
} catch (Exception e) {
}
return object;
}
private SurfaceHolder holdMe;
private Camera theCamera;
private void open() {
theCamera = isCameraAvailiable();
if (theCamera != null) {
Parameters parameters = theCamera.getParameters();
parameters.setRotation(90);
theCamera.setParameters(parameters);
}
holdMe = getHolder();
holdMe.addCallback(this);
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
try {
theCamera.setPreviewDisplay(surfaceHolder);
theCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
theCamera.setPreviewDisplay(holder);
theCamera.startPreview();
} catch (IOException e) {
}
}
public void takePicture(final TakePictureListener takePictureListener) {
PictureCallback capturedIt = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);
if (bitmap == null) {
takePictureListener.takeFail();
// Toast.makeText(getContext(), "not taken",
// Toast.LENGTH_SHORT).show();
} else {
takePictureListener.takeSucess(bitmap);
// Toast.makeText(getContext(), "taken", Toast.LENGTH_SHORT)
// .show();
}
theCamera.startPreview();
// theCamera.release();
// open();
}
};
if (theCamera != null) {
theCamera.takePicture(null, null, capturedIt);
} else {
takePictureListener.takeFail();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
if (theCamera != null) {
theCamera.stopPreview();
theCamera.release();
theCamera = null;
}
}
} | 2,930 | 0.717747 | 0.716382 | 123 | 22.829268 | 19.886551 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.130081 | false | false | 0 |
5d7f99faafbbc1a4c2de61a1888dac4dc0b7a5cc | 30,940,944,459,299 | 275229548f2a258dffa0bd478e2d3a3214d6fb15 | /catalyst-web/src/test/java/com/intellecteu/catalyst/web/project/ProjectGenerationSmokeTests.java | b25f4f1a0393681b2b26717853a0b3ec4354a808 | [
"Apache-2.0"
]
| permissive | IntellectEU/catalyst-bootstrap | https://github.com/IntellectEU/catalyst-bootstrap | 762448c457b005367a1fe4ab0a4025f68f8a35af | 02a7bb0812a66db52338bd2ec631776c68c3c7fe | refs/heads/master | 2021-01-24T08:15:36.065000 | 2018-09-17T07:23:07 | 2018-09-17T07:23:07 | 122,975,502 | 5 | 0 | Apache-2.0 | false | 2018-09-07T12:37:11 | 2018-02-26T13:42:14 | 2018-09-06T12:34:14 | 2018-09-07T12:37:10 | 3,753 | 4 | 0 | 1 | Java | false | null | /*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellecteu.catalyst.web.project;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.intellecteu.catalyst.test.generator.ProjectAssert;
import com.intellecteu.catalyst.web.AbstractFullStackInitializrIntegrationTests;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.util.StreamUtils;
/**
* @author Dave Syer
* @author Stephane Nicoll
*/
@ActiveProfiles("test-default")
public class ProjectGenerationSmokeTests
extends AbstractFullStackInitializrIntegrationTests {
private File downloadDir;
private WebDriver driver;
private Action enterAction;
@Before
public void setup() throws IOException {
Assume.assumeTrue("Smoke tests disabled (set System property 'smoke.test')",
Boolean.getBoolean("smoke.test"));
downloadDir = folder.newFolder();
FirefoxProfile fxProfile = new FirefoxProfile();
fxProfile.setPreference("browser.download.folderList", 2);
fxProfile.setPreference("browser.download.manager.showWhenStarting", false);
fxProfile.setPreference("browser.download.dir", downloadDir.getAbsolutePath());
fxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/zip,application/x-compress,application/octet-stream");
FirefoxOptions options = new FirefoxOptions().setProfile(fxProfile);
driver = new FirefoxDriver(options);
Actions actions = new Actions(driver);
enterAction = actions.sendKeys(Keys.ENTER).build();
}
@After
public void destroy() {
if (driver != null) {
driver.close();
}
}
@Test
public void createSimpleProject() throws Exception {
HomePage page = toHome();
page.submit();
assertSimpleProject().isMavenProject().pomAssert().hasDependenciesCount(2)
.hasSpringBootStarterRootDependency().hasSpringBootStarterTest();
}
@Test
public void createSimpleProjectWithGradle() throws Exception {
HomePage page = toHome();
page.type("gradle-project");
page.submit();
assertSimpleProject().isGradleProject().gradleBuildAssert()
.contains("compile('org.springframework.boot:spring-boot-starter')")
.contains(
"testCompile('org.springframework.boot:spring-boot-starter-test')");
}
@Test
public void createSimpleProjectWithDifferentBootVersion() throws Exception {
HomePage page = toHome();
page.bootVersion("1.0.2.RELEASE");
page.submit();
assertSimpleProject().isMavenProject().pomAssert()
.hasSpringBootParent("1.0.2.RELEASE").hasDependenciesCount(2)
.hasSpringBootStarterRootDependency().hasSpringBootStarterTest();
}
@Test
public void createSimpleProjectWithDependencies() throws Exception {
HomePage page = toHome();
selectDependency(page, "Data JPA");
selectDependency(page, "Security");
page.submit();
assertSimpleProject().isMavenProject().pomAssert().hasDependenciesCount(3)
.hasSpringBootStarterDependency("data-jpa")
.hasSpringBootStarterDependency("security").hasSpringBootStarterTest();
}
@Test
public void selectDependencyTwiceRemovesIt() throws Exception {
HomePage page = toHome();
selectDependency(page, "Data JPA");
selectDependency(page, "Security");
selectDependency(page, "Security"); // remove
page.submit();
assertSimpleProject().isMavenProject().pomAssert().hasDependenciesCount(2)
.hasSpringBootStarterDependency("data-jpa").hasSpringBootStarterTest();
}
@Test
public void selectDependencyAndChangeToIncompatibleVersionRemovesIt()
throws Exception {
HomePage page = toHome();
selectDependency(page, "Data JPA");
selectDependency(page, "org.acme:bur");
page.bootVersion("1.0.2.RELEASE"); // Bur isn't available anymore
page.submit();
assertSimpleProject().isMavenProject().pomAssert()
.hasSpringBootParent("1.0.2.RELEASE").hasDependenciesCount(2)
.hasSpringBootStarterDependency("data-jpa").hasSpringBootStarterTest();
}
@Test
public void customArtifactIdUpdateNameAutomatically() throws Exception {
HomePage page = toHome();
page.groupId("org.foo");
page.submit();
zipProjectAssert(from("demo.zip")).hasBaseDir("demo")
.isJavaProject("org.foo.demo", "DemoApplication");
}
@Test
public void customGroupIdIdUpdatePackageAutomatically() throws Exception {
HomePage page = toHome();
page.artifactId("my-project");
page.submit();
zipProjectAssert(from("my-project.zip")).hasBaseDir("my-project")
.isJavaProject("com.example.myproject", "MyProjectApplication");
}
@Test
public void customArtifactIdWithInvalidPackageNameIsHandled() throws Exception {
HomePage page = toHome();
page.artifactId("42my-project");
page.submit();
zipProjectAssert(from("42my-project.zip")).hasBaseDir("42my-project")
.isJavaProject("com.example.myproject", "Application");
}
@Test
public void createGroovyProject() throws Exception {
HomePage page = toHome();
page.language("groovy");
page.submit();
ProjectAssert projectAssert = zipProjectAssert(from("demo.zip"));
projectAssert.hasBaseDir("demo").isMavenProject().isGroovyProject()
.hasStaticAndTemplatesResources(false).pomAssert().hasDependenciesCount(3)
.hasSpringBootStarterRootDependency().hasSpringBootStarterTest()
.hasDependency("org.codehaus.groovy", "groovy");
}
@Test
public void createKotlinProject() throws Exception {
HomePage page = toHome();
page.language("kotlin");
page.submit();
ProjectAssert projectAssert = zipProjectAssert(from("demo.zip"));
projectAssert.hasBaseDir("demo").isMavenProject().isKotlinProject()
.hasStaticAndTemplatesResources(false).pomAssert().hasDependenciesCount(4)
.hasSpringBootStarterRootDependency().hasSpringBootStarterTest()
.hasDependency("org.jetbrains.kotlin", "kotlin-stdlib-jdk8")
.hasDependency("org.jetbrains.kotlin", "kotlin-reflect");
}
@Test
public void createWarProject() throws Exception {
HomePage page = toHome();
page.advanced();
page.packaging("war");
page.submit();
ProjectAssert projectAssert = zipProjectAssert(from("demo.zip"));
projectAssert.hasBaseDir("demo").isMavenProject().isJavaWarProject().pomAssert()
.hasPackaging("war").hasDependenciesCount(3)
.hasSpringBootStarterDependency("web") // Added with war packaging
.hasSpringBootStarterTomcat().hasSpringBootStarterTest();
}
@Test
public void createJavaProjectWithCustomDefaults() throws Exception {
HomePage page = toHome();
page.groupId("com.acme");
page.artifactId("foo-bar");
page.advanced();
page.name("My project");
page.description("A description for my project");
page.packageName("com.example.foo");
page.dependency("web").click();
page.dependency("data-jpa").click();
page.submit();
ProjectAssert projectAssert = zipProjectAssert(from("foo-bar.zip"));
projectAssert.hasBaseDir("foo-bar").isMavenProject()
.isJavaProject("com.example.foo", "MyProjectApplication")
.hasStaticAndTemplatesResources(true).pomAssert().hasGroupId("com.acme")
.hasArtifactId("foo-bar").hasName("My project")
.hasDescription("A description for my project")
.hasSpringBootStarterDependency("web")
.hasSpringBootStarterDependency("data-jpa").hasSpringBootStarterTest();
}
@Test
public void createKotlinProjectWithCustomDefaults() throws Exception {
HomePage page = toHome();
page.groupId("com.acme");
page.artifactId("foo-bar");
page.language("kotlin");
page.advanced();
page.name("My project");
page.description("A description for my Kotlin project");
page.packageName("com.example.foo");
page.dependency("web").click();
page.dependency("data-jpa").click();
page.submit();
ProjectAssert projectAssert = zipProjectAssert(from("foo-bar.zip"));
projectAssert.hasBaseDir("foo-bar").isMavenProject()
.isKotlinProject("com.example.foo", "MyProjectApplication")
.hasStaticAndTemplatesResources(true).pomAssert().hasGroupId("com.acme")
.hasArtifactId("foo-bar").hasName("My project")
.hasDescription("A description for my Kotlin project")
.hasSpringBootStarterDependency("web")
.hasSpringBootStarterDependency("data-jpa").hasSpringBootStarterTest();
}
@Test
public void createGroovyProjectWithCustomDefaults() throws Exception {
HomePage page = toHome();
page.groupId("com.acme");
page.artifactId("foo-bar");
page.language("groovy");
page.advanced();
page.name("My project");
page.description("A description for my Groovy project");
page.packageName("com.example.foo");
page.dependency("web").click();
page.dependency("data-jpa").click();
page.submit();
ProjectAssert projectAssert = zipProjectAssert(from("foo-bar.zip"));
projectAssert.hasBaseDir("foo-bar").isMavenProject()
.isGroovyProject("com.example.foo", "MyProjectApplication")
.hasStaticAndTemplatesResources(true).pomAssert().hasGroupId("com.acme")
.hasArtifactId("foo-bar").hasName("My project")
.hasDescription("A description for my Groovy project")
.hasSpringBootStarterDependency("web")
.hasSpringBootStarterDependency("data-jpa").hasSpringBootStarterTest();
}
@Test
public void dependencyHiddenAccordingToRange() throws Exception {
HomePage page = toHome(); // bur: [1.1.4.RELEASE,1.2.0.BUILD-SNAPSHOT)
page.advanced();
assertThat(page.dependency("org.acme:bur").isEnabled()).isTrue();
page.bootVersion("1.0.2.RELEASE");
assertThat(page.dependency("org.acme:bur").isEnabled()).isFalse();
assertThat(page.dependency("org.acme:biz").isEnabled()).isFalse();
page.bootVersion("1.1.4.RELEASE");
assertThat(page.dependency("org.acme:bur").isEnabled()).isTrue();
assertThat(page.dependency("org.acme:biz").isEnabled()).isFalse();
page.bootVersion("Latest SNAPSHOT");
assertThat(page.dependency("org.acme:bur").isEnabled()).isFalse();
assertThat(page.dependency("org.acme:biz").isEnabled()).isTrue();
}
@Test
public void dependencyUncheckedWhenHidden() throws Exception {
HomePage page = toHome(); // bur: [1.1.4.RELEASE,1.2.0.BUILD-SNAPSHOT)
page.advanced();
page.dependency("org.acme:bur").click();
assertThat(page.dependency("org.acme:bur").isSelected()).isTrue();
page.bootVersion("1.0.2.RELEASE");
assertThat(page.dependency("org.acme:bur").isEnabled()).isFalse();
page.bootVersion("1.1.4.RELEASE");
assertThat(page.dependency("org.acme:bur").isEnabled()).isTrue();
assertThat(page.dependency("org.acme:bur").isSelected()).isFalse();
}
@Test
public void customizationShowsUpInDefaultView() throws Exception {
HomePage page = toHome("/#!language=groovy&packageName=com.example.acme");
assertEquals("groovy", page.value("language"));
assertEquals("com.example.acme", page.value("packageName"));
page.submit();
ProjectAssert projectAssert = zipProjectAssert(from("demo.zip"));
projectAssert.hasBaseDir("demo").isMavenProject()
.isGroovyProject("com.example.acme",
ProjectAssert.DEFAULT_APPLICATION_NAME)
.hasStaticAndTemplatesResources(false).pomAssert().hasDependenciesCount(3)
.hasSpringBootStarterRootDependency().hasSpringBootStarterTest()
.hasDependency("org.codehaus.groovy", "groovy");
}
@Test
public void customizationsShowsUpWhenViewIsSwitched() throws Exception {
HomePage page = toHome("/#!packaging=war&javaVersion=1.7");
assertEquals("war", page.value("packaging"));
assertEquals("1.7", page.value("javaVersion"));
page.advanced();
assertEquals("war", page.value("packaging"));
assertEquals("1.7", page.value("javaVersion"));
page.simple();
assertEquals("war", page.value("packaging"));
assertEquals("1.7", page.value("javaVersion"));
}
@Test
public void customizationsOnGroupIdAndArtifactId() throws Exception {
HomePage page = toHome("/#!groupId=com.example.acme&artifactId=my-project");
page.submit();
ProjectAssert projectAssert = zipProjectAssert(from("my-project.zip"));
projectAssert.hasBaseDir("my-project").isMavenProject()
.isJavaProject("com.example.acme.myproject", "MyProjectApplication")
.hasStaticAndTemplatesResources(false).pomAssert()
.hasGroupId("com.example.acme").hasArtifactId("my-project")
.hasDependenciesCount(2).hasSpringBootStarterRootDependency()
.hasSpringBootStarterTest();
}
private HomePage toHome() {
return toHome("/");
}
private HomePage toHome(String path) {
driver.get("http://localhost:" + port + path);
return new HomePage(driver);
}
private ProjectAssert assertSimpleProject() throws Exception {
return zipProjectAssert(from("demo.zip")).hasBaseDir("demo").isJavaProject()
.hasStaticAndTemplatesResources(false);
}
private void selectDependency(HomePage page, String text) {
page.autocomplete(text);
enterAction.perform();
}
private byte[] from(String fileName) throws Exception {
return StreamUtils.copyToByteArray(new FileInputStream(getArchive(fileName)));
}
private File getArchive(String fileName) {
File archive = new File(downloadDir, fileName);
assertTrue("Expected content with name " + fileName, archive.exists());
return archive;
}
}
| UTF-8 | Java | 14,696 | java | ProjectGenerationSmokeTests.java | Java | [
{
"context": ".springframework.util.StreamUtils;\n\n/**\n * @author Dave Syer\n * @author Stephane Nicoll\n */\n@ActiveProfiles(\"t",
"end": 1583,
"score": 0.9998382925987244,
"start": 1574,
"tag": "NAME",
"value": "Dave Syer"
},
{
"context": ".StreamUtils;\n\n/**\n * @author Dave Syer\n * @author Stephane Nicoll\n */\n@ActiveProfiles(\"test-default\")\npublic class ",
"end": 1610,
"score": 0.9998798370361328,
"start": 1595,
"tag": "NAME",
"value": "Stephane Nicoll"
}
]
| null | []
| /*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellecteu.catalyst.web.project;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.intellecteu.catalyst.test.generator.ProjectAssert;
import com.intellecteu.catalyst.web.AbstractFullStackInitializrIntegrationTests;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.util.StreamUtils;
/**
* @author <NAME>
* @author <NAME>
*/
@ActiveProfiles("test-default")
public class ProjectGenerationSmokeTests
extends AbstractFullStackInitializrIntegrationTests {
private File downloadDir;
private WebDriver driver;
private Action enterAction;
@Before
public void setup() throws IOException {
Assume.assumeTrue("Smoke tests disabled (set System property 'smoke.test')",
Boolean.getBoolean("smoke.test"));
downloadDir = folder.newFolder();
FirefoxProfile fxProfile = new FirefoxProfile();
fxProfile.setPreference("browser.download.folderList", 2);
fxProfile.setPreference("browser.download.manager.showWhenStarting", false);
fxProfile.setPreference("browser.download.dir", downloadDir.getAbsolutePath());
fxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/zip,application/x-compress,application/octet-stream");
FirefoxOptions options = new FirefoxOptions().setProfile(fxProfile);
driver = new FirefoxDriver(options);
Actions actions = new Actions(driver);
enterAction = actions.sendKeys(Keys.ENTER).build();
}
@After
public void destroy() {
if (driver != null) {
driver.close();
}
}
@Test
public void createSimpleProject() throws Exception {
HomePage page = toHome();
page.submit();
assertSimpleProject().isMavenProject().pomAssert().hasDependenciesCount(2)
.hasSpringBootStarterRootDependency().hasSpringBootStarterTest();
}
@Test
public void createSimpleProjectWithGradle() throws Exception {
HomePage page = toHome();
page.type("gradle-project");
page.submit();
assertSimpleProject().isGradleProject().gradleBuildAssert()
.contains("compile('org.springframework.boot:spring-boot-starter')")
.contains(
"testCompile('org.springframework.boot:spring-boot-starter-test')");
}
@Test
public void createSimpleProjectWithDifferentBootVersion() throws Exception {
HomePage page = toHome();
page.bootVersion("1.0.2.RELEASE");
page.submit();
assertSimpleProject().isMavenProject().pomAssert()
.hasSpringBootParent("1.0.2.RELEASE").hasDependenciesCount(2)
.hasSpringBootStarterRootDependency().hasSpringBootStarterTest();
}
@Test
public void createSimpleProjectWithDependencies() throws Exception {
HomePage page = toHome();
selectDependency(page, "Data JPA");
selectDependency(page, "Security");
page.submit();
assertSimpleProject().isMavenProject().pomAssert().hasDependenciesCount(3)
.hasSpringBootStarterDependency("data-jpa")
.hasSpringBootStarterDependency("security").hasSpringBootStarterTest();
}
@Test
public void selectDependencyTwiceRemovesIt() throws Exception {
HomePage page = toHome();
selectDependency(page, "Data JPA");
selectDependency(page, "Security");
selectDependency(page, "Security"); // remove
page.submit();
assertSimpleProject().isMavenProject().pomAssert().hasDependenciesCount(2)
.hasSpringBootStarterDependency("data-jpa").hasSpringBootStarterTest();
}
@Test
public void selectDependencyAndChangeToIncompatibleVersionRemovesIt()
throws Exception {
HomePage page = toHome();
selectDependency(page, "Data JPA");
selectDependency(page, "org.acme:bur");
page.bootVersion("1.0.2.RELEASE"); // Bur isn't available anymore
page.submit();
assertSimpleProject().isMavenProject().pomAssert()
.hasSpringBootParent("1.0.2.RELEASE").hasDependenciesCount(2)
.hasSpringBootStarterDependency("data-jpa").hasSpringBootStarterTest();
}
@Test
public void customArtifactIdUpdateNameAutomatically() throws Exception {
HomePage page = toHome();
page.groupId("org.foo");
page.submit();
zipProjectAssert(from("demo.zip")).hasBaseDir("demo")
.isJavaProject("org.foo.demo", "DemoApplication");
}
@Test
public void customGroupIdIdUpdatePackageAutomatically() throws Exception {
HomePage page = toHome();
page.artifactId("my-project");
page.submit();
zipProjectAssert(from("my-project.zip")).hasBaseDir("my-project")
.isJavaProject("com.example.myproject", "MyProjectApplication");
}
@Test
public void customArtifactIdWithInvalidPackageNameIsHandled() throws Exception {
HomePage page = toHome();
page.artifactId("42my-project");
page.submit();
zipProjectAssert(from("42my-project.zip")).hasBaseDir("42my-project")
.isJavaProject("com.example.myproject", "Application");
}
@Test
public void createGroovyProject() throws Exception {
HomePage page = toHome();
page.language("groovy");
page.submit();
ProjectAssert projectAssert = zipProjectAssert(from("demo.zip"));
projectAssert.hasBaseDir("demo").isMavenProject().isGroovyProject()
.hasStaticAndTemplatesResources(false).pomAssert().hasDependenciesCount(3)
.hasSpringBootStarterRootDependency().hasSpringBootStarterTest()
.hasDependency("org.codehaus.groovy", "groovy");
}
@Test
public void createKotlinProject() throws Exception {
HomePage page = toHome();
page.language("kotlin");
page.submit();
ProjectAssert projectAssert = zipProjectAssert(from("demo.zip"));
projectAssert.hasBaseDir("demo").isMavenProject().isKotlinProject()
.hasStaticAndTemplatesResources(false).pomAssert().hasDependenciesCount(4)
.hasSpringBootStarterRootDependency().hasSpringBootStarterTest()
.hasDependency("org.jetbrains.kotlin", "kotlin-stdlib-jdk8")
.hasDependency("org.jetbrains.kotlin", "kotlin-reflect");
}
@Test
public void createWarProject() throws Exception {
HomePage page = toHome();
page.advanced();
page.packaging("war");
page.submit();
ProjectAssert projectAssert = zipProjectAssert(from("demo.zip"));
projectAssert.hasBaseDir("demo").isMavenProject().isJavaWarProject().pomAssert()
.hasPackaging("war").hasDependenciesCount(3)
.hasSpringBootStarterDependency("web") // Added with war packaging
.hasSpringBootStarterTomcat().hasSpringBootStarterTest();
}
@Test
public void createJavaProjectWithCustomDefaults() throws Exception {
HomePage page = toHome();
page.groupId("com.acme");
page.artifactId("foo-bar");
page.advanced();
page.name("My project");
page.description("A description for my project");
page.packageName("com.example.foo");
page.dependency("web").click();
page.dependency("data-jpa").click();
page.submit();
ProjectAssert projectAssert = zipProjectAssert(from("foo-bar.zip"));
projectAssert.hasBaseDir("foo-bar").isMavenProject()
.isJavaProject("com.example.foo", "MyProjectApplication")
.hasStaticAndTemplatesResources(true).pomAssert().hasGroupId("com.acme")
.hasArtifactId("foo-bar").hasName("My project")
.hasDescription("A description for my project")
.hasSpringBootStarterDependency("web")
.hasSpringBootStarterDependency("data-jpa").hasSpringBootStarterTest();
}
@Test
public void createKotlinProjectWithCustomDefaults() throws Exception {
HomePage page = toHome();
page.groupId("com.acme");
page.artifactId("foo-bar");
page.language("kotlin");
page.advanced();
page.name("My project");
page.description("A description for my Kotlin project");
page.packageName("com.example.foo");
page.dependency("web").click();
page.dependency("data-jpa").click();
page.submit();
ProjectAssert projectAssert = zipProjectAssert(from("foo-bar.zip"));
projectAssert.hasBaseDir("foo-bar").isMavenProject()
.isKotlinProject("com.example.foo", "MyProjectApplication")
.hasStaticAndTemplatesResources(true).pomAssert().hasGroupId("com.acme")
.hasArtifactId("foo-bar").hasName("My project")
.hasDescription("A description for my Kotlin project")
.hasSpringBootStarterDependency("web")
.hasSpringBootStarterDependency("data-jpa").hasSpringBootStarterTest();
}
@Test
public void createGroovyProjectWithCustomDefaults() throws Exception {
HomePage page = toHome();
page.groupId("com.acme");
page.artifactId("foo-bar");
page.language("groovy");
page.advanced();
page.name("My project");
page.description("A description for my Groovy project");
page.packageName("com.example.foo");
page.dependency("web").click();
page.dependency("data-jpa").click();
page.submit();
ProjectAssert projectAssert = zipProjectAssert(from("foo-bar.zip"));
projectAssert.hasBaseDir("foo-bar").isMavenProject()
.isGroovyProject("com.example.foo", "MyProjectApplication")
.hasStaticAndTemplatesResources(true).pomAssert().hasGroupId("com.acme")
.hasArtifactId("foo-bar").hasName("My project")
.hasDescription("A description for my Groovy project")
.hasSpringBootStarterDependency("web")
.hasSpringBootStarterDependency("data-jpa").hasSpringBootStarterTest();
}
@Test
public void dependencyHiddenAccordingToRange() throws Exception {
HomePage page = toHome(); // bur: [1.1.4.RELEASE,1.2.0.BUILD-SNAPSHOT)
page.advanced();
assertThat(page.dependency("org.acme:bur").isEnabled()).isTrue();
page.bootVersion("1.0.2.RELEASE");
assertThat(page.dependency("org.acme:bur").isEnabled()).isFalse();
assertThat(page.dependency("org.acme:biz").isEnabled()).isFalse();
page.bootVersion("1.1.4.RELEASE");
assertThat(page.dependency("org.acme:bur").isEnabled()).isTrue();
assertThat(page.dependency("org.acme:biz").isEnabled()).isFalse();
page.bootVersion("Latest SNAPSHOT");
assertThat(page.dependency("org.acme:bur").isEnabled()).isFalse();
assertThat(page.dependency("org.acme:biz").isEnabled()).isTrue();
}
@Test
public void dependencyUncheckedWhenHidden() throws Exception {
HomePage page = toHome(); // bur: [1.1.4.RELEASE,1.2.0.BUILD-SNAPSHOT)
page.advanced();
page.dependency("org.acme:bur").click();
assertThat(page.dependency("org.acme:bur").isSelected()).isTrue();
page.bootVersion("1.0.2.RELEASE");
assertThat(page.dependency("org.acme:bur").isEnabled()).isFalse();
page.bootVersion("1.1.4.RELEASE");
assertThat(page.dependency("org.acme:bur").isEnabled()).isTrue();
assertThat(page.dependency("org.acme:bur").isSelected()).isFalse();
}
@Test
public void customizationShowsUpInDefaultView() throws Exception {
HomePage page = toHome("/#!language=groovy&packageName=com.example.acme");
assertEquals("groovy", page.value("language"));
assertEquals("com.example.acme", page.value("packageName"));
page.submit();
ProjectAssert projectAssert = zipProjectAssert(from("demo.zip"));
projectAssert.hasBaseDir("demo").isMavenProject()
.isGroovyProject("com.example.acme",
ProjectAssert.DEFAULT_APPLICATION_NAME)
.hasStaticAndTemplatesResources(false).pomAssert().hasDependenciesCount(3)
.hasSpringBootStarterRootDependency().hasSpringBootStarterTest()
.hasDependency("org.codehaus.groovy", "groovy");
}
@Test
public void customizationsShowsUpWhenViewIsSwitched() throws Exception {
HomePage page = toHome("/#!packaging=war&javaVersion=1.7");
assertEquals("war", page.value("packaging"));
assertEquals("1.7", page.value("javaVersion"));
page.advanced();
assertEquals("war", page.value("packaging"));
assertEquals("1.7", page.value("javaVersion"));
page.simple();
assertEquals("war", page.value("packaging"));
assertEquals("1.7", page.value("javaVersion"));
}
@Test
public void customizationsOnGroupIdAndArtifactId() throws Exception {
HomePage page = toHome("/#!groupId=com.example.acme&artifactId=my-project");
page.submit();
ProjectAssert projectAssert = zipProjectAssert(from("my-project.zip"));
projectAssert.hasBaseDir("my-project").isMavenProject()
.isJavaProject("com.example.acme.myproject", "MyProjectApplication")
.hasStaticAndTemplatesResources(false).pomAssert()
.hasGroupId("com.example.acme").hasArtifactId("my-project")
.hasDependenciesCount(2).hasSpringBootStarterRootDependency()
.hasSpringBootStarterTest();
}
private HomePage toHome() {
return toHome("/");
}
private HomePage toHome(String path) {
driver.get("http://localhost:" + port + path);
return new HomePage(driver);
}
private ProjectAssert assertSimpleProject() throws Exception {
return zipProjectAssert(from("demo.zip")).hasBaseDir("demo").isJavaProject()
.hasStaticAndTemplatesResources(false);
}
private void selectDependency(HomePage page, String text) {
page.autocomplete(text);
enterAction.perform();
}
private byte[] from(String fileName) throws Exception {
return StreamUtils.copyToByteArray(new FileInputStream(getArchive(fileName)));
}
private File getArchive(String fileName) {
File archive = new File(downloadDir, fileName);
assertTrue("Expected content with name " + fileName, archive.exists());
return archive;
}
}
| 14,684 | 0.716522 | 0.711486 | 379 | 37.773087 | 27.111832 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.593668 | false | false | 0 |
05ab43c2e66bcf7be83a39ba412b9c5a0e85d7d3 | 10,153,302,749,326 | 7dc4804a5a385e7e8dd996ea86760864fddc18bb | /src/main/java/com/jt/plt/product/vo/ins/InsuranceObjectVO.java | 81b63b1f4ff2bc42fbcc7083303311994d8df0fc | []
| no_license | HongMu7/prod-svc | https://github.com/HongMu7/prod-svc | 11e23e2a62a1e1213a87af258088978e1708eaf7 | 78966a745f3dd0f7ad3cdc7bcd4a96d7165a59f0 | refs/heads/develop | 2020-06-16T22:47:16.421000 | 2020-04-23T04:21:49 | 2020-04-23T04:21:49 | 195,721,259 | 0 | 0 | null | false | 2020-12-04T11:58:14 | 2019-07-08T02:18:11 | 2020-12-04T11:57:50 | 2020-12-04T11:58:13 | 10,010 | 0 | 0 | 2 | Java | false | false | package com.jt.plt.product.vo.ins;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import java.util.Date;
import java.util.List;
@Data
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class InsuranceObjectVO {
@ApiModelProperty("标的ID")
private Long id;
@ApiModelProperty(name = "标的类型", value = "标的类型, 学生:00;教师:01;医生:10;电梯:20;索道:21;客运汽车:30;货运汽车:31,40被保分社")
private String objectType;
@ApiModelProperty(name = "标的唯一标识号", value = "标的唯一标识号(特设电梯编号或出厂编号、教保身份证号、旅游分社社会信用代码)1")
private String objectId;
@ApiModelProperty(name = "标的名称(针对教保查询)", value = "标的名称(针对教保查询)")
private String objectName;
@ApiModelProperty(name = "标的开始日期", value = "标的开始日期")
private Date startDate;
@ApiModelProperty(name = "标的结束时间", value = "标的结束时间")
private Date endDate;
@ApiModelProperty(name = "序号", value = "序号")
private Integer no;
@ApiModelProperty(name = "被保人ID", value = "被保人ID")
private Long tInsuredInfoId;
@ApiModelProperty(name = "投保单号", value = "投保单号")
private String applicationFormCode;
@ApiModelProperty(name = "保单号", value = "保单号")
private String insurancePolicyNo;
@ApiModelProperty("批单申请日期")
private Date applyDate;
/**
* 被保人编号
*/
private Integer insuredNo;
}
| UTF-8 | Java | 1,621 | java | InsuranceObjectVO.java | Java | []
| null | []
| package com.jt.plt.product.vo.ins;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import java.util.Date;
import java.util.List;
@Data
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class InsuranceObjectVO {
@ApiModelProperty("标的ID")
private Long id;
@ApiModelProperty(name = "标的类型", value = "标的类型, 学生:00;教师:01;医生:10;电梯:20;索道:21;客运汽车:30;货运汽车:31,40被保分社")
private String objectType;
@ApiModelProperty(name = "标的唯一标识号", value = "标的唯一标识号(特设电梯编号或出厂编号、教保身份证号、旅游分社社会信用代码)1")
private String objectId;
@ApiModelProperty(name = "标的名称(针对教保查询)", value = "标的名称(针对教保查询)")
private String objectName;
@ApiModelProperty(name = "标的开始日期", value = "标的开始日期")
private Date startDate;
@ApiModelProperty(name = "标的结束时间", value = "标的结束时间")
private Date endDate;
@ApiModelProperty(name = "序号", value = "序号")
private Integer no;
@ApiModelProperty(name = "被保人ID", value = "被保人ID")
private Long tInsuredInfoId;
@ApiModelProperty(name = "投保单号", value = "投保单号")
private String applicationFormCode;
@ApiModelProperty(name = "保单号", value = "保单号")
private String insurancePolicyNo;
@ApiModelProperty("批单申请日期")
private Date applyDate;
/**
* 被保人编号
*/
private Integer insuredNo;
}
| 1,621 | 0.687932 | 0.674865 | 54 | 23.092592 | 23.875656 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62963 | false | false | 0 |
2321d093106fb16340957a34ce39369ce250e398 | 10,153,302,749,853 | 9810faa92701567b945436d1507f6ab2ebbdff35 | /src/com/scatterlogic/games/spyrunner/MusicPlayerOld.java | a2248b1325b990cbf04a629d949bb47f97746b0b | []
| no_license | TheVoidReturns/SpyRunner | https://github.com/TheVoidReturns/SpyRunner | 1eb271184b1fd579fafe742c274396a710a48055 | 377b37b41f8f481cdfd0a1b79edc08e91857e64f | refs/heads/master | 2021-01-10T20:20:55.781000 | 2014-01-18T17:53:35 | 2014-01-18T17:53:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.scatterlogic.games.spyrunner;
import java.io.IOException;
import android.util.Log;
import java.util.ArrayList;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.os.PowerManager;
public class MusicPlayerOld extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
/*Still need to implement:
Audio Focus stuff
audio becoming noisy (user unplugging earphones for example)
Read user's music content - this will also be needed in the music setup activity to assign ratings etc.
*/
boolean isPrepared = false;
boolean isPlaying = false;
MediaPlayer musicPlayer = null;
Uri contentUri;
// private static final String ACTION_PLAY = "com.example.action.PLAY";
String songName = "Test Songname";
int notification_id = 1234;
ArrayList<String> songTitles = new ArrayList<String>();
ArrayList<Long> songIds = new ArrayList<Long>();
int numSongs;
boolean cursorError;
/*
public void onCreate() {
musicPlayer.setOnErrorListener(this);
musicPlayer.setOnPreparedListener(this);
musicPlayer.reset();
}
*/
@SuppressWarnings("deprecation")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// if (intent.getAction().equals(ACTION_PLAY)) {
musicPlayer = new MediaPlayer();
musicPlayer.setOnPreparedListener(this);
musicPlayer.setOnErrorListener(this);
getUserMusic();
Log.d("MusicPlayer" , "gotusermusic");
Log.d("MusicPlayer", songTitles.get(0));
//Test song
if(cursorError !=true) {
musicPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
contentUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, songIds.get(201));
try {
musicPlayer.setDataSource(getApplicationContext(), contentUri);
Log.e("MusicPlayer", "Data Source is set");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
musicPlayer.prepareAsync(); // prepare asynchronously to not block main thread (could take a while to initialise)
musicPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
//Need to run as a foreground status, with an entry in the notification bar and a way for the user to use that notification to
//open the Mission Control activity
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(getApplicationContext(), MissionControlActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification();
notification.tickerText = "Hello Hello Hello!";
notification.icon = R.drawable.robin8bit;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
//This method is deprecated but am using for this first implementation
notification.setLatestEventInfo(getApplicationContext(), "MusicPlayerSample",
"Playing: " + songName, pi);
startForeground(notification_id, notification);
}
// }
//Fudge
return 1;
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
this.isPrepared = true;
player.start();
}
public boolean onError(MediaPlayer mp, int what, int extra) {
// Need to react to the error?
// The MediaPlayer has moved to the Error state, must be reset!
mp.reset();
mp.prepareAsync();
//Fudge
return true;
}
//Ensure the media player is released properly - don't rely on the garbage collector;
@Override
public void onDestroy() {
if (musicPlayer != null) musicPlayer.release();
}
public void getUserMusic() {
ContentResolver contentResolver = getContentResolver();
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Log.d("MusicPlayer" , "uri");
Cursor cursor = null;
try{
cursor = contentResolver.query(uri, null, null, null, null);
cursorError = false;
}
finally{
cursorError = true;
}
Log.d("MusicPlayer" , "cursor");
if (cursor == null) {
// query failed, handle error.
} else if (!cursor.moveToFirst()) {
// no media on the device
} else {
int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
do {
songIds.add(cursor.getLong(idColumn));
songTitles.add(cursor.getString(titleColumn));
} while (cursor.moveToNext());
numSongs = songIds.size();
String songID1test = songIds.get(201).toString();
String songTitleTest = songTitles.get(201);
Log.d("MusicPlayer", songID1test);
Log.d("MusicPlayer", songTitleTest);
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void play() {
this.musicPlayer.start();
this.isPlaying = true;
stopForeground(false);
}
public void playSong() {
long id = (long)songIds.get(1);
contentUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
musicPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
musicPlayer.setDataSource(getApplicationContext(), contentUri);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void pause() {
this.musicPlayer.pause();
this.isPlaying = false;
}
public void stop() {
this.musicPlayer.stop();
this.isPlaying = false;
stopForeground(true);
musicPlayer.release();
}
public void skip() {
//this.musicPlayer.selectTrack(1);
}
}
| UTF-8 | Java | 7,248 | java | MusicPlayerOld.java | Java | []
| null | []
| package com.scatterlogic.games.spyrunner;
import java.io.IOException;
import android.util.Log;
import java.util.ArrayList;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.os.PowerManager;
public class MusicPlayerOld extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
/*Still need to implement:
Audio Focus stuff
audio becoming noisy (user unplugging earphones for example)
Read user's music content - this will also be needed in the music setup activity to assign ratings etc.
*/
boolean isPrepared = false;
boolean isPlaying = false;
MediaPlayer musicPlayer = null;
Uri contentUri;
// private static final String ACTION_PLAY = "com.example.action.PLAY";
String songName = "Test Songname";
int notification_id = 1234;
ArrayList<String> songTitles = new ArrayList<String>();
ArrayList<Long> songIds = new ArrayList<Long>();
int numSongs;
boolean cursorError;
/*
public void onCreate() {
musicPlayer.setOnErrorListener(this);
musicPlayer.setOnPreparedListener(this);
musicPlayer.reset();
}
*/
@SuppressWarnings("deprecation")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// if (intent.getAction().equals(ACTION_PLAY)) {
musicPlayer = new MediaPlayer();
musicPlayer.setOnPreparedListener(this);
musicPlayer.setOnErrorListener(this);
getUserMusic();
Log.d("MusicPlayer" , "gotusermusic");
Log.d("MusicPlayer", songTitles.get(0));
//Test song
if(cursorError !=true) {
musicPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
contentUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, songIds.get(201));
try {
musicPlayer.setDataSource(getApplicationContext(), contentUri);
Log.e("MusicPlayer", "Data Source is set");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
musicPlayer.prepareAsync(); // prepare asynchronously to not block main thread (could take a while to initialise)
musicPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
//Need to run as a foreground status, with an entry in the notification bar and a way for the user to use that notification to
//open the Mission Control activity
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(getApplicationContext(), MissionControlActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification();
notification.tickerText = "Hello Hello Hello!";
notification.icon = R.drawable.robin8bit;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
//This method is deprecated but am using for this first implementation
notification.setLatestEventInfo(getApplicationContext(), "MusicPlayerSample",
"Playing: " + songName, pi);
startForeground(notification_id, notification);
}
// }
//Fudge
return 1;
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
this.isPrepared = true;
player.start();
}
public boolean onError(MediaPlayer mp, int what, int extra) {
// Need to react to the error?
// The MediaPlayer has moved to the Error state, must be reset!
mp.reset();
mp.prepareAsync();
//Fudge
return true;
}
//Ensure the media player is released properly - don't rely on the garbage collector;
@Override
public void onDestroy() {
if (musicPlayer != null) musicPlayer.release();
}
public void getUserMusic() {
ContentResolver contentResolver = getContentResolver();
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Log.d("MusicPlayer" , "uri");
Cursor cursor = null;
try{
cursor = contentResolver.query(uri, null, null, null, null);
cursorError = false;
}
finally{
cursorError = true;
}
Log.d("MusicPlayer" , "cursor");
if (cursor == null) {
// query failed, handle error.
} else if (!cursor.moveToFirst()) {
// no media on the device
} else {
int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
do {
songIds.add(cursor.getLong(idColumn));
songTitles.add(cursor.getString(titleColumn));
} while (cursor.moveToNext());
numSongs = songIds.size();
String songID1test = songIds.get(201).toString();
String songTitleTest = songTitles.get(201);
Log.d("MusicPlayer", songID1test);
Log.d("MusicPlayer", songTitleTest);
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void play() {
this.musicPlayer.start();
this.isPlaying = true;
stopForeground(false);
}
public void playSong() {
long id = (long)songIds.get(1);
contentUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
musicPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
musicPlayer.setDataSource(getApplicationContext(), contentUri);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void pause() {
this.musicPlayer.pause();
this.isPlaying = false;
}
public void stop() {
this.musicPlayer.stop();
this.isPlaying = false;
stopForeground(true);
musicPlayer.release();
}
public void skip() {
//this.musicPlayer.selectTrack(1);
}
}
| 7,248 | 0.640315 | 0.637417 | 209 | 32.669857 | 25.772303 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.904306 | false | false | 0 |
a0e7240bfac8303ad214f20b9e48eff355937cc5 | 10,153,302,752,210 | ddf8208932453c0edfda63beb796ce31c30550c5 | /4lab/src/main/java/com/orfac/lab/model/User.java | c7db111c45d5eadacbfe9bfeda586e6bc2b0e123 | []
| no_license | Orfac/IAD-labs | https://github.com/Orfac/IAD-labs | 93853895a20f8229017bf2662c31c3dc844dace3 | 8363e61ce3d5319fd0dfdfbdceb22cab6cc47d0b | refs/heads/master | 2021-06-21T10:59:21.841000 | 2021-01-06T00:12:50 | 2021-01-06T00:12:50 | 147,250,551 | 0 | 0 | null | false | 2021-01-06T00:12:51 | 2018-09-03T20:26:47 | 2020-01-29T22:15:11 | 2021-01-06T00:12:50 | 413 | 0 | 0 | 0 | JavaScript | false | false | package com.orfac.lab.model;
import javax.persistence.*;
import java.util.List;
@Table(name = "users")
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(nullable = false, unique = true)
private String login;
@Column(nullable = false)
private String password;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
@OrderBy("id ASC")
private List<Point> pointList;
public User() { }
public User(String login, String password) {
this.login = login;
this.password = password;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void addPoint(Point point) {
pointList.add(point);
}
public List<Point> getPointList() {
return pointList;
}
public void setPointList(List<Point> pointList) {
this.pointList = pointList;
}
public boolean isNew() {
return id == null;
}
}
| UTF-8 | Java | 1,332 | java | User.java | Java | [
{
"context": "assword(String password) {\n this.password = password;\n }\n\n public Integer getId() {\n retu",
"end": 892,
"score": 0.9408981800079346,
"start": 884,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package com.orfac.lab.model;
import javax.persistence.*;
import java.util.List;
@Table(name = "users")
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(nullable = false, unique = true)
private String login;
@Column(nullable = false)
private String password;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
@OrderBy("id ASC")
private List<Point> pointList;
public User() { }
public User(String login, String password) {
this.login = login;
this.password = password;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void addPoint(Point point) {
pointList.add(point);
}
public List<Point> getPointList() {
return pointList;
}
public void setPointList(List<Point> pointList) {
this.pointList = pointList;
}
public boolean isNew() {
return id == null;
}
}
| 1,334 | 0.603604 | 0.603604 | 69 | 18.304348 | 16.38867 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.318841 | false | false | 0 |
3c801bcd1093c51535c8d15a12579c0a4eee2794 | 15,968,688,445,663 | f4317790ca3d5ff5230e857d91f9c64fdb874e9e | /Stabilise 2/src/com/stabilise/entity/EntityEnemy.java | 45f77d33bdc969d1060ce2beaa33bf41b48e7f2a | []
| no_license | WeenAFK/Stabilise-2-Old- | https://github.com/WeenAFK/Stabilise-2-Old- | ba507022aa42d886fd0ab22505cdd1872f0eedb5 | 59e0aca09f33f69f9f6ed76e87d252a9b8bcb26b | refs/heads/master | 2016-09-11T13:11:56.930000 | 2014-12-13T04:27:09 | 2014-12-13T04:27:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.stabilise.entity;
import com.stabilise.entity.controller.IdleController;
import com.stabilise.opengl.render.WorldRenderer;
import com.stabilise.util.shape.AxisAlignedBoundingBox;
import com.stabilise.world.Direction;
import com.stabilise.world.World;
import com.stabilise.world.tile.Tile;
/**
* A generic test enemy.
*/
public class EntityEnemy extends EntityMob {
/** Actions for the AI. */
private static enum EnumAction {
IDLE, MOVE;
};
/** The AABB for enemy entities. */
private static final AxisAlignedBoundingBox ENEMY_AABB = new AxisAlignedBoundingBox.Precomputed(-0.5f, 0, 1, 2);
/** The number of ticks for which the enemy is to continue its current
* action.*/
private int actionTimeout = 1;
/** The enemy's current action. */
private EnumAction action = EnumAction.IDLE;
/**
* Creates a new generic test enemy.
*
* @param world The world in which the generic test enemy is to be placed.
*/
public EntityEnemy(World world) {
super(world);
}
@Override
protected AxisAlignedBoundingBox getAABB() {
return ENEMY_AABB;
}
@Override
protected void initProperties() {
// Temporary initial value setting
maxHealth = 20;
health = 20;
jumpVelocity = 0.5f;
jumpCrouchDuration = 8;
//jumpVelocity = PhysicsUtil.jumpHeightToInitialJumpVelocity(4, gravity);
swimAcceleration = 0.08f;
acceleration = 0.22f;
airAcceleration = AIR_TRACTION;
maxDx = 0.5f;
state = State.IDLE;
setController(IdleController.INSTANCE);
}
@Override
public void onAdd() {
world.hostileMobCount++;
}
@Override
public void update() {
if(!dead) {
if(--actionTimeout == 0) {
float rnd = world.rng.nextFloat();
if(rnd < 0.45) {
action = EnumAction.IDLE;
actionTimeout = 180 + (int)(world.rng.nextFloat() * 180);
} else if(rnd < 0.55) {
action = EnumAction.IDLE;
setFacingRight(!facingRight);
actionTimeout = 120 + (int)(world.rng.nextFloat() * 180);
} else if(rnd < 0.70) {
action = EnumAction.IDLE;
if(onGround) dy = jumpVelocity;
actionTimeout = 180 + (int)(world.rng.nextFloat() * 180);
} else {
if(rnd < 0.85) setFacingRight(!facingRight);
action = EnumAction.MOVE;
actionTimeout = 30 + (int)(world.rng.nextFloat() * 90);
}
}
if(action == EnumAction.MOVE) {
if(facingRight)
accelerate(acceleration);
else
accelerate(-acceleration);
}
}
super.update();
}
/**
* Accelerates the mob.
*
* @param ddx The base amount by which to modify the velocity.
*/
private void accelerate(float ddx) {
if(!state.canMove)
return;
// Some sort of scaling
ddx *= (maxDx - Math.abs(dx));
// Note that for the purposes of acceleration the friction of a tile is
// treated as its traction.
if(onGround)
dx += ddx * Tile.getTile(floorTile).getFriction();
else
dx += ddx * airAcceleration;
}
@Override
public void render(WorldRenderer renderer) {
renderer.renderEnemy(this);
}
@Override
public void kill() {
super.kill();
/*
dropItem(1, 1, 0.75f); // sword
dropItem(2, 1, 0.75f); // apple
dropItem(3, 1, 0.75f); // arrow
*/
}
@Override
public void destroy() {
super.destroy();
world.hostileMobCount--;
}
@Override
public void attack(Direction direction) {
// TODO Auto-generated method stub
}
@Override
public void specialAttack(Direction direction) {
// TODO Auto-generated method stub
}
}
| UTF-8 | Java | 3,619 | java | EntityEnemy.java | Java | []
| null | []
| package com.stabilise.entity;
import com.stabilise.entity.controller.IdleController;
import com.stabilise.opengl.render.WorldRenderer;
import com.stabilise.util.shape.AxisAlignedBoundingBox;
import com.stabilise.world.Direction;
import com.stabilise.world.World;
import com.stabilise.world.tile.Tile;
/**
* A generic test enemy.
*/
public class EntityEnemy extends EntityMob {
/** Actions for the AI. */
private static enum EnumAction {
IDLE, MOVE;
};
/** The AABB for enemy entities. */
private static final AxisAlignedBoundingBox ENEMY_AABB = new AxisAlignedBoundingBox.Precomputed(-0.5f, 0, 1, 2);
/** The number of ticks for which the enemy is to continue its current
* action.*/
private int actionTimeout = 1;
/** The enemy's current action. */
private EnumAction action = EnumAction.IDLE;
/**
* Creates a new generic test enemy.
*
* @param world The world in which the generic test enemy is to be placed.
*/
public EntityEnemy(World world) {
super(world);
}
@Override
protected AxisAlignedBoundingBox getAABB() {
return ENEMY_AABB;
}
@Override
protected void initProperties() {
// Temporary initial value setting
maxHealth = 20;
health = 20;
jumpVelocity = 0.5f;
jumpCrouchDuration = 8;
//jumpVelocity = PhysicsUtil.jumpHeightToInitialJumpVelocity(4, gravity);
swimAcceleration = 0.08f;
acceleration = 0.22f;
airAcceleration = AIR_TRACTION;
maxDx = 0.5f;
state = State.IDLE;
setController(IdleController.INSTANCE);
}
@Override
public void onAdd() {
world.hostileMobCount++;
}
@Override
public void update() {
if(!dead) {
if(--actionTimeout == 0) {
float rnd = world.rng.nextFloat();
if(rnd < 0.45) {
action = EnumAction.IDLE;
actionTimeout = 180 + (int)(world.rng.nextFloat() * 180);
} else if(rnd < 0.55) {
action = EnumAction.IDLE;
setFacingRight(!facingRight);
actionTimeout = 120 + (int)(world.rng.nextFloat() * 180);
} else if(rnd < 0.70) {
action = EnumAction.IDLE;
if(onGround) dy = jumpVelocity;
actionTimeout = 180 + (int)(world.rng.nextFloat() * 180);
} else {
if(rnd < 0.85) setFacingRight(!facingRight);
action = EnumAction.MOVE;
actionTimeout = 30 + (int)(world.rng.nextFloat() * 90);
}
}
if(action == EnumAction.MOVE) {
if(facingRight)
accelerate(acceleration);
else
accelerate(-acceleration);
}
}
super.update();
}
/**
* Accelerates the mob.
*
* @param ddx The base amount by which to modify the velocity.
*/
private void accelerate(float ddx) {
if(!state.canMove)
return;
// Some sort of scaling
ddx *= (maxDx - Math.abs(dx));
// Note that for the purposes of acceleration the friction of a tile is
// treated as its traction.
if(onGround)
dx += ddx * Tile.getTile(floorTile).getFriction();
else
dx += ddx * airAcceleration;
}
@Override
public void render(WorldRenderer renderer) {
renderer.renderEnemy(this);
}
@Override
public void kill() {
super.kill();
/*
dropItem(1, 1, 0.75f); // sword
dropItem(2, 1, 0.75f); // apple
dropItem(3, 1, 0.75f); // arrow
*/
}
@Override
public void destroy() {
super.destroy();
world.hostileMobCount--;
}
@Override
public void attack(Direction direction) {
// TODO Auto-generated method stub
}
@Override
public void specialAttack(Direction direction) {
// TODO Auto-generated method stub
}
}
| 3,619 | 0.637469 | 0.617574 | 154 | 21.5 | 20.26136 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.233766 | false | false | 0 |
396f70f5274ceef049edd1d01bd8a03213d451cb | 4,191,888,108,696 | 2315ceac091d9fb777716bdb9a74c8bd18cee640 | /Canopy/Canopy-Plugins/ChippingManagerPlugin/chipping-manager-common/src/main/java/com/monsanto/tcc/breedingtechchippingmanager/common/util/ChippingManagerAppender.java | 78a3eb5a88aecd3b363164c4cdff358203d46543 | []
| no_license | chawtrey/Play-Projects | https://github.com/chawtrey/Play-Projects | c6e0ba601862df764b2d7894b1e74c605892928b | 0166f8c16b8592d85544727b3e3d27e64121e79b | refs/heads/master | 2016-09-06T10:47:21.514000 | 2011-08-20T16:03:29 | 2011-08-20T16:03:29 | 2,239,270 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
Copyright: Copyright © 2007 Monsanto. All rights reserved.
This software was produced using Monsanto resources and is the sole property of Monsanto.
Any duplication or public release of the code and/or logic is a direct infringement of Monsanto's copyright
*/
package com.monsanto.tcc.breedingtechchippingmanager.common.util;
import org.apache.log4j.FileAppender;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Filename: $RCSfile: ChippingManagerAppender.java,v $ Label: $Name: $ Last Change: $Author: ynadkar $ On: $Date: 2007/12/05 14:41:43 $
*
* @author ynadkar
* @version $Revision: 1.2 $
*/
public class ChippingManagerAppender extends FileAppender {
File logFile = null;
public ChippingManagerAppender() {
}
public void activateOptions() {
// Get the date format, the location and database
StringBuilder logName = new StringBuilder("logs/ChippingManager_");
String dateSuffix = (new SimpleDateFormat("MM-dd-yyyy")).format(new Date());
String function = System.getProperty("lsi.function");
if (function != null) {
if (function.equals("dev")) {
logName.append("Development");
} else if (function.equals("prod")) {
logName.append("Production@StLouis");
} else if (function.equals("test")) {
logName.append("test");
} else if (function.equals("ankeny")) {
logName.append("Production@Ankeny");
}
}
logName.append("_" + dateSuffix + ".log");
try {
logFile = new File(logName.toString());
setFile(logFile.toString(), fileAppend, bufferedIO, bufferSize);
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean requiresLayout() {
return true;
}
public void close() {
logFile = null;
}
}
| WINDOWS-1252 | Java | 1,919 | java | ChippingManagerAppender.java | Java | [
{
"context": "a,v $ Label: $Name: $ Last Change: $Author: ynadkar $ \t On:\t$Date: 2007/12/05 14:41:43 $\n *\n * @au",
"end": 597,
"score": 0.9997113347053528,
"start": 590,
"tag": "USERNAME",
"value": "ynadkar"
},
{
"context": " \t On:\t$Date: 2007/12/05 14:41:43 $\n *\n * @author ynadkar\n * @version $Revision: 1.2 $\n */\npublic class Chi",
"end": 659,
"score": 0.9995849132537842,
"start": 652,
"tag": "USERNAME",
"value": "ynadkar"
}
]
| null | []
| /*
Copyright: Copyright © 2007 Monsanto. All rights reserved.
This software was produced using Monsanto resources and is the sole property of Monsanto.
Any duplication or public release of the code and/or logic is a direct infringement of Monsanto's copyright
*/
package com.monsanto.tcc.breedingtechchippingmanager.common.util;
import org.apache.log4j.FileAppender;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Filename: $RCSfile: ChippingManagerAppender.java,v $ Label: $Name: $ Last Change: $Author: ynadkar $ On: $Date: 2007/12/05 14:41:43 $
*
* @author ynadkar
* @version $Revision: 1.2 $
*/
public class ChippingManagerAppender extends FileAppender {
File logFile = null;
public ChippingManagerAppender() {
}
public void activateOptions() {
// Get the date format, the location and database
StringBuilder logName = new StringBuilder("logs/ChippingManager_");
String dateSuffix = (new SimpleDateFormat("MM-dd-yyyy")).format(new Date());
String function = System.getProperty("lsi.function");
if (function != null) {
if (function.equals("dev")) {
logName.append("Development");
} else if (function.equals("prod")) {
logName.append("Production@StLouis");
} else if (function.equals("test")) {
logName.append("test");
} else if (function.equals("ankeny")) {
logName.append("Production@Ankeny");
}
}
logName.append("_" + dateSuffix + ".log");
try {
logFile = new File(logName.toString());
setFile(logFile.toString(), fileAppend, bufferedIO, bufferSize);
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean requiresLayout() {
return true;
}
public void close() {
logFile = null;
}
}
| 1,919 | 0.672576 | 0.661627 | 62 | 29.935484 | 29.503893 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.451613 | false | false | 0 |
29fb5c6fddfb7f39de0d290224f7d0dacd6e1529 | 11,510,512,393,277 | e63e88395c42fc5109c7549be7e09facf14f9068 | /src/org/acm/seguin/pmd/rules/UnnecessaryConversionTemporaryRule.java | 5f536ef87d69a99ae14123e852f507a073b85a49 | []
| no_license | lyestoo/jrefactory | https://github.com/lyestoo/jrefactory | 2e1671f4a1afc4b2c01202fbc73e57be8a931a48 | 188a18b54a2798d10fa4718fd586e82fe2d90308 | refs/heads/master | 2021-01-19T09:57:27.527000 | 2015-07-08T20:27:10 | 2015-07-08T20:27:10 | 38,776,938 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.acm.seguin.pmd.rules;
import org.acm.seguin.pmd.AbstractRule;
import org.acm.seguin.pmd.Rule;
import org.acm.seguin.pmd.RuleContext;
import org.acm.seguin.parser.ast.ASTAllocationExpression;
import org.acm.seguin.parser.ast.ASTName;
import org.acm.seguin.parser.ast.ASTPrimaryExpression;
import org.acm.seguin.parser.ast.ASTPrimarySuffix;
import org.acm.seguin.parser.ast.SimpleNode;
import java.util.HashSet;
import java.util.Set;
public class UnnecessaryConversionTemporaryRule extends AbstractRule implements Rule {
private boolean inPrimaryExpressionContext;
private boolean usingPrimitiveWrapperAllocation;
private Set primitiveWrappers = new HashSet();
public UnnecessaryConversionTemporaryRule() {
primitiveWrappers.add("Integer");
primitiveWrappers.add("Boolean");
primitiveWrappers.add("Double");
primitiveWrappers.add("Long");
primitiveWrappers.add("Short");
primitiveWrappers.add("Byte");
primitiveWrappers.add("Float");
}
public Object visit(ASTPrimaryExpression node, Object data) {
if (node.jjtGetNumChildren() == 0 || (node.jjtGetFirstChild()).jjtGetNumChildren() == 0 || !(node.jjtGetFirstChild().jjtGetFirstChild() instanceof ASTAllocationExpression)) {
return super.visit(node, data);
}
// TODO... hmmm... is this inPrimaryExpressionContext gibberish necessary?
inPrimaryExpressionContext = true;
Object report = super.visit(node, data);
inPrimaryExpressionContext = false;
usingPrimitiveWrapperAllocation = false;
return report;
}
public Object visit(ASTAllocationExpression node, Object data) {
if (!inPrimaryExpressionContext || !(node.jjtGetFirstChild() instanceof ASTName)) {
return super.visit(node, data);
}
if (!primitiveWrappers.contains(((SimpleNode) node.jjtGetFirstChild()).getImage())) {
return super.visit(node, data);
}
usingPrimitiveWrapperAllocation = true;
return super.visit(node, data);
}
public Object visit(ASTPrimarySuffix node, Object data) {
if (!inPrimaryExpressionContext || !usingPrimitiveWrapperAllocation) {
return super.visit(node, data);
}
if (node.getImage() != null && node.getImage().equals("toString")) {
RuleContext ctx = (RuleContext) data;
ctx.getReport().addRuleViolation(createRuleViolation(ctx, node.getBeginLine()));
}
return super.visit(node, data);
}
}
| UTF-8 | Java | 2,561 | java | UnnecessaryConversionTemporaryRule.java | Java | []
| null | []
| package org.acm.seguin.pmd.rules;
import org.acm.seguin.pmd.AbstractRule;
import org.acm.seguin.pmd.Rule;
import org.acm.seguin.pmd.RuleContext;
import org.acm.seguin.parser.ast.ASTAllocationExpression;
import org.acm.seguin.parser.ast.ASTName;
import org.acm.seguin.parser.ast.ASTPrimaryExpression;
import org.acm.seguin.parser.ast.ASTPrimarySuffix;
import org.acm.seguin.parser.ast.SimpleNode;
import java.util.HashSet;
import java.util.Set;
public class UnnecessaryConversionTemporaryRule extends AbstractRule implements Rule {
private boolean inPrimaryExpressionContext;
private boolean usingPrimitiveWrapperAllocation;
private Set primitiveWrappers = new HashSet();
public UnnecessaryConversionTemporaryRule() {
primitiveWrappers.add("Integer");
primitiveWrappers.add("Boolean");
primitiveWrappers.add("Double");
primitiveWrappers.add("Long");
primitiveWrappers.add("Short");
primitiveWrappers.add("Byte");
primitiveWrappers.add("Float");
}
public Object visit(ASTPrimaryExpression node, Object data) {
if (node.jjtGetNumChildren() == 0 || (node.jjtGetFirstChild()).jjtGetNumChildren() == 0 || !(node.jjtGetFirstChild().jjtGetFirstChild() instanceof ASTAllocationExpression)) {
return super.visit(node, data);
}
// TODO... hmmm... is this inPrimaryExpressionContext gibberish necessary?
inPrimaryExpressionContext = true;
Object report = super.visit(node, data);
inPrimaryExpressionContext = false;
usingPrimitiveWrapperAllocation = false;
return report;
}
public Object visit(ASTAllocationExpression node, Object data) {
if (!inPrimaryExpressionContext || !(node.jjtGetFirstChild() instanceof ASTName)) {
return super.visit(node, data);
}
if (!primitiveWrappers.contains(((SimpleNode) node.jjtGetFirstChild()).getImage())) {
return super.visit(node, data);
}
usingPrimitiveWrapperAllocation = true;
return super.visit(node, data);
}
public Object visit(ASTPrimarySuffix node, Object data) {
if (!inPrimaryExpressionContext || !usingPrimitiveWrapperAllocation) {
return super.visit(node, data);
}
if (node.getImage() != null && node.getImage().equals("toString")) {
RuleContext ctx = (RuleContext) data;
ctx.getReport().addRuleViolation(createRuleViolation(ctx, node.getBeginLine()));
}
return super.visit(node, data);
}
}
| 2,561 | 0.691527 | 0.690746 | 65 | 38.400002 | 31.513025 | 182 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.830769 | false | false | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.