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
985341ef90a66bd1abe6ee3586b2b49de7ccc78d
25,872,882,993,948
aea9373b9ac3f298bf44cf81be45a057754e648d
/src/main/java/JSONTypes/JSONString.java
66ec62c0bf6b9e80dad0305c54d729ebe4425100
[ "MIT" ]
permissive
vasylenson/jacey-java
https://github.com/vasylenson/jacey-java
c4ef70162ef64dbe71f0388ff6155a41060a1914
f449581748e71017c6ec4b38ee0910c6339ea597
refs/heads/master
2023-07-01T16:36:52.851000
2021-08-11T20:17:43
2021-08-11T20:17:43
390,432,460
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main.java.JSONTypes; import main.java.JSONElementVisitor; public class JSONString implements JSONElement { String value; public String getValue() { return value; } public JSONString(String value) { this.value = value; } public void accept(JSONElementVisitor visitor) { visitor.visit(this); } @Override public boolean equals(JSONElement other) { return (other instanceof JSONString) && ((JSONString) other).value.equals(value); } }
UTF-8
Java
517
java
JSONString.java
Java
[]
null
[]
package main.java.JSONTypes; import main.java.JSONElementVisitor; public class JSONString implements JSONElement { String value; public String getValue() { return value; } public JSONString(String value) { this.value = value; } public void accept(JSONElementVisitor visitor) { visitor.visit(this); } @Override public boolean equals(JSONElement other) { return (other instanceof JSONString) && ((JSONString) other).value.equals(value); } }
517
0.663443
0.663443
25
19.719999
22.077173
89
false
false
0
0
0
0
0
0
0.28
false
false
9
cf590858c3bb2b95df2500ed8d0e6ce85bed4c04
7,189,775,308,304
352163a8f69f64bc87a9e14471c947e51bd6b27d
/bin/platform/ext/core/testsrc/de/hybris/platform/test/AbstractCacheUnitThreadTest.java
cf9bfe8eae25932d76cb0951c81102b800015e37
[]
no_license
GTNDYanagisawa/merchandise
https://github.com/GTNDYanagisawa/merchandise
2ad5209480d5dc7d946a442479cfd60649137109
e9773338d63d4f053954d396835ac25ef71039d3
refs/heads/master
2021-01-22T20:45:31.217000
2015-05-20T06:23:45
2015-05-20T06:23:45
35,868,211
3
5
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * [y] hybris Platform * * Copyright (c) 2000-2013 hybris AG * All rights reserved. * * This software is the confidential and proprietary information of hybris * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with hybris. * * */ package de.hybris.platform.test; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertEquals; import de.hybris.platform.cache.AbstractCacheUnit; import de.hybris.platform.cache.Cache; import de.hybris.platform.cache.impl.DefaultCache; import de.hybris.platform.core.Registry; import de.hybris.platform.core.Tenant; import de.hybris.platform.test.TestThreadsHolder.RunnerCreator; import de.hybris.platform.testframework.HybrisJUnit4Test; import de.hybris.platform.testframework.TestUtils; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * Test {@link AbstractCacheUnit} and {@link Cache} behavior, especially in multi-threaded mode. */ @Ignore("BAM-520 PLA-11076") public class AbstractCacheUnitThreadTest extends HybrisJUnit4Test { private static final int THREADS = 100; private static final int CACHE_SIZE = 50000; private static final int MAX_GAIN_PER_THREAD = 50; private static final int DURATION_SEC = 20; /** * Tests multiple threads accessing {@link AbstractCacheUnit} and implicitely {@link Cache}, without testing for * correctness! * * Instead it compares the memory before access, after filling up and after clearing the cache. The test will fail if * after clear the memory gain is higher than a allowed gain (atm 50 bytes per thread, which is 5000 bytes for 100 * threads). */ @Test public void testMultiThreadedAccessAndMemory() throws InterruptedException { Registry.getCurrentTenant().getCache().clear(); final Cache cache = new DefaultCache(Registry.getCurrentTenantNoFallback(), CACHE_SIZE); final long memoryBefore = TestUtils.dumpMemory(); TestThreadsHolder<MyPerfRunner> threadHolder = new TestThreadsHolder<MyPerfRunner>(THREADS, new RunnerCreator<MyPerfRunner>() { @Override public MyPerfRunner newRunner(final int threadNumber) { return new MyPerfRunner(cache); } }); threadHolder.startAll(); Thread.sleep(DURATION_SEC * 1000); assertTrue("Not all runners finished orderly", threadHolder.stopAndDestroy(10)); assertNoRunnerErrors(threadHolder); final long memoryFullCache = TestUtils.dumpMemory(); cache.clear(); threadHolder = null; final long memoryAfterClear = TestUtils.dumpMemory(); System.out.println("Memory before run: " + memoryBefore + " kb"); System.out.println("Memory after run: " + memoryFullCache + " kb"); System.out.println("Memory after clear: " + memoryAfterClear + " kb"); final long delta = memoryAfterClear - memoryBefore; final long maxAllowedDelta = THREADS * MAX_GAIN_PER_THREAD; assertTrue("memory delta of " + delta + " exceeds allowed delta " + maxAllowedDelta + "!", delta <= maxAllowedDelta); } private void assertNoRunnerErrors(final TestThreadsHolder threadHolder) { final Map<Integer, Exception> errors = threadHolder.getErrors(); assertEquals("got unexpected runner errors: " + errors, Collections.EMPTY_MAP, errors); } /** * Tests whether {@link Cache#getOrAddUnit(AbstractCacheUnit)} is ensuring that only one unit per key is being added * even if multiple threads are trying that at the same time. * * To enforce potential errors the test runs several turns of all threads trying to add a unit with the same key per * turn. */ @Test public void testExclusiveUnitAddToCache() throws InterruptedException { testExclusiveUnitAddToCache(1000, THREADS, 1010, 30); } private void testExclusiveUnitAddToCache(final int TURNS, final int THREADS, final int CACHE_SIZE, final int waitSeconds) throws InterruptedException { final CyclicBarrier gate = new CyclicBarrier(THREADS/* * , new Runnable() { volatile int turn = 0; * * @Override public void run() { * System.out.println("Starting turn " + turn); turn++; } } */); final Cache cache = new DefaultCache(Registry.getCurrentTenantNoFallback(), CACHE_SIZE); final TestThreadsHolder<ExclusiveAddUnitRunner> holder = new TestThreadsHolder<ExclusiveAddUnitRunner>(THREADS, new RunnerCreator<ExclusiveAddUnitRunner>() { @Override public ExclusiveAddUnitRunner newRunner(final int threadNumber) { return new ExclusiveAddUnitRunner(cache, gate, TURNS); } }); // start turns holder.startAll(); // wait for runners to finish assertTrue("not all runners finished", holder.waitAndDestroy(30)); assertNoRunnerErrors(holder); cache.destroy(); // assert same amount of units recorded for (final ExclusiveAddUnitRunner runner : holder.getRunners()) { assertEquals(TURNS, runner.recordedUnits.length); } final Map<Integer, Integer> allTurnFailures = checkRecordedCacheUnits(holder, TURNS); assertEquals("Cache.getOrAddUnit() produced different units (failures per turn: " + allTurnFailures + ")", // Collections.EMPTY_MAP, allTurnFailures); } private Map<Integer, Integer> checkRecordedCacheUnits(final TestThreadsHolder<ExclusiveAddUnitRunner> holder, final int TURNS) { final Map<Integer, Integer> allFailures = new HashMap<Integer, Integer>(); // assert same unit per turn for all runners for (int turn = 0; turn < TURNS; turn++) { AbstractCacheUnit turnUnit = null; int turnFailures = 0; for (final ExclusiveAddUnitRunner runner : holder.getRunners()) { final AbstractCacheUnit unit = runner.recordedUnits[turn]; if (unit == null) { turnFailures++; } else if (turnUnit == null) { turnUnit = unit; } else if (turnUnit != unit) { turnFailures++; } } if (turnFailures > 0) { allFailures.put(Integer.valueOf(turn), Integer.valueOf(turnFailures)); } } return allFailures; } private static class ExclusiveAddUnitRunner implements Runnable { private final Cache cache; private final CyclicBarrier gate; private final int numberOfTurns; private volatile AbstractCacheUnit[] recordedUnits; ExclusiveAddUnitRunner(final Cache c, final CyclicBarrier gate, final int numberOfTurns) { this.cache = c; this.gate = gate; this.numberOfTurns = numberOfTurns; } @Override public void run() { final AbstractCacheUnit[] units = new AbstractCacheUnit[numberOfTurns]; try { for (int turn = 0; turn < numberOfTurns; turn++) { // create new unit as key final AbstractCacheUnit newCacheUnit = newUnit(Integer.valueOf(turn)); //System.out.println("before turn " + turn); // wait for all runners to meet at this barrier to have the // most 'brutal' effect on Cache.getOrAddUnit() gate.await(); // query or add this unit // register returned unit -> all runners should have the same each turn units[turn] = cache.getOrAddUnit(newCacheUnit); } } catch (final InterruptedException e) { // fine } catch (final BrokenBarrierException e) { // TODO ? } finally { this.recordedUnits = units; // volatile write } } AbstractCacheUnit newUnit(final Object key) { return new ExclusiveAddUnitTestUnit(cache, key); } } private static class ExclusiveAddUnitTestUnit extends AbstractCacheUnit { private final Object key; public ExclusiveAddUnitTestUnit(final Cache c, final Object key) { super(c); this.key = key; } @Override public Object compute() throws Exception { return "Value"; } @Override public Object[] createKey() { return new Object[] { this.key }; } } /** * Tests whether {@link AbstractCacheUnit#compute()} is really working exclusively when * {@link Cache#isForceExclusiveComputation()} is switched on. * * To test this we let many threads try to access the cache using one unit per thread having the same key. */ @Test public void testExclusiveComputation() throws InterruptedException { testExclusiveComputation(THREADS, 1000, 1010, 30); } private void testExclusiveComputation(final int threads, final int turns, final int cacheSize, final int timeWaitSeconds) throws InterruptedException { final TestThreadsHolder<ExclusiveComputationRunner> threadHolder = prepareExclusiveComputationTest(threads, cacheSize, turns); threadHolder.startAll(); assertTrue("Not all runners finished orderly", threadHolder.waitAndDestroy(timeWaitSeconds)); assertNoRunnerErrors(threadHolder); final Map<Integer, Integer> allTurnErrors = checkRecordedComputations(threadHolder, turns); assertEquals("Testing exclusive computation mode found errors in some turns: " + allTurnErrors, // Collections.EMPTY_MAP, allTurnErrors); } private TestThreadsHolder<ExclusiveComputationRunner> prepareExclusiveComputationTest(final int threads, final int cacheSize, final int turns) { final Tenant tenant = Registry.getCurrentTenantNoFallback(); final CyclicBarrier gate = new CyclicBarrier(threads/* * , new Runnable() { private volatile int turn = 0; * * @Override public void run() { * System.out.println("Exclusive computation test: before turn " * + turn); turn++; } } */); final Cache cache = new DefaultCache(tenant, cacheSize, // true /* we switch in forceExclusiveComputation no matter what global setting has been chosen */); return new TestThreadsHolder<ExclusiveComputationRunner>(threads, new RunnerCreator<ExclusiveComputationRunner>() { @Override public ExclusiveComputationRunner newRunner(final int threadNumber) { return new ExclusiveComputationRunner(cache, gate, turns); } }); } private Map<Integer, Integer> checkRecordedComputations(final TestThreadsHolder<ExclusiveComputationRunner> holder, final int turns) { final Map<Integer, Integer> ret = new LinkedHashMap<Integer, Integer>(); for (int turn = 0; turn < turns; turn++) { int computingRunnerIndex = -1; int turnErrors = 0; int runnerIdx = 0; for (final ExclusiveComputationRunner r : holder.getRunners()) { if (r.recordedComputationStates[turn]) // runner did compute { if (computingRunnerIndex == -1) // first one -> fine { computingRunnerIndex = runnerIdx; } else // second one -> error { turnErrors++; } } runnerIdx++; } if (computingRunnerIndex == -1) // no runner did compute -> error too { turnErrors = -1; // use special number } if (turnErrors != 0) { ret.put(Integer.valueOf(turn), Integer.valueOf(turnErrors)); } } return ret; } private static class ExclusiveComputationRunner implements Runnable { private final Cache cache; private final CyclicBarrier gate; private final int turns; private volatile boolean[] recordedComputationStates; ExclusiveComputationRunner(final Cache cache, final CyclicBarrier gate, final int turns) { this.cache = cache; this.turns = turns; this.gate = gate; } @Override public void run() { final boolean[] results = new boolean[turns]; try { for (int turn = 0; turn < turns; turn++) { final ExclusiveComputationCacheUnit u = new ExclusiveComputationCacheUnit(cache, turn); // let all workers meet here to have the maximum effect per turn gate.await(); results[turn] = u.simulateGet(); } } catch (final Exception e) { throw new IllegalStateException(e); } finally { this.recordedComputationStates = results; // volatile write for safe publishing } } } private static class ExclusiveComputationCacheUnit extends AbstractCacheUnit { private final int turnNumber; private boolean computed = false; ExclusiveComputationCacheUnit(final Cache c, final int turnNumber) { super(c); this.turnNumber = turnNumber; } // returns true only if this very unit actually did perform computation boolean simulateGet() throws Exception { final Object result = super.get(); Assert.assertNotNull(result); // we assume that each runner has its own unit and therefore it's safe to // access 'computed' without any synchronization return this.computed; } @Override public Object compute() throws Exception { this.computed = true; return "Foo"; } @Override public Object[] createKey() { return new Object[] { Integer.valueOf(turnNumber) }; } } private static class MyPerfRunner implements Runnable { private final Cache cache; private long overallSum = 0; private int serial = 0; MyPerfRunner(final Cache cache) { this.cache = cache; } @Override public void run() { while (!Thread.currentThread().isInterrupted()) { final TestCacheUnit unit = new TestCacheUnit(cache, serial++); Integer result; try { result = (Integer) unit.get(); overallSum += result.intValue(); } catch (final Exception e) { throw new IllegalStateException(e); } } } } private static class TestCacheUnit extends AbstractCacheUnit { private final int serialNumber; TestCacheUnit(final Cache c, final int serialNumber) { super(c); this.serialNumber = serialNumber; } @Override public Object compute() throws Exception { return Integer.valueOf((int) (Integer.MAX_VALUE * Math.random())); } @Override public Object[] createKey() { return new Object[] { "test", "unit", Integer.valueOf(serialNumber) }; } } }
UTF-8
Java
14,575
java
AbstractCacheUnitThreadTest.java
Java
[]
null
[]
/* * [y] hybris Platform * * Copyright (c) 2000-2013 hybris AG * All rights reserved. * * This software is the confidential and proprietary information of hybris * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with hybris. * * */ package de.hybris.platform.test; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertEquals; import de.hybris.platform.cache.AbstractCacheUnit; import de.hybris.platform.cache.Cache; import de.hybris.platform.cache.impl.DefaultCache; import de.hybris.platform.core.Registry; import de.hybris.platform.core.Tenant; import de.hybris.platform.test.TestThreadsHolder.RunnerCreator; import de.hybris.platform.testframework.HybrisJUnit4Test; import de.hybris.platform.testframework.TestUtils; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * Test {@link AbstractCacheUnit} and {@link Cache} behavior, especially in multi-threaded mode. */ @Ignore("BAM-520 PLA-11076") public class AbstractCacheUnitThreadTest extends HybrisJUnit4Test { private static final int THREADS = 100; private static final int CACHE_SIZE = 50000; private static final int MAX_GAIN_PER_THREAD = 50; private static final int DURATION_SEC = 20; /** * Tests multiple threads accessing {@link AbstractCacheUnit} and implicitely {@link Cache}, without testing for * correctness! * * Instead it compares the memory before access, after filling up and after clearing the cache. The test will fail if * after clear the memory gain is higher than a allowed gain (atm 50 bytes per thread, which is 5000 bytes for 100 * threads). */ @Test public void testMultiThreadedAccessAndMemory() throws InterruptedException { Registry.getCurrentTenant().getCache().clear(); final Cache cache = new DefaultCache(Registry.getCurrentTenantNoFallback(), CACHE_SIZE); final long memoryBefore = TestUtils.dumpMemory(); TestThreadsHolder<MyPerfRunner> threadHolder = new TestThreadsHolder<MyPerfRunner>(THREADS, new RunnerCreator<MyPerfRunner>() { @Override public MyPerfRunner newRunner(final int threadNumber) { return new MyPerfRunner(cache); } }); threadHolder.startAll(); Thread.sleep(DURATION_SEC * 1000); assertTrue("Not all runners finished orderly", threadHolder.stopAndDestroy(10)); assertNoRunnerErrors(threadHolder); final long memoryFullCache = TestUtils.dumpMemory(); cache.clear(); threadHolder = null; final long memoryAfterClear = TestUtils.dumpMemory(); System.out.println("Memory before run: " + memoryBefore + " kb"); System.out.println("Memory after run: " + memoryFullCache + " kb"); System.out.println("Memory after clear: " + memoryAfterClear + " kb"); final long delta = memoryAfterClear - memoryBefore; final long maxAllowedDelta = THREADS * MAX_GAIN_PER_THREAD; assertTrue("memory delta of " + delta + " exceeds allowed delta " + maxAllowedDelta + "!", delta <= maxAllowedDelta); } private void assertNoRunnerErrors(final TestThreadsHolder threadHolder) { final Map<Integer, Exception> errors = threadHolder.getErrors(); assertEquals("got unexpected runner errors: " + errors, Collections.EMPTY_MAP, errors); } /** * Tests whether {@link Cache#getOrAddUnit(AbstractCacheUnit)} is ensuring that only one unit per key is being added * even if multiple threads are trying that at the same time. * * To enforce potential errors the test runs several turns of all threads trying to add a unit with the same key per * turn. */ @Test public void testExclusiveUnitAddToCache() throws InterruptedException { testExclusiveUnitAddToCache(1000, THREADS, 1010, 30); } private void testExclusiveUnitAddToCache(final int TURNS, final int THREADS, final int CACHE_SIZE, final int waitSeconds) throws InterruptedException { final CyclicBarrier gate = new CyclicBarrier(THREADS/* * , new Runnable() { volatile int turn = 0; * * @Override public void run() { * System.out.println("Starting turn " + turn); turn++; } } */); final Cache cache = new DefaultCache(Registry.getCurrentTenantNoFallback(), CACHE_SIZE); final TestThreadsHolder<ExclusiveAddUnitRunner> holder = new TestThreadsHolder<ExclusiveAddUnitRunner>(THREADS, new RunnerCreator<ExclusiveAddUnitRunner>() { @Override public ExclusiveAddUnitRunner newRunner(final int threadNumber) { return new ExclusiveAddUnitRunner(cache, gate, TURNS); } }); // start turns holder.startAll(); // wait for runners to finish assertTrue("not all runners finished", holder.waitAndDestroy(30)); assertNoRunnerErrors(holder); cache.destroy(); // assert same amount of units recorded for (final ExclusiveAddUnitRunner runner : holder.getRunners()) { assertEquals(TURNS, runner.recordedUnits.length); } final Map<Integer, Integer> allTurnFailures = checkRecordedCacheUnits(holder, TURNS); assertEquals("Cache.getOrAddUnit() produced different units (failures per turn: " + allTurnFailures + ")", // Collections.EMPTY_MAP, allTurnFailures); } private Map<Integer, Integer> checkRecordedCacheUnits(final TestThreadsHolder<ExclusiveAddUnitRunner> holder, final int TURNS) { final Map<Integer, Integer> allFailures = new HashMap<Integer, Integer>(); // assert same unit per turn for all runners for (int turn = 0; turn < TURNS; turn++) { AbstractCacheUnit turnUnit = null; int turnFailures = 0; for (final ExclusiveAddUnitRunner runner : holder.getRunners()) { final AbstractCacheUnit unit = runner.recordedUnits[turn]; if (unit == null) { turnFailures++; } else if (turnUnit == null) { turnUnit = unit; } else if (turnUnit != unit) { turnFailures++; } } if (turnFailures > 0) { allFailures.put(Integer.valueOf(turn), Integer.valueOf(turnFailures)); } } return allFailures; } private static class ExclusiveAddUnitRunner implements Runnable { private final Cache cache; private final CyclicBarrier gate; private final int numberOfTurns; private volatile AbstractCacheUnit[] recordedUnits; ExclusiveAddUnitRunner(final Cache c, final CyclicBarrier gate, final int numberOfTurns) { this.cache = c; this.gate = gate; this.numberOfTurns = numberOfTurns; } @Override public void run() { final AbstractCacheUnit[] units = new AbstractCacheUnit[numberOfTurns]; try { for (int turn = 0; turn < numberOfTurns; turn++) { // create new unit as key final AbstractCacheUnit newCacheUnit = newUnit(Integer.valueOf(turn)); //System.out.println("before turn " + turn); // wait for all runners to meet at this barrier to have the // most 'brutal' effect on Cache.getOrAddUnit() gate.await(); // query or add this unit // register returned unit -> all runners should have the same each turn units[turn] = cache.getOrAddUnit(newCacheUnit); } } catch (final InterruptedException e) { // fine } catch (final BrokenBarrierException e) { // TODO ? } finally { this.recordedUnits = units; // volatile write } } AbstractCacheUnit newUnit(final Object key) { return new ExclusiveAddUnitTestUnit(cache, key); } } private static class ExclusiveAddUnitTestUnit extends AbstractCacheUnit { private final Object key; public ExclusiveAddUnitTestUnit(final Cache c, final Object key) { super(c); this.key = key; } @Override public Object compute() throws Exception { return "Value"; } @Override public Object[] createKey() { return new Object[] { this.key }; } } /** * Tests whether {@link AbstractCacheUnit#compute()} is really working exclusively when * {@link Cache#isForceExclusiveComputation()} is switched on. * * To test this we let many threads try to access the cache using one unit per thread having the same key. */ @Test public void testExclusiveComputation() throws InterruptedException { testExclusiveComputation(THREADS, 1000, 1010, 30); } private void testExclusiveComputation(final int threads, final int turns, final int cacheSize, final int timeWaitSeconds) throws InterruptedException { final TestThreadsHolder<ExclusiveComputationRunner> threadHolder = prepareExclusiveComputationTest(threads, cacheSize, turns); threadHolder.startAll(); assertTrue("Not all runners finished orderly", threadHolder.waitAndDestroy(timeWaitSeconds)); assertNoRunnerErrors(threadHolder); final Map<Integer, Integer> allTurnErrors = checkRecordedComputations(threadHolder, turns); assertEquals("Testing exclusive computation mode found errors in some turns: " + allTurnErrors, // Collections.EMPTY_MAP, allTurnErrors); } private TestThreadsHolder<ExclusiveComputationRunner> prepareExclusiveComputationTest(final int threads, final int cacheSize, final int turns) { final Tenant tenant = Registry.getCurrentTenantNoFallback(); final CyclicBarrier gate = new CyclicBarrier(threads/* * , new Runnable() { private volatile int turn = 0; * * @Override public void run() { * System.out.println("Exclusive computation test: before turn " * + turn); turn++; } } */); final Cache cache = new DefaultCache(tenant, cacheSize, // true /* we switch in forceExclusiveComputation no matter what global setting has been chosen */); return new TestThreadsHolder<ExclusiveComputationRunner>(threads, new RunnerCreator<ExclusiveComputationRunner>() { @Override public ExclusiveComputationRunner newRunner(final int threadNumber) { return new ExclusiveComputationRunner(cache, gate, turns); } }); } private Map<Integer, Integer> checkRecordedComputations(final TestThreadsHolder<ExclusiveComputationRunner> holder, final int turns) { final Map<Integer, Integer> ret = new LinkedHashMap<Integer, Integer>(); for (int turn = 0; turn < turns; turn++) { int computingRunnerIndex = -1; int turnErrors = 0; int runnerIdx = 0; for (final ExclusiveComputationRunner r : holder.getRunners()) { if (r.recordedComputationStates[turn]) // runner did compute { if (computingRunnerIndex == -1) // first one -> fine { computingRunnerIndex = runnerIdx; } else // second one -> error { turnErrors++; } } runnerIdx++; } if (computingRunnerIndex == -1) // no runner did compute -> error too { turnErrors = -1; // use special number } if (turnErrors != 0) { ret.put(Integer.valueOf(turn), Integer.valueOf(turnErrors)); } } return ret; } private static class ExclusiveComputationRunner implements Runnable { private final Cache cache; private final CyclicBarrier gate; private final int turns; private volatile boolean[] recordedComputationStates; ExclusiveComputationRunner(final Cache cache, final CyclicBarrier gate, final int turns) { this.cache = cache; this.turns = turns; this.gate = gate; } @Override public void run() { final boolean[] results = new boolean[turns]; try { for (int turn = 0; turn < turns; turn++) { final ExclusiveComputationCacheUnit u = new ExclusiveComputationCacheUnit(cache, turn); // let all workers meet here to have the maximum effect per turn gate.await(); results[turn] = u.simulateGet(); } } catch (final Exception e) { throw new IllegalStateException(e); } finally { this.recordedComputationStates = results; // volatile write for safe publishing } } } private static class ExclusiveComputationCacheUnit extends AbstractCacheUnit { private final int turnNumber; private boolean computed = false; ExclusiveComputationCacheUnit(final Cache c, final int turnNumber) { super(c); this.turnNumber = turnNumber; } // returns true only if this very unit actually did perform computation boolean simulateGet() throws Exception { final Object result = super.get(); Assert.assertNotNull(result); // we assume that each runner has its own unit and therefore it's safe to // access 'computed' without any synchronization return this.computed; } @Override public Object compute() throws Exception { this.computed = true; return "Foo"; } @Override public Object[] createKey() { return new Object[] { Integer.valueOf(turnNumber) }; } } private static class MyPerfRunner implements Runnable { private final Cache cache; private long overallSum = 0; private int serial = 0; MyPerfRunner(final Cache cache) { this.cache = cache; } @Override public void run() { while (!Thread.currentThread().isInterrupted()) { final TestCacheUnit unit = new TestCacheUnit(cache, serial++); Integer result; try { result = (Integer) unit.get(); overallSum += result.intValue(); } catch (final Exception e) { throw new IllegalStateException(e); } } } } private static class TestCacheUnit extends AbstractCacheUnit { private final int serialNumber; TestCacheUnit(final Cache c, final int serialNumber) { super(c); this.serialNumber = serialNumber; } @Override public Object compute() throws Exception { return Integer.valueOf((int) (Integer.MAX_VALUE * Math.random())); } @Override public Object[] createKey() { return new Object[] { "test", "unit", Integer.valueOf(serialNumber) }; } } }
14,575
0.678285
0.672521
511
26.522505
30.483562
127
false
false
0
0
0
0
0
0
2.772994
false
false
9
a7619c2b27294d6efee4d48423df8fa84f828d87
32,710,470,987,700
019b1201599525809569b5ab59b93d6701b796c8
/transaction-management/src/main/java/com/trendcore/TableDescriptor.java
a35c6622f140dd7bc05cc4dd1175b293a9ae884f
[]
no_license
AnuragBotre/algorithms
https://github.com/AnuragBotre/algorithms
cd84853909717677db7aea58faeb9674767d4a7c
2531dae1e951d9dc55cb40be694e048b375b7c72
refs/heads/master
2022-12-22T17:04:45.495000
2021-01-06T06:03:58
2021-01-06T06:03:58
111,985,010
0
0
null
false
2022-12-16T10:41:50
2017-11-25T07:23:51
2021-01-06T06:04:06
2022-12-16T10:41:47
12,051
0
0
28
Java
false
false
package com.trendcore; import com.trendcore.sql.Column; import java.util.HashSet; import java.util.Set; public class TableDescriptor { private Set<Column<?>> list = new HashSet<>(); private Set<Column<?>> primaryKeys = new HashSet<>(2); private String tablename = ""; public void add(Column<?> c){ list.add(c); } public Set<Column<?>> getColumns() { return list; } public String getTablename() { return tablename; } public void setTablename(String tablename) { this.tablename = tablename; } public void setPrimaryKey(Column<Integer> id) { primaryKeys.add(id); id.setPrimaryKey(true); } public Set<Column<?>> getPrimaryKeys() { return primaryKeys; } }
UTF-8
Java
779
java
TableDescriptor.java
Java
[]
null
[]
package com.trendcore; import com.trendcore.sql.Column; import java.util.HashSet; import java.util.Set; public class TableDescriptor { private Set<Column<?>> list = new HashSet<>(); private Set<Column<?>> primaryKeys = new HashSet<>(2); private String tablename = ""; public void add(Column<?> c){ list.add(c); } public Set<Column<?>> getColumns() { return list; } public String getTablename() { return tablename; } public void setTablename(String tablename) { this.tablename = tablename; } public void setPrimaryKey(Column<Integer> id) { primaryKeys.add(id); id.setPrimaryKey(true); } public Set<Column<?>> getPrimaryKeys() { return primaryKeys; } }
779
0.616175
0.614891
40
18.475
17.889923
58
false
false
0
0
0
0
0
0
0.35
false
false
9
361fe11eaa19a291a3849a2874fd951aa5efe43c
27,273,042,344,943
e628e5c3cda50d1895d565eeb57f53379f808c88
/client/src/main/java/presentation/FinanceUI/PaymentManageUI.java
44f342b5c08340a7f52e744e58ae6fa751563911
[]
no_license
KingsleyAdamWang/B425Gearage
https://github.com/KingsleyAdamWang/B425Gearage
1d821de6ab765eec0d17cf13efc61cf6bebbfd1c
2389a77a6582cf8d5c60f6e7c26bb9f53cc9949b
refs/heads/master
2016-06-16T17:24:06.060000
2016-01-05T04:04:22
2016-01-05T04:04:22
49,043,248
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//package presentation.FinanceUI; // //import java.awt.Graphics; //import java.awt.event.ActionEvent; //import java.awt.event.ActionListener; //import java.rmi.RemoteException; //import java.util.Date; //import java.util.List; //import java.util.Vector; // //import javax.swing.BorderFactory; //import javax.swing.JButton; //import javax.swing.JDialog; //import javax.swing.JLabel; //import javax.swing.JPanel; //import javax.swing.JScrollPane; //import javax.swing.JTable; //import javax.swing.JTextField; // //import presentation.MainFrame; //import presentation.LogUI.LogUI; //import presentation.ManageUI.ManagerUI; //import util.DateUtil; //import vo.FinanceVo.IncomeVO; //import vo.FinanceVo.PaymentVO; //import businessLogic.businessHallBL.CashRegisterController; //import businessLogic.financeBL.PaymentController; //import client.ClientInitException; //import client.Main; // //public class PaymentManageUI extends JPanel { // private static final long serialVersionUID = 1L; // // private PaymentController pc; // private JButton searchDateBtn; // private JButton searchUserBtn; // private JButton returnBtn; // private JTable table; // private Vector<Vector<String>> vData; // private JScrollPane sp; // private List<PaymentVO> list; // // public PaymentManageUI() throws RemoteException { // this.pc = new PaymentController(); // vData = new Vector<Vector<String>>(); // this.initList(); // this.initComponents(); // this.validate(); // } // // protected void paintComponent(Graphics g) { // g.drawImage(MainFrame.background.getImage(), 0, 0, this); // } // // private void initComponents() { // this.setLayout(null); // // String[] info = { "员工编号", "付款单编号", "付款日期", "付款金额", "付款人姓名", "付款账号", // "付款种类", "次数" }; // Vector<String> vColumns = new Vector<String>(); // for (int i = 0; i < 8; i++) { // vColumns.add(info[i]); // } // // table = new JTable(vData, vColumns) { // private static final long serialVersionUID = 1L; // // public boolean isCellEditable(int row, int column) { // return false; // } // }; // table.setBorder(BorderFactory.createEtchedBorder()); // table.setRowHeight(35); // table.setRowSelectionAllowed(true); // // sp = new JScrollPane(); // sp.getViewport().add(table); // sp.setBounds(50, 50, 700, 400); // table.setFillsViewportHeight(true); // this.add(sp); // // searchDateBtn = new JButton("按日期检索"); // searchDateBtn.setBounds(150, 480, 100, 30); // this.add(searchDateBtn); // // searchUserBtn = new JButton("按用户检索"); // // searchUserBtn.setBounds(350, 480, 100, 30); // // this.add(searchUserBtn); // returnBtn = new JButton("返回"); // returnBtn.setBounds(550, 480, 100, 30); // this.add(returnBtn); // // searchDateBtn.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // PaymentDateDialog d = new PaymentDateDialog(getThis()); // } // }); // // // searchUserBtn.addActionListener(new ActionListener() { // // public void actionPerformed(ActionEvent e) { // // String s = (String) JOptionPane.showInputDialog(null, // // "请输入需查询的员工编号:\n", "title", JOptionPane.PLAIN_MESSAGE, // // null, null, ""); // // if (s == null) { // // return; // // } // // list = cc.getLogListOfUser(s); // // reInitList(s); // // return; // // } // // }); // // returnBtn.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // String str = MainFrame.getUser().getWork().getPositionString(); // if (str.equals("财务人员(高)")) { // Main.frame.setView(new FinanceHighUI()); // } else if (str.equals("财务人员(高)")) { // Main.frame.setView(new FinanceHighUI()); // } else if (str.equals("总经理")) { // Main.frame.setView(new ManagerUI()); // } // } // }); // } // // private PaymentManageUI getThis() { // return this; // } // // private void initList() { // list = pc.getAllLogList(); // vData = getShowList(); // // table.validate(); // // scrollPane.getViewport().removeAll(); // // scrollPane.getViewport().add(table); // // this.initComponents(); // this.repaint(); // } // // public void reInitList(Date d1, Date d2) { // list = pc.betweenDate(d1, d2); // vData.clear(); // // for (PaymentVO vo : list) { // vData.add(toVector(vo)); // } // // sp.getViewport().removeAll(); // sp.getViewport().add(table); // table.repaint(); // sp.repaint(); // this.repaint(); // } // // // private void reInitList(String s) { // // list = cc.getLogListOfUser(s); // // vData.clear(); // // // // for (IncomeVO vo : list) { // // vData.add(toVector(vo)); // // } // // // // sp.getViewport().removeAll(); // // sp.getViewport().add(table); // // table.repaint(); // // sp.repaint(); // // this.repaint(); // // } // // private Vector<Vector<String>> getShowList() { // Vector<Vector<String>> v = new Vector<Vector<String>>(); // int n = list.size(); // for (int i = 0; i < n; i++) { // Vector<String> tmp = toVector(list.get(i)); // v.add(tmp); // // System.out.println(vo.getName()); // } // return v; // } // // private Vector<String> toVector(PaymentVO vo) { // Vector<String> tmp = new Vector<String>(); // tmp.add(vo.userID); // tmp.add(vo.payID); // tmp.add(DateUtil.dateToString(vo.d)); // tmp.add(vo.payment + ""); // tmp.add(vo.payName); // tmp.add(vo.bankID); // tmp.add(vo.type); // tmp.add(vo.times + ""); // return tmp; // } // //class PaymentDateDialog extends JDialog { // private static final long serialVersionUID = 1L; // private JLabel label1; // private JLabel label2; // private JTextField field1; // private JTextField field2; // private JButton btn1; // private JButton btn2; // private IncomeManageUI ui; // // public PaymentDateDialog(IncomeManageUI ui) { // this.ui = ui; // this.setVisible(true); // this.setResizable(false); // this.setLayout(null); // this.setSize(300, 200); // this.setLocationRelativeTo(null); // // initComponents(); // } // // private void initComponents() { // label1 = new JLabel("起始日期:"); // label1.setBounds(25, 25, 50, 15); // label2 = new JLabel("结束日期:"); // label2.setBounds(25, 75, 50, 15); // field1 = new JTextField(); // field1.setBounds(100, 20, 175, 25); // field1.setText(DateUtil.dateToString()); // field2 = new JTextField(); // field2.setBounds(100, 70, 175, 25); // field2.setText(DateUtil.dateToString()); // this.getContentPane().add(label1); // this.getContentPane().add(label2); // this.getContentPane().add(field1); // this.getContentPane().add(field2); // // btn1 = new JButton("确定"); // btn1.setBounds(50, 120, 75, 30); // this.getContentPane().add(btn1); // btn2 = new JButton("返回"); // btn2.setBounds(50, 120, 75, 30); // this.getContentPane().add(btn2); // btn1.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // Date d1 = DateUtil.stringToDate(field1.getText()); // Date d2 = DateUtil.stringToDate(field2.getText()); // ui.reInitList(d1, d2); // } // }); // btn2.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // setVisible(false); // } // }); // } //}
UTF-8
Java
7,250
java
PaymentManageUI.java
Java
[]
null
[]
//package presentation.FinanceUI; // //import java.awt.Graphics; //import java.awt.event.ActionEvent; //import java.awt.event.ActionListener; //import java.rmi.RemoteException; //import java.util.Date; //import java.util.List; //import java.util.Vector; // //import javax.swing.BorderFactory; //import javax.swing.JButton; //import javax.swing.JDialog; //import javax.swing.JLabel; //import javax.swing.JPanel; //import javax.swing.JScrollPane; //import javax.swing.JTable; //import javax.swing.JTextField; // //import presentation.MainFrame; //import presentation.LogUI.LogUI; //import presentation.ManageUI.ManagerUI; //import util.DateUtil; //import vo.FinanceVo.IncomeVO; //import vo.FinanceVo.PaymentVO; //import businessLogic.businessHallBL.CashRegisterController; //import businessLogic.financeBL.PaymentController; //import client.ClientInitException; //import client.Main; // //public class PaymentManageUI extends JPanel { // private static final long serialVersionUID = 1L; // // private PaymentController pc; // private JButton searchDateBtn; // private JButton searchUserBtn; // private JButton returnBtn; // private JTable table; // private Vector<Vector<String>> vData; // private JScrollPane sp; // private List<PaymentVO> list; // // public PaymentManageUI() throws RemoteException { // this.pc = new PaymentController(); // vData = new Vector<Vector<String>>(); // this.initList(); // this.initComponents(); // this.validate(); // } // // protected void paintComponent(Graphics g) { // g.drawImage(MainFrame.background.getImage(), 0, 0, this); // } // // private void initComponents() { // this.setLayout(null); // // String[] info = { "员工编号", "付款单编号", "付款日期", "付款金额", "付款人姓名", "付款账号", // "付款种类", "次数" }; // Vector<String> vColumns = new Vector<String>(); // for (int i = 0; i < 8; i++) { // vColumns.add(info[i]); // } // // table = new JTable(vData, vColumns) { // private static final long serialVersionUID = 1L; // // public boolean isCellEditable(int row, int column) { // return false; // } // }; // table.setBorder(BorderFactory.createEtchedBorder()); // table.setRowHeight(35); // table.setRowSelectionAllowed(true); // // sp = new JScrollPane(); // sp.getViewport().add(table); // sp.setBounds(50, 50, 700, 400); // table.setFillsViewportHeight(true); // this.add(sp); // // searchDateBtn = new JButton("按日期检索"); // searchDateBtn.setBounds(150, 480, 100, 30); // this.add(searchDateBtn); // // searchUserBtn = new JButton("按用户检索"); // // searchUserBtn.setBounds(350, 480, 100, 30); // // this.add(searchUserBtn); // returnBtn = new JButton("返回"); // returnBtn.setBounds(550, 480, 100, 30); // this.add(returnBtn); // // searchDateBtn.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // PaymentDateDialog d = new PaymentDateDialog(getThis()); // } // }); // // // searchUserBtn.addActionListener(new ActionListener() { // // public void actionPerformed(ActionEvent e) { // // String s = (String) JOptionPane.showInputDialog(null, // // "请输入需查询的员工编号:\n", "title", JOptionPane.PLAIN_MESSAGE, // // null, null, ""); // // if (s == null) { // // return; // // } // // list = cc.getLogListOfUser(s); // // reInitList(s); // // return; // // } // // }); // // returnBtn.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // String str = MainFrame.getUser().getWork().getPositionString(); // if (str.equals("财务人员(高)")) { // Main.frame.setView(new FinanceHighUI()); // } else if (str.equals("财务人员(高)")) { // Main.frame.setView(new FinanceHighUI()); // } else if (str.equals("总经理")) { // Main.frame.setView(new ManagerUI()); // } // } // }); // } // // private PaymentManageUI getThis() { // return this; // } // // private void initList() { // list = pc.getAllLogList(); // vData = getShowList(); // // table.validate(); // // scrollPane.getViewport().removeAll(); // // scrollPane.getViewport().add(table); // // this.initComponents(); // this.repaint(); // } // // public void reInitList(Date d1, Date d2) { // list = pc.betweenDate(d1, d2); // vData.clear(); // // for (PaymentVO vo : list) { // vData.add(toVector(vo)); // } // // sp.getViewport().removeAll(); // sp.getViewport().add(table); // table.repaint(); // sp.repaint(); // this.repaint(); // } // // // private void reInitList(String s) { // // list = cc.getLogListOfUser(s); // // vData.clear(); // // // // for (IncomeVO vo : list) { // // vData.add(toVector(vo)); // // } // // // // sp.getViewport().removeAll(); // // sp.getViewport().add(table); // // table.repaint(); // // sp.repaint(); // // this.repaint(); // // } // // private Vector<Vector<String>> getShowList() { // Vector<Vector<String>> v = new Vector<Vector<String>>(); // int n = list.size(); // for (int i = 0; i < n; i++) { // Vector<String> tmp = toVector(list.get(i)); // v.add(tmp); // // System.out.println(vo.getName()); // } // return v; // } // // private Vector<String> toVector(PaymentVO vo) { // Vector<String> tmp = new Vector<String>(); // tmp.add(vo.userID); // tmp.add(vo.payID); // tmp.add(DateUtil.dateToString(vo.d)); // tmp.add(vo.payment + ""); // tmp.add(vo.payName); // tmp.add(vo.bankID); // tmp.add(vo.type); // tmp.add(vo.times + ""); // return tmp; // } // //class PaymentDateDialog extends JDialog { // private static final long serialVersionUID = 1L; // private JLabel label1; // private JLabel label2; // private JTextField field1; // private JTextField field2; // private JButton btn1; // private JButton btn2; // private IncomeManageUI ui; // // public PaymentDateDialog(IncomeManageUI ui) { // this.ui = ui; // this.setVisible(true); // this.setResizable(false); // this.setLayout(null); // this.setSize(300, 200); // this.setLocationRelativeTo(null); // // initComponents(); // } // // private void initComponents() { // label1 = new JLabel("起始日期:"); // label1.setBounds(25, 25, 50, 15); // label2 = new JLabel("结束日期:"); // label2.setBounds(25, 75, 50, 15); // field1 = new JTextField(); // field1.setBounds(100, 20, 175, 25); // field1.setText(DateUtil.dateToString()); // field2 = new JTextField(); // field2.setBounds(100, 70, 175, 25); // field2.setText(DateUtil.dateToString()); // this.getContentPane().add(label1); // this.getContentPane().add(label2); // this.getContentPane().add(field1); // this.getContentPane().add(field2); // // btn1 = new JButton("确定"); // btn1.setBounds(50, 120, 75, 30); // this.getContentPane().add(btn1); // btn2 = new JButton("返回"); // btn2.setBounds(50, 120, 75, 30); // this.getContentPane().add(btn2); // btn1.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // Date d1 = DateUtil.stringToDate(field1.getText()); // Date d2 = DateUtil.stringToDate(field2.getText()); // ui.reInitList(d1, d2); // } // }); // btn2.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // setVisible(false); // } // }); // } //}
7,250
0.642837
0.621503
250
27.312
16.916225
71
false
false
0
0
0
0
0
0
2.392
false
false
9
26a3406f96672fced69bb6aaa377a655cc63c9ab
27,273,042,344,650
6a625032bbc989ca2a598f2ac8c29626369c3894
/core/src/main/java/com/gapfyl/exceptions/users/UserHaveNoPermissionException.java
7eb777c0c565c0bcf95d69e94a0e7fc098e60551
[]
no_license
vigneshwaran26/gapfyl_application
https://github.com/vigneshwaran26/gapfyl_application
037caf26d3916f5be127d8a33d3867d8e944ceff
b1c9e2fb5b6abaac665b51cac4957e10f5f284a6
refs/heads/master
2023-08-28T14:14:27.628000
2021-09-19T18:02:03
2021-09-19T18:02:03
408,198,965
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gapfyl.exceptions.users; import com.gapfyl.constants.ErrorCode; import com.gapfyl.exceptions.GapFylException; public class UserHaveNoPermissionException extends GapFylException { public UserHaveNoPermissionException(String id) { super(ErrorCode.USER_HAVE_NO_PERMISSION,"user.have.no.permission",new Object[] {id}); } }
UTF-8
Java
349
java
UserHaveNoPermissionException.java
Java
[]
null
[]
package com.gapfyl.exceptions.users; import com.gapfyl.constants.ErrorCode; import com.gapfyl.exceptions.GapFylException; public class UserHaveNoPermissionException extends GapFylException { public UserHaveNoPermissionException(String id) { super(ErrorCode.USER_HAVE_NO_PERMISSION,"user.have.no.permission",new Object[] {id}); } }
349
0.7851
0.7851
10
33.900002
30.628256
93
false
false
0
0
0
0
0
0
0.6
false
false
9
9d5df83e875481300c66f80c7970e414099f2a38
26,001,732,041,139
a004c21d39f60263154018c088b62defb9c9cf66
/sample/target/sample-0.0.1-SNAPSHOT/WEB-INF/classes/com/example/services/OrderService.java
bc2fcc0d904a6fa6b9962d9fbd5b250500787e8c
[]
no_license
deepaswamy7/MyFirstRepository
https://github.com/deepaswamy7/MyFirstRepository
b9465ded21e17382b67342e0976b004590c3bfe7
fe841b3cb7a0b883758e5e234e3dd8f68939fa0c
refs/heads/master
2021-01-11T12:17:06.545000
2017-04-26T18:57:52
2017-04-26T18:57:52
76,510,426
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.service; import java.util.List; import com.example.model.Orders; public interface OrderService { List<Orders> findAll(); }
UTF-8
Java
158
java
OrderService.java
Java
[]
null
[]
package com.example.service; import java.util.List; import com.example.model.Orders; public interface OrderService { List<Orders> findAll(); }
158
0.71519
0.71519
10
13.8
13.876599
32
false
false
0
0
0
0
0
0
0.5
false
false
9
d25f1c86f6742d4195271f98c99bb04627e25601
16,844,861,762,250
9bb289e9bdae8546221473ab075434df3eafc89c
/src/main/java/com/my/core/repository/MenuRepository.java
89ca14dfd79f09ffdad1263cd58c50cf5dc6a216
[]
no_license
YTHXQ/ECCS
https://github.com/YTHXQ/ECCS
1a2481d61d44aade2a35f81d9ac2f736cbfe9a2d
8953aedaaaf7756ab244f79715545a1b8cb620b7
refs/heads/master
2016-09-05T15:38:29.980000
2015-04-14T14:43:46
2015-04-14T14:43:46
32,019,905
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.my.core.repository; import com.my.core.domain.Menu; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * Created by Administrator on 2015/3/18. */ public interface MenuRepository extends JpaRepository<Menu,Integer> { List<Menu> findByType(int type); }
UTF-8
Java
312
java
MenuRepository.java
Java
[ { "context": "sitory;\n\nimport java.util.List;\n\n/**\n * Created by Administrator on 2015/3/18.\n */\npublic interface MenuRepository", "end": 183, "score": 0.5303927063941956, "start": 170, "tag": "USERNAME", "value": "Administrator" } ]
null
[]
package com.my.core.repository; import com.my.core.domain.Menu; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * Created by Administrator on 2015/3/18. */ public interface MenuRepository extends JpaRepository<Menu,Integer> { List<Menu> findByType(int type); }
312
0.766026
0.74359
14
21.285715
23.20846
69
false
false
0
0
0
0
0
0
0.428571
false
false
9
26f4c28c0aaa110cb5f4fae73c2009d493f97587
25,254,407,729,619
063f3b313356c366f7c12dd73eb988a73130f9c9
/erp_ejb/src_nomina/com/bydan/erp/nomina/util/EstadoNovedadNomiConstantesFunciones.java
8bd2e5eb9ba5b7656c8c329060ed68500dc70443
[ "Apache-2.0" ]
permissive
bydan/pre
https://github.com/bydan/pre
0c6cdfe987b964e6744ae546360785e44508045f
54674f4dcffcac5dbf458cdf57a4c69fde5c55ff
refs/heads/master
2020-12-25T14:58:12.316000
2016-09-01T03:29:06
2016-09-01T03:29:06
67,094,354
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* *AVISO LEGAL © Copyright *Este programa esta protegido por la ley de derechos de autor. *La reproduccion o distribucion ilicita de este programa o de cualquiera de *sus partes esta penado por la ley con severas sanciones civiles y penales, *y seran objeto de todas las sanciones legales que correspondan. *Su contenido no puede copiarse para fines comerciales o de otras, *ni puede mostrarse, incluso en una version modificada, en otros sitios Web. Solo esta permitido colocar hipervinculos al sitio web. */ package com.bydan.erp.nomina.util; import org.apache.log4j.Logger; import java.sql.Time; import java.sql.Timestamp; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.util.CellRangeAddress; import javax.swing.border.Border; import java.io.InputStream; import java.util.Scanner; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.Date; //import java.util.ArrayList; import com.bydan.framework.erp.business.entity.GeneralEntity; import com.bydan.framework.erp.business.entity.GeneralEntityReturnGeneral; import com.bydan.framework.erp.business.entity.GeneralEntityParameterGeneral; import com.bydan.framework.erp.business.entity.DatoGeneral; import com.bydan.framework.erp.business.entity.OrderBy; import com.bydan.framework.erp.business.entity.Classe; import com.bydan.framework.erp.business.entity.Reporte; import com.bydan.framework.erp.util.ConstantesJsp; import com.bydan.framework.erp.business.dataaccess.ConstantesSql; import com.bydan.erp.nomina.util.EstadoNovedadNomiConstantesFunciones; import com.bydan.erp.nomina.util.EstadoNovedadNomiParameterReturnGeneral; //import com.bydan.erp.nomina.util.EstadoNovedadNomiParameterGeneral; import com.bydan.framework.erp.business.logic.DatosCliente; import com.bydan.framework.erp.util.*; import com.bydan.erp.nomina.business.entity.*; //import com.bydan.framework.erp.util.*; //import com.bydan.framework.erp.business.logic.*; //import com.bydan.erp.nomina.business.dataaccess.*; //import com.bydan.erp.nomina.business.logic.*; //import java.sql.SQLException; //CONTROL_INCLUDE import com.bydan.erp.seguridad.business.entity.*; @SuppressWarnings("unused") final public class EstadoNovedadNomiConstantesFunciones extends EstadoNovedadNomiConstantesFuncionesAdditional { public static String S_TIPOREPORTE_EXTRA=""; //USADO MAS EN RELACIONADO PARA MANTENIMIENTO MAESTRO-DETALLE public static Integer TAMANIO_ALTO_MAXIMO_TABLADATOS=Constantes.ISWING_TAMANIOMAXIMO_TABLADATOS; public static Integer TAMANIO_ALTO_MINIMO_TABLADATOS=Constantes.ISWING_TAMANIOMINIMO_TABLADATOS; //PARA TABLA RELACIONES(DESCRIPCION HEIGHTPE_REL_TAB) public static Integer ALTO_TABPANE_RELACIONES=Constantes.ISWING_ALTO_TABPANE + Funciones2.getValorProporcion(Constantes.ISWING_ALTO_TABPANE,0); //PARA TABLA RELACIONADO(DESCRIPTION HEIGHTPE_REL) public static Integer TAMANIO_ALTO_MAXIMO_TABLADATOSREL=Constantes.ISWING_TAMANIOMAXIMO_TABLADATOSREL + Funciones2.getValorProporcion(Constantes.ISWING_TAMANIOMAXIMO_TABLADATOSREL,0); public static Integer TAMANIO_ALTO_MINIMO_TABLADATOSREL=Constantes.ISWING_TAMANIOMINIMO_TABLADATOSREL + Funciones2.getValorProporcion(Constantes.ISWING_TAMANIOMINIMO_TABLADATOSREL,0); //PARA CAMBIAR TODO--> SE CAMBIA EN TABLA RELACIONES Y TABLAS RELACIONADOS /* PARA MANEJAR EL TAB RELACIONES CON TABLA DE DATOS SE DEBE MODIFICAR Y VERIFICAR LOS VALORES CONTANTES: final public static Integer ISWING_TAMANIOMAXIMO_TABLADATOSREL=240;//230;350; final public static Integer ISWING_TAMANIOMINIMO_TABLADATOSREL=240;//230;260 final public static Integer ISWING_ALTO_TABPANE=375;//375;400;260; CASO CONTRARIO, ESTOS VALORES SERIAN PARA CADA CASO (NO CONSTANTES) NOTA: * LA ALINEACION HORIZONTAL,FALTA */ public static final String SFINALQUERY=Constantes.SFINALQUERY; public static final String SNOMBREOPCION="EstadoNovedadNomi"; public static final String SPATHOPCION="Nomina"; public static final String SPATHMODULO="nomina/"; public static final String SPERSISTENCECONTEXTNAME=""; public static final String SPERSISTENCENAME="EstadoNovedadNomi"+EstadoNovedadNomiConstantesFunciones.SPERSISTENCECONTEXTNAME+Constantes.SPERSISTENCECONTEXTNAME; public static final String SEJBNAME="EstadoNovedadNomiHomeRemote"; public static final String SEJBNAME_ADDITIONAL="EstadoNovedadNomiHomeRemoteAdditional"; //RMI public static final String SLOCALEJBNAME_RMI=EstadoNovedadNomiConstantesFunciones.SCHEMA+"_"+EstadoNovedadNomiConstantesFunciones.SEJBNAME+"_"+Constantes.SEJBLOCAL;//"erp/EstadoNovedadNomiHomeRemote/local" public static final String SREMOTEEJBNAME_RMI=EstadoNovedadNomiConstantesFunciones.SCHEMA+"_"+EstadoNovedadNomiConstantesFunciones.SEJBNAME+"_"+Constantes.SEJBREMOTE;//remote public static final String SLOCALEJBNAMEADDITIONAL_RMI=EstadoNovedadNomiConstantesFunciones.SCHEMA+"_"+EstadoNovedadNomiConstantesFunciones.SEJBNAME+Constantes.SEJBADDITIONAL+"_"+Constantes.SEJBLOCAL;//"erp/EstadoNovedadNomiHomeRemote/local" public static final String SREMOTEEJBNAMEADDITIONAL_RMI=EstadoNovedadNomiConstantesFunciones.SCHEMA+"_"+EstadoNovedadNomiConstantesFunciones.SEJBNAME+Constantes.SEJBADDITIONAL+"_"+Constantes.SEJBREMOTE;//remote //RMI //JBOSS5.1 public static final String SLOCALEJBNAME=Constantes.SEJBPACKAGE+Constantes.SEJBSEPARATOR+EstadoNovedadNomiConstantesFunciones.SEJBNAME+Constantes.SEJBSEPARATOR+Constantes.SEJBLOCAL;//"erp/EstadoNovedadNomiHomeRemote/local" public static final String SREMOTEEJBNAME=Constantes.SEJBPACKAGE+Constantes.SEJBSEPARATOR+EstadoNovedadNomiConstantesFunciones.SEJBNAME+Constantes.SEJBSEPARATOR+Constantes.SEJBREMOTE;//remote public static final String SLOCALEJBNAMEADDITIONAL=Constantes.SEJBPACKAGE+Constantes.SEJBSEPARATOR+EstadoNovedadNomiConstantesFunciones.SEJBNAME+Constantes.SEJBADDITIONAL+Constantes.SEJBSEPARATOR+Constantes.SEJBLOCAL;//"erp/EstadoNovedadNomiHomeRemote/local" public static final String SREMOTEEJBNAMEADDITIONAL=Constantes.SEJBPACKAGE+Constantes.SEJBSEPARATOR+EstadoNovedadNomiConstantesFunciones.SEJBNAME+Constantes.SEJBADDITIONAL+Constantes.SEJBSEPARATOR+Constantes.SEJBREMOTE;//remote //JBOSS5.1 public static final String SSESSIONNAME=EstadoNovedadNomiConstantesFunciones.OBJECTNAME + Constantes.SSESSIONBEAN; public static final String SSESSIONNAME_FACE=Constantes.SFACE_INI+EstadoNovedadNomiConstantesFunciones.SSESSIONNAME + Constantes.SFACE_FIN; public static final String SREQUESTNAME=EstadoNovedadNomiConstantesFunciones.OBJECTNAME + Constantes.SREQUESTBEAN; public static final String SREQUESTNAME_FACE=Constantes.SFACE_INI+EstadoNovedadNomiConstantesFunciones.SREQUESTNAME + Constantes.SFACE_FIN; public static final String SCLASSNAMETITULOREPORTES="Estado Novedads"; public static final String SRELATIVEPATH="../../../"; public static final String SCLASSPLURAL="s"; public static final String SCLASSWEBTITULO="Estado Novedad"; public static final String SCLASSWEBTITULO_LOWER="Estado Novedad Nomi"; public static Integer INUMEROPAGINACION=10; public static Integer ITAMANIOFILATABLA=Constantes.ISWING_ALTO_FILA; public static Boolean ES_DEBUG=false; public static Boolean CON_DESCRIPCION_DETALLADO=false; public static final String CLASSNAME="EstadoNovedadNomi"; public static final String OBJECTNAME="estadonovedadnomi"; //PARA FORMAR QUERYS public static final String SCHEMA=Constantes.SCHEMA_NOMINA; public static final String TABLENAME="estado_novedad_nomi"; public static final String SQL_SECUENCIAL=SCHEMA+"."+TABLENAME+"_id_seq"; public static String QUERYSELECT="select estadonovedadnomi from "+EstadoNovedadNomiConstantesFunciones.SPERSISTENCENAME+" estadonovedadnomi"; public static String QUERYSELECTNATIVE="select "+EstadoNovedadNomiConstantesFunciones.SCHEMA+"."+EstadoNovedadNomiConstantesFunciones.TABLENAME+".id,"+EstadoNovedadNomiConstantesFunciones.SCHEMA+"."+EstadoNovedadNomiConstantesFunciones.TABLENAME+".version_row,"+EstadoNovedadNomiConstantesFunciones.SCHEMA+"."+EstadoNovedadNomiConstantesFunciones.TABLENAME+".codigo,"+EstadoNovedadNomiConstantesFunciones.SCHEMA+"."+EstadoNovedadNomiConstantesFunciones.TABLENAME+".nombre from "+EstadoNovedadNomiConstantesFunciones.SCHEMA+"."+EstadoNovedadNomiConstantesFunciones.TABLENAME;//+" as "+EstadoNovedadNomiConstantesFunciones.TABLENAME; //AUDITORIA public static Boolean ISCONAUDITORIA=false; public static Boolean ISCONAUDITORIADETALLE=true; //GUARDAR SOLO MAESTRO DETALLE FUNCIONALIDAD public static Boolean ISGUARDARREL=false; protected EstadoNovedadNomiConstantesFuncionesAdditional estadonovedadnomiConstantesFuncionesAdditional=null; public EstadoNovedadNomiConstantesFuncionesAdditional getEstadoNovedadNomiConstantesFuncionesAdditional() { return this.estadonovedadnomiConstantesFuncionesAdditional; } public void setEstadoNovedadNomiConstantesFuncionesAdditional(EstadoNovedadNomiConstantesFuncionesAdditional estadonovedadnomiConstantesFuncionesAdditional) { try { this.estadonovedadnomiConstantesFuncionesAdditional=estadonovedadnomiConstantesFuncionesAdditional; } catch(Exception e) { ; } } public static final String ID=ConstantesSql.ID; public static final String VERSIONROW=ConstantesSql.VERSIONROW; public static final String CODIGO= "codigo"; public static final String NOMBRE= "nombre"; //TITULO CAMPO public static final String LABEL_ID= "Id"; public static final String LABEL_ID_LOWER= "id"; public static final String LABEL_VERSIONROW= "Versionrow"; public static final String LABEL_VERSIONROW_LOWER= "version Row"; public static final String LABEL_CODIGO= "Codigo"; public static final String LABEL_CODIGO_LOWER= "Codigo"; public static final String LABEL_NOMBRE= "Nombre"; public static final String LABEL_NOMBRE_LOWER= "Nombre"; public static final String SREGEXCODIGO=ConstantesValidacion.SREGEXCADENA; public static final String SMENSAJEREGEXCODIGO=ConstantesValidacion.SVALIDACIONCADENA; public static final String SREGEXNOMBRE=ConstantesValidacion.SREGEXCADENA; public static final String SMENSAJEREGEXNOMBRE=ConstantesValidacion.SVALIDACIONCADENA; public static String getEstadoNovedadNomiLabelDesdeNombre(String sNombreColumna) { String sLabelColumna=""; if(sNombreColumna.equals(EstadoNovedadNomiConstantesFunciones.CODIGO)) {sLabelColumna=EstadoNovedadNomiConstantesFunciones.LABEL_CODIGO;} if(sNombreColumna.equals(EstadoNovedadNomiConstantesFunciones.NOMBRE)) {sLabelColumna=EstadoNovedadNomiConstantesFunciones.LABEL_NOMBRE;} if(sLabelColumna.equals("")) { sLabelColumna=sNombreColumna; } return sLabelColumna; } public static String getNombreEjb_JBoss81(String sAplicacion,String sModule,String sClaseEjb,String sInterfaceEjb) throws Exception { String sDescripcion=""; sDescripcion="ejb:"+sAplicacion+"/"+sModule+"/"+sClaseEjb+"!" + sInterfaceEjb; return sDescripcion; } public static String getEstadoNovedadNomiDescripcion(EstadoNovedadNomi estadonovedadnomi) { String sDescripcion=Constantes.SCAMPONONE; if(estadonovedadnomi !=null/* && estadonovedadnomi.getId()!=0*/) { sDescripcion=estadonovedadnomi.getcodigo();//estadonovedadnomiestadonovedadnomi.getcodigo().trim(); } return sDescripcion; } public static String getEstadoNovedadNomiDescripcionDetallado(EstadoNovedadNomi estadonovedadnomi) { String sDescripcion=""; sDescripcion+=EstadoNovedadNomiConstantesFunciones.ID+"="; sDescripcion+=estadonovedadnomi.getId().toString()+","; sDescripcion+=EstadoNovedadNomiConstantesFunciones.VERSIONROW+"="; sDescripcion+=estadonovedadnomi.getVersionRow().toString()+","; sDescripcion+=EstadoNovedadNomiConstantesFunciones.CODIGO+"="; sDescripcion+=estadonovedadnomi.getcodigo()+","; sDescripcion+=EstadoNovedadNomiConstantesFunciones.NOMBRE+"="; sDescripcion+=estadonovedadnomi.getnombre()+","; return sDescripcion; } public static void setEstadoNovedadNomiDescripcion(EstadoNovedadNomi estadonovedadnomi,String sValor) throws Exception { if(estadonovedadnomi !=null) { estadonovedadnomi.setcodigo(sValor);;//estadonovedadnomiestadonovedadnomi.getcodigo().trim(); } } public static String getNombreIndice(String sNombreIndice) { if(sNombreIndice.equals("Todos")) { sNombreIndice="Tipo=Todos"; } else if(sNombreIndice.equals("PorId")) { sNombreIndice="Tipo=Por Id"; } return sNombreIndice; } public static String getDetalleIndicePorId(Long id) { return "Parametros->Porid="+id.toString(); } public static void quitarEspaciosEstadoNovedadNomi(EstadoNovedadNomi estadonovedadnomi,ArrayList<DatoGeneral> arrDatoGeneral) throws Exception { estadonovedadnomi.setcodigo(estadonovedadnomi.getcodigo().trim()); estadonovedadnomi.setnombre(estadonovedadnomi.getnombre().trim()); } public static void quitarEspaciosEstadoNovedadNomis(List<EstadoNovedadNomi> estadonovedadnomis,ArrayList<DatoGeneral> arrDatoGeneral) throws Exception { for(EstadoNovedadNomi estadonovedadnomi: estadonovedadnomis) { estadonovedadnomi.setcodigo(estadonovedadnomi.getcodigo().trim()); estadonovedadnomi.setnombre(estadonovedadnomi.getnombre().trim()); } } public static void InicializarGeneralEntityAuxiliaresEstadoNovedadNomi(EstadoNovedadNomi estadonovedadnomi,Boolean conAsignarBase,Boolean conInicializarAuxiliar) throws Exception { if(conAsignarBase && estadonovedadnomi.getConCambioAuxiliar()) { estadonovedadnomi.setIsDeleted(estadonovedadnomi.getIsDeletedAuxiliar()); estadonovedadnomi.setIsNew(estadonovedadnomi.getIsNewAuxiliar()); estadonovedadnomi.setIsChanged(estadonovedadnomi.getIsChangedAuxiliar()); //YA RESTAURO, NO DEBERIA HACERLO NUEVAMENTE AL MENOS NO HASTA GUARDAR OTRA VEZ estadonovedadnomi.setConCambioAuxiliar(false); } if(conInicializarAuxiliar) { estadonovedadnomi.setIsDeletedAuxiliar(false); estadonovedadnomi.setIsNewAuxiliar(false); estadonovedadnomi.setIsChangedAuxiliar(false); estadonovedadnomi.setConCambioAuxiliar(false); } } public static void InicializarGeneralEntityAuxiliaresEstadoNovedadNomis(List<EstadoNovedadNomi> estadonovedadnomis,Boolean conAsignarBase,Boolean conInicializarAuxiliar) throws Exception { for(EstadoNovedadNomi estadonovedadnomi : estadonovedadnomis) { if(conAsignarBase && estadonovedadnomi.getConCambioAuxiliar()) { estadonovedadnomi.setIsDeleted(estadonovedadnomi.getIsDeletedAuxiliar()); estadonovedadnomi.setIsNew(estadonovedadnomi.getIsNewAuxiliar()); estadonovedadnomi.setIsChanged(estadonovedadnomi.getIsChangedAuxiliar()); //YA RESTAURO, NO DEBERIA HACERLO NUEVAMENTE AL MENOS NO HASTA GUARDAR OTRA VEZ estadonovedadnomi.setConCambioAuxiliar(false); } if(conInicializarAuxiliar) { estadonovedadnomi.setIsDeletedAuxiliar(false); estadonovedadnomi.setIsNewAuxiliar(false); estadonovedadnomi.setIsChangedAuxiliar(false); estadonovedadnomi.setConCambioAuxiliar(false); } } } public static void InicializarValoresEstadoNovedadNomi(EstadoNovedadNomi estadonovedadnomi,Boolean conEnteros) throws Exception { if(conEnteros) { Short ish_value=0; } } public static void InicializarValoresEstadoNovedadNomis(List<EstadoNovedadNomi> estadonovedadnomis,Boolean conEnteros) throws Exception { for(EstadoNovedadNomi estadonovedadnomi: estadonovedadnomis) { if(conEnteros) { Short ish_value=0; } } } public static void TotalizarValoresFilaEstadoNovedadNomi(List<EstadoNovedadNomi> estadonovedadnomis,EstadoNovedadNomi estadonovedadnomiAux) throws Exception { EstadoNovedadNomiConstantesFunciones.InicializarValoresEstadoNovedadNomi(estadonovedadnomiAux,true); for(EstadoNovedadNomi estadonovedadnomi: estadonovedadnomis) { if(estadonovedadnomi.getsType().equals(Constantes2.S_TOTALES)) { continue; } } } public static ArrayList<String> getArrayColumnasGlobalesEstadoNovedadNomi(ArrayList<DatoGeneral> arrDatoGeneral) throws Exception { ArrayList<String> arrColumnasGlobales=new ArrayList<String>(); arrColumnasGlobales=EstadoNovedadNomiConstantesFunciones.getArrayColumnasGlobalesEstadoNovedadNomi(arrDatoGeneral,new ArrayList<String>()); return arrColumnasGlobales; } public static ArrayList<String> getArrayColumnasGlobalesEstadoNovedadNomi(ArrayList<DatoGeneral> arrDatoGeneral,ArrayList<String> arrColumnasGlobalesNo) throws Exception { ArrayList<String> arrColumnasGlobales=new ArrayList<String>(); Boolean noExiste=false; return arrColumnasGlobales; } public static ArrayList<String> getArrayColumnasGlobalesNoEstadoNovedadNomi(ArrayList<DatoGeneral> arrDatoGeneral) throws Exception { ArrayList<String> arrColumnasGlobales=new ArrayList<String>(); return arrColumnasGlobales; } public static Boolean ExisteEnLista(List<EstadoNovedadNomi> estadonovedadnomis,EstadoNovedadNomi estadonovedadnomi,Boolean conIdNulo) throws Exception { Boolean existe=false; for(EstadoNovedadNomi estadonovedadnomiAux: estadonovedadnomis) { if(estadonovedadnomiAux!=null && estadonovedadnomi!=null) { if((estadonovedadnomiAux.getId()==null && estadonovedadnomi.getId()==null) && conIdNulo) { existe=true; break; } else if(estadonovedadnomiAux.getId()!=null && estadonovedadnomi.getId()!=null){ if(estadonovedadnomiAux.getId().equals(estadonovedadnomi.getId())) { existe=true; break; } } } } return existe; } public static ArrayList<DatoGeneral> getTotalesListaEstadoNovedadNomi(List<EstadoNovedadNomi> estadonovedadnomis) throws Exception { ArrayList<DatoGeneral> arrTotalesDatoGeneral=new ArrayList<DatoGeneral>(); DatoGeneral datoGeneral=new DatoGeneral(); for(EstadoNovedadNomi estadonovedadnomi: estadonovedadnomis) { if(estadonovedadnomi.getsType().equals(Constantes2.S_TOTALES)) { continue; } } return arrTotalesDatoGeneral; } public static ArrayList<OrderBy> getOrderByListaEstadoNovedadNomi() throws Exception { ArrayList<OrderBy> arrOrderBy=new ArrayList<OrderBy>(); OrderBy orderBy=new OrderBy(); orderBy=new OrderBy(false,EstadoNovedadNomiConstantesFunciones.LABEL_ID, EstadoNovedadNomiConstantesFunciones.ID,false,""); arrOrderBy.add(orderBy); orderBy=new OrderBy(false,EstadoNovedadNomiConstantesFunciones.LABEL_VERSIONROW, EstadoNovedadNomiConstantesFunciones.VERSIONROW,false,""); arrOrderBy.add(orderBy); orderBy=new OrderBy(false,EstadoNovedadNomiConstantesFunciones.LABEL_CODIGO, EstadoNovedadNomiConstantesFunciones.CODIGO,false,""); arrOrderBy.add(orderBy); orderBy=new OrderBy(false,EstadoNovedadNomiConstantesFunciones.LABEL_NOMBRE, EstadoNovedadNomiConstantesFunciones.NOMBRE,false,""); arrOrderBy.add(orderBy); return arrOrderBy; } public static List<String> getTodosTiposColumnasEstadoNovedadNomi() throws Exception { List<String> arrTiposColumnas=new ArrayList<String>(); String sTipoColumna=new String(); sTipoColumna=new String(); sTipoColumna=EstadoNovedadNomiConstantesFunciones.ID; arrTiposColumnas.add(sTipoColumna); sTipoColumna=new String(); sTipoColumna=EstadoNovedadNomiConstantesFunciones.VERSIONROW; arrTiposColumnas.add(sTipoColumna); sTipoColumna=new String(); sTipoColumna=EstadoNovedadNomiConstantesFunciones.CODIGO; arrTiposColumnas.add(sTipoColumna); sTipoColumna=new String(); sTipoColumna=EstadoNovedadNomiConstantesFunciones.NOMBRE; arrTiposColumnas.add(sTipoColumna); return arrTiposColumnas; } public static ArrayList<Reporte> getTiposSeleccionarEstadoNovedadNomi() throws Exception { return EstadoNovedadNomiConstantesFunciones.getTiposSeleccionarEstadoNovedadNomi(false,true,true,true,true); } public static ArrayList<Reporte> getTiposSeleccionarEstadoNovedadNomi(Boolean conFk) throws Exception { return EstadoNovedadNomiConstantesFunciones.getTiposSeleccionarEstadoNovedadNomi(conFk,true,true,true,true); } public static ArrayList<Reporte> getTiposSeleccionarEstadoNovedadNomi(Boolean conFk,Boolean conStringColumn,Boolean conValorColumn,Boolean conFechaColumn,Boolean conBitColumn) throws Exception { ArrayList<Reporte> arrTiposSeleccionarTodos=new ArrayList<Reporte>(); Reporte reporte=new Reporte(); if(conStringColumn) { reporte=new Reporte(); reporte.setsCodigo(EstadoNovedadNomiConstantesFunciones.LABEL_CODIGO); reporte.setsDescripcion(EstadoNovedadNomiConstantesFunciones.LABEL_CODIGO); arrTiposSeleccionarTodos.add(reporte); } if(conStringColumn) { reporte=new Reporte(); reporte.setsCodigo(EstadoNovedadNomiConstantesFunciones.LABEL_NOMBRE); reporte.setsDescripcion(EstadoNovedadNomiConstantesFunciones.LABEL_NOMBRE); arrTiposSeleccionarTodos.add(reporte); } return arrTiposSeleccionarTodos; } public static ArrayList<Reporte> getTiposRelacionesEstadoNovedadNomi(Boolean conEspecial) throws Exception { ArrayList<Reporte> arrTiposRelacionesTodos=new ArrayList<Reporte>(); Reporte reporte=new Reporte(); //ESTO ESTA EN CONTROLLER return arrTiposRelacionesTodos; } public static void refrescarForeignKeysDescripcionesEstadoNovedadNomi(EstadoNovedadNomi estadonovedadnomiAux) throws Exception { } public static void refrescarForeignKeysDescripcionesEstadoNovedadNomi(List<EstadoNovedadNomi> estadonovedadnomisTemp) throws Exception { for(EstadoNovedadNomi estadonovedadnomiAux:estadonovedadnomisTemp) { } } public static ArrayList<Classe> getClassesForeignKeysOfEstadoNovedadNomi(ArrayList<Classe> classesP,DeepLoadType deepLoadType)throws Exception { try { ArrayList<Classe> classes=new ArrayList<Classe>(); if(deepLoadType.equals(DeepLoadType.NONE)) { } else if(deepLoadType.equals(DeepLoadType.INCLUDE)) { } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { } return classes; } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesForeignKeysFromStringsOfEstadoNovedadNomi(ArrayList<String> arrClasses,DeepLoadType deepLoadType)throws Exception { try { ArrayList<Classe> classes=new ArrayList<Classe>(); if(deepLoadType.equals(DeepLoadType.NONE)) { for(String sClasse:arrClasses) { } } else if(deepLoadType.equals(DeepLoadType.INCLUDE)) { for(String sClasse:arrClasses) { } } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { } return classes; } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesRelationshipsOfEstadoNovedadNomi(ArrayList<Classe> classesP,DeepLoadType deepLoadType)throws Exception { try { return EstadoNovedadNomiConstantesFunciones.getClassesRelationshipsOfEstadoNovedadNomi(classesP,deepLoadType,true); } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesRelationshipsOfEstadoNovedadNomi(ArrayList<Classe> classesP,DeepLoadType deepLoadType,Boolean conMuchosAMuchos)throws Exception { try { ArrayList<Classe> classes=new ArrayList<Classe>(); if(deepLoadType.equals(DeepLoadType.NONE)) { classes.add(new Classe(NovedadNomi.class)); } else if(deepLoadType.equals(DeepLoadType.INCLUDE)) { for(Classe clas:classesP) { if(clas.clas.equals(NovedadNomi.class)) { classes.add(new Classe(NovedadNomi.class)); break; } } } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { } return classes; } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesRelationshipsFromStringsOfEstadoNovedadNomi(ArrayList<String> arrClasses,DeepLoadType deepLoadType)throws Exception { try { return EstadoNovedadNomiConstantesFunciones.getClassesRelationshipsFromStringsOfEstadoNovedadNomi(arrClasses,deepLoadType,true); } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesRelationshipsFromStringsOfEstadoNovedadNomi(ArrayList<String> arrClasses,DeepLoadType deepLoadType,Boolean conMuchosAMuchos)throws Exception { try { ArrayList<Classe> classes=new ArrayList<Classe>(); if(deepLoadType.equals(DeepLoadType.NONE)) { for(String sClasse:arrClasses) { if(NovedadNomi.class.getSimpleName().equals(sClasse)) { classes.add(new Classe(NovedadNomi.class)); continue; } } } else if(deepLoadType.equals(DeepLoadType.INCLUDE)) { for(String sClasse:arrClasses) { if(NovedadNomi.class.getSimpleName().equals(sClasse)) { classes.add(new Classe(NovedadNomi.class)); continue; } } } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { } return classes; } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } //FUNCIONES CONTROLLER public static void actualizarLista(EstadoNovedadNomi estadonovedadnomi,List<EstadoNovedadNomi> estadonovedadnomis,Boolean permiteQuitar) throws Exception { try { Boolean existe=false; EstadoNovedadNomi estadonovedadnomiEncontrado=null; for(EstadoNovedadNomi estadonovedadnomiLocal:estadonovedadnomis) { if(estadonovedadnomiLocal.getId().equals(estadonovedadnomi.getId())) { estadonovedadnomiEncontrado=estadonovedadnomiLocal; estadonovedadnomiLocal.setIsChanged(estadonovedadnomi.getIsChanged()); estadonovedadnomiLocal.setIsNew(estadonovedadnomi.getIsNew()); estadonovedadnomiLocal.setIsDeleted(estadonovedadnomi.getIsDeleted()); estadonovedadnomiLocal.setGeneralEntityOriginal(estadonovedadnomi.getGeneralEntityOriginal()); estadonovedadnomiLocal.setId(estadonovedadnomi.getId()); estadonovedadnomiLocal.setVersionRow(estadonovedadnomi.getVersionRow()); estadonovedadnomiLocal.setcodigo(estadonovedadnomi.getcodigo()); estadonovedadnomiLocal.setnombre(estadonovedadnomi.getnombre()); estadonovedadnomiLocal.setNovedadNomis(estadonovedadnomi.getNovedadNomis()); existe=true; break; } } if(!estadonovedadnomi.getIsDeleted()) { if(!existe) { estadonovedadnomis.add(estadonovedadnomi); } } else { if(estadonovedadnomiEncontrado!=null && permiteQuitar) { estadonovedadnomis.remove(estadonovedadnomiEncontrado); } } } catch(Exception e) { throw e; } } public static void actualizarSelectedLista(EstadoNovedadNomi estadonovedadnomi,List<EstadoNovedadNomi> estadonovedadnomis) throws Exception { try { for(EstadoNovedadNomi estadonovedadnomiLocal:estadonovedadnomis) { if(estadonovedadnomiLocal.getId().equals(estadonovedadnomi.getId())) { estadonovedadnomiLocal.setIsSelected(estadonovedadnomi.getIsSelected()); break; } } } catch(Exception e) { throw e; } } public static void setEstadosInicialesEstadoNovedadNomi(List<EstadoNovedadNomi> estadonovedadnomisAux) throws Exception { //this.estadonovedadnomisAux=estadonovedadnomisAux; for(EstadoNovedadNomi estadonovedadnomiAux:estadonovedadnomisAux) { if(estadonovedadnomiAux.getIsChanged()) { estadonovedadnomiAux.setIsChanged(false); } if(estadonovedadnomiAux.getIsNew()) { estadonovedadnomiAux.setIsNew(false); } if(estadonovedadnomiAux.getIsDeleted()) { estadonovedadnomiAux.setIsDeleted(false); } } } public static void setEstadosInicialesEstadoNovedadNomi(EstadoNovedadNomi estadonovedadnomiAux) throws Exception { //this.estadonovedadnomiAux=estadonovedadnomiAux; if(estadonovedadnomiAux.getIsChanged()) { estadonovedadnomiAux.setIsChanged(false); } if(estadonovedadnomiAux.getIsNew()) { estadonovedadnomiAux.setIsNew(false); } if(estadonovedadnomiAux.getIsDeleted()) { estadonovedadnomiAux.setIsDeleted(false); } } public static void seleccionarAsignar(EstadoNovedadNomi estadonovedadnomiAsignar,EstadoNovedadNomi estadonovedadnomi) throws Exception { estadonovedadnomiAsignar.setId(estadonovedadnomi.getId()); estadonovedadnomiAsignar.setVersionRow(estadonovedadnomi.getVersionRow()); estadonovedadnomiAsignar.setcodigo(estadonovedadnomi.getcodigo()); estadonovedadnomiAsignar.setnombre(estadonovedadnomi.getnombre()); } public static void inicializarEstadoNovedadNomi(EstadoNovedadNomi estadonovedadnomi) throws Exception { try { estadonovedadnomi.setId(0L); estadonovedadnomi.setcodigo(""); estadonovedadnomi.setnombre(""); } catch(Exception e) { throw e; } } public static void generarExcelReporteHeaderEstadoNovedadNomi(String sTipo,Row row,Workbook workbook) { Cell cell=null; int iCell=0; CellStyle cellStyle = Funciones2.getStyleTitulo(workbook,"PRINCIPAL"); if(sTipo.equals("RELACIONADO")) { iCell++; } cell = row.createCell(iCell++); cell.setCellValue(EstadoNovedadNomiConstantesFunciones.LABEL_CODIGO); cell.setCellStyle(cellStyle); cell = row.createCell(iCell++); cell.setCellValue(EstadoNovedadNomiConstantesFunciones.LABEL_NOMBRE); cell.setCellStyle(cellStyle); } public static void generarExcelReporteDataEstadoNovedadNomi(String sTipo,Row row,Workbook workbook,EstadoNovedadNomi estadonovedadnomi,CellStyle cellStyle) throws Exception { Cell cell=null; int iCell=0; if(sTipo.equals("RELACIONADO")) { iCell++; } cell = row.createCell(iCell++); cell.setCellValue(estadonovedadnomi.getcodigo()); if(cellStyle!=null) { cell.setCellStyle(cellStyle); } cell = row.createCell(iCell++); cell.setCellValue(estadonovedadnomi.getnombre()); if(cellStyle!=null) { cell.setCellStyle(cellStyle); } } //FUNCIONES CONTROLLER public String sFinalQueryEstadoNovedadNomi=Constantes.SFINALQUERY; public String getsFinalQueryEstadoNovedadNomi() { return this.sFinalQueryEstadoNovedadNomi; } public void setsFinalQueryEstadoNovedadNomi(String sFinalQueryEstadoNovedadNomi) { this.sFinalQueryEstadoNovedadNomi= sFinalQueryEstadoNovedadNomi; } public Border resaltarSeleccionarEstadoNovedadNomi=null; public Border setResaltarSeleccionarEstadoNovedadNomi(ParametroGeneralUsuario parametroGeneralUsuario/*EstadoNovedadNomiBeanSwingJInternalFrame estadonovedadnomiBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //estadonovedadnomiBeanSwingJInternalFrame.jTtoolBarEstadoNovedadNomi.setBorder(borderResaltar); this.resaltarSeleccionarEstadoNovedadNomi= borderResaltar; return borderResaltar; } public Border getResaltarSeleccionarEstadoNovedadNomi() { return this.resaltarSeleccionarEstadoNovedadNomi; } public void setResaltarSeleccionarEstadoNovedadNomi(Border borderResaltarSeleccionarEstadoNovedadNomi) { this.resaltarSeleccionarEstadoNovedadNomi= borderResaltarSeleccionarEstadoNovedadNomi; } //RESALTAR,VISIBILIDAD,HABILITAR COLUMNA public Border resaltaridEstadoNovedadNomi=null; public Boolean mostraridEstadoNovedadNomi=true; public Boolean activaridEstadoNovedadNomi=true; public Border resaltarcodigoEstadoNovedadNomi=null; public Boolean mostrarcodigoEstadoNovedadNomi=true; public Boolean activarcodigoEstadoNovedadNomi=true; public Border resaltarnombreEstadoNovedadNomi=null; public Boolean mostrarnombreEstadoNovedadNomi=true; public Boolean activarnombreEstadoNovedadNomi=true; public Border setResaltaridEstadoNovedadNomi(ParametroGeneralUsuario parametroGeneralUsuario/*EstadoNovedadNomiBeanSwingJInternalFrame estadonovedadnomiBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //estadonovedadnomiBeanSwingJInternalFrame.jTtoolBarEstadoNovedadNomi.setBorder(borderResaltar); this.resaltaridEstadoNovedadNomi= borderResaltar; return borderResaltar; } public Border getresaltaridEstadoNovedadNomi() { return this.resaltaridEstadoNovedadNomi; } public void setResaltaridEstadoNovedadNomi(Border borderResaltar) { this.resaltaridEstadoNovedadNomi= borderResaltar; } public Boolean getMostraridEstadoNovedadNomi() { return this.mostraridEstadoNovedadNomi; } public void setMostraridEstadoNovedadNomi(Boolean mostraridEstadoNovedadNomi) { this.mostraridEstadoNovedadNomi= mostraridEstadoNovedadNomi; } public Boolean getActivaridEstadoNovedadNomi() { return this.activaridEstadoNovedadNomi; } public void setActivaridEstadoNovedadNomi(Boolean activaridEstadoNovedadNomi) { this.activaridEstadoNovedadNomi= activaridEstadoNovedadNomi; } public Border setResaltarcodigoEstadoNovedadNomi(ParametroGeneralUsuario parametroGeneralUsuario/*EstadoNovedadNomiBeanSwingJInternalFrame estadonovedadnomiBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //estadonovedadnomiBeanSwingJInternalFrame.jTtoolBarEstadoNovedadNomi.setBorder(borderResaltar); this.resaltarcodigoEstadoNovedadNomi= borderResaltar; return borderResaltar; } public Border getresaltarcodigoEstadoNovedadNomi() { return this.resaltarcodigoEstadoNovedadNomi; } public void setResaltarcodigoEstadoNovedadNomi(Border borderResaltar) { this.resaltarcodigoEstadoNovedadNomi= borderResaltar; } public Boolean getMostrarcodigoEstadoNovedadNomi() { return this.mostrarcodigoEstadoNovedadNomi; } public void setMostrarcodigoEstadoNovedadNomi(Boolean mostrarcodigoEstadoNovedadNomi) { this.mostrarcodigoEstadoNovedadNomi= mostrarcodigoEstadoNovedadNomi; } public Boolean getActivarcodigoEstadoNovedadNomi() { return this.activarcodigoEstadoNovedadNomi; } public void setActivarcodigoEstadoNovedadNomi(Boolean activarcodigoEstadoNovedadNomi) { this.activarcodigoEstadoNovedadNomi= activarcodigoEstadoNovedadNomi; } public Border setResaltarnombreEstadoNovedadNomi(ParametroGeneralUsuario parametroGeneralUsuario/*EstadoNovedadNomiBeanSwingJInternalFrame estadonovedadnomiBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //estadonovedadnomiBeanSwingJInternalFrame.jTtoolBarEstadoNovedadNomi.setBorder(borderResaltar); this.resaltarnombreEstadoNovedadNomi= borderResaltar; return borderResaltar; } public Border getresaltarnombreEstadoNovedadNomi() { return this.resaltarnombreEstadoNovedadNomi; } public void setResaltarnombreEstadoNovedadNomi(Border borderResaltar) { this.resaltarnombreEstadoNovedadNomi= borderResaltar; } public Boolean getMostrarnombreEstadoNovedadNomi() { return this.mostrarnombreEstadoNovedadNomi; } public void setMostrarnombreEstadoNovedadNomi(Boolean mostrarnombreEstadoNovedadNomi) { this.mostrarnombreEstadoNovedadNomi= mostrarnombreEstadoNovedadNomi; } public Boolean getActivarnombreEstadoNovedadNomi() { return this.activarnombreEstadoNovedadNomi; } public void setActivarnombreEstadoNovedadNomi(Boolean activarnombreEstadoNovedadNomi) { this.activarnombreEstadoNovedadNomi= activarnombreEstadoNovedadNomi; } public void setMostrarCampos(DeepLoadType deepLoadType,ArrayList<Classe> campos)throws Exception { Boolean esInicial=false; Boolean esAsigna=false; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=false; esAsigna=true; } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=true; esAsigna=false; } this.setMostraridEstadoNovedadNomi(esInicial); this.setMostrarcodigoEstadoNovedadNomi(esInicial); this.setMostrarnombreEstadoNovedadNomi(esInicial); for(Classe campo:campos) { if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.ID)) { this.setMostraridEstadoNovedadNomi(esAsigna); continue; } if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.CODIGO)) { this.setMostrarcodigoEstadoNovedadNomi(esAsigna); continue; } if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.NOMBRE)) { this.setMostrarnombreEstadoNovedadNomi(esAsigna); continue; } } } public void setActivarCampos(DeepLoadType deepLoadType,ArrayList<Classe> campos)throws Exception { Boolean esInicial=false; Boolean esAsigna=false; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=false; esAsigna=true; } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=true; esAsigna=false; } this.setActivaridEstadoNovedadNomi(esInicial); this.setActivarcodigoEstadoNovedadNomi(esInicial); this.setActivarnombreEstadoNovedadNomi(esInicial); for(Classe campo:campos) { if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.ID)) { this.setActivaridEstadoNovedadNomi(esAsigna); continue; } if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.CODIGO)) { this.setActivarcodigoEstadoNovedadNomi(esAsigna); continue; } if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.NOMBRE)) { this.setActivarnombreEstadoNovedadNomi(esAsigna); continue; } } } public void setResaltarCampos(DeepLoadType deepLoadType,ArrayList<Classe> campos,ParametroGeneralUsuario parametroGeneralUsuario/*,EstadoNovedadNomiBeanSwingJInternalFrame estadonovedadnomiBeanSwingJInternalFrame*/)throws Exception { Border esInicial=null; Border esAsigna=null; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=null; esAsigna=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); esAsigna=null; } this.setResaltaridEstadoNovedadNomi(esInicial); this.setResaltarcodigoEstadoNovedadNomi(esInicial); this.setResaltarnombreEstadoNovedadNomi(esInicial); for(Classe campo:campos) { if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.ID)) { this.setResaltaridEstadoNovedadNomi(esAsigna); continue; } if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.CODIGO)) { this.setResaltarcodigoEstadoNovedadNomi(esAsigna); continue; } if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.NOMBRE)) { this.setResaltarnombreEstadoNovedadNomi(esAsigna); continue; } } } public Border resaltarNovedadNomiEstadoNovedadNomi=null; public Border getResaltarNovedadNomiEstadoNovedadNomi() { return this.resaltarNovedadNomiEstadoNovedadNomi; } public void setResaltarNovedadNomiEstadoNovedadNomi(Border borderResaltarNovedadNomi) { if(borderResaltarNovedadNomi!=null) { this.resaltarNovedadNomiEstadoNovedadNomi= borderResaltarNovedadNomi; } } public Border setResaltarNovedadNomiEstadoNovedadNomi(ParametroGeneralUsuario parametroGeneralUsuario/*EstadoNovedadNomiBeanSwingJInternalFrame estadonovedadnomiBeanSwingJInternalFrame*/) { Border borderResaltarNovedadNomi=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //estadonovedadnomiBeanSwingJInternalFrame.jTtoolBarEstadoNovedadNomi.setBorder(borderResaltarNovedadNomi); this.resaltarNovedadNomiEstadoNovedadNomi= borderResaltarNovedadNomi; return borderResaltarNovedadNomi; } public Boolean mostrarNovedadNomiEstadoNovedadNomi=true; public Boolean getMostrarNovedadNomiEstadoNovedadNomi() { return this.mostrarNovedadNomiEstadoNovedadNomi; } public void setMostrarNovedadNomiEstadoNovedadNomi(Boolean visibilidadResaltarNovedadNomi) { this.mostrarNovedadNomiEstadoNovedadNomi= visibilidadResaltarNovedadNomi; } public Boolean activarNovedadNomiEstadoNovedadNomi=true; public Boolean gethabilitarResaltarNovedadNomiEstadoNovedadNomi() { return this.activarNovedadNomiEstadoNovedadNomi; } public void setActivarNovedadNomiEstadoNovedadNomi(Boolean habilitarResaltarNovedadNomi) { this.activarNovedadNomiEstadoNovedadNomi= habilitarResaltarNovedadNomi; } public void setMostrarRelaciones(DeepLoadType deepLoadType,ArrayList<Classe> clases)throws Exception { Boolean esInicial=false; Boolean esAsigna=false; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=false; esAsigna=true; } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=true; esAsigna=false; } this.setMostrarNovedadNomiEstadoNovedadNomi(esInicial); for(Classe clase:clases) { if(clase.clas.equals(NovedadNomi.class)) { this.setMostrarNovedadNomiEstadoNovedadNomi(esAsigna); continue; } } } public void setActivarRelaciones(DeepLoadType deepLoadType,ArrayList<Classe> clases)throws Exception { Boolean esInicial=false; Boolean esAsigna=false; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=false; esAsigna=true; } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=true; esAsigna=false; } this.setActivarNovedadNomiEstadoNovedadNomi(esInicial); for(Classe clase:clases) { if(clase.clas.equals(NovedadNomi.class)) { this.setActivarNovedadNomiEstadoNovedadNomi(esAsigna); continue; } } } public void setResaltarRelaciones(DeepLoadType deepLoadType,ArrayList<Classe> clases,ParametroGeneralUsuario parametroGeneralUsuario/*,EstadoNovedadNomiBeanSwingJInternalFrame estadonovedadnomiBeanSwingJInternalFrame*/)throws Exception { Border esInicial=null; Border esAsigna=null; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=null; esAsigna=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); esAsigna=null; } this.setResaltarNovedadNomiEstadoNovedadNomi(esInicial); for(Classe clase:clases) { if(clase.clas.equals(NovedadNomi.class)) { this.setResaltarNovedadNomiEstadoNovedadNomi(esAsigna); continue; } } } //CONTROL_FUNCION2 }
UTF-8
Java
43,924
java
EstadoNovedadNomiConstantesFunciones.java
Java
[ { "context": "/*\r\n*AVISO LEGAL\r\n© Copyright\r\n*Este programa esta protegido por l", "end": 16, "score": 0.5968689322471619, "start": 5, "tag": "NAME", "value": "AVISO LEGAL" }, { "context": "iones2.getBorderResaltar(parametroGeneralUsuario,\"COLUMNA\");\r\n\t\t\tesAsigna=null;\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\tthis.setRes", "end": 39360, "score": 0.9941288828849792, "start": 39353, "tag": "USERNAME", "value": "COLUMNA" } ]
null
[]
/* *<NAME> © Copyright *Este programa esta protegido por la ley de derechos de autor. *La reproduccion o distribucion ilicita de este programa o de cualquiera de *sus partes esta penado por la ley con severas sanciones civiles y penales, *y seran objeto de todas las sanciones legales que correspondan. *Su contenido no puede copiarse para fines comerciales o de otras, *ni puede mostrarse, incluso en una version modificada, en otros sitios Web. Solo esta permitido colocar hipervinculos al sitio web. */ package com.bydan.erp.nomina.util; import org.apache.log4j.Logger; import java.sql.Time; import java.sql.Timestamp; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.util.CellRangeAddress; import javax.swing.border.Border; import java.io.InputStream; import java.util.Scanner; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.Date; //import java.util.ArrayList; import com.bydan.framework.erp.business.entity.GeneralEntity; import com.bydan.framework.erp.business.entity.GeneralEntityReturnGeneral; import com.bydan.framework.erp.business.entity.GeneralEntityParameterGeneral; import com.bydan.framework.erp.business.entity.DatoGeneral; import com.bydan.framework.erp.business.entity.OrderBy; import com.bydan.framework.erp.business.entity.Classe; import com.bydan.framework.erp.business.entity.Reporte; import com.bydan.framework.erp.util.ConstantesJsp; import com.bydan.framework.erp.business.dataaccess.ConstantesSql; import com.bydan.erp.nomina.util.EstadoNovedadNomiConstantesFunciones; import com.bydan.erp.nomina.util.EstadoNovedadNomiParameterReturnGeneral; //import com.bydan.erp.nomina.util.EstadoNovedadNomiParameterGeneral; import com.bydan.framework.erp.business.logic.DatosCliente; import com.bydan.framework.erp.util.*; import com.bydan.erp.nomina.business.entity.*; //import com.bydan.framework.erp.util.*; //import com.bydan.framework.erp.business.logic.*; //import com.bydan.erp.nomina.business.dataaccess.*; //import com.bydan.erp.nomina.business.logic.*; //import java.sql.SQLException; //CONTROL_INCLUDE import com.bydan.erp.seguridad.business.entity.*; @SuppressWarnings("unused") final public class EstadoNovedadNomiConstantesFunciones extends EstadoNovedadNomiConstantesFuncionesAdditional { public static String S_TIPOREPORTE_EXTRA=""; //USADO MAS EN RELACIONADO PARA MANTENIMIENTO MAESTRO-DETALLE public static Integer TAMANIO_ALTO_MAXIMO_TABLADATOS=Constantes.ISWING_TAMANIOMAXIMO_TABLADATOS; public static Integer TAMANIO_ALTO_MINIMO_TABLADATOS=Constantes.ISWING_TAMANIOMINIMO_TABLADATOS; //PARA TABLA RELACIONES(DESCRIPCION HEIGHTPE_REL_TAB) public static Integer ALTO_TABPANE_RELACIONES=Constantes.ISWING_ALTO_TABPANE + Funciones2.getValorProporcion(Constantes.ISWING_ALTO_TABPANE,0); //PARA TABLA RELACIONADO(DESCRIPTION HEIGHTPE_REL) public static Integer TAMANIO_ALTO_MAXIMO_TABLADATOSREL=Constantes.ISWING_TAMANIOMAXIMO_TABLADATOSREL + Funciones2.getValorProporcion(Constantes.ISWING_TAMANIOMAXIMO_TABLADATOSREL,0); public static Integer TAMANIO_ALTO_MINIMO_TABLADATOSREL=Constantes.ISWING_TAMANIOMINIMO_TABLADATOSREL + Funciones2.getValorProporcion(Constantes.ISWING_TAMANIOMINIMO_TABLADATOSREL,0); //PARA CAMBIAR TODO--> SE CAMBIA EN TABLA RELACIONES Y TABLAS RELACIONADOS /* PARA MANEJAR EL TAB RELACIONES CON TABLA DE DATOS SE DEBE MODIFICAR Y VERIFICAR LOS VALORES CONTANTES: final public static Integer ISWING_TAMANIOMAXIMO_TABLADATOSREL=240;//230;350; final public static Integer ISWING_TAMANIOMINIMO_TABLADATOSREL=240;//230;260 final public static Integer ISWING_ALTO_TABPANE=375;//375;400;260; CASO CONTRARIO, ESTOS VALORES SERIAN PARA CADA CASO (NO CONSTANTES) NOTA: * LA ALINEACION HORIZONTAL,FALTA */ public static final String SFINALQUERY=Constantes.SFINALQUERY; public static final String SNOMBREOPCION="EstadoNovedadNomi"; public static final String SPATHOPCION="Nomina"; public static final String SPATHMODULO="nomina/"; public static final String SPERSISTENCECONTEXTNAME=""; public static final String SPERSISTENCENAME="EstadoNovedadNomi"+EstadoNovedadNomiConstantesFunciones.SPERSISTENCECONTEXTNAME+Constantes.SPERSISTENCECONTEXTNAME; public static final String SEJBNAME="EstadoNovedadNomiHomeRemote"; public static final String SEJBNAME_ADDITIONAL="EstadoNovedadNomiHomeRemoteAdditional"; //RMI public static final String SLOCALEJBNAME_RMI=EstadoNovedadNomiConstantesFunciones.SCHEMA+"_"+EstadoNovedadNomiConstantesFunciones.SEJBNAME+"_"+Constantes.SEJBLOCAL;//"erp/EstadoNovedadNomiHomeRemote/local" public static final String SREMOTEEJBNAME_RMI=EstadoNovedadNomiConstantesFunciones.SCHEMA+"_"+EstadoNovedadNomiConstantesFunciones.SEJBNAME+"_"+Constantes.SEJBREMOTE;//remote public static final String SLOCALEJBNAMEADDITIONAL_RMI=EstadoNovedadNomiConstantesFunciones.SCHEMA+"_"+EstadoNovedadNomiConstantesFunciones.SEJBNAME+Constantes.SEJBADDITIONAL+"_"+Constantes.SEJBLOCAL;//"erp/EstadoNovedadNomiHomeRemote/local" public static final String SREMOTEEJBNAMEADDITIONAL_RMI=EstadoNovedadNomiConstantesFunciones.SCHEMA+"_"+EstadoNovedadNomiConstantesFunciones.SEJBNAME+Constantes.SEJBADDITIONAL+"_"+Constantes.SEJBREMOTE;//remote //RMI //JBOSS5.1 public static final String SLOCALEJBNAME=Constantes.SEJBPACKAGE+Constantes.SEJBSEPARATOR+EstadoNovedadNomiConstantesFunciones.SEJBNAME+Constantes.SEJBSEPARATOR+Constantes.SEJBLOCAL;//"erp/EstadoNovedadNomiHomeRemote/local" public static final String SREMOTEEJBNAME=Constantes.SEJBPACKAGE+Constantes.SEJBSEPARATOR+EstadoNovedadNomiConstantesFunciones.SEJBNAME+Constantes.SEJBSEPARATOR+Constantes.SEJBREMOTE;//remote public static final String SLOCALEJBNAMEADDITIONAL=Constantes.SEJBPACKAGE+Constantes.SEJBSEPARATOR+EstadoNovedadNomiConstantesFunciones.SEJBNAME+Constantes.SEJBADDITIONAL+Constantes.SEJBSEPARATOR+Constantes.SEJBLOCAL;//"erp/EstadoNovedadNomiHomeRemote/local" public static final String SREMOTEEJBNAMEADDITIONAL=Constantes.SEJBPACKAGE+Constantes.SEJBSEPARATOR+EstadoNovedadNomiConstantesFunciones.SEJBNAME+Constantes.SEJBADDITIONAL+Constantes.SEJBSEPARATOR+Constantes.SEJBREMOTE;//remote //JBOSS5.1 public static final String SSESSIONNAME=EstadoNovedadNomiConstantesFunciones.OBJECTNAME + Constantes.SSESSIONBEAN; public static final String SSESSIONNAME_FACE=Constantes.SFACE_INI+EstadoNovedadNomiConstantesFunciones.SSESSIONNAME + Constantes.SFACE_FIN; public static final String SREQUESTNAME=EstadoNovedadNomiConstantesFunciones.OBJECTNAME + Constantes.SREQUESTBEAN; public static final String SREQUESTNAME_FACE=Constantes.SFACE_INI+EstadoNovedadNomiConstantesFunciones.SREQUESTNAME + Constantes.SFACE_FIN; public static final String SCLASSNAMETITULOREPORTES="Estado Novedads"; public static final String SRELATIVEPATH="../../../"; public static final String SCLASSPLURAL="s"; public static final String SCLASSWEBTITULO="Estado Novedad"; public static final String SCLASSWEBTITULO_LOWER="Estado Novedad Nomi"; public static Integer INUMEROPAGINACION=10; public static Integer ITAMANIOFILATABLA=Constantes.ISWING_ALTO_FILA; public static Boolean ES_DEBUG=false; public static Boolean CON_DESCRIPCION_DETALLADO=false; public static final String CLASSNAME="EstadoNovedadNomi"; public static final String OBJECTNAME="estadonovedadnomi"; //PARA FORMAR QUERYS public static final String SCHEMA=Constantes.SCHEMA_NOMINA; public static final String TABLENAME="estado_novedad_nomi"; public static final String SQL_SECUENCIAL=SCHEMA+"."+TABLENAME+"_id_seq"; public static String QUERYSELECT="select estadonovedadnomi from "+EstadoNovedadNomiConstantesFunciones.SPERSISTENCENAME+" estadonovedadnomi"; public static String QUERYSELECTNATIVE="select "+EstadoNovedadNomiConstantesFunciones.SCHEMA+"."+EstadoNovedadNomiConstantesFunciones.TABLENAME+".id,"+EstadoNovedadNomiConstantesFunciones.SCHEMA+"."+EstadoNovedadNomiConstantesFunciones.TABLENAME+".version_row,"+EstadoNovedadNomiConstantesFunciones.SCHEMA+"."+EstadoNovedadNomiConstantesFunciones.TABLENAME+".codigo,"+EstadoNovedadNomiConstantesFunciones.SCHEMA+"."+EstadoNovedadNomiConstantesFunciones.TABLENAME+".nombre from "+EstadoNovedadNomiConstantesFunciones.SCHEMA+"."+EstadoNovedadNomiConstantesFunciones.TABLENAME;//+" as "+EstadoNovedadNomiConstantesFunciones.TABLENAME; //AUDITORIA public static Boolean ISCONAUDITORIA=false; public static Boolean ISCONAUDITORIADETALLE=true; //GUARDAR SOLO MAESTRO DETALLE FUNCIONALIDAD public static Boolean ISGUARDARREL=false; protected EstadoNovedadNomiConstantesFuncionesAdditional estadonovedadnomiConstantesFuncionesAdditional=null; public EstadoNovedadNomiConstantesFuncionesAdditional getEstadoNovedadNomiConstantesFuncionesAdditional() { return this.estadonovedadnomiConstantesFuncionesAdditional; } public void setEstadoNovedadNomiConstantesFuncionesAdditional(EstadoNovedadNomiConstantesFuncionesAdditional estadonovedadnomiConstantesFuncionesAdditional) { try { this.estadonovedadnomiConstantesFuncionesAdditional=estadonovedadnomiConstantesFuncionesAdditional; } catch(Exception e) { ; } } public static final String ID=ConstantesSql.ID; public static final String VERSIONROW=ConstantesSql.VERSIONROW; public static final String CODIGO= "codigo"; public static final String NOMBRE= "nombre"; //TITULO CAMPO public static final String LABEL_ID= "Id"; public static final String LABEL_ID_LOWER= "id"; public static final String LABEL_VERSIONROW= "Versionrow"; public static final String LABEL_VERSIONROW_LOWER= "version Row"; public static final String LABEL_CODIGO= "Codigo"; public static final String LABEL_CODIGO_LOWER= "Codigo"; public static final String LABEL_NOMBRE= "Nombre"; public static final String LABEL_NOMBRE_LOWER= "Nombre"; public static final String SREGEXCODIGO=ConstantesValidacion.SREGEXCADENA; public static final String SMENSAJEREGEXCODIGO=ConstantesValidacion.SVALIDACIONCADENA; public static final String SREGEXNOMBRE=ConstantesValidacion.SREGEXCADENA; public static final String SMENSAJEREGEXNOMBRE=ConstantesValidacion.SVALIDACIONCADENA; public static String getEstadoNovedadNomiLabelDesdeNombre(String sNombreColumna) { String sLabelColumna=""; if(sNombreColumna.equals(EstadoNovedadNomiConstantesFunciones.CODIGO)) {sLabelColumna=EstadoNovedadNomiConstantesFunciones.LABEL_CODIGO;} if(sNombreColumna.equals(EstadoNovedadNomiConstantesFunciones.NOMBRE)) {sLabelColumna=EstadoNovedadNomiConstantesFunciones.LABEL_NOMBRE;} if(sLabelColumna.equals("")) { sLabelColumna=sNombreColumna; } return sLabelColumna; } public static String getNombreEjb_JBoss81(String sAplicacion,String sModule,String sClaseEjb,String sInterfaceEjb) throws Exception { String sDescripcion=""; sDescripcion="ejb:"+sAplicacion+"/"+sModule+"/"+sClaseEjb+"!" + sInterfaceEjb; return sDescripcion; } public static String getEstadoNovedadNomiDescripcion(EstadoNovedadNomi estadonovedadnomi) { String sDescripcion=Constantes.SCAMPONONE; if(estadonovedadnomi !=null/* && estadonovedadnomi.getId()!=0*/) { sDescripcion=estadonovedadnomi.getcodigo();//estadonovedadnomiestadonovedadnomi.getcodigo().trim(); } return sDescripcion; } public static String getEstadoNovedadNomiDescripcionDetallado(EstadoNovedadNomi estadonovedadnomi) { String sDescripcion=""; sDescripcion+=EstadoNovedadNomiConstantesFunciones.ID+"="; sDescripcion+=estadonovedadnomi.getId().toString()+","; sDescripcion+=EstadoNovedadNomiConstantesFunciones.VERSIONROW+"="; sDescripcion+=estadonovedadnomi.getVersionRow().toString()+","; sDescripcion+=EstadoNovedadNomiConstantesFunciones.CODIGO+"="; sDescripcion+=estadonovedadnomi.getcodigo()+","; sDescripcion+=EstadoNovedadNomiConstantesFunciones.NOMBRE+"="; sDescripcion+=estadonovedadnomi.getnombre()+","; return sDescripcion; } public static void setEstadoNovedadNomiDescripcion(EstadoNovedadNomi estadonovedadnomi,String sValor) throws Exception { if(estadonovedadnomi !=null) { estadonovedadnomi.setcodigo(sValor);;//estadonovedadnomiestadonovedadnomi.getcodigo().trim(); } } public static String getNombreIndice(String sNombreIndice) { if(sNombreIndice.equals("Todos")) { sNombreIndice="Tipo=Todos"; } else if(sNombreIndice.equals("PorId")) { sNombreIndice="Tipo=Por Id"; } return sNombreIndice; } public static String getDetalleIndicePorId(Long id) { return "Parametros->Porid="+id.toString(); } public static void quitarEspaciosEstadoNovedadNomi(EstadoNovedadNomi estadonovedadnomi,ArrayList<DatoGeneral> arrDatoGeneral) throws Exception { estadonovedadnomi.setcodigo(estadonovedadnomi.getcodigo().trim()); estadonovedadnomi.setnombre(estadonovedadnomi.getnombre().trim()); } public static void quitarEspaciosEstadoNovedadNomis(List<EstadoNovedadNomi> estadonovedadnomis,ArrayList<DatoGeneral> arrDatoGeneral) throws Exception { for(EstadoNovedadNomi estadonovedadnomi: estadonovedadnomis) { estadonovedadnomi.setcodigo(estadonovedadnomi.getcodigo().trim()); estadonovedadnomi.setnombre(estadonovedadnomi.getnombre().trim()); } } public static void InicializarGeneralEntityAuxiliaresEstadoNovedadNomi(EstadoNovedadNomi estadonovedadnomi,Boolean conAsignarBase,Boolean conInicializarAuxiliar) throws Exception { if(conAsignarBase && estadonovedadnomi.getConCambioAuxiliar()) { estadonovedadnomi.setIsDeleted(estadonovedadnomi.getIsDeletedAuxiliar()); estadonovedadnomi.setIsNew(estadonovedadnomi.getIsNewAuxiliar()); estadonovedadnomi.setIsChanged(estadonovedadnomi.getIsChangedAuxiliar()); //YA RESTAURO, NO DEBERIA HACERLO NUEVAMENTE AL MENOS NO HASTA GUARDAR OTRA VEZ estadonovedadnomi.setConCambioAuxiliar(false); } if(conInicializarAuxiliar) { estadonovedadnomi.setIsDeletedAuxiliar(false); estadonovedadnomi.setIsNewAuxiliar(false); estadonovedadnomi.setIsChangedAuxiliar(false); estadonovedadnomi.setConCambioAuxiliar(false); } } public static void InicializarGeneralEntityAuxiliaresEstadoNovedadNomis(List<EstadoNovedadNomi> estadonovedadnomis,Boolean conAsignarBase,Boolean conInicializarAuxiliar) throws Exception { for(EstadoNovedadNomi estadonovedadnomi : estadonovedadnomis) { if(conAsignarBase && estadonovedadnomi.getConCambioAuxiliar()) { estadonovedadnomi.setIsDeleted(estadonovedadnomi.getIsDeletedAuxiliar()); estadonovedadnomi.setIsNew(estadonovedadnomi.getIsNewAuxiliar()); estadonovedadnomi.setIsChanged(estadonovedadnomi.getIsChangedAuxiliar()); //YA RESTAURO, NO DEBERIA HACERLO NUEVAMENTE AL MENOS NO HASTA GUARDAR OTRA VEZ estadonovedadnomi.setConCambioAuxiliar(false); } if(conInicializarAuxiliar) { estadonovedadnomi.setIsDeletedAuxiliar(false); estadonovedadnomi.setIsNewAuxiliar(false); estadonovedadnomi.setIsChangedAuxiliar(false); estadonovedadnomi.setConCambioAuxiliar(false); } } } public static void InicializarValoresEstadoNovedadNomi(EstadoNovedadNomi estadonovedadnomi,Boolean conEnteros) throws Exception { if(conEnteros) { Short ish_value=0; } } public static void InicializarValoresEstadoNovedadNomis(List<EstadoNovedadNomi> estadonovedadnomis,Boolean conEnteros) throws Exception { for(EstadoNovedadNomi estadonovedadnomi: estadonovedadnomis) { if(conEnteros) { Short ish_value=0; } } } public static void TotalizarValoresFilaEstadoNovedadNomi(List<EstadoNovedadNomi> estadonovedadnomis,EstadoNovedadNomi estadonovedadnomiAux) throws Exception { EstadoNovedadNomiConstantesFunciones.InicializarValoresEstadoNovedadNomi(estadonovedadnomiAux,true); for(EstadoNovedadNomi estadonovedadnomi: estadonovedadnomis) { if(estadonovedadnomi.getsType().equals(Constantes2.S_TOTALES)) { continue; } } } public static ArrayList<String> getArrayColumnasGlobalesEstadoNovedadNomi(ArrayList<DatoGeneral> arrDatoGeneral) throws Exception { ArrayList<String> arrColumnasGlobales=new ArrayList<String>(); arrColumnasGlobales=EstadoNovedadNomiConstantesFunciones.getArrayColumnasGlobalesEstadoNovedadNomi(arrDatoGeneral,new ArrayList<String>()); return arrColumnasGlobales; } public static ArrayList<String> getArrayColumnasGlobalesEstadoNovedadNomi(ArrayList<DatoGeneral> arrDatoGeneral,ArrayList<String> arrColumnasGlobalesNo) throws Exception { ArrayList<String> arrColumnasGlobales=new ArrayList<String>(); Boolean noExiste=false; return arrColumnasGlobales; } public static ArrayList<String> getArrayColumnasGlobalesNoEstadoNovedadNomi(ArrayList<DatoGeneral> arrDatoGeneral) throws Exception { ArrayList<String> arrColumnasGlobales=new ArrayList<String>(); return arrColumnasGlobales; } public static Boolean ExisteEnLista(List<EstadoNovedadNomi> estadonovedadnomis,EstadoNovedadNomi estadonovedadnomi,Boolean conIdNulo) throws Exception { Boolean existe=false; for(EstadoNovedadNomi estadonovedadnomiAux: estadonovedadnomis) { if(estadonovedadnomiAux!=null && estadonovedadnomi!=null) { if((estadonovedadnomiAux.getId()==null && estadonovedadnomi.getId()==null) && conIdNulo) { existe=true; break; } else if(estadonovedadnomiAux.getId()!=null && estadonovedadnomi.getId()!=null){ if(estadonovedadnomiAux.getId().equals(estadonovedadnomi.getId())) { existe=true; break; } } } } return existe; } public static ArrayList<DatoGeneral> getTotalesListaEstadoNovedadNomi(List<EstadoNovedadNomi> estadonovedadnomis) throws Exception { ArrayList<DatoGeneral> arrTotalesDatoGeneral=new ArrayList<DatoGeneral>(); DatoGeneral datoGeneral=new DatoGeneral(); for(EstadoNovedadNomi estadonovedadnomi: estadonovedadnomis) { if(estadonovedadnomi.getsType().equals(Constantes2.S_TOTALES)) { continue; } } return arrTotalesDatoGeneral; } public static ArrayList<OrderBy> getOrderByListaEstadoNovedadNomi() throws Exception { ArrayList<OrderBy> arrOrderBy=new ArrayList<OrderBy>(); OrderBy orderBy=new OrderBy(); orderBy=new OrderBy(false,EstadoNovedadNomiConstantesFunciones.LABEL_ID, EstadoNovedadNomiConstantesFunciones.ID,false,""); arrOrderBy.add(orderBy); orderBy=new OrderBy(false,EstadoNovedadNomiConstantesFunciones.LABEL_VERSIONROW, EstadoNovedadNomiConstantesFunciones.VERSIONROW,false,""); arrOrderBy.add(orderBy); orderBy=new OrderBy(false,EstadoNovedadNomiConstantesFunciones.LABEL_CODIGO, EstadoNovedadNomiConstantesFunciones.CODIGO,false,""); arrOrderBy.add(orderBy); orderBy=new OrderBy(false,EstadoNovedadNomiConstantesFunciones.LABEL_NOMBRE, EstadoNovedadNomiConstantesFunciones.NOMBRE,false,""); arrOrderBy.add(orderBy); return arrOrderBy; } public static List<String> getTodosTiposColumnasEstadoNovedadNomi() throws Exception { List<String> arrTiposColumnas=new ArrayList<String>(); String sTipoColumna=new String(); sTipoColumna=new String(); sTipoColumna=EstadoNovedadNomiConstantesFunciones.ID; arrTiposColumnas.add(sTipoColumna); sTipoColumna=new String(); sTipoColumna=EstadoNovedadNomiConstantesFunciones.VERSIONROW; arrTiposColumnas.add(sTipoColumna); sTipoColumna=new String(); sTipoColumna=EstadoNovedadNomiConstantesFunciones.CODIGO; arrTiposColumnas.add(sTipoColumna); sTipoColumna=new String(); sTipoColumna=EstadoNovedadNomiConstantesFunciones.NOMBRE; arrTiposColumnas.add(sTipoColumna); return arrTiposColumnas; } public static ArrayList<Reporte> getTiposSeleccionarEstadoNovedadNomi() throws Exception { return EstadoNovedadNomiConstantesFunciones.getTiposSeleccionarEstadoNovedadNomi(false,true,true,true,true); } public static ArrayList<Reporte> getTiposSeleccionarEstadoNovedadNomi(Boolean conFk) throws Exception { return EstadoNovedadNomiConstantesFunciones.getTiposSeleccionarEstadoNovedadNomi(conFk,true,true,true,true); } public static ArrayList<Reporte> getTiposSeleccionarEstadoNovedadNomi(Boolean conFk,Boolean conStringColumn,Boolean conValorColumn,Boolean conFechaColumn,Boolean conBitColumn) throws Exception { ArrayList<Reporte> arrTiposSeleccionarTodos=new ArrayList<Reporte>(); Reporte reporte=new Reporte(); if(conStringColumn) { reporte=new Reporte(); reporte.setsCodigo(EstadoNovedadNomiConstantesFunciones.LABEL_CODIGO); reporte.setsDescripcion(EstadoNovedadNomiConstantesFunciones.LABEL_CODIGO); arrTiposSeleccionarTodos.add(reporte); } if(conStringColumn) { reporte=new Reporte(); reporte.setsCodigo(EstadoNovedadNomiConstantesFunciones.LABEL_NOMBRE); reporte.setsDescripcion(EstadoNovedadNomiConstantesFunciones.LABEL_NOMBRE); arrTiposSeleccionarTodos.add(reporte); } return arrTiposSeleccionarTodos; } public static ArrayList<Reporte> getTiposRelacionesEstadoNovedadNomi(Boolean conEspecial) throws Exception { ArrayList<Reporte> arrTiposRelacionesTodos=new ArrayList<Reporte>(); Reporte reporte=new Reporte(); //ESTO ESTA EN CONTROLLER return arrTiposRelacionesTodos; } public static void refrescarForeignKeysDescripcionesEstadoNovedadNomi(EstadoNovedadNomi estadonovedadnomiAux) throws Exception { } public static void refrescarForeignKeysDescripcionesEstadoNovedadNomi(List<EstadoNovedadNomi> estadonovedadnomisTemp) throws Exception { for(EstadoNovedadNomi estadonovedadnomiAux:estadonovedadnomisTemp) { } } public static ArrayList<Classe> getClassesForeignKeysOfEstadoNovedadNomi(ArrayList<Classe> classesP,DeepLoadType deepLoadType)throws Exception { try { ArrayList<Classe> classes=new ArrayList<Classe>(); if(deepLoadType.equals(DeepLoadType.NONE)) { } else if(deepLoadType.equals(DeepLoadType.INCLUDE)) { } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { } return classes; } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesForeignKeysFromStringsOfEstadoNovedadNomi(ArrayList<String> arrClasses,DeepLoadType deepLoadType)throws Exception { try { ArrayList<Classe> classes=new ArrayList<Classe>(); if(deepLoadType.equals(DeepLoadType.NONE)) { for(String sClasse:arrClasses) { } } else if(deepLoadType.equals(DeepLoadType.INCLUDE)) { for(String sClasse:arrClasses) { } } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { } return classes; } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesRelationshipsOfEstadoNovedadNomi(ArrayList<Classe> classesP,DeepLoadType deepLoadType)throws Exception { try { return EstadoNovedadNomiConstantesFunciones.getClassesRelationshipsOfEstadoNovedadNomi(classesP,deepLoadType,true); } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesRelationshipsOfEstadoNovedadNomi(ArrayList<Classe> classesP,DeepLoadType deepLoadType,Boolean conMuchosAMuchos)throws Exception { try { ArrayList<Classe> classes=new ArrayList<Classe>(); if(deepLoadType.equals(DeepLoadType.NONE)) { classes.add(new Classe(NovedadNomi.class)); } else if(deepLoadType.equals(DeepLoadType.INCLUDE)) { for(Classe clas:classesP) { if(clas.clas.equals(NovedadNomi.class)) { classes.add(new Classe(NovedadNomi.class)); break; } } } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { } return classes; } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesRelationshipsFromStringsOfEstadoNovedadNomi(ArrayList<String> arrClasses,DeepLoadType deepLoadType)throws Exception { try { return EstadoNovedadNomiConstantesFunciones.getClassesRelationshipsFromStringsOfEstadoNovedadNomi(arrClasses,deepLoadType,true); } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesRelationshipsFromStringsOfEstadoNovedadNomi(ArrayList<String> arrClasses,DeepLoadType deepLoadType,Boolean conMuchosAMuchos)throws Exception { try { ArrayList<Classe> classes=new ArrayList<Classe>(); if(deepLoadType.equals(DeepLoadType.NONE)) { for(String sClasse:arrClasses) { if(NovedadNomi.class.getSimpleName().equals(sClasse)) { classes.add(new Classe(NovedadNomi.class)); continue; } } } else if(deepLoadType.equals(DeepLoadType.INCLUDE)) { for(String sClasse:arrClasses) { if(NovedadNomi.class.getSimpleName().equals(sClasse)) { classes.add(new Classe(NovedadNomi.class)); continue; } } } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { } return classes; } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } //FUNCIONES CONTROLLER public static void actualizarLista(EstadoNovedadNomi estadonovedadnomi,List<EstadoNovedadNomi> estadonovedadnomis,Boolean permiteQuitar) throws Exception { try { Boolean existe=false; EstadoNovedadNomi estadonovedadnomiEncontrado=null; for(EstadoNovedadNomi estadonovedadnomiLocal:estadonovedadnomis) { if(estadonovedadnomiLocal.getId().equals(estadonovedadnomi.getId())) { estadonovedadnomiEncontrado=estadonovedadnomiLocal; estadonovedadnomiLocal.setIsChanged(estadonovedadnomi.getIsChanged()); estadonovedadnomiLocal.setIsNew(estadonovedadnomi.getIsNew()); estadonovedadnomiLocal.setIsDeleted(estadonovedadnomi.getIsDeleted()); estadonovedadnomiLocal.setGeneralEntityOriginal(estadonovedadnomi.getGeneralEntityOriginal()); estadonovedadnomiLocal.setId(estadonovedadnomi.getId()); estadonovedadnomiLocal.setVersionRow(estadonovedadnomi.getVersionRow()); estadonovedadnomiLocal.setcodigo(estadonovedadnomi.getcodigo()); estadonovedadnomiLocal.setnombre(estadonovedadnomi.getnombre()); estadonovedadnomiLocal.setNovedadNomis(estadonovedadnomi.getNovedadNomis()); existe=true; break; } } if(!estadonovedadnomi.getIsDeleted()) { if(!existe) { estadonovedadnomis.add(estadonovedadnomi); } } else { if(estadonovedadnomiEncontrado!=null && permiteQuitar) { estadonovedadnomis.remove(estadonovedadnomiEncontrado); } } } catch(Exception e) { throw e; } } public static void actualizarSelectedLista(EstadoNovedadNomi estadonovedadnomi,List<EstadoNovedadNomi> estadonovedadnomis) throws Exception { try { for(EstadoNovedadNomi estadonovedadnomiLocal:estadonovedadnomis) { if(estadonovedadnomiLocal.getId().equals(estadonovedadnomi.getId())) { estadonovedadnomiLocal.setIsSelected(estadonovedadnomi.getIsSelected()); break; } } } catch(Exception e) { throw e; } } public static void setEstadosInicialesEstadoNovedadNomi(List<EstadoNovedadNomi> estadonovedadnomisAux) throws Exception { //this.estadonovedadnomisAux=estadonovedadnomisAux; for(EstadoNovedadNomi estadonovedadnomiAux:estadonovedadnomisAux) { if(estadonovedadnomiAux.getIsChanged()) { estadonovedadnomiAux.setIsChanged(false); } if(estadonovedadnomiAux.getIsNew()) { estadonovedadnomiAux.setIsNew(false); } if(estadonovedadnomiAux.getIsDeleted()) { estadonovedadnomiAux.setIsDeleted(false); } } } public static void setEstadosInicialesEstadoNovedadNomi(EstadoNovedadNomi estadonovedadnomiAux) throws Exception { //this.estadonovedadnomiAux=estadonovedadnomiAux; if(estadonovedadnomiAux.getIsChanged()) { estadonovedadnomiAux.setIsChanged(false); } if(estadonovedadnomiAux.getIsNew()) { estadonovedadnomiAux.setIsNew(false); } if(estadonovedadnomiAux.getIsDeleted()) { estadonovedadnomiAux.setIsDeleted(false); } } public static void seleccionarAsignar(EstadoNovedadNomi estadonovedadnomiAsignar,EstadoNovedadNomi estadonovedadnomi) throws Exception { estadonovedadnomiAsignar.setId(estadonovedadnomi.getId()); estadonovedadnomiAsignar.setVersionRow(estadonovedadnomi.getVersionRow()); estadonovedadnomiAsignar.setcodigo(estadonovedadnomi.getcodigo()); estadonovedadnomiAsignar.setnombre(estadonovedadnomi.getnombre()); } public static void inicializarEstadoNovedadNomi(EstadoNovedadNomi estadonovedadnomi) throws Exception { try { estadonovedadnomi.setId(0L); estadonovedadnomi.setcodigo(""); estadonovedadnomi.setnombre(""); } catch(Exception e) { throw e; } } public static void generarExcelReporteHeaderEstadoNovedadNomi(String sTipo,Row row,Workbook workbook) { Cell cell=null; int iCell=0; CellStyle cellStyle = Funciones2.getStyleTitulo(workbook,"PRINCIPAL"); if(sTipo.equals("RELACIONADO")) { iCell++; } cell = row.createCell(iCell++); cell.setCellValue(EstadoNovedadNomiConstantesFunciones.LABEL_CODIGO); cell.setCellStyle(cellStyle); cell = row.createCell(iCell++); cell.setCellValue(EstadoNovedadNomiConstantesFunciones.LABEL_NOMBRE); cell.setCellStyle(cellStyle); } public static void generarExcelReporteDataEstadoNovedadNomi(String sTipo,Row row,Workbook workbook,EstadoNovedadNomi estadonovedadnomi,CellStyle cellStyle) throws Exception { Cell cell=null; int iCell=0; if(sTipo.equals("RELACIONADO")) { iCell++; } cell = row.createCell(iCell++); cell.setCellValue(estadonovedadnomi.getcodigo()); if(cellStyle!=null) { cell.setCellStyle(cellStyle); } cell = row.createCell(iCell++); cell.setCellValue(estadonovedadnomi.getnombre()); if(cellStyle!=null) { cell.setCellStyle(cellStyle); } } //FUNCIONES CONTROLLER public String sFinalQueryEstadoNovedadNomi=Constantes.SFINALQUERY; public String getsFinalQueryEstadoNovedadNomi() { return this.sFinalQueryEstadoNovedadNomi; } public void setsFinalQueryEstadoNovedadNomi(String sFinalQueryEstadoNovedadNomi) { this.sFinalQueryEstadoNovedadNomi= sFinalQueryEstadoNovedadNomi; } public Border resaltarSeleccionarEstadoNovedadNomi=null; public Border setResaltarSeleccionarEstadoNovedadNomi(ParametroGeneralUsuario parametroGeneralUsuario/*EstadoNovedadNomiBeanSwingJInternalFrame estadonovedadnomiBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //estadonovedadnomiBeanSwingJInternalFrame.jTtoolBarEstadoNovedadNomi.setBorder(borderResaltar); this.resaltarSeleccionarEstadoNovedadNomi= borderResaltar; return borderResaltar; } public Border getResaltarSeleccionarEstadoNovedadNomi() { return this.resaltarSeleccionarEstadoNovedadNomi; } public void setResaltarSeleccionarEstadoNovedadNomi(Border borderResaltarSeleccionarEstadoNovedadNomi) { this.resaltarSeleccionarEstadoNovedadNomi= borderResaltarSeleccionarEstadoNovedadNomi; } //RESALTAR,VISIBILIDAD,HABILITAR COLUMNA public Border resaltaridEstadoNovedadNomi=null; public Boolean mostraridEstadoNovedadNomi=true; public Boolean activaridEstadoNovedadNomi=true; public Border resaltarcodigoEstadoNovedadNomi=null; public Boolean mostrarcodigoEstadoNovedadNomi=true; public Boolean activarcodigoEstadoNovedadNomi=true; public Border resaltarnombreEstadoNovedadNomi=null; public Boolean mostrarnombreEstadoNovedadNomi=true; public Boolean activarnombreEstadoNovedadNomi=true; public Border setResaltaridEstadoNovedadNomi(ParametroGeneralUsuario parametroGeneralUsuario/*EstadoNovedadNomiBeanSwingJInternalFrame estadonovedadnomiBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //estadonovedadnomiBeanSwingJInternalFrame.jTtoolBarEstadoNovedadNomi.setBorder(borderResaltar); this.resaltaridEstadoNovedadNomi= borderResaltar; return borderResaltar; } public Border getresaltaridEstadoNovedadNomi() { return this.resaltaridEstadoNovedadNomi; } public void setResaltaridEstadoNovedadNomi(Border borderResaltar) { this.resaltaridEstadoNovedadNomi= borderResaltar; } public Boolean getMostraridEstadoNovedadNomi() { return this.mostraridEstadoNovedadNomi; } public void setMostraridEstadoNovedadNomi(Boolean mostraridEstadoNovedadNomi) { this.mostraridEstadoNovedadNomi= mostraridEstadoNovedadNomi; } public Boolean getActivaridEstadoNovedadNomi() { return this.activaridEstadoNovedadNomi; } public void setActivaridEstadoNovedadNomi(Boolean activaridEstadoNovedadNomi) { this.activaridEstadoNovedadNomi= activaridEstadoNovedadNomi; } public Border setResaltarcodigoEstadoNovedadNomi(ParametroGeneralUsuario parametroGeneralUsuario/*EstadoNovedadNomiBeanSwingJInternalFrame estadonovedadnomiBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //estadonovedadnomiBeanSwingJInternalFrame.jTtoolBarEstadoNovedadNomi.setBorder(borderResaltar); this.resaltarcodigoEstadoNovedadNomi= borderResaltar; return borderResaltar; } public Border getresaltarcodigoEstadoNovedadNomi() { return this.resaltarcodigoEstadoNovedadNomi; } public void setResaltarcodigoEstadoNovedadNomi(Border borderResaltar) { this.resaltarcodigoEstadoNovedadNomi= borderResaltar; } public Boolean getMostrarcodigoEstadoNovedadNomi() { return this.mostrarcodigoEstadoNovedadNomi; } public void setMostrarcodigoEstadoNovedadNomi(Boolean mostrarcodigoEstadoNovedadNomi) { this.mostrarcodigoEstadoNovedadNomi= mostrarcodigoEstadoNovedadNomi; } public Boolean getActivarcodigoEstadoNovedadNomi() { return this.activarcodigoEstadoNovedadNomi; } public void setActivarcodigoEstadoNovedadNomi(Boolean activarcodigoEstadoNovedadNomi) { this.activarcodigoEstadoNovedadNomi= activarcodigoEstadoNovedadNomi; } public Border setResaltarnombreEstadoNovedadNomi(ParametroGeneralUsuario parametroGeneralUsuario/*EstadoNovedadNomiBeanSwingJInternalFrame estadonovedadnomiBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //estadonovedadnomiBeanSwingJInternalFrame.jTtoolBarEstadoNovedadNomi.setBorder(borderResaltar); this.resaltarnombreEstadoNovedadNomi= borderResaltar; return borderResaltar; } public Border getresaltarnombreEstadoNovedadNomi() { return this.resaltarnombreEstadoNovedadNomi; } public void setResaltarnombreEstadoNovedadNomi(Border borderResaltar) { this.resaltarnombreEstadoNovedadNomi= borderResaltar; } public Boolean getMostrarnombreEstadoNovedadNomi() { return this.mostrarnombreEstadoNovedadNomi; } public void setMostrarnombreEstadoNovedadNomi(Boolean mostrarnombreEstadoNovedadNomi) { this.mostrarnombreEstadoNovedadNomi= mostrarnombreEstadoNovedadNomi; } public Boolean getActivarnombreEstadoNovedadNomi() { return this.activarnombreEstadoNovedadNomi; } public void setActivarnombreEstadoNovedadNomi(Boolean activarnombreEstadoNovedadNomi) { this.activarnombreEstadoNovedadNomi= activarnombreEstadoNovedadNomi; } public void setMostrarCampos(DeepLoadType deepLoadType,ArrayList<Classe> campos)throws Exception { Boolean esInicial=false; Boolean esAsigna=false; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=false; esAsigna=true; } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=true; esAsigna=false; } this.setMostraridEstadoNovedadNomi(esInicial); this.setMostrarcodigoEstadoNovedadNomi(esInicial); this.setMostrarnombreEstadoNovedadNomi(esInicial); for(Classe campo:campos) { if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.ID)) { this.setMostraridEstadoNovedadNomi(esAsigna); continue; } if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.CODIGO)) { this.setMostrarcodigoEstadoNovedadNomi(esAsigna); continue; } if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.NOMBRE)) { this.setMostrarnombreEstadoNovedadNomi(esAsigna); continue; } } } public void setActivarCampos(DeepLoadType deepLoadType,ArrayList<Classe> campos)throws Exception { Boolean esInicial=false; Boolean esAsigna=false; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=false; esAsigna=true; } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=true; esAsigna=false; } this.setActivaridEstadoNovedadNomi(esInicial); this.setActivarcodigoEstadoNovedadNomi(esInicial); this.setActivarnombreEstadoNovedadNomi(esInicial); for(Classe campo:campos) { if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.ID)) { this.setActivaridEstadoNovedadNomi(esAsigna); continue; } if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.CODIGO)) { this.setActivarcodigoEstadoNovedadNomi(esAsigna); continue; } if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.NOMBRE)) { this.setActivarnombreEstadoNovedadNomi(esAsigna); continue; } } } public void setResaltarCampos(DeepLoadType deepLoadType,ArrayList<Classe> campos,ParametroGeneralUsuario parametroGeneralUsuario/*,EstadoNovedadNomiBeanSwingJInternalFrame estadonovedadnomiBeanSwingJInternalFrame*/)throws Exception { Border esInicial=null; Border esAsigna=null; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=null; esAsigna=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); esAsigna=null; } this.setResaltaridEstadoNovedadNomi(esInicial); this.setResaltarcodigoEstadoNovedadNomi(esInicial); this.setResaltarnombreEstadoNovedadNomi(esInicial); for(Classe campo:campos) { if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.ID)) { this.setResaltaridEstadoNovedadNomi(esAsigna); continue; } if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.CODIGO)) { this.setResaltarcodigoEstadoNovedadNomi(esAsigna); continue; } if(campo.clase.equals(EstadoNovedadNomiConstantesFunciones.NOMBRE)) { this.setResaltarnombreEstadoNovedadNomi(esAsigna); continue; } } } public Border resaltarNovedadNomiEstadoNovedadNomi=null; public Border getResaltarNovedadNomiEstadoNovedadNomi() { return this.resaltarNovedadNomiEstadoNovedadNomi; } public void setResaltarNovedadNomiEstadoNovedadNomi(Border borderResaltarNovedadNomi) { if(borderResaltarNovedadNomi!=null) { this.resaltarNovedadNomiEstadoNovedadNomi= borderResaltarNovedadNomi; } } public Border setResaltarNovedadNomiEstadoNovedadNomi(ParametroGeneralUsuario parametroGeneralUsuario/*EstadoNovedadNomiBeanSwingJInternalFrame estadonovedadnomiBeanSwingJInternalFrame*/) { Border borderResaltarNovedadNomi=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //estadonovedadnomiBeanSwingJInternalFrame.jTtoolBarEstadoNovedadNomi.setBorder(borderResaltarNovedadNomi); this.resaltarNovedadNomiEstadoNovedadNomi= borderResaltarNovedadNomi; return borderResaltarNovedadNomi; } public Boolean mostrarNovedadNomiEstadoNovedadNomi=true; public Boolean getMostrarNovedadNomiEstadoNovedadNomi() { return this.mostrarNovedadNomiEstadoNovedadNomi; } public void setMostrarNovedadNomiEstadoNovedadNomi(Boolean visibilidadResaltarNovedadNomi) { this.mostrarNovedadNomiEstadoNovedadNomi= visibilidadResaltarNovedadNomi; } public Boolean activarNovedadNomiEstadoNovedadNomi=true; public Boolean gethabilitarResaltarNovedadNomiEstadoNovedadNomi() { return this.activarNovedadNomiEstadoNovedadNomi; } public void setActivarNovedadNomiEstadoNovedadNomi(Boolean habilitarResaltarNovedadNomi) { this.activarNovedadNomiEstadoNovedadNomi= habilitarResaltarNovedadNomi; } public void setMostrarRelaciones(DeepLoadType deepLoadType,ArrayList<Classe> clases)throws Exception { Boolean esInicial=false; Boolean esAsigna=false; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=false; esAsigna=true; } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=true; esAsigna=false; } this.setMostrarNovedadNomiEstadoNovedadNomi(esInicial); for(Classe clase:clases) { if(clase.clas.equals(NovedadNomi.class)) { this.setMostrarNovedadNomiEstadoNovedadNomi(esAsigna); continue; } } } public void setActivarRelaciones(DeepLoadType deepLoadType,ArrayList<Classe> clases)throws Exception { Boolean esInicial=false; Boolean esAsigna=false; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=false; esAsigna=true; } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=true; esAsigna=false; } this.setActivarNovedadNomiEstadoNovedadNomi(esInicial); for(Classe clase:clases) { if(clase.clas.equals(NovedadNomi.class)) { this.setActivarNovedadNomiEstadoNovedadNomi(esAsigna); continue; } } } public void setResaltarRelaciones(DeepLoadType deepLoadType,ArrayList<Classe> clases,ParametroGeneralUsuario parametroGeneralUsuario/*,EstadoNovedadNomiBeanSwingJInternalFrame estadonovedadnomiBeanSwingJInternalFrame*/)throws Exception { Border esInicial=null; Border esAsigna=null; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=null; esAsigna=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); esAsigna=null; } this.setResaltarNovedadNomiEstadoNovedadNomi(esInicial); for(Classe clase:clases) { if(clase.clas.equals(NovedadNomi.class)) { this.setResaltarNovedadNomiEstadoNovedadNomi(esAsigna); continue; } } } //CONTROL_FUNCION2 }
43,919
0.777543
0.776085
1,203
34.512886
45.830841
632
false
false
0
0
0
0
93
0.002117
2.411471
false
false
9
34b799c3a321865f4275047a89b7a85644b8c329
33,457,795,265,451
9019dadbcb6dbc57272182e9f0d04cb4793ecbc9
/robobinding/src/main/java/org/robobinding/viewattribute/compoundbutton/CheckedAttribute.java
bccd23bf17a1aba8ee0e20a42c19418870b85316
[ "Apache-2.0" ]
permissive
romanlum/RoboBinding
https://github.com/romanlum/RoboBinding
fdbb855581195a8f5694f6fc4d8c76f914e111d9
570274320d0119db09c8e3d1224b6bfa3aff7139
refs/heads/master
2021-01-12T21:53:30.678000
2013-09-25T10:19:54
2013-09-25T10:19:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright 2011 Cheng Wei, Robert Taylor * * 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.robobinding.viewattribute.compoundbutton; import org.robobinding.property.ValueModel; import org.robobinding.viewattribute.AbstractPropertyViewAttribute; import org.robobinding.viewattribute.view.ViewListenersAware; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; /** * * @since 1.0 * @version $Revision: 1.0 $ * @author Robert Taylor */ public class CheckedAttribute extends AbstractPropertyViewAttribute<CompoundButton, Boolean> implements ViewListenersAware<CompoundButtonListeners> { private CompoundButtonListeners viewListeners; @Override public void setViewListeners(CompoundButtonListeners viewListeners) { this.viewListeners = viewListeners; } @Override protected void valueModelUpdated(Boolean newValue) { view.setChecked(newValue); } @Override protected void observeChangesOnTheView(final ValueModel<Boolean> valueModel) { viewListeners.addOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { valueModel.setValue(isChecked); } }); } }
UTF-8
Java
1,780
java
CheckedAttribute.java
Java
[ { "context": "/**\n * Copyright 2011 Cheng Wei, Robert Taylor\n *\n * Licensed under the Apache Li", "end": 31, "score": 0.9997751712799072, "start": 22, "tag": "NAME", "value": "Cheng Wei" }, { "context": "/**\n * Copyright 2011 Cheng Wei, Robert Taylor\n *\n * Licensed under the Apache License, Version ", "end": 46, "score": 0.999793529510498, "start": 33, "tag": "NAME", "value": "Robert Taylor" }, { "context": "@since 1.0\n * @version $Revision: 1.0 $\n * @author Robert Taylor\n */\npublic class CheckedAttribute extends Abstrac", "end": 1013, "score": 0.9997372627258301, "start": 1000, "tag": "NAME", "value": "Robert Taylor" } ]
null
[]
/** * Copyright 2011 <NAME>, <NAME> * * 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.robobinding.viewattribute.compoundbutton; import org.robobinding.property.ValueModel; import org.robobinding.viewattribute.AbstractPropertyViewAttribute; import org.robobinding.viewattribute.view.ViewListenersAware; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; /** * * @since 1.0 * @version $Revision: 1.0 $ * @author <NAME> */ public class CheckedAttribute extends AbstractPropertyViewAttribute<CompoundButton, Boolean> implements ViewListenersAware<CompoundButtonListeners> { private CompoundButtonListeners viewListeners; @Override public void setViewListeners(CompoundButtonListeners viewListeners) { this.viewListeners = viewListeners; } @Override protected void valueModelUpdated(Boolean newValue) { view.setChecked(newValue); } @Override protected void observeChangesOnTheView(final ValueModel<Boolean> valueModel) { viewListeners.addOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { valueModel.setValue(isChecked); } }); } }
1,763
0.774157
0.767416
53
32.584908
32.052689
149
false
false
0
0
0
0
0
0
0.528302
false
false
9
c88fc1c94be0ff3fffcb18c2f11b1b2495a872d1
13,030,930,808,198
4298e09fd23f5be906ad5931954c19fe12b5105d
/trap/dep/Enemy.java
9b977692523f79e58d5e417d5df6e22a74a75a38
[]
no_license
jcao14/a2fp_JASCAM
https://github.com/jcao14/a2fp_JASCAM
18baa6ca58025e707b2fbe4cf6a69ad47c79207c
44fc5ba5af7f2c268feb7f426882f083ec5e1347
refs/heads/master
2021-01-21T14:48:04.320000
2016-06-13T11:09:09
2016-06-13T11:09:09
59,441,969
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.LinkedList; public interface Enemy extends Character { public void getNextPatrol(); public boolean nearbyPlayer(); public void invokeAI(); public void setDirectionTo(Tile t); //public TilePath getPath(); public LinkedList<Enemy> getGroup(); }
UTF-8
Java
284
java
Enemy.java
Java
[]
null
[]
import java.util.LinkedList; public interface Enemy extends Character { public void getNextPatrol(); public boolean nearbyPlayer(); public void invokeAI(); public void setDirectionTo(Tile t); //public TilePath getPath(); public LinkedList<Enemy> getGroup(); }
284
0.721831
0.721831
10
27.4
13.901079
40
false
false
0
0
0
0
0
0
0.7
false
false
9
01e4fb50eb79ef78e4f6dbf1956ebcb1ed986bd5
3,178,275,836,759
8d168c16551fe7c78606a2e097c0afe81536a938
/src/main/java/com/artisb/twitest/controller/ExceptionController.java
8c48fbb3ea48d9ed2b273384c6a8f96165a87756
[]
no_license
artisb/twitest
https://github.com/artisb/twitest
936e568a4b48bba428ccd161eba8a655b9437f42
dca8de14cde1b780b8cb7d9307b1a80a9ab92025
refs/heads/master
2020-04-21T18:33:27.888000
2019-02-15T07:03:09
2019-02-15T07:03:09
169,774,104
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.artisb.twitest.controller; import com.artisb.twitest.exception.ForbiddenException; import com.artisb.twitest.exception.ResourceNotFoundExcepton; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @ControllerAdvice @RestController public class ExceptionController extends ResponseEntityExceptionHandler { @ExceptionHandler(ForbiddenException.class) @ResponseStatus(HttpStatus.FORBIDDEN) public String handleForbiddenException(Exception e) { return e.getMessage(); } @ExceptionHandler(ResourceNotFoundExcepton.class) @ResponseStatus(HttpStatus.NOT_FOUND) public String handleResourceNotFoundException(Exception e) { return e.getMessage(); } }
UTF-8
Java
1,046
java
ExceptionController.java
Java
[]
null
[]
package com.artisb.twitest.controller; import com.artisb.twitest.exception.ForbiddenException; import com.artisb.twitest.exception.ResourceNotFoundExcepton; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @ControllerAdvice @RestController public class ExceptionController extends ResponseEntityExceptionHandler { @ExceptionHandler(ForbiddenException.class) @ResponseStatus(HttpStatus.FORBIDDEN) public String handleForbiddenException(Exception e) { return e.getMessage(); } @ExceptionHandler(ResourceNotFoundExcepton.class) @ResponseStatus(HttpStatus.NOT_FOUND) public String handleResourceNotFoundException(Exception e) { return e.getMessage(); } }
1,046
0.823136
0.823136
26
39.23077
26.155317
92
false
false
0
0
0
0
0
0
0.423077
false
false
9
a3269fface53e4a32d0ad7e88cd1d279ff260f33
2,370,821,978,947
1a871e191fae3e18028d70aa6c199822c5e378ad
/app/src/main/java/com/wangou/robot/constant/HttpUrl.java
71967cb9ff927f1b62088262f78dd7be16ef08e3
[]
no_license
wangou/Robot
https://github.com/wangou/Robot
34358b8b9930fcc3d7ee82359f731ac1448c5727
437fda8e394c9df40ff4f2e7d862b16df7019f69
refs/heads/master
2021-01-20T19:33:30.906000
2016-08-09T10:44:50
2016-08-09T10:44:50
64,656,411
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wangou.robot.constant; /** * Created by Administrator on 2016/8/3. */ public class HttpUrl { public static final String API_KEY = "26c4dfb4be69435c8d254beed6efe4c5"; public static final String API_URL = "http://www.tuling123.com/openapi/api"; public static final String API_SECRET = "213705225fcad5d2"; }
UTF-8
Java
333
java
HttpUrl.java
Java
[ { "context": "pUrl {\n\n public static final String API_KEY = \"26c4dfb4be69435c8d254beed6efe4c5\";\n public static final String API_URL = \"http:", "end": 183, "score": 0.9995613694190979, "start": 151, "tag": "KEY", "value": "26c4dfb4be69435c8d254beed6efe4c5" }, { "context": "pi\";\n public static final String API_SECRET = \"213705225fcad5d2\";\n}\n", "end": 328, "score": 0.9994133114814758, "start": 312, "tag": "KEY", "value": "213705225fcad5d2" } ]
null
[]
package com.wangou.robot.constant; /** * Created by Administrator on 2016/8/3. */ public class HttpUrl { public static final String API_KEY = "26c4dfb4be69435c8d254beed6efe4c5"; public static final String API_URL = "http://www.tuling123.com/openapi/api"; public static final String API_SECRET = "213705225fcad5d2"; }
333
0.732733
0.624625
11
29.272728
30.118225
80
false
false
0
0
0
0
0
0
0.363636
false
false
9
8b0580f6f991925ec7b1e6638ec36425558b7e0f
24,927,990,216,718
e1260170daa6b30a85350fae614fff325c3463c7
/src/main/java/com/voltbus/network/Request.java
aa020a2b24f9fdf09d0c07e52b5d2d93a6d56155
[ "MIT" ]
permissive
jrachiele/VoltBus
https://github.com/jrachiele/VoltBus
6bfad8be9ee78edd3a7846187767c2c84686df2d
2ca36e5179795fa1044a4f15453995badd277357
refs/heads/master
2021-01-17T13:15:49.086000
2017-02-20T09:04:17
2017-02-20T09:04:17
44,029,768
0
0
null
false
2015-10-10T21:56:46
2015-10-10T21:52:36
2015-10-10T21:52:36
2015-10-10T21:56:46
0
0
0
0
null
null
null
package com.voltbus.network; /** * Created by jacob on 2/15/16. */ public interface Request<T> { Response<T> request(); }
UTF-8
Java
130
java
Request.java
Java
[ { "context": "package com.voltbus.network;\n\n/**\n * Created by jacob on 2/15/16.\n */\npublic interface Request<T> {\n\n ", "end": 53, "score": 0.9981541633605957, "start": 48, "tag": "USERNAME", "value": "jacob" } ]
null
[]
package com.voltbus.network; /** * Created by jacob on 2/15/16. */ public interface Request<T> { Response<T> request(); }
130
0.646154
0.607692
9
13.444445
13.557377
31
false
false
0
0
0
0
0
0
0.222222
false
false
9
8abb7c7801b48fcc000d97f5022f338b320c50f6
23,871,428,271,534
ddf6048b7b80d0abf7f50ebccae726bfa99988ed
/Uebungen/src/uebung6/QuerSumme.java
b092b930bc58d743aa21f605d9ab88b2aec50503
[]
no_license
coderbyheart/hsrm-mi-prog1
https://github.com/coderbyheart/hsrm-mi-prog1
6e4dce01fd50fda5a6c47aa433a686c67e8a664e
57fcf17c555640ec0aeea0a003c8b597d3911c09
refs/heads/master
2021-01-01T06:39:04.522000
2011-11-02T13:52:21
2011-11-02T13:52:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uebung6; import berdux.In; public class QuerSumme { public static void main (String args[]) { System.out.println("Bitte geben Sie eine Zahl ein:"); String zahl = In.readString(); long sum = 0; for(int i = 0; i < zahl.length(); i++) { sum += Long.parseLong(zahl.substring(i, i + 1)); } System.out.println("Ziffernsumme: " + sum); } }
UTF-8
Java
365
java
QuerSumme.java
Java
[]
null
[]
package uebung6; import berdux.In; public class QuerSumme { public static void main (String args[]) { System.out.println("Bitte geben Sie eine Zahl ein:"); String zahl = In.readString(); long sum = 0; for(int i = 0; i < zahl.length(); i++) { sum += Long.parseLong(zahl.substring(i, i + 1)); } System.out.println("Ziffernsumme: " + sum); } }
365
0.632877
0.621918
18
19.333334
19.264244
55
false
false
0
0
0
0
0
0
1.722222
false
false
9
a6010484e718e105d1dd85abf2a5408ebdaeee42
10,110,353,055,351
352aae0466253724aff631aea6566839c4336320
/modules/lang-painless/src/main/java/org/elasticsearch/painless/node/PSubNullSafeField.java
3c6606642617b79df786a79ecc11cdded6d47c62
[ "Apache-2.0" ]
permissive
beihuxiansheng/elasticsearch-token
https://github.com/beihuxiansheng/elasticsearch-token
94abe11e64cd0a09252194f1d3796049379820b2
a5d6ea630b053385d7b86feeb31058a3f7865b0d
refs/heads/master
2020-03-29T15:28:33.208000
2017-06-19T07:19:45
2017-06-19T07:19:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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. */ end_comment begin_package DECL|package|org.elasticsearch.painless.node package|package name|org operator|. name|elasticsearch operator|. name|painless operator|. name|node package|; end_package begin_import import|import name|org operator|. name|elasticsearch operator|. name|painless operator|. name|Definition operator|. name|Type import|; end_import begin_import import|import name|org operator|. name|elasticsearch operator|. name|painless operator|. name|Globals import|; end_import begin_import import|import name|org operator|. name|elasticsearch operator|. name|painless operator|. name|Locals import|; end_import begin_import import|import name|org operator|. name|elasticsearch operator|. name|painless operator|. name|Location import|; end_import begin_import import|import name|org operator|. name|elasticsearch operator|. name|painless operator|. name|MethodWriter import|; end_import begin_import import|import name|org operator|. name|objectweb operator|. name|asm operator|. name|Label import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Set import|; end_import begin_comment comment|/** * Implements a field who's value is null if the prefix is null rather than throwing an NPE. */ end_comment begin_class DECL|class|PSubNullSafeField specifier|public class|class name|PSubNullSafeField extends|extends name|AStoreable block|{ DECL|field|guarded specifier|private name|AStoreable name|guarded decl_stmt|; DECL|method|PSubNullSafeField specifier|public name|PSubNullSafeField parameter_list|( name|Location name|location parameter_list|, name|AStoreable name|guarded parameter_list|) block|{ name|super argument_list|( name|location argument_list|) expr_stmt|; name|this operator|. name|guarded operator|= name|guarded expr_stmt|; block|} annotation|@ name|Override DECL|method|extractVariables name|void name|extractVariables parameter_list|( name|Set argument_list|< name|String argument_list|> name|variables parameter_list|) block|{ name|guarded operator|. name|extractVariables argument_list|( name|variables argument_list|) expr_stmt|; block|} annotation|@ name|Override DECL|method|analyze name|void name|analyze parameter_list|( name|Locals name|locals parameter_list|) block|{ if|if condition|( name|write condition|) block|{ throw|throw name|createError argument_list|( operator|new name|IllegalArgumentException argument_list|( literal|"Can't write to null safe reference" argument_list|) argument_list|) throw|; block|} name|guarded operator|. name|read operator|= name|read expr_stmt|; name|guarded operator|. name|analyze argument_list|( name|locals argument_list|) expr_stmt|; name|actual operator|= name|guarded operator|. name|actual expr_stmt|; if|if condition|( name|actual operator|. name|sort operator|. name|primitive condition|) block|{ throw|throw operator|new name|IllegalArgumentException argument_list|( literal|"Result of null safe operator must be nullable" argument_list|) throw|; block|} block|} annotation|@ name|Override DECL|method|accessElementCount name|int name|accessElementCount parameter_list|() block|{ return|return name|guarded operator|. name|accessElementCount argument_list|() return|; block|} annotation|@ name|Override DECL|method|isDefOptimized name|boolean name|isDefOptimized parameter_list|() block|{ return|return name|guarded operator|. name|isDefOptimized argument_list|() return|; block|} annotation|@ name|Override DECL|method|updateActual name|void name|updateActual parameter_list|( name|Type name|actual parameter_list|) block|{ name|guarded operator|. name|updateActual argument_list|( name|actual argument_list|) expr_stmt|; block|} annotation|@ name|Override DECL|method|write name|void name|write parameter_list|( name|MethodWriter name|writer parameter_list|, name|Globals name|globals parameter_list|) block|{ name|Label name|end init|= operator|new name|Label argument_list|() decl_stmt|; name|writer operator|. name|dup argument_list|() expr_stmt|; name|writer operator|. name|ifNull argument_list|( name|end argument_list|) expr_stmt|; name|guarded operator|. name|write argument_list|( name|writer argument_list|, name|globals argument_list|) expr_stmt|; name|writer operator|. name|mark argument_list|( name|end argument_list|) expr_stmt|; block|} annotation|@ name|Override DECL|method|setup name|void name|setup parameter_list|( name|MethodWriter name|writer parameter_list|, name|Globals name|globals parameter_list|) block|{ throw|throw name|createError argument_list|( operator|new name|IllegalArgumentException argument_list|( literal|"Can't write to null safe field" argument_list|) argument_list|) throw|; block|} annotation|@ name|Override DECL|method|load name|void name|load parameter_list|( name|MethodWriter name|writer parameter_list|, name|Globals name|globals parameter_list|) block|{ throw|throw name|createError argument_list|( operator|new name|IllegalArgumentException argument_list|( literal|"Can't write to null safe field" argument_list|) argument_list|) throw|; block|} annotation|@ name|Override DECL|method|store name|void name|store parameter_list|( name|MethodWriter name|writer parameter_list|, name|Globals name|globals parameter_list|) block|{ throw|throw name|createError argument_list|( operator|new name|IllegalArgumentException argument_list|( literal|"Can't write to null safe field" argument_list|) argument_list|) throw|; block|} annotation|@ name|Override DECL|method|toString specifier|public name|String name|toString parameter_list|() block|{ return|return name|singleLineToString argument_list|( name|guarded argument_list|) return|; block|} block|} end_class end_unit
UTF-8
Java
6,527
java
PSubNullSafeField.java
Java
[]
null
[]
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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. */ end_comment begin_package DECL|package|org.elasticsearch.painless.node package|package name|org operator|. name|elasticsearch operator|. name|painless operator|. name|node package|; end_package begin_import import|import name|org operator|. name|elasticsearch operator|. name|painless operator|. name|Definition operator|. name|Type import|; end_import begin_import import|import name|org operator|. name|elasticsearch operator|. name|painless operator|. name|Globals import|; end_import begin_import import|import name|org operator|. name|elasticsearch operator|. name|painless operator|. name|Locals import|; end_import begin_import import|import name|org operator|. name|elasticsearch operator|. name|painless operator|. name|Location import|; end_import begin_import import|import name|org operator|. name|elasticsearch operator|. name|painless operator|. name|MethodWriter import|; end_import begin_import import|import name|org operator|. name|objectweb operator|. name|asm operator|. name|Label import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Set import|; end_import begin_comment comment|/** * Implements a field who's value is null if the prefix is null rather than throwing an NPE. */ end_comment begin_class DECL|class|PSubNullSafeField specifier|public class|class name|PSubNullSafeField extends|extends name|AStoreable block|{ DECL|field|guarded specifier|private name|AStoreable name|guarded decl_stmt|; DECL|method|PSubNullSafeField specifier|public name|PSubNullSafeField parameter_list|( name|Location name|location parameter_list|, name|AStoreable name|guarded parameter_list|) block|{ name|super argument_list|( name|location argument_list|) expr_stmt|; name|this operator|. name|guarded operator|= name|guarded expr_stmt|; block|} annotation|@ name|Override DECL|method|extractVariables name|void name|extractVariables parameter_list|( name|Set argument_list|< name|String argument_list|> name|variables parameter_list|) block|{ name|guarded operator|. name|extractVariables argument_list|( name|variables argument_list|) expr_stmt|; block|} annotation|@ name|Override DECL|method|analyze name|void name|analyze parameter_list|( name|Locals name|locals parameter_list|) block|{ if|if condition|( name|write condition|) block|{ throw|throw name|createError argument_list|( operator|new name|IllegalArgumentException argument_list|( literal|"Can't write to null safe reference" argument_list|) argument_list|) throw|; block|} name|guarded operator|. name|read operator|= name|read expr_stmt|; name|guarded operator|. name|analyze argument_list|( name|locals argument_list|) expr_stmt|; name|actual operator|= name|guarded operator|. name|actual expr_stmt|; if|if condition|( name|actual operator|. name|sort operator|. name|primitive condition|) block|{ throw|throw operator|new name|IllegalArgumentException argument_list|( literal|"Result of null safe operator must be nullable" argument_list|) throw|; block|} block|} annotation|@ name|Override DECL|method|accessElementCount name|int name|accessElementCount parameter_list|() block|{ return|return name|guarded operator|. name|accessElementCount argument_list|() return|; block|} annotation|@ name|Override DECL|method|isDefOptimized name|boolean name|isDefOptimized parameter_list|() block|{ return|return name|guarded operator|. name|isDefOptimized argument_list|() return|; block|} annotation|@ name|Override DECL|method|updateActual name|void name|updateActual parameter_list|( name|Type name|actual parameter_list|) block|{ name|guarded operator|. name|updateActual argument_list|( name|actual argument_list|) expr_stmt|; block|} annotation|@ name|Override DECL|method|write name|void name|write parameter_list|( name|MethodWriter name|writer parameter_list|, name|Globals name|globals parameter_list|) block|{ name|Label name|end init|= operator|new name|Label argument_list|() decl_stmt|; name|writer operator|. name|dup argument_list|() expr_stmt|; name|writer operator|. name|ifNull argument_list|( name|end argument_list|) expr_stmt|; name|guarded operator|. name|write argument_list|( name|writer argument_list|, name|globals argument_list|) expr_stmt|; name|writer operator|. name|mark argument_list|( name|end argument_list|) expr_stmt|; block|} annotation|@ name|Override DECL|method|setup name|void name|setup parameter_list|( name|MethodWriter name|writer parameter_list|, name|Globals name|globals parameter_list|) block|{ throw|throw name|createError argument_list|( operator|new name|IllegalArgumentException argument_list|( literal|"Can't write to null safe field" argument_list|) argument_list|) throw|; block|} annotation|@ name|Override DECL|method|load name|void name|load parameter_list|( name|MethodWriter name|writer parameter_list|, name|Globals name|globals parameter_list|) block|{ throw|throw name|createError argument_list|( operator|new name|IllegalArgumentException argument_list|( literal|"Can't write to null safe field" argument_list|) argument_list|) throw|; block|} annotation|@ name|Override DECL|method|store name|void name|store parameter_list|( name|MethodWriter name|writer parameter_list|, name|Globals name|globals parameter_list|) block|{ throw|throw name|createError argument_list|( operator|new name|IllegalArgumentException argument_list|( literal|"Can't write to null safe field" argument_list|) argument_list|) throw|; block|} annotation|@ name|Override DECL|method|toString specifier|public name|String name|toString parameter_list|() block|{ return|return name|singleLineToString argument_list|( name|guarded argument_list|) return|; block|} block|} end_class end_unit
6,527
0.790716
0.789183
412
14.839806
39.349365
796
false
false
0
0
0
0
0
0
1.053398
false
false
9
c67fe9f0237057c3d35124e2861f2c2c30caece4
10,110,353,055,966
6d7bc1c632391edd535593887f8a974c7bde793d
/src/test/java/PassengerTest.java
e3a98c1e010b5cb9c383d7938250223d8eb8f4c8
[]
no_license
RickS80/wk11_weekend_homework
https://github.com/RickS80/wk11_weekend_homework
0705351e716963acb2f3a3cee9e6754732c68427
a99cc782fcf6d6dc3d4430914b72d609fae11050
refs/heads/master
2020-04-23T02:22:50.629000
2019-02-16T16:58:49
2019-02-16T16:58:49
170,844,759
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class PassengerTest { Passenger passenger; Booking booking; @Before public void before(){ passenger = new Passenger("Rick", 2); booking = new Booking(passenger.getName(), 105,"Rome", 1); } @Test public void canGetPaxName(){ assertEquals("Rick", passenger.getName()); } @Test public void canGetLuggage(){ assertEquals(2, passenger.getLuggage()); } @Test public void paxStartwithZeroBookings(){ assertEquals(0,passenger.getBookings()); } @Test public void paxCanAddBooking(){ passenger.addBookingToPassenger(booking); assertEquals(1, passenger.getBookings()); } }
UTF-8
Java
799
java
PassengerTest.java
Java
[ { "context": "void before(){\n passenger = new Passenger(\"Rick\", 2);\n booking = new Booking(passenger.get", "end": 250, "score": 0.9998583793640137, "start": 246, "tag": "NAME", "value": "Rick" }, { "context": " booking = new Booking(passenger.getName(), 105,\"Rome\", 1);\n }\n\n @Test\n public void canGetPaxN", "end": 317, "score": 0.999853253364563, "start": 313, "tag": "NAME", "value": "Rome" }, { "context": "ublic void canGetPaxName(){\n assertEquals(\"Rick\", passenger.getName());\n }\n\n @Test\n publ", "end": 400, "score": 0.9998308420181274, "start": 396, "tag": "NAME", "value": "Rick" } ]
null
[]
import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class PassengerTest { Passenger passenger; Booking booking; @Before public void before(){ passenger = new Passenger("Rick", 2); booking = new Booking(passenger.getName(), 105,"Rome", 1); } @Test public void canGetPaxName(){ assertEquals("Rick", passenger.getName()); } @Test public void canGetLuggage(){ assertEquals(2, passenger.getLuggage()); } @Test public void paxStartwithZeroBookings(){ assertEquals(0,passenger.getBookings()); } @Test public void paxCanAddBooking(){ passenger.addBookingToPassenger(booking); assertEquals(1, passenger.getBookings()); } }
799
0.638298
0.628285
42
18.023809
19.347065
66
false
false
0
0
0
0
0
0
0.47619
false
false
9
467d0cfb488c23264425d8706e307db55c410af3
18,777,597,057,209
2fbe48360b5306badaddd566673a83fa9d1a0fa7
/src/ClassInJava/quiz2.java
1d356cf50fc73e70f7e64273c842791194a48e03
[]
no_license
aza13/Javaprojects
https://github.com/aza13/Javaprojects
ca086b79174e69ebdd6bb759efa20fb2b095c55e
d781a02ca8f4edf29c3502f0a8561438208bd83b
refs/heads/master
2022-01-06T23:09:58.733000
2019-05-03T00:18:21
2019-05-03T00:18:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ClassInJava; public class quiz2 { public static void main(String[] args) { int count=0; do{ do{ count++; }while (count<2); break; }while (true); System.out.println(count); } }
UTF-8
Java
279
java
quiz2.java
Java
[]
null
[]
package ClassInJava; public class quiz2 { public static void main(String[] args) { int count=0; do{ do{ count++; }while (count<2); break; }while (true); System.out.println(count); } }
279
0.458781
0.448029
16
16.4375
12.663771
44
false
false
0
0
0
0
0
0
0.4375
false
false
9
d71be7cd69e93123a2d7a10a00fa5c1d02d11d5d
12,412,455,527,264
cb3bf8f937b30ffbbdee4ca9911c393d86cd5089
/src/main/java/cn/think/in/java/concurrent/tools/CyclicBarrierDemo.java
9bdafa8b0dc95446c2094893b693565215b32c7e
[]
no_license
hjsw1/2018-study-demo
https://github.com/hjsw1/2018-study-demo
e3c0a43607d1a0d45525e3d699793c64b719f78a
55571aa08b8dd3c01ca5869ae833710ce24eff50
refs/heads/master
2021-09-07T15:51:36.780000
2018-02-25T14:05:54
2018-02-25T14:05:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.think.in.java.tools; import java.util.Random; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * 循环栅栏 * * 比 CountDownLatch 非常类似,但是更复杂,更强大 * * 阻止线程继续执行,要求线程在栅栏出等待。 * * cyclic 表示循环,表示这个计数器可以反复使用。而CountDownLatch无法进行重复使用。 */ public class CyclicBarrierDemo { static class Soldier implements Runnable { // 军人 String soldier; // 循环栅栏 final CyclicBarrier cyclic; public Soldier(CyclicBarrier cyclic, String soldier) { this.cyclic = cyclic; this.soldier = soldier; } @Override public void run() { // 等待所有士兵到齐 try { System.out.println("准备"); /* * 内部维护一个数字,梅个 * */ cyclic.await();// 到了 10 才开始走,否则线程等待 doWork(); // 等待所有士兵完成工作 cyclic.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } private void doWork() { try { Thread.sleep(Math.abs(new Random().nextInt() % 10000)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(soldier + ": 任务完成"); } } /** * 当计数器一次计数完成后,系统会派一个线程执行的这个线程的run方法。 */ static class BarrierRun implements Runnable { boolean flag; int N; public BarrierRun(boolean flag, int n) { this.flag = flag; N = n; } @Override public void run() { if (flag) { System.out.println("司令:【士兵 " + N + "个, 任务完成!】"); } else { System.out.println("司令:【士兵 " + N + "个, 集合完毕!】"); flag = true; } } } public static void main(String[] args) { final int n = 10; Thread[] allSoldier = new Thread[n]; boolean flag = false; // parties 表示计数总数,也就是参与的线程总数, barrierAction 就是当计数器一次计数完成后,系统会执行的动作 CyclicBarrier cyclic = new CyclicBarrier(n, new BarrierRun(false, n)); // 设置屏障点,主要是为了执行这个方法 System.out.println("集合队伍"); for (int i = 0; i < n; i++) { System.out.println("士兵" + i + "报道"); allSoldier[i] = new Thread(new Soldier(cyclic, "士兵" + i)); allSoldier[i].start(); // if (i== 5){ // 会导致所有的线程全部停止 BrokenBarrierException * 9 + InterruptedException * 1 // allSoldier[i].interrupt(); // // } } } }
UTF-8
Java
2,805
java
CyclicBarrierDemo.java
Java
[]
null
[]
package cn.think.in.java.tools; import java.util.Random; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * 循环栅栏 * * 比 CountDownLatch 非常类似,但是更复杂,更强大 * * 阻止线程继续执行,要求线程在栅栏出等待。 * * cyclic 表示循环,表示这个计数器可以反复使用。而CountDownLatch无法进行重复使用。 */ public class CyclicBarrierDemo { static class Soldier implements Runnable { // 军人 String soldier; // 循环栅栏 final CyclicBarrier cyclic; public Soldier(CyclicBarrier cyclic, String soldier) { this.cyclic = cyclic; this.soldier = soldier; } @Override public void run() { // 等待所有士兵到齐 try { System.out.println("准备"); /* * 内部维护一个数字,梅个 * */ cyclic.await();// 到了 10 才开始走,否则线程等待 doWork(); // 等待所有士兵完成工作 cyclic.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } private void doWork() { try { Thread.sleep(Math.abs(new Random().nextInt() % 10000)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(soldier + ": 任务完成"); } } /** * 当计数器一次计数完成后,系统会派一个线程执行的这个线程的run方法。 */ static class BarrierRun implements Runnable { boolean flag; int N; public BarrierRun(boolean flag, int n) { this.flag = flag; N = n; } @Override public void run() { if (flag) { System.out.println("司令:【士兵 " + N + "个, 任务完成!】"); } else { System.out.println("司令:【士兵 " + N + "个, 集合完毕!】"); flag = true; } } } public static void main(String[] args) { final int n = 10; Thread[] allSoldier = new Thread[n]; boolean flag = false; // parties 表示计数总数,也就是参与的线程总数, barrierAction 就是当计数器一次计数完成后,系统会执行的动作 CyclicBarrier cyclic = new CyclicBarrier(n, new BarrierRun(false, n)); // 设置屏障点,主要是为了执行这个方法 System.out.println("集合队伍"); for (int i = 0; i < n; i++) { System.out.println("士兵" + i + "报道"); allSoldier[i] = new Thread(new Soldier(cyclic, "士兵" + i)); allSoldier[i].start(); // if (i== 5){ // 会导致所有的线程全部停止 BrokenBarrierException * 9 + InterruptedException * 1 // allSoldier[i].interrupt(); // // } } } }
2,805
0.58337
0.577681
105
20.761906
20.282539
89
false
false
0
0
0
0
0
0
0.380952
false
false
9
e5e152e8c2c363f4ec34c51ad62c41baaa84c4f9
17,334,488,048,578
7dcfbd6cc220dd636088e9a47c60afd4c8d5cad9
/src/main/java/com/pigthinkingtec/src/main/java/com/pigthinkingtec/framework/spring/mvc/tags/form/TextareaTagImpl.java
ffd2ebbfe18ee9e0b6f2c9c88ce80044ca53529c
[ "Apache-2.0" ]
permissive
PigThinkingTec/Application
https://github.com/PigThinkingTec/Application
f8c523e34d0350516cce7673a9f2a183e0b69c56
8df19dd4664ba33504b566ca114b932d6273415d
refs/heads/master
2021-01-02T08:13:24.320000
2017-08-01T08:54:36
2017-08-01T08:54:36
98,964,533
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pigthinkingtec.framework.spring.mvc.tags.form; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.jsp.JspException; import org.springframework.web.servlet.tags.form.TagWriter; import org.springframework.web.servlet.tags.form.TextareaTag; import com.pigthinkingtec.framework.spring.mvc.util.PropertiesUtil; /** * SpringのTextareaTagを継承したクラス * * @author yizhou */ @SuppressWarnings("serial") public class TextareaTagImpl extends TextareaTag { @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(TextareaTagImpl.class); private boolean required; protected boolean ime; private String wrap = null; private final String WRAPS_ATTRIBUTE = "wraps"; private String maskPatterns = null; private boolean escapeMaskFlg = false; /** * imeを取得する * * @return Returns the ime. */ public boolean getIme() { return ime; } /** * imeをセットする * * @param ime The ime to set. */ public void setIme(boolean ime) { this.ime = ime; //setStyleSheet(); } public boolean getRequired() { return required; } public String getWrap() { return wrap; } public void setWrap(String wrap) { this.wrap = wrap; } public void setRequired(boolean required) { this.required = required; //setStyleSheet(); } /** * マスクパターンを取得する * * @return */ public String getMaskPatterns() { return maskPatterns; } /** * Maskするパターンを設定する * 複数してする場合は、カンマ区切りで指定する * * @param maskPatterns */ public void setMaskPatterns(String maskPatterns) { this.maskPatterns = maskPatterns; } /** * エスケープマスクフラグを取得する * @return */ public Boolean isEscapeMaskFlg() { return escapeMaskFlg; } /** * エスケープマスクフラグを設定する * @param escapeMaskFlg */ public void setEscapeMaskFlg (Boolean escapeMaskFlg) { this.escapeMaskFlg = escapeMaskFlg; } private void setStyleSheet(){ if(required){ if(ime){ setCssClass("require ime_mode_on"); setCssErrorClass("require_error ime_mode_on"); } else{ setCssClass("require ime_mode_off"); setCssErrorClass("require_error ime_mode_off"); } } else { if(ime){ setCssClass("text ime_mode_on"); setCssErrorClass("text_error ime_mode_on"); } else{ setCssClass("text ime_mode_off"); setCssErrorClass("text_error ime_mode_off"); } } } @Override protected int writeTagContent(TagWriter tagWriter) throws JspException { prepare(tagWriter); tagWriter.startTag("textarea"); writeDefaultAttributes(tagWriter); writeOptionalAttribute(tagWriter, ROWS_ATTRIBUTE, getRows()); writeOptionalAttribute(tagWriter, COLS_ATTRIBUTE, getCols()); writeOptionalAttribute(tagWriter, WRAPS_ATTRIBUTE, getWrap()); writeOptionalAttribute(tagWriter, ONSELECT_ATTRIBUTE, getOnselect()); if (getDisabledFlg()==true) { writeOptionalAttribute(tagWriter, DISABLED_ATTRIBUTE, "true"); } String value = getDisplayString(getBoundValue(), getPropertyEditor()); tagWriter.appendValue(processFieldValue(getName(), value, "textarea")); tagWriter.endTag(); return SKIP_BODY; } @Override public void doFinally() { // tomcatで実行する場合は初期化処理を実施。 if (PropertiesUtil.getProperty("cleanAtDoFinally").equals("true")) { super.doFinally(); this.ime = false; this.required = false; this.wrap = null; this.maskPatterns = null; this.escapeMaskFlg = false; this.setRows(null); this.setCols(null); this.setOnselect(null); this.setDisabled(false); } } /** * Disabledにするかどうかを判定するメソッド * * @return * @throws JspException */ protected boolean getDisabledFlg() throws JspException { if (isDisabled()) { return true; } FormTagImpl formTag = TagUtil.getFormTag(this); String formClassName = formTag.getModelAttribute(); //マスクパターンに応じたdisable設定 if (maskPatterns != null) { String maskPattern = TagUtil.getMaskPattern(formClassName, pageContext); if (maskPattern != null) { String[] maskPatternArray = maskPatterns.split(","); for (int i = 0; i < maskPatternArray.length; i++) { if (maskPattern.equals(maskPatternArray[i])) { return true; } } } } //マスクフラグに応じたdisable設定 Boolean maskFlg = TagUtil.getMaskFlg(formClassName, pageContext); if (maskFlg == true && escapeMaskFlg == false) { return true; } return false; } /** * writeTagContent の 前処理 * * @param tagWriter * @throws JspException */ protected void prepare(TagWriter tagWriter) throws JspException { setStyleSheet(); } }
UTF-8
Java
5,240
java
TextareaTagImpl.java
Java
[ { "context": "\n\n/**\n * SpringのTextareaTagを継承したクラス\n * \n * @author yizhou\n */\n@SuppressWarnings(\"serial\")\npublic class Text", "end": 404, "score": 0.9994611144065857, "start": 398, "tag": "USERNAME", "value": "yizhou" } ]
null
[]
package com.pigthinkingtec.framework.spring.mvc.tags.form; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.jsp.JspException; import org.springframework.web.servlet.tags.form.TagWriter; import org.springframework.web.servlet.tags.form.TextareaTag; import com.pigthinkingtec.framework.spring.mvc.util.PropertiesUtil; /** * SpringのTextareaTagを継承したクラス * * @author yizhou */ @SuppressWarnings("serial") public class TextareaTagImpl extends TextareaTag { @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(TextareaTagImpl.class); private boolean required; protected boolean ime; private String wrap = null; private final String WRAPS_ATTRIBUTE = "wraps"; private String maskPatterns = null; private boolean escapeMaskFlg = false; /** * imeを取得する * * @return Returns the ime. */ public boolean getIme() { return ime; } /** * imeをセットする * * @param ime The ime to set. */ public void setIme(boolean ime) { this.ime = ime; //setStyleSheet(); } public boolean getRequired() { return required; } public String getWrap() { return wrap; } public void setWrap(String wrap) { this.wrap = wrap; } public void setRequired(boolean required) { this.required = required; //setStyleSheet(); } /** * マスクパターンを取得する * * @return */ public String getMaskPatterns() { return maskPatterns; } /** * Maskするパターンを設定する * 複数してする場合は、カンマ区切りで指定する * * @param maskPatterns */ public void setMaskPatterns(String maskPatterns) { this.maskPatterns = maskPatterns; } /** * エスケープマスクフラグを取得する * @return */ public Boolean isEscapeMaskFlg() { return escapeMaskFlg; } /** * エスケープマスクフラグを設定する * @param escapeMaskFlg */ public void setEscapeMaskFlg (Boolean escapeMaskFlg) { this.escapeMaskFlg = escapeMaskFlg; } private void setStyleSheet(){ if(required){ if(ime){ setCssClass("require ime_mode_on"); setCssErrorClass("require_error ime_mode_on"); } else{ setCssClass("require ime_mode_off"); setCssErrorClass("require_error ime_mode_off"); } } else { if(ime){ setCssClass("text ime_mode_on"); setCssErrorClass("text_error ime_mode_on"); } else{ setCssClass("text ime_mode_off"); setCssErrorClass("text_error ime_mode_off"); } } } @Override protected int writeTagContent(TagWriter tagWriter) throws JspException { prepare(tagWriter); tagWriter.startTag("textarea"); writeDefaultAttributes(tagWriter); writeOptionalAttribute(tagWriter, ROWS_ATTRIBUTE, getRows()); writeOptionalAttribute(tagWriter, COLS_ATTRIBUTE, getCols()); writeOptionalAttribute(tagWriter, WRAPS_ATTRIBUTE, getWrap()); writeOptionalAttribute(tagWriter, ONSELECT_ATTRIBUTE, getOnselect()); if (getDisabledFlg()==true) { writeOptionalAttribute(tagWriter, DISABLED_ATTRIBUTE, "true"); } String value = getDisplayString(getBoundValue(), getPropertyEditor()); tagWriter.appendValue(processFieldValue(getName(), value, "textarea")); tagWriter.endTag(); return SKIP_BODY; } @Override public void doFinally() { // tomcatで実行する場合は初期化処理を実施。 if (PropertiesUtil.getProperty("cleanAtDoFinally").equals("true")) { super.doFinally(); this.ime = false; this.required = false; this.wrap = null; this.maskPatterns = null; this.escapeMaskFlg = false; this.setRows(null); this.setCols(null); this.setOnselect(null); this.setDisabled(false); } } /** * Disabledにするかどうかを判定するメソッド * * @return * @throws JspException */ protected boolean getDisabledFlg() throws JspException { if (isDisabled()) { return true; } FormTagImpl formTag = TagUtil.getFormTag(this); String formClassName = formTag.getModelAttribute(); //マスクパターンに応じたdisable設定 if (maskPatterns != null) { String maskPattern = TagUtil.getMaskPattern(formClassName, pageContext); if (maskPattern != null) { String[] maskPatternArray = maskPatterns.split(","); for (int i = 0; i < maskPatternArray.length; i++) { if (maskPattern.equals(maskPatternArray[i])) { return true; } } } } //マスクフラグに応じたdisable設定 Boolean maskFlg = TagUtil.getMaskFlg(formClassName, pageContext); if (maskFlg == true && escapeMaskFlg == false) { return true; } return false; } /** * writeTagContent の 前処理 * * @param tagWriter * @throws JspException */ protected void prepare(TagWriter tagWriter) throws JspException { setStyleSheet(); } }
5,240
0.638911
0.638302
205
23.024391
21.42746
85
false
false
0
0
0
0
0
0
1.336585
false
false
9
05deea9c858a7c03caf4afd969b586a4a164eb56
33,311,766,390,298
fdae8ac9555530c0e40c7717d36502dc8b5f6930
/src/ShopBean.java
3c7ef6480ac8af36ec2db0ac2089d2e18f52d10c
[]
no_license
andreasmalling/flowerpower
https://github.com/andreasmalling/flowerpower
bb6df920970638b958e3939814155d2342ad4b43
5c19637d08623176bb5c013c019332c53fce1738
refs/heads/master
2021-01-01T19:10:58.869000
2014-02-21T19:39:10
2014-02-21T19:39:10
16,490,227
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.IOException; import java.util.ArrayList; import javax.faces.bean.ApplicationScoped; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import org.jdom2.JDOMException; @ManagedBean(name="ShopBean") @ApplicationScoped public class ShopBean { private String message; private String createItem; private ArrayList<Item> items = null; private Item item = null; public ShopBean(){ updateItems(); } public String modifyAction() { System.out.println("Modify"); if (item != null) System.out.println(item.getItemID()); else System.out.println("null"); return "MODIFY"; } public ArrayList<Item> getItems(){ return items; } public ArrayList<Item> updateItems(){ try { items = new Communication().getItems(); } catch(Exception e) { message = e.getMessage(); } return items; } public String modify(){ try { new Communication().modifyItem(item); updateItems(); System.out.println("OK MODIFY"); } catch (Exception e) { message = e.getMessage(); System.out.println("WRONG MODIFY"); return "WRONG"; } return "OK"; } public Item getItem(){ return item; } public void setItem(Item i){ System.out.println("Setting item to " + i.getItemID()); item = i; } public String getMessage(){ return message; } }
UTF-8
Java
1,327
java
ShopBean.java
Java
[]
null
[]
import java.io.IOException; import java.util.ArrayList; import javax.faces.bean.ApplicationScoped; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import org.jdom2.JDOMException; @ManagedBean(name="ShopBean") @ApplicationScoped public class ShopBean { private String message; private String createItem; private ArrayList<Item> items = null; private Item item = null; public ShopBean(){ updateItems(); } public String modifyAction() { System.out.println("Modify"); if (item != null) System.out.println(item.getItemID()); else System.out.println("null"); return "MODIFY"; } public ArrayList<Item> getItems(){ return items; } public ArrayList<Item> updateItems(){ try { items = new Communication().getItems(); } catch(Exception e) { message = e.getMessage(); } return items; } public String modify(){ try { new Communication().modifyItem(item); updateItems(); System.out.println("OK MODIFY"); } catch (Exception e) { message = e.getMessage(); System.out.println("WRONG MODIFY"); return "WRONG"; } return "OK"; } public Item getItem(){ return item; } public void setItem(Item i){ System.out.println("Setting item to " + i.getItemID()); item = i; } public String getMessage(){ return message; } }
1,327
0.683497
0.682743
70
17.957144
14.537082
57
false
false
0
0
0
0
0
0
1.771429
false
false
9
06c37c148bfb1e29e5978fb5df5395dbbbe8d551
22,016,002,377,897
9fff68cedeeb9f321d05dedb7e75a1ac1101f089
/src/main/java/com/groupon/spaceman/persistence/domain/ReservationRecord.java
d9c8e8ad4807347ee61850376b8e3e61e7e206f3
[]
no_license
bluebone29/myspring-integ-kafka
https://github.com/bluebone29/myspring-integ-kafka
51d09f500d4c3a47fbefafc1086d2d3f5b5ebd43
4ed03795b40169dc3bc9a4c4986d000902ad522e
refs/heads/master
2018-05-02T22:53:16.310000
2015-05-19T13:13:41
2015-05-19T13:13:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.groupon.spaceman.persistence.domain; import java.time.Instant; import java.util.Date; import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.Type; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; @Entity @Table(name = "reservation_record") public class ReservationRecord { @Id @GeneratedValue private Long id; @Column(name = "reservation_id") @Type(type = "pg-uuid") private UUID reservationId; @Column(name = "inventory_product_id") @Type(type = "pg-uuid") private UUID inventoryProductId; @Column(name = "inventory_unit_id") @Type(type = "pg-uuid") private UUID inventoryUnitId; @Column(name = "status") private String status; @CreatedDate @Temporal(TemporalType.TIMESTAMP) @Column(name = "created_timestamp") private Date createdTimestamp; @LastModifiedDate @Temporal(TemporalType.TIMESTAMP) @Column(name = "last_modified_timestamp") private Date lastModifiedTimestamp; public UUID getReservationId() { return reservationId; } public void setReservationId(UUID reservationId) { this.reservationId = reservationId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
UTF-8
Java
1,617
java
ReservationRecord.java
Java
[]
null
[]
package com.groupon.spaceman.persistence.domain; import java.time.Instant; import java.util.Date; import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.Type; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; @Entity @Table(name = "reservation_record") public class ReservationRecord { @Id @GeneratedValue private Long id; @Column(name = "reservation_id") @Type(type = "pg-uuid") private UUID reservationId; @Column(name = "inventory_product_id") @Type(type = "pg-uuid") private UUID inventoryProductId; @Column(name = "inventory_unit_id") @Type(type = "pg-uuid") private UUID inventoryUnitId; @Column(name = "status") private String status; @CreatedDate @Temporal(TemporalType.TIMESTAMP) @Column(name = "created_timestamp") private Date createdTimestamp; @LastModifiedDate @Temporal(TemporalType.TIMESTAMP) @Column(name = "last_modified_timestamp") private Date lastModifiedTimestamp; public UUID getReservationId() { return reservationId; } public void setReservationId(UUID reservationId) { this.reservationId = reservationId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
1,617
0.718615
0.718615
65
23.876923
16.776823
60
false
false
0
0
0
0
0
0
0.384615
false
false
9
e342a63f4eb08768f7bf6f736db75ac703fc2528
26,319,559,632,976
036aaa6dc328914760c451016b5a4b4e03ace2b0
/src/org/dimigo/basic/PrimitiveDataType.java
6121da9779fa38c5d956e2282510645f538105a7
[]
no_license
seongjinemong/JavaClass
https://github.com/seongjinemong/JavaClass
c356fe4685d82cfcbef56f406ed5b4ac58f96711
9294c7772713336f39cf820bdd9e62e1377f18be
refs/heads/master
2023-07-09T02:35:12.122000
2019-07-10T00:20:09
2019-07-10T00:20:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.dimigo.basic; public class PrimitiveDataType { static boolean flag; public static void main(String[] args) { /* if (flag == true) System.out.println("참입니다!"); else System.out.println("거짓입니다!"); */ System.out.println(flag ? "참입니다!" : "거짓입니다!"); char c1 = 'A'; char c2 = 65; char c3 = '\u0041'; System.out.println(c1 + "\n" + c2 + "\n" + c3 + "\n" ); System.out.println("뷁"); String name = "조성진"; System.out.println("My name is " + name); int index = 3; System.out.println("value of index = " + index); System.out.println(Byte.MIN_VALUE + " ~ " + Byte.MAX_VALUE); System.out.println(Integer.MIN_VALUE + " ~ " + Integer.MAX_VALUE); long a = 10000000000L; float f1 = 3.14f; double d1 = 3.14; float f2 = 0.12345678901234567890f; double d2 = 0.12345678901234567890; System.out.println(f2); System.out.println(d2); } }
UTF-8
Java
1,105
java
PrimitiveDataType.java
Java
[ { "context": " System.out.println(\"뷁\");\n\n String name = \"조성진\";\n System.out.println(\"My name is \" + name", "end": 533, "score": 0.9996277689933777, "start": 530, "tag": "NAME", "value": "조성진" } ]
null
[]
package org.dimigo.basic; public class PrimitiveDataType { static boolean flag; public static void main(String[] args) { /* if (flag == true) System.out.println("참입니다!"); else System.out.println("거짓입니다!"); */ System.out.println(flag ? "참입니다!" : "거짓입니다!"); char c1 = 'A'; char c2 = 65; char c3 = '\u0041'; System.out.println(c1 + "\n" + c2 + "\n" + c3 + "\n" ); System.out.println("뷁"); String name = "조성진"; System.out.println("My name is " + name); int index = 3; System.out.println("value of index = " + index); System.out.println(Byte.MIN_VALUE + " ~ " + Byte.MAX_VALUE); System.out.println(Integer.MIN_VALUE + " ~ " + Integer.MAX_VALUE); long a = 10000000000L; float f1 = 3.14f; double d1 = 3.14; float f2 = 0.12345678901234567890f; double d2 = 0.12345678901234567890; System.out.println(f2); System.out.println(d2); } }
1,105
0.518379
0.444863
48
21.104166
21.063633
74
false
false
0
0
0
0
0
0
0.479167
false
false
9
decd9f759182dfec91f0fa21d3425387498c2835
8,040,178,807,165
77d2de9bb548665cb26ef641e1b6c0333815cd36
/src/main/java/kgfsl/stalk/controller/SegmentController.java
dd2f7dbe28655c9664bcc39eb1b0ee75a95ab487
[]
no_license
AkshayaPR/City_Master_BO
https://github.com/AkshayaPR/City_Master_BO
ff89352fdfc68e9db30dcdceda619fcd6c9b8cad
c14bb32e6778928f371eb7c887aa4f6c7945588a
refs/heads/master
2021-07-06T15:24:38.173000
2017-09-26T05:27:42
2017-09-26T05:27:42
104,839,434
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kgfsl.stalk.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import kgfsl.genie.makerchecker.AbstractMasterController; import kgfsl.genie.makerchecker.Base4EyeService; import kgfsl.stalk.entity.Segment; import kgfsl.stalk.entity.wrapper.SegmentWrapper; import kgfsl.stalk.service.SegmentService; @RestController @RequestMapping("/master/segment") public class SegmentController extends AbstractMasterController<Segment, String> { @Autowired private SegmentService service; @RequestMapping(value = "/getmainactive", method = RequestMethod.GET) public List<Segment> getActiveSegments() { return service.getActiveSegments(); } @Override public Base4EyeService<Segment, String> getMCService() { return service; } @RequestMapping(value = "/segmentlist/getsegmentcodeandnamelist", method = RequestMethod.GET) public List<SegmentWrapper> getSegmentCodeAndNameList() throws Exception { return service.getSegmentWrapper(); } }
UTF-8
Java
1,227
java
SegmentController.java
Java
[]
null
[]
package kgfsl.stalk.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import kgfsl.genie.makerchecker.AbstractMasterController; import kgfsl.genie.makerchecker.Base4EyeService; import kgfsl.stalk.entity.Segment; import kgfsl.stalk.entity.wrapper.SegmentWrapper; import kgfsl.stalk.service.SegmentService; @RestController @RequestMapping("/master/segment") public class SegmentController extends AbstractMasterController<Segment, String> { @Autowired private SegmentService service; @RequestMapping(value = "/getmainactive", method = RequestMethod.GET) public List<Segment> getActiveSegments() { return service.getActiveSegments(); } @Override public Base4EyeService<Segment, String> getMCService() { return service; } @RequestMapping(value = "/segmentlist/getsegmentcodeandnamelist", method = RequestMethod.GET) public List<SegmentWrapper> getSegmentCodeAndNameList() throws Exception { return service.getSegmentWrapper(); } }
1,227
0.793806
0.792176
38
30.289474
27.889734
94
false
false
0
0
0
0
0
0
0.947368
false
false
9
96f8cc4f9fb8d954f5cbb625cddbf78ca021efce
11,536,282,193,280
1574ad3176a775ed09d8f1089d888171e6962626
/UTS/uts/src/uts/Mesin.java
eea150d583de90f10b12fdcce3336a820048e234
[]
no_license
LulukMufida015/PBO-1941720052
https://github.com/LulukMufida015/PBO-1941720052
a50b93b2b84c1c502c1336342ee46664d4288036
b67c08c22ea746899fd94dbe01d359bde79e0a5e
refs/heads/master
2023-01-29T02:09:57.575000
2020-12-06T14:11:12
2020-12-06T14:11:12
291,656,903
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 uts; /** * * @author Windows 10 */ public class Mesin { private String merek; private double kecepatan; public Mesin() { } public String getMerek() { return merek; } public void setMerek(String merek) { this.merek = merek; } public double getKecepatan() { return kecepatan; } public void setKecepatan(double kecepatan) { this.kecepatan = kecepatan; } public void tambahkecepatan(double x){ if (kecepatan <= 100) kecepatan += x; } public void kurangiKecepatan(double x){ if (kecepatan >= 0) kecepatan -= x; } }
UTF-8
Java
844
java
Mesin.java
Java
[ { "context": "in the editor.\n */\npackage uts;\n\n/**\n *\n * @author Windows 10\n */\npublic class Mesin {\n private String merek", "end": 227, "score": 0.8599893450737, "start": 217, "tag": "USERNAME", "value": "Windows 10" } ]
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 uts; /** * * @author Windows 10 */ public class Mesin { private String merek; private double kecepatan; public Mesin() { } public String getMerek() { return merek; } public void setMerek(String merek) { this.merek = merek; } public double getKecepatan() { return kecepatan; } public void setKecepatan(double kecepatan) { this.kecepatan = kecepatan; } public void tambahkecepatan(double x){ if (kecepatan <= 100) kecepatan += x; } public void kurangiKecepatan(double x){ if (kecepatan >= 0) kecepatan -= x; } }
844
0.606635
0.599526
43
18.651163
18.269156
79
false
false
0
0
0
0
0
0
0.27907
false
false
9
ec9c035b76321dbd76295cd192dd1d68afcab00f
20,942,260,571,869
20029355d55d58188f29491ea5d09549ffc75549
/ego-manage/src/main/java/com/ego/manage/service/TBContentCategoryService.java
908ea2da11870da6ef785f9f43a647a83cf07d45
[]
no_license
hackaming/ego
https://github.com/hackaming/ego
1735f16b8c919850bea7257e93cd9c8e514ee617
56c2d16f364885e75efb7330e0cbcfdcdba1a982
refs/heads/master
2020-03-27T15:37:41.175000
2018-10-26T02:34:47
2018-10-26T02:34:47
146,729,241
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ego.manage.service; import java.util.List; import com.ego.commons.pojo.EasyUIDataGrid; import com.ego.commons.pojo.EasyUITree; import com.ego.commons.pojo.EgoResult; import com.ego.pojo.TbContentCategory; public interface TBContentCategoryService { List<EasyUITree> list(long id); EgoResult insContentCategory(TbContentCategory cat); int insContentCategoryWithRollback(TbContentCategory cat) throws Exception; int updateContentCategory(TbContentCategory cat) throws Exception; TbContentCategory getCatById(long id); int delContentCategoryWithRollback(TbContentCategory cat) throws Exception; }
UTF-8
Java
615
java
TBContentCategoryService.java
Java
[]
null
[]
package com.ego.manage.service; import java.util.List; import com.ego.commons.pojo.EasyUIDataGrid; import com.ego.commons.pojo.EasyUITree; import com.ego.commons.pojo.EgoResult; import com.ego.pojo.TbContentCategory; public interface TBContentCategoryService { List<EasyUITree> list(long id); EgoResult insContentCategory(TbContentCategory cat); int insContentCategoryWithRollback(TbContentCategory cat) throws Exception; int updateContentCategory(TbContentCategory cat) throws Exception; TbContentCategory getCatById(long id); int delContentCategoryWithRollback(TbContentCategory cat) throws Exception; }
615
0.84065
0.84065
17
35.176472
24.147184
76
false
false
0
0
0
0
0
0
1.058824
false
false
9
83439ae4466e57365c5c7a12547edcc28ccf28c5
10,917,806,926,595
29bda2762eeb2fb26aa781906e829070c8a15c9b
/trianglescontainorigineasy-java/TrianglesContainOriginEasy.java
fa3f1fadbe9d26c0569dc004af282c19a8f744d2
[]
no_license
ahmed-fathy-aly/TopCoder
https://github.com/ahmed-fathy-aly/TopCoder
d1410bac08f54b97beb47ac6ec7dbe2fcc80f9f7
bba25d88323470582d5ec06edb8fc2bd1b1b63d2
refs/heads/master
2021-01-17T07:10:37.770000
2016-05-01T01:58:21
2016-05-01T01:58:21
29,813,887
8
3
null
null
null
null
null
null
null
null
null
null
null
null
null
public class TrianglesContainOriginEasy { public int count(int[] x, int[] y) { int count = 0; int n = x.length; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) { // real area Vector2 a = new Vector2(x[i] - x[j], y[i] - y[j]); Vector2 b = new Vector2(x[i] - x[k], y[i] - y[k]); double area = Math.abs(a.cross(b)); // area around zero double area2 = 0; area2 += Math.abs(new Vector2(-x[i], -y[i]).cross(new Vector2(-x[j], -y[j]))); area2 += Math.abs(new Vector2(-x[i], -y[i]).cross(new Vector2(-x[k], -y[k]))); area2 += Math.abs(new Vector2(-x[k], -y[k]).cross(new Vector2(-x[j], -y[j]))); if (Math.abs(area - area2) < 0.00001) count++; } return count; } } class Vector2 { int x, y; public Vector2(int x, int y) { this.x = x; this.y = y; } double cross(Vector2 other) { return 1.0 * (x * other.y - y * other.x); } }
UTF-8
Java
960
java
TrianglesContainOriginEasy.java
Java
[]
null
[]
public class TrianglesContainOriginEasy { public int count(int[] x, int[] y) { int count = 0; int n = x.length; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) { // real area Vector2 a = new Vector2(x[i] - x[j], y[i] - y[j]); Vector2 b = new Vector2(x[i] - x[k], y[i] - y[k]); double area = Math.abs(a.cross(b)); // area around zero double area2 = 0; area2 += Math.abs(new Vector2(-x[i], -y[i]).cross(new Vector2(-x[j], -y[j]))); area2 += Math.abs(new Vector2(-x[i], -y[i]).cross(new Vector2(-x[k], -y[k]))); area2 += Math.abs(new Vector2(-x[k], -y[k]).cross(new Vector2(-x[j], -y[j]))); if (Math.abs(area - area2) < 0.00001) count++; } return count; } } class Vector2 { int x, y; public Vector2(int x, int y) { this.x = x; this.y = y; } double cross(Vector2 other) { return 1.0 * (x * other.y - y * other.x); } }
960
0.514583
0.482292
46
19.891304
23.028553
83
false
false
0
0
0
0
0
0
2.76087
false
false
9
8c91909f5c799beaa664db72c86522ec98069532
26,388,279,097,627
88a5ed761e4a9c41789fb3098cadc9a433a1e8e2
/app/src/main/java/com/xydata/hedi/face/PeopleBean.java
237923e910a4ad3e79c21524b38e34bed7a8102e
[]
no_license
vampirehedi/face
https://github.com/vampirehedi/face
262bc60526f691d6e8dc16bd060dd2d5650df1c9
2efb029da7c6e9bdbaba9c361a44678d8d54c0d7
refs/heads/master
2017-05-08T17:57:23.780000
2017-03-21T08:41:42
2017-03-21T08:41:42
82,269,053
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xydata.hedi.face; /** * 项目名称:face * 类描述: * 创建人:hedi * 创建时间:2017/1/5 上午10:14 * 修改人:hedi * 修改时间:2017/1/5 上午10:14 * 修改备注: */ public class PeopleBean { private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } }
UTF-8
Java
375
java
PeopleBean.java
Java
[ { "context": "ydata.hedi.face;\n\n/**\n * 项目名称:face\n * 类描述:\n * 创建人:hedi\n * 创建时间:2017/1/5 上午10:14\n * 修改人:hedi\n * 修改时间:2017", "end": 67, "score": 0.6764694452285767, "start": 63, "tag": "USERNAME", "value": "hedi" }, { "context": " 类描述:\n * 创建人:hedi\n * 创建时间:2017/1/5 上午10:14\n * 修改人:hedi\n * 修改时间:2017/1/5 上午10:14\n * 修改备注:\n */\npublic clas", "end": 104, "score": 0.5950945615768433, "start": 100, "tag": "USERNAME", "value": "hedi" } ]
null
[]
package com.xydata.hedi.face; /** * 项目名称:face * 类描述: * 创建人:hedi * 创建时间:2017/1/5 上午10:14 * 修改人:hedi * 修改时间:2017/1/5 上午10:14 * 修改备注: */ public class PeopleBean { private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } }
375
0.554455
0.488449
22
12.772727
10.13514
31
false
false
0
0
0
0
0
0
0.181818
false
false
9
69b7c1fb1e8287c5b0050c2a58f48954948d4a3b
3,100,966,427,308
d20f1f5c5eeec61122ee1ca8fb0ca6a5b1d88b73
/src/com/jinan/www/entity/Student1.java
c03c85525ffff2ea7e6ee7bf859b3d30c8546daa
[]
no_license
wangdpdreamit/hibernate_003
https://github.com/wangdpdreamit/hibernate_003
edcd8dba7327ba330bf5a2cca5d9a3a670ef3c57
8c342c64aef770893bff367bfe803a9a6d716c9b
refs/heads/master
2022-08-28T09:50:15.367000
2018-09-13T08:38:47
2018-09-13T08:38:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jinan.www.entity; import java.io.Serializable; public class Student1 implements Serializable { private int sid; private String sname; private String sex; /* * 在多方定义一个一方的引用 * 加上一个grade1的属性,就相当于增加了一个grade属性。 */ private Grade1 grade1; public Grade1 getGrade1() { return grade1; } public void setGrade1(Grade1 grade1) { this.grade1 = grade1; } public Student1(String sname, String sex, Grade1 grade1) { this.sname = sname; this.sex = sex; this.grade1 = grade1; } public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Student1() { super(); } public Student1(int sid, String sname, String sex) { super(); this.sid = sid; this.sname = sname; this.sex = sex; } @Override public String toString() { return "Student1 [sid=" + sid + ", sname=" + sname + ", sex=" + sex + ", grade1=" + grade1 + "]"; } }
GB18030
Java
1,334
java
Student1.java
Java
[]
null
[]
package com.jinan.www.entity; import java.io.Serializable; public class Student1 implements Serializable { private int sid; private String sname; private String sex; /* * 在多方定义一个一方的引用 * 加上一个grade1的属性,就相当于增加了一个grade属性。 */ private Grade1 grade1; public Grade1 getGrade1() { return grade1; } public void setGrade1(Grade1 grade1) { this.grade1 = grade1; } public Student1(String sname, String sex, Grade1 grade1) { this.sname = sname; this.sex = sex; this.grade1 = grade1; } public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Student1() { super(); } public Student1(int sid, String sname, String sex) { super(); this.sid = sid; this.sname = sname; this.sex = sex; } @Override public String toString() { return "Student1 [sid=" + sid + ", sname=" + sname + ", sex=" + sex + ", grade1=" + grade1 + "]"; } }
1,334
0.573228
0.555906
72
15.638889
17.1329
100
false
false
0
0
0
0
0
0
2.416667
false
false
9
e6b1e0fdb46aa28d4e1fd2445b7e22ce4c9d3d49
24,970,939,902,671
ca93cab51eccad5309af5551ff793f56e51fac6f
/src/communication/messages/server_to_client/channel_modification/SendChannelUsersMessage.java
1732523d4978e7a8aa15bf98397de40d1a71cd97
[]
no_license
doanhat/Java-chat-application
https://github.com/doanhat/Java-chat-application
edf5cd922222d94ae29da1e6a4ec96cddf6beb7c
efa43916aeebd4c89d0ae002bd42468b20c8b9da
refs/heads/master
2023-03-06T12:22:13.061000
2021-01-03T16:15:59
2021-01-03T16:15:59
339,647,643
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package communication.messages.server_to_client.channel_modification; import communication.client.CommunicationClientController; import communication.messages.abstracts.ServerToClientMessage; import common.shared_data.UserLite; import java.util.List; import java.util.UUID; public class SendChannelUsersMessage extends ServerToClientMessage { private static final long serialVersionUID = -164319089062L; private final UUID channelID; private final List<UserLite> activeUsers; /** * Message transmettant les liste des utilisateurs ayant acces a un channel * @param channelID Channel * @param activeUsers liste des utilisateurs */ public SendChannelUsersMessage(UUID channelID, List<UserLite> activeUsers) { this.channelID = channelID; this.activeUsers = activeUsers; } @Override protected void handle(CommunicationClientController commClientController) { commClientController.mainHandler().deliverChannelUsersList(channelID, activeUsers); } }
UTF-8
Java
1,066
java
SendChannelUsersMessage.java
Java
[]
null
[]
package communication.messages.server_to_client.channel_modification; import communication.client.CommunicationClientController; import communication.messages.abstracts.ServerToClientMessage; import common.shared_data.UserLite; import java.util.List; import java.util.UUID; public class SendChannelUsersMessage extends ServerToClientMessage { private static final long serialVersionUID = -164319089062L; private final UUID channelID; private final List<UserLite> activeUsers; /** * Message transmettant les liste des utilisateurs ayant acces a un channel * @param channelID Channel * @param activeUsers liste des utilisateurs */ public SendChannelUsersMessage(UUID channelID, List<UserLite> activeUsers) { this.channelID = channelID; this.activeUsers = activeUsers; } @Override protected void handle(CommunicationClientController commClientController) { commClientController.mainHandler().deliverChannelUsersList(channelID, activeUsers); } }
1,066
0.743902
0.732645
30
34.533333
30.288319
91
false
false
0
0
0
0
0
0
0.466667
false
false
9
c5dd76cd51e9fca970009f33c23a8a6d5262d7bd
33,706,903,366,763
be13ad1e7395a09da1e89746104bd05c2c1eed8e
/gta/gen/main/java/uif/rs/relate/RelateF_involucradoToCuenta_bancariaWith_r_inv_cuenta_banc_Controller.java
acb24468edbac582d6c534d3f8959e5a7aebe7f5
[]
no_license
jtrellest/GTA
https://github.com/jtrellest/GTA
f24e5dcde7d0f6056ce54d5aadc26ffc141edb2f
e8c6b3ec11272ece90d6498bb49305c825280136
refs/heads/master
2020-05-30T09:53:31.204000
2013-10-29T23:02:39
2013-10-29T23:02:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uif.rs.relate; import com.emc.xcp.services.framework.rs.AbstractRelationshipCreateController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import uif.domain.r_inv_cuenta_banc.Cuenta_bancariaSourceRelation; import uif.domain.r_inv_cuenta_banc.Cuenta_bancariaToF_involucradoAssociation; import uif.domain.r_inv_cuenta_banc.F_involucradoTargetRelation; import uif.domain.r_inv_cuenta_banc.RelationshipInput; @Controller(value = "uif.rs.relate.RelateF_involucradoToCuenta_bancariaWith_r_inv_cuenta_banc_Controller") @RequestMapping(value = "/application/uif_f_involucrados/{id}/cuenta_bancarias", method = RequestMethod.POST, params = "type=r_inv_cuenta_banc") public class RelateF_involucradoToCuenta_bancariaWith_r_inv_cuenta_banc_Controller extends AbstractRelationshipCreateController<F_involucradoTargetRelation,Cuenta_bancariaSourceRelation,Cuenta_bancariaToF_involucradoAssociation,RelationshipInput> { public RelateF_involucradoToCuenta_bancariaWith_r_inv_cuenta_banc_Controller() { super(F_involucradoTargetRelation.class,Cuenta_bancariaSourceRelation.class,Cuenta_bancariaToF_involucradoAssociation.class); } }
UTF-8
Java
1,273
java
RelateF_involucradoToCuenta_bancariaWith_r_inv_cuenta_banc_Controller.java
Java
[]
null
[]
package uif.rs.relate; import com.emc.xcp.services.framework.rs.AbstractRelationshipCreateController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import uif.domain.r_inv_cuenta_banc.Cuenta_bancariaSourceRelation; import uif.domain.r_inv_cuenta_banc.Cuenta_bancariaToF_involucradoAssociation; import uif.domain.r_inv_cuenta_banc.F_involucradoTargetRelation; import uif.domain.r_inv_cuenta_banc.RelationshipInput; @Controller(value = "uif.rs.relate.RelateF_involucradoToCuenta_bancariaWith_r_inv_cuenta_banc_Controller") @RequestMapping(value = "/application/uif_f_involucrados/{id}/cuenta_bancarias", method = RequestMethod.POST, params = "type=r_inv_cuenta_banc") public class RelateF_involucradoToCuenta_bancariaWith_r_inv_cuenta_banc_Controller extends AbstractRelationshipCreateController<F_involucradoTargetRelation,Cuenta_bancariaSourceRelation,Cuenta_bancariaToF_involucradoAssociation,RelationshipInput> { public RelateF_involucradoToCuenta_bancariaWith_r_inv_cuenta_banc_Controller() { super(F_involucradoTargetRelation.class,Cuenta_bancariaSourceRelation.class,Cuenta_bancariaToF_involucradoAssociation.class); } }
1,273
0.842105
0.842105
19
66.052635
60.409546
248
false
false
0
0
0
0
0
0
0.894737
false
false
9
ca6c2db6f2c672fc293783cb31e2c2b2a1117559
24,111,946,416,054
c8fde0e9388e1c4bd537c17e4997941b767bc2ea
/src/main/java/discordbot/command/fun/SayCommand.java
7edd79af27aca090dc3966ba0d5739c23fc3e9fa
[]
no_license
R3T1CAL/DiscordBot
https://github.com/R3T1CAL/DiscordBot
47825bcd93ff5ceaea5b5c9ca54ce43e78d9aa83
4b8c6e114a7c7847fbc1a13a0773d6df22f048f2
refs/heads/master
2021-01-12T03:37:26.240000
2017-01-06T17:15:36
2017-01-06T17:15:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package discordbot.command.fun; import com.google.api.client.repackaged.com.google.common.base.Joiner; import discordbot.core.AbstractCommand; import discordbot.handler.Template; import discordbot.main.DiscordBot; import discordbot.permission.SimpleRank; import discordbot.util.DisUtil; import net.dv8tion.jda.core.entities.MessageChannel; import net.dv8tion.jda.core.entities.User; /** * !say * make the bot say something */ public class SayCommand extends AbstractCommand { public SayCommand() { super(); } @Override public String getDescription() { return "repeats you"; } @Override public String getCommand() { return "say"; } @Override public boolean isListed() { return false; } @Override public String[] getUsage() { return new String[]{"say <anything>"}; } @Override public String[] getAliases() { return new String[]{}; } @Override public String execute(DiscordBot bot, String[] args, MessageChannel channel, User author) { if (args.length > 0) { String output = Joiner.on(" ").join(args); if (DisUtil.isUserMention(output)) { if (bot.security.getSimpleRank(author, channel).isAtLeast(SimpleRank.GUILD_ADMIN)) { return output; } return Template.get("command_say_contains_mention"); } return output; } else { return Template.get("command_say_whatexactly"); } } }
UTF-8
Java
1,351
java
SayCommand.java
Java
[]
null
[]
package discordbot.command.fun; import com.google.api.client.repackaged.com.google.common.base.Joiner; import discordbot.core.AbstractCommand; import discordbot.handler.Template; import discordbot.main.DiscordBot; import discordbot.permission.SimpleRank; import discordbot.util.DisUtil; import net.dv8tion.jda.core.entities.MessageChannel; import net.dv8tion.jda.core.entities.User; /** * !say * make the bot say something */ public class SayCommand extends AbstractCommand { public SayCommand() { super(); } @Override public String getDescription() { return "repeats you"; } @Override public String getCommand() { return "say"; } @Override public boolean isListed() { return false; } @Override public String[] getUsage() { return new String[]{"say <anything>"}; } @Override public String[] getAliases() { return new String[]{}; } @Override public String execute(DiscordBot bot, String[] args, MessageChannel channel, User author) { if (args.length > 0) { String output = Joiner.on(" ").join(args); if (DisUtil.isUserMention(output)) { if (bot.security.getSimpleRank(author, channel).isAtLeast(SimpleRank.GUILD_ADMIN)) { return output; } return Template.get("command_say_contains_mention"); } return output; } else { return Template.get("command_say_whatexactly"); } } }
1,351
0.716506
0.714286
61
21.163935
21.587929
92
false
false
0
0
0
0
0
0
1.540984
false
false
9
c3e11cea4b8ee56de88ae69eeb0adcb0e04f1e6f
25,417,616,522,003
f6175d3666249ebce28d80a3cd4044acea3b4396
/3.JavaMultithreading/src/com/javarush/task/task30/task3010/Solution.java
cf58617b19f2f4fd19b789efb906758b4ad7b915
[]
no_license
phbzr/JavaRush
https://github.com/phbzr/JavaRush
2fa83ab377c0868dc8593d9fcf90601ab40159ab
97c1c478d5a67ba798b733b4f86ed426b52800ff
refs/heads/master
2020-05-20T10:17:15.817000
2019-05-16T01:43:14
2019-05-16T01:43:14
185,521,813
0
0
null
false
2019-05-16T00:48:41
2019-05-08T03:32:24
2019-05-08T03:37:42
2019-05-16T00:48:40
171
0
0
0
Java
false
false
package com.javarush.task.task30.task3010; /* Минимальное допустимое основание системы счисления */ import java.math.BigInteger; public class Solution { public static void main(String[] args) { int j = 0; Boolean found = false; for (j = 36; j >= 2; ) { try { new BigInteger(args[0], j).toString(); found = true; j--; } catch (Exception e) { break; } } if (found) System.out.println(j+1); else System.out.println("incorrect"); } }
UTF-8
Java
639
java
Solution.java
Java
[]
null
[]
package com.javarush.task.task30.task3010; /* Минимальное допустимое основание системы счисления */ import java.math.BigInteger; public class Solution { public static void main(String[] args) { int j = 0; Boolean found = false; for (j = 36; j >= 2; ) { try { new BigInteger(args[0], j).toString(); found = true; j--; } catch (Exception e) { break; } } if (found) System.out.println(j+1); else System.out.println("incorrect"); } }
639
0.504216
0.48398
29
19.482759
17.686193
54
false
false
0
0
0
0
0
0
0.448276
false
false
9
87f8fcc312925e4570cdcf639dcba1a539467602
2,430,951,492,900
742b8d5bf74eb0fd55a61ab7ef9712f37233f07b
/approval-core/src/main/java/com/github/approval/Approvals.java
ae993b935924c457d021551b288f0d7418fbdc9d
[ "Apache-2.0" ]
permissive
nikolavp/approval
https://github.com/nikolavp/approval
91fe778962a1b6940ba041136dd9e986b0da9d6f
07f4d7476f6ce837edf9f656be2387da8bb2a20c
refs/heads/master
2023-08-26T12:33:41.357000
2023-07-25T15:00:35
2023-07-25T15:00:35
16,391,713
15
5
Apache-2.0
false
2023-05-04T12:52:12
2014-01-30T21:36:25
2023-05-04T12:49:34
2023-05-04T12:52:11
548
10
7
2
Java
false
false
package com.github.approval; /* * #%L * approval * %% * Copyright (C) 2014 Nikolavp * %% * 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. * #L% */ import com.github.approval.reporters.Reporters; import com.github.approval.reporters.StringEqualsJunitReporter; import com.github.approval.reporters.SystemPropertyReporter; import java.nio.file.Path; /** * Approvals for primitive types. * <p>This is a convenient static utility class that is the first thing to try when you want to use the library. If you happen to be lucky and * need to verify only primitive types or array of primitive types then we got you covered. * </p> */ public final class Approvals { private static Reporter reporter = Reporters.firstWorking( SystemPropertyReporter.getInstance("default.approval.reporter"), new StringEqualsJunitReporter(), Reporters.console(), Reporters.fileLauncher() ); private Approvals() { } /** * An overload for verifying int arrays. This will call the approval object with proper reporter and use the path for verification. * * @param ints the int array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(int[] ints, Path path) { Approval.of(int[].class) .withReporter(reporter) .build() .verify(ints, path); } /** * An overload for verifying byte arrays. This will call the approval object with proper reporter and use the path for verification. * * @param bytes the byte array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(byte[] bytes, Path path) { Approval.of(byte[].class) .withReporter(reporter) .build() .verify(bytes, path); } /** * An overload for verifying short arrays. This will call the approval object with proper reporter and use the path for verification. * * @param shorts the short array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(short[] shorts, Path path) { Approval.of(short[].class) .withReporter(reporter) .build() .verify(shorts, path); } /** * An overload for verifying long arrays. This will call the approval object with proper reporter and use the path for verification. * * @param longs the long array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(long[] longs, Path path) { Approval.of(long[].class) .withReporter(reporter) .build() .verify(longs, path); } /** * An overload for verifying float arrays. This will call the approval object with proper reporter and use the path for verification. * * @param floats the float array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(float[] floats, Path path) { Approval.of(float[].class) .withReporter(reporter) .build() .verify(floats, path); } /** * An overload for verifying double arrays. This will call the approval object with proper reporter and use the path for verification. * * @param doubles the double array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(double[] doubles, Path path) { Approval.of(double[].class) .withReporter(reporter) .build() .verify(doubles, path); } /** * An overload for verifying boolean arrays. This will call the approval object with proper reporter and use the path for verification. * * @param booleans the boolean array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(boolean[] booleans, Path path) { Approval.of(boolean[].class) .withReporter(reporter) .build() .verify(booleans, path); } /** * An overload for verifying char arrays. This will call the approval object with proper reporter and use the path for verification. * * @param chars the char array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(char[] chars, Path path) { Approval.of(char[].class) .withReporter(reporter) .build() .verify(chars, path); } /** * An overload for verifying string arrays. This will call the approval object with proper reporter and use the path for verification. * * @param strings the string array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(String[] strings, Path path) { Approval.of(String[].class) .withReporter(reporter) .build() .verify(strings, path); } /** * An overload for verifying a single byte value. This will call the approval object with proper reporter and use the path for verification. * * @param value the byte that needs to be verified * @param path the path in which to store the approval file */ public static void verify(byte value, Path path) { Approval.of(byte.class) .withReporter(reporter) .build() .verify(value, path); } /** * An overload for verifying a single short value. This will call the approval object with proper reporter and use the path for verification. * * @param value the short that needs to be verified * @param path the path in which to store the approval file */ public static void verify(short value, Path path) { Approval.of(short.class) .withReporter(reporter) .build() .verify(value, path); } /** * An overload for verifying a single int value. This will call the approval object with proper reporter and use the path for verification. * * @param value the int that needs to be verified * @param path the path in which to store the approval file */ public static void verify(int value, Path path) { Approval.of(int.class) .withReporter(reporter) .build() .verify(value, path); } /** * An overload for verifying a single long value. This will call the approval object with proper reporter and use the path for verification. * * @param value the long that needs to be verified * @param path the path in which to store the approval file */ public static void verify(long value, Path path) { Approval.of(long.class) .withReporter(reporter) .build() .verify(value, path); } /** * An overload for verifying a single float value. This will call the approval object with proper reporter and use the path for verification. * * @param value the float that needs to be verified * @param path the path in which to store the approval file */ public static void verify(float value, Path path) { Approval.of(float.class) .withReporter(reporter) .build() .verify(value, path); } /** * An overload for verifying a single double value. This will call the approval object with proper reporter and use the path for verification. * * @param value the double that needs to be verified * @param path the path in which to store the approval file */ public static void verify(double value, Path path) { Approval.of(double.class) .withReporter(reporter) .build() .verify(value, path); } /** * An overload for verifying a single boolean value. This will call the approval object with proper reporter and use the path for verification. * * @param value the boolean that needs to be verified * @param path the path in which to store the approval file */ public static void verify(boolean value, Path path) { Approval.of(boolean.class) .withReporter(reporter) .build() .verify(value, path); } /** * An overload for verifying a single char value. This will call the approval object with proper reporter and use the path for verification. * * @param value the char that needs to be verified * @param path the path in which to store the approval file */ public static void verify(char value, Path path) { Approval.of(char.class) .withReporter(reporter) .build() .verify(value, path); } /** * An overload for verifying a single String value. This will call the approval object with proper reporter and use the path for verification. * * @param value the String that needs to be verified * @param path the path in which to store the approval file */ public static void verify(String value, Path path) { Approval.of(String.class) .withReporter(reporter) .build() .verify(value, path); } /** * Sets the global static reporter that will be used by the utility. * * @param reporterToUse the reporter to use. Please make this portable and use {@link Reporters#firstWorking(Reporter...)} */ public static void setReporter(Reporter reporterToUse) { reporter = reporterToUse; } }
UTF-8
Java
10,634
java
Approvals.java
Java
[ { "context": "\n/*\n * #%L\n * approval\n * %%\n * Copyright (C) 2014 Nikolavp\n * %%\n * Licensed under the Apache License, Versi", "end": 88, "score": 0.9997064471244812, "start": 80, "tag": "NAME", "value": "Nikolavp" } ]
null
[]
package com.github.approval; /* * #%L * approval * %% * Copyright (C) 2014 Nikolavp * %% * 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. * #L% */ import com.github.approval.reporters.Reporters; import com.github.approval.reporters.StringEqualsJunitReporter; import com.github.approval.reporters.SystemPropertyReporter; import java.nio.file.Path; /** * Approvals for primitive types. * <p>This is a convenient static utility class that is the first thing to try when you want to use the library. If you happen to be lucky and * need to verify only primitive types or array of primitive types then we got you covered. * </p> */ public final class Approvals { private static Reporter reporter = Reporters.firstWorking( SystemPropertyReporter.getInstance("default.approval.reporter"), new StringEqualsJunitReporter(), Reporters.console(), Reporters.fileLauncher() ); private Approvals() { } /** * An overload for verifying int arrays. This will call the approval object with proper reporter and use the path for verification. * * @param ints the int array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(int[] ints, Path path) { Approval.of(int[].class) .withReporter(reporter) .build() .verify(ints, path); } /** * An overload for verifying byte arrays. This will call the approval object with proper reporter and use the path for verification. * * @param bytes the byte array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(byte[] bytes, Path path) { Approval.of(byte[].class) .withReporter(reporter) .build() .verify(bytes, path); } /** * An overload for verifying short arrays. This will call the approval object with proper reporter and use the path for verification. * * @param shorts the short array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(short[] shorts, Path path) { Approval.of(short[].class) .withReporter(reporter) .build() .verify(shorts, path); } /** * An overload for verifying long arrays. This will call the approval object with proper reporter and use the path for verification. * * @param longs the long array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(long[] longs, Path path) { Approval.of(long[].class) .withReporter(reporter) .build() .verify(longs, path); } /** * An overload for verifying float arrays. This will call the approval object with proper reporter and use the path for verification. * * @param floats the float array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(float[] floats, Path path) { Approval.of(float[].class) .withReporter(reporter) .build() .verify(floats, path); } /** * An overload for verifying double arrays. This will call the approval object with proper reporter and use the path for verification. * * @param doubles the double array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(double[] doubles, Path path) { Approval.of(double[].class) .withReporter(reporter) .build() .verify(doubles, path); } /** * An overload for verifying boolean arrays. This will call the approval object with proper reporter and use the path for verification. * * @param booleans the boolean array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(boolean[] booleans, Path path) { Approval.of(boolean[].class) .withReporter(reporter) .build() .verify(booleans, path); } /** * An overload for verifying char arrays. This will call the approval object with proper reporter and use the path for verification. * * @param chars the char array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(char[] chars, Path path) { Approval.of(char[].class) .withReporter(reporter) .build() .verify(chars, path); } /** * An overload for verifying string arrays. This will call the approval object with proper reporter and use the path for verification. * * @param strings the string array that needs to be verified * @param path the path in which to store the approval file */ public static void verify(String[] strings, Path path) { Approval.of(String[].class) .withReporter(reporter) .build() .verify(strings, path); } /** * An overload for verifying a single byte value. This will call the approval object with proper reporter and use the path for verification. * * @param value the byte that needs to be verified * @param path the path in which to store the approval file */ public static void verify(byte value, Path path) { Approval.of(byte.class) .withReporter(reporter) .build() .verify(value, path); } /** * An overload for verifying a single short value. This will call the approval object with proper reporter and use the path for verification. * * @param value the short that needs to be verified * @param path the path in which to store the approval file */ public static void verify(short value, Path path) { Approval.of(short.class) .withReporter(reporter) .build() .verify(value, path); } /** * An overload for verifying a single int value. This will call the approval object with proper reporter and use the path for verification. * * @param value the int that needs to be verified * @param path the path in which to store the approval file */ public static void verify(int value, Path path) { Approval.of(int.class) .withReporter(reporter) .build() .verify(value, path); } /** * An overload for verifying a single long value. This will call the approval object with proper reporter and use the path for verification. * * @param value the long that needs to be verified * @param path the path in which to store the approval file */ public static void verify(long value, Path path) { Approval.of(long.class) .withReporter(reporter) .build() .verify(value, path); } /** * An overload for verifying a single float value. This will call the approval object with proper reporter and use the path for verification. * * @param value the float that needs to be verified * @param path the path in which to store the approval file */ public static void verify(float value, Path path) { Approval.of(float.class) .withReporter(reporter) .build() .verify(value, path); } /** * An overload for verifying a single double value. This will call the approval object with proper reporter and use the path for verification. * * @param value the double that needs to be verified * @param path the path in which to store the approval file */ public static void verify(double value, Path path) { Approval.of(double.class) .withReporter(reporter) .build() .verify(value, path); } /** * An overload for verifying a single boolean value. This will call the approval object with proper reporter and use the path for verification. * * @param value the boolean that needs to be verified * @param path the path in which to store the approval file */ public static void verify(boolean value, Path path) { Approval.of(boolean.class) .withReporter(reporter) .build() .verify(value, path); } /** * An overload for verifying a single char value. This will call the approval object with proper reporter and use the path for verification. * * @param value the char that needs to be verified * @param path the path in which to store the approval file */ public static void verify(char value, Path path) { Approval.of(char.class) .withReporter(reporter) .build() .verify(value, path); } /** * An overload for verifying a single String value. This will call the approval object with proper reporter and use the path for verification. * * @param value the String that needs to be verified * @param path the path in which to store the approval file */ public static void verify(String value, Path path) { Approval.of(String.class) .withReporter(reporter) .build() .verify(value, path); } /** * Sets the global static reporter that will be used by the utility. * * @param reporterToUse the reporter to use. Please make this portable and use {@link Reporters#firstWorking(Reporter...)} */ public static void setReporter(Reporter reporterToUse) { reporter = reporterToUse; } }
10,634
0.625635
0.624882
288
35.923611
36.376709
147
false
false
0
0
0
0
0
0
0.239583
false
false
9
fcff3e7173908f14540675adab316872ef2a0722
28,475,633,227,411
a442007cf643f0059f8484c47522fe67237169af
/RestApiSpringBoot/src/main/java/com/nirmal/springbootrest/service/IBookService.java
a9b7b436cc24f2dfa3d904ae98eaa5cdeb8a3019
[]
no_license
NirmalBalasooriya/RestApiSpringBoot
https://github.com/NirmalBalasooriya/RestApiSpringBoot
acdd076c3e44868b09cffb6ea6c1ad3c28fecd73
089ed572c444ac41d1919d34bc4b031944e1634d
refs/heads/master
2021-08-19T18:19:23.378000
2018-12-14T16:13:06
2018-12-14T16:13:06
161,021,390
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nirmal.springbootrest.service; import org.springframework.stereotype.Component; import com.nirmal.springbootrest.model.Book; /** * BookService interfacce with abstract methods about Book Service * * @author Nirmal Balasooriya * */ @Component public interface IBookService { /** * to save or update the book on database * * @param book * @return bookIsbm */ public String saveOrUpdateBook(Book book); /** * to retrive the book from database * * @param String String * @return book */ public Book getBook(String isbm); /** * Delete Book on database * @param isbm */ public void deleteBook(String isbm); }
UTF-8
Java
697
java
IBookService.java
Java
[ { "context": "stract methods about Book Service\r\n * \r\n * @author Nirmal Balasooriya\r\n *\r\n */\r\n@Component\r\npublic interface IBookServi", "end": 253, "score": 0.9998903274536133, "start": 235, "tag": "NAME", "value": "Nirmal Balasooriya" } ]
null
[]
package com.nirmal.springbootrest.service; import org.springframework.stereotype.Component; import com.nirmal.springbootrest.model.Book; /** * BookService interfacce with abstract methods about Book Service * * @author <NAME> * */ @Component public interface IBookService { /** * to save or update the book on database * * @param book * @return bookIsbm */ public String saveOrUpdateBook(Book book); /** * to retrive the book from database * * @param String String * @return book */ public Book getBook(String isbm); /** * Delete Book on database * @param isbm */ public void deleteBook(String isbm); }
685
0.66571
0.66571
37
16.891891
17.845861
66
false
false
0
0
0
0
0
0
0.702703
false
false
9
9e6e719b2dc794ac7b5df3ae17655a495f9530d6
30,829,275,272,143
0cda232f9c2280626b59c5e9de6804bbd4e781a6
/Project/app/src/main/java/project/cis350/upenn/edu/project/Goal.java
7e889ca20625f5f6f6a1f45060ef921fe471bb5d
[]
no_license
jtomli/CIS350LifeStats
https://github.com/jtomli/CIS350LifeStats
a709fe4cc61d914ee11ae4f0af678794215c14af
c235d166958b6dca4b6fa8ee77b800844a6fa998
refs/heads/master
2021-01-21T14:23:34.602000
2017-05-01T00:38:20
2017-05-01T00:38:20
95,273,425
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package project.cis350.upenn.edu.project; import java.io.Serializable; import java.util.Calendar; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; /** * Goal contains a name, a reason for that goal, and a set of events for which * that goal takes place */ public class Goal implements Serializable, Comparable<Goal> { private String name; protected Set<Event> events; private String reason = ""; public Goal(String name) { this.name = name; events = new TreeSet<>(); } public String getName() { return name; } public void addEvent(Event e) { events.add(e); } public void removeEvent(Event e) { events.remove(e); } /** * Calculates percentage of goal events that have been completed. * @return ratio of completed events to total events */ public double getTotalCompletion() { int total = 0; int completed = 0; for (Event e : events) { total++; if (e.isCompleted()) completed++; } if (total == 0) return 1.0; else return (double) completed / (double) total; } /** * Calculates percentage of goal events that have been completed and converts result into a * String percentage with at most 4 digits. * @return percentage of completed events with respect to total events */ public String getTotalCompletionPercent() { String s = "" + getTotalCompletion()*100; if (s.length() > 5) { s = s.substring(0, 5); } return s + "%"; } /** * Calculates percentage of goal events that have been completed during the current month. * @param month is the current month as an int * @return ratio of completed events this month to total events this month */ public double getMonthlyCompletion(int month) { int total = 0; int completed = 0; for (Event e : events) { if (e.getStart().get(Calendar.MONTH) == month) { total++; if (e.isCompleted()) { completed++; } } } if (total == 0) return 1.0; else return (double) completed / (double) total; } /** * Calculates percentage of goal events that have been completed during the current month and * converts the result into a String percentage with at most 4 digits. * @param month is the current month as an int * @return percentage of completed events with respect to total events */ public String getMonthlyCompletionPercent(int month) { String s = "" + getMonthlyCompletion(month)*100; if (s.length() > 5) { s = s.substring(0, 5); } return s + "%"; } public void setReason(String reason) { this.reason = reason; } public void removeReason(String reason) { this.reason = ""; } public String getReason() { return reason; } public Set<Event> getEvents() { return Collections.unmodifiableSet(events); } @Override public String toString() { return name + "\n \t Progress: " + getTotalCompletionPercent(); } @Override public int compareTo(Goal o) { return name.compareTo(o.getName()); } }
UTF-8
Java
3,323
java
Goal.java
Java
[]
null
[]
package project.cis350.upenn.edu.project; import java.io.Serializable; import java.util.Calendar; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; /** * Goal contains a name, a reason for that goal, and a set of events for which * that goal takes place */ public class Goal implements Serializable, Comparable<Goal> { private String name; protected Set<Event> events; private String reason = ""; public Goal(String name) { this.name = name; events = new TreeSet<>(); } public String getName() { return name; } public void addEvent(Event e) { events.add(e); } public void removeEvent(Event e) { events.remove(e); } /** * Calculates percentage of goal events that have been completed. * @return ratio of completed events to total events */ public double getTotalCompletion() { int total = 0; int completed = 0; for (Event e : events) { total++; if (e.isCompleted()) completed++; } if (total == 0) return 1.0; else return (double) completed / (double) total; } /** * Calculates percentage of goal events that have been completed and converts result into a * String percentage with at most 4 digits. * @return percentage of completed events with respect to total events */ public String getTotalCompletionPercent() { String s = "" + getTotalCompletion()*100; if (s.length() > 5) { s = s.substring(0, 5); } return s + "%"; } /** * Calculates percentage of goal events that have been completed during the current month. * @param month is the current month as an int * @return ratio of completed events this month to total events this month */ public double getMonthlyCompletion(int month) { int total = 0; int completed = 0; for (Event e : events) { if (e.getStart().get(Calendar.MONTH) == month) { total++; if (e.isCompleted()) { completed++; } } } if (total == 0) return 1.0; else return (double) completed / (double) total; } /** * Calculates percentage of goal events that have been completed during the current month and * converts the result into a String percentage with at most 4 digits. * @param month is the current month as an int * @return percentage of completed events with respect to total events */ public String getMonthlyCompletionPercent(int month) { String s = "" + getMonthlyCompletion(month)*100; if (s.length() > 5) { s = s.substring(0, 5); } return s + "%"; } public void setReason(String reason) { this.reason = reason; } public void removeReason(String reason) { this.reason = ""; } public String getReason() { return reason; } public Set<Event> getEvents() { return Collections.unmodifiableSet(events); } @Override public String toString() { return name + "\n \t Progress: " + getTotalCompletionPercent(); } @Override public int compareTo(Goal o) { return name.compareTo(o.getName()); } }
3,323
0.604875
0.59675
117
27.410257
24.255461
97
false
false
0
0
0
0
0
0
0.376068
false
false
9
3988c95d166f1bf0451ce8dc7be70f92471f9188
17,068,200,050,936
96a15c1da471aea868fd4ab23795a829ecab504d
/src/TamGiacVuong.java
a182a39f167d7568adba3d251db325db28c8766d
[]
no_license
baotoan-codegym/songuyentobehon100
https://github.com/baotoan-codegym/songuyentobehon100
acb850604ab19c91e715d0d9baae46f677b59903
17cc7f88161a8c7cc32fb6135ac0afa6486f71ce
refs/heads/master
2023-04-06T22:03:49.012000
2021-04-05T08:08:35
2021-04-05T08:08:35
354,691,231
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package PACKAGE_NAME;public class TamGiacVuong { }
UTF-8
Java
51
java
TamGiacVuong.java
Java
[]
null
[]
package PACKAGE_NAME;public class TamGiacVuong { }
51
0.803922
0.803922
2
24.5
23.5
48
false
false
0
0
0
0
0
0
0.5
false
false
9
5d852491fb1b4f75eca2245a2ba7a8e0dee764ca
24,550,033,105,883
233e54a5161f91c46b0bcf86475888966006f26c
/app/src/main/java/com/singgo/cn/timewindows/mvp/biz/impl/DbMovieBiz.java
ef81dec9c8a50e260cc81259978d58bd471a7f87
[]
no_license
tigersshi/timewindows
https://github.com/tigersshi/timewindows
758b9472951554ebda94cf654b1627970117092a
797ef1977933650c4a57d213f01c5a5d23941f93
refs/heads/master
2017-05-11T13:39:33.625000
2017-02-19T06:55:08
2017-02-19T06:55:08
82,668,238
1
1
null
true
2017-02-21T10:42:07
2017-02-21T10:42:07
2017-02-19T06:56:19
2017-02-19T06:55:37
1,504
0
0
0
null
null
null
package com.singgo.cn.timewindows.mvp.biz.impl; import android.util.Log; import com.singgo.cn.timewindows.mvp.bean.Celebrity; import com.singgo.cn.timewindows.mvp.bean.MovieList; import com.singgo.cn.timewindows.mvp.bean.Subjects; import com.singgo.cn.timewindows.mvp.view.ICastsInfoView; import com.singgo.cn.timewindows.mvp.view.IMovieItemView; import com.singgo.cn.timewindows.mvp.view.IMovieView; import com.singgo.cn.timewindows.retrofit.ApiFactory; import java.io.IOException; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by hxz on 2016/12/8. */ public class DbMovieBiz { public void getInTheaters(final IMovieView view,final int type){ Call<MovieList>call = ApiFactory.getDBApi().getInTheaters(view.count(),view.start()); call.enqueue(new Callback<MovieList>() { @Override public void onResponse(Call<MovieList> call, Response<MovieList> response) { view.getMovieList(response.body(),type); } @Override public void onFailure(Call<MovieList> call, Throwable t) { } }); } public void getComingSong(final IMovieView view,final int type){ Call<MovieList>call = ApiFactory.getDBApi().getComingSoon(view.count(),view.start()); call.enqueue(new Callback<MovieList>() { @Override public void onResponse(Call<MovieList> call, Response<MovieList> response) { view.getMovieList(response.body(),type); } @Override public void onFailure(Call<MovieList> call, Throwable t) { } }); } public void getTop250(final IMovieView view,final int type){ Call<MovieList>call = ApiFactory.getDBApi().getTop250(view.count(),view.start()); call.enqueue(new Callback<MovieList>() { @Override public void onResponse(Call<MovieList> call, Response<MovieList> response) { view.getMovieList(response.body(),type); } @Override public void onFailure(Call<MovieList> call, Throwable t) { } }); } /** * 得到单个电影信息 */ public void getMovie(final IMovieItemView view){ Call<Subjects>call = ApiFactory.getDBApi().getMovie(view.getMovieId()); call.enqueue(new Callback<Subjects>() { @Override public void onResponse(Call<Subjects> call, Response<Subjects> response) { view.getMovieItem(response.body()); } @Override public void onFailure(Call<Subjects> call, Throwable t) { } }); } /** * 得到单个演员信息 * @param view */ public void getCelebrity(final ICastsInfoView view){ Call<Celebrity>call = ApiFactory.getDBApi().getCelebrity(view.getCastsId()); call.enqueue(new Callback<Celebrity>() { @Override public void onResponse(Call<Celebrity> call, Response<Celebrity> response) { view.getCastsInfo(response.body()); } @Override public void onFailure(Call<Celebrity> call, Throwable t) { } }); } public void getSearchList(final IMovieView view){ Call<MovieList>call = ApiFactory.getDBApi().getSearchList(view.getSearch(),view.count(),view.start()); call.enqueue(new Callback<MovieList>() { @Override public void onResponse(Call<MovieList> call, Response<MovieList> response) { view.getMovieList(response.body(),-1); } @Override public void onFailure(Call<MovieList> call, Throwable t) { } }); } public void getTagList(final IMovieView view){ Call<MovieList>call = ApiFactory.getDBApi().getTagList(view.getTags(),view.count(),view.start()); call.enqueue(new Callback<MovieList>() { @Override public void onResponse(Call<MovieList> call, Response<MovieList> response) { view.getMovieList(response.body(),-1); } @Override public void onFailure(Call<MovieList> call, Throwable t) { } }); } }
UTF-8
Java
4,483
java
DbMovieBiz.java
Java
[ { "context": "\r\nimport retrofit2.Response;\r\n\r\n/**\r\n * Created by hxz on 2016/12/8.\r\n */\r\n\r\npublic class DbMovieBiz {\r\n", "end": 635, "score": 0.9996652603149414, "start": 632, "tag": "USERNAME", "value": "hxz" } ]
null
[]
package com.singgo.cn.timewindows.mvp.biz.impl; import android.util.Log; import com.singgo.cn.timewindows.mvp.bean.Celebrity; import com.singgo.cn.timewindows.mvp.bean.MovieList; import com.singgo.cn.timewindows.mvp.bean.Subjects; import com.singgo.cn.timewindows.mvp.view.ICastsInfoView; import com.singgo.cn.timewindows.mvp.view.IMovieItemView; import com.singgo.cn.timewindows.mvp.view.IMovieView; import com.singgo.cn.timewindows.retrofit.ApiFactory; import java.io.IOException; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by hxz on 2016/12/8. */ public class DbMovieBiz { public void getInTheaters(final IMovieView view,final int type){ Call<MovieList>call = ApiFactory.getDBApi().getInTheaters(view.count(),view.start()); call.enqueue(new Callback<MovieList>() { @Override public void onResponse(Call<MovieList> call, Response<MovieList> response) { view.getMovieList(response.body(),type); } @Override public void onFailure(Call<MovieList> call, Throwable t) { } }); } public void getComingSong(final IMovieView view,final int type){ Call<MovieList>call = ApiFactory.getDBApi().getComingSoon(view.count(),view.start()); call.enqueue(new Callback<MovieList>() { @Override public void onResponse(Call<MovieList> call, Response<MovieList> response) { view.getMovieList(response.body(),type); } @Override public void onFailure(Call<MovieList> call, Throwable t) { } }); } public void getTop250(final IMovieView view,final int type){ Call<MovieList>call = ApiFactory.getDBApi().getTop250(view.count(),view.start()); call.enqueue(new Callback<MovieList>() { @Override public void onResponse(Call<MovieList> call, Response<MovieList> response) { view.getMovieList(response.body(),type); } @Override public void onFailure(Call<MovieList> call, Throwable t) { } }); } /** * 得到单个电影信息 */ public void getMovie(final IMovieItemView view){ Call<Subjects>call = ApiFactory.getDBApi().getMovie(view.getMovieId()); call.enqueue(new Callback<Subjects>() { @Override public void onResponse(Call<Subjects> call, Response<Subjects> response) { view.getMovieItem(response.body()); } @Override public void onFailure(Call<Subjects> call, Throwable t) { } }); } /** * 得到单个演员信息 * @param view */ public void getCelebrity(final ICastsInfoView view){ Call<Celebrity>call = ApiFactory.getDBApi().getCelebrity(view.getCastsId()); call.enqueue(new Callback<Celebrity>() { @Override public void onResponse(Call<Celebrity> call, Response<Celebrity> response) { view.getCastsInfo(response.body()); } @Override public void onFailure(Call<Celebrity> call, Throwable t) { } }); } public void getSearchList(final IMovieView view){ Call<MovieList>call = ApiFactory.getDBApi().getSearchList(view.getSearch(),view.count(),view.start()); call.enqueue(new Callback<MovieList>() { @Override public void onResponse(Call<MovieList> call, Response<MovieList> response) { view.getMovieList(response.body(),-1); } @Override public void onFailure(Call<MovieList> call, Throwable t) { } }); } public void getTagList(final IMovieView view){ Call<MovieList>call = ApiFactory.getDBApi().getTagList(view.getTags(),view.count(),view.start()); call.enqueue(new Callback<MovieList>() { @Override public void onResponse(Call<MovieList> call, Response<MovieList> response) { view.getMovieList(response.body(),-1); } @Override public void onFailure(Call<MovieList> call, Throwable t) { } }); } }
4,483
0.5929
0.588632
133
31.466166
29.738344
110
false
false
0
0
0
0
0
0
0.481203
false
false
9
147e8fb6154bfdc747e78cd407049565cf1ad561
17,918,603,559,098
78178d5859a66a48608768c5ec2d9cc5f987dd19
/app/src/main/java/com/ksl/kevinlee/claremontmenu/adapters/SchoolAdapterTest.java
5b3e8c69ce1c0ac86d6fd48629d98d961fb51e48
[]
no_license
kevinsangholee/ClaremontMenu
https://github.com/kevinsangholee/ClaremontMenu
01731dde9aea74706500377baa58589054c014c6
ef3e3fe64c46f916dafce8908b8b6502d29e0fde
refs/heads/master
2021-01-25T05:43:53.960000
2017-04-14T20:42:03
2017-04-14T20:42:03
80,667,073
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ksl.kevinlee.claremontmenu.adapters; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.ksl.kevinlee.claremontmenu.data.network.DBConfig; import com.ksl.kevinlee.claremontmenu.screen.SchoolFragment; /** * Created by kevinlee on 12/23/16. */ public class SchoolAdapterTest extends FragmentPagerAdapter { public static final String DINING_HALL_KEY = "dining_hall"; private String tabTitles[] = {"Frank", "Frary", "Oldenborg", "CMC", "Scripps", "Pitzer", "Mudd"}; int school; public SchoolAdapterTest(FragmentManager fm, int school) { super(fm); this.school = school; } @Override public Fragment getItem(int position) { Bundle bundle = new Bundle(); SchoolFragment f = new SchoolFragment(); switch(position) { case 0: bundle.putInt(DINING_HALL_KEY, school); f.setArguments(bundle); return f; case 1: bundle.putInt(DINING_HALL_KEY, DBConfig.FRARY); f.setArguments(bundle); return f; case 2: bundle.putInt(DINING_HALL_KEY, DBConfig.OLDENBORG); f.setArguments(bundle); return f; case 3: bundle.putInt(DINING_HALL_KEY, DBConfig.CMC); f.setArguments(bundle); return f; case 4: bundle.putInt(DINING_HALL_KEY, DBConfig.SCRIPPS); f.setArguments(bundle); return f; default: return null; } } @Override public int getCount() { return 5; } @Override public CharSequence getPageTitle(int position) { return tabTitles[position]; } }
UTF-8
Java
1,915
java
SchoolAdapterTest.java
Java
[ { "context": "montmenu.screen.SchoolFragment;\n\n/**\n * Created by kevinlee on 12/23/16.\n */\n\npublic class SchoolAdapterTest ", "end": 365, "score": 0.9996423721313477, "start": 357, "tag": "USERNAME", "value": "kevinlee" }, { "context": " public static final String DINING_HALL_KEY = \"dining_hall\";\n private String tabTitles[] = {\"Frank\", \"Fra", "end": 508, "score": 0.6700553894042969, "start": 498, "tag": "KEY", "value": "ining_hall" }, { "context": "\"dining_hall\";\n private String tabTitles[] = {\"Frank\", \"Frary\", \"Oldenborg\", \"CMC\", \"Scripps\", \"Pitzer", "end": 551, "score": 0.993230402469635, "start": 546, "tag": "NAME", "value": "Frank" }, { "context": "all\";\n private String tabTitles[] = {\"Frank\", \"Frary\", \"Oldenborg\", \"CMC\", \"Scripps\", \"Pitzer\", \"Mudd\"", "end": 560, "score": 0.9400311708450317, "start": 555, "tag": "NAME", "value": "Frary" }, { "context": "\"Frank\", \"Frary\", \"Oldenborg\", \"CMC\", \"Scripps\", \"Pitzer\", \"Mudd\"};\n int school;\n\n public SchoolAdap", "end": 601, "score": 0.8623034358024597, "start": 595, "tag": "NAME", "value": "Pitzer" }, { "context": "ary\", \"Oldenborg\", \"CMC\", \"Scripps\", \"Pitzer\", \"Mudd\"};\n int school;\n\n public SchoolAdapterTest(", "end": 609, "score": 0.529971718788147, "start": 607, "tag": "NAME", "value": "dd" } ]
null
[]
package com.ksl.kevinlee.claremontmenu.adapters; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.ksl.kevinlee.claremontmenu.data.network.DBConfig; import com.ksl.kevinlee.claremontmenu.screen.SchoolFragment; /** * Created by kevinlee on 12/23/16. */ public class SchoolAdapterTest extends FragmentPagerAdapter { public static final String DINING_HALL_KEY = "dining_hall"; private String tabTitles[] = {"Frank", "Frary", "Oldenborg", "CMC", "Scripps", "Pitzer", "Mudd"}; int school; public SchoolAdapterTest(FragmentManager fm, int school) { super(fm); this.school = school; } @Override public Fragment getItem(int position) { Bundle bundle = new Bundle(); SchoolFragment f = new SchoolFragment(); switch(position) { case 0: bundle.putInt(DINING_HALL_KEY, school); f.setArguments(bundle); return f; case 1: bundle.putInt(DINING_HALL_KEY, DBConfig.FRARY); f.setArguments(bundle); return f; case 2: bundle.putInt(DINING_HALL_KEY, DBConfig.OLDENBORG); f.setArguments(bundle); return f; case 3: bundle.putInt(DINING_HALL_KEY, DBConfig.CMC); f.setArguments(bundle); return f; case 4: bundle.putInt(DINING_HALL_KEY, DBConfig.SCRIPPS); f.setArguments(bundle); return f; default: return null; } } @Override public int getCount() { return 5; } @Override public CharSequence getPageTitle(int position) { return tabTitles[position]; } }
1,915
0.586945
0.579112
68
27.161764
22.864441
101
false
false
0
0
0
0
0
0
0.647059
false
false
9
d76b55c086ce344e462cc1c48c76c4011efb0099
20,864,951,194,113
846d398ebe695f3db25f9fe78a554874539c85a3
/MackCommerce-war/src/java/br/mack/controller/command/FactoryMethod.java
6a7517284a1c3fbc2ae8c86f934394fdc50700ca
[]
no_license
Lucas7490/MackCommerce
https://github.com/Lucas7490/MackCommerce
2c392ae8187c1591e5ebb11b2bae88abfb109407
bb793cca788294252bae3e63d7526900440cca9c
refs/heads/master
2016-09-06T19:16:01.587000
2015-04-07T17:10:51
2015-04-07T17:10:51
32,899,296
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.mack.controller.command; /** * * @author Grupo 01 - Tema: Loja virtual */ public class FactoryMethod { public Command getCommand() {return null;} public Command findCommand() {return null;} }
UTF-8
Java
223
java
FactoryMethod.java
Java
[ { "context": "e br.mack.controller.command;\r\n/**\r\n *\r\n * @author Grupo 01 - Tema: Loja virtual\r\n */\r\npublic class FactoryMe", "end": 65, "score": 0.9946966767311096, "start": 57, "tag": "NAME", "value": "Grupo 01" } ]
null
[]
package br.mack.controller.command; /** * * @author <NAME> - Tema: Loja virtual */ public class FactoryMethod { public Command getCommand() {return null;} public Command findCommand() {return null;} }
221
0.668161
0.659193
9
22.777779
19.112404
47
false
false
0
0
0
0
0
0
0.333333
false
false
9
3b93d4664e8a1fca3a061148c0c4fe1b630c21e9
4,758,823,775,192
9580b336230d8b459bff8e71a808f89a8b9b4e72
/Dispatch/app/src/main/java/io/dispatch/dispatch/CrashService.java
6a5e1b78db432d3e1896b3e118c0308abe60a525
[]
no_license
GetDispatch/Dispatch-android
https://github.com/GetDispatch/Dispatch-android
2fe0b9f1b3a394ddc0518220d4032b5d5b44a0c6
0215b8f44397b69682f566eaa2f6d34941c06d07
refs/heads/master
2016-09-05T09:55:15.686000
2015-07-31T20:31:06
2015-07-31T20:31:06
35,744,655
1
1
null
false
2015-05-17T18:36:53
2015-05-16T23:47:41
2015-05-17T12:44:28
2015-05-17T18:36:53
0
1
0
0
Java
null
null
package io.dispatch.dispatch; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.Service; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.DatabaseUtils; import android.hardware.Sensor; import android.hardware.SensorManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.media.MediaPlayer; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.os.IBinder; import android.os.Vibrator; import android.util.Log; import com.parse.ParsePush; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Created by Daniel on 5/16/2015. */ public class CrashService extends Service { private CrashListener listener; private LocationManager locationManager; private LocationListener locationListener; private float currentSpeed=0; private float pastSpeed=0; @Override public int onStartCommand(Intent intent, int flags, int startId) { if(intent != null) { if (intent.getExtras().containsKey("listener")) { listener = (CrashListener) intent.getExtras().get("listener"); } checkCrash(getApplicationContext()); // listener.onPossibleCrash(this, ActivityManager.getActivity()); } return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { return null; } public void checkCrash(final Context context){ locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { public void onLocationChanged(Location location) { // Called when a new location is found by the network location provider. Log.d("Long/Lat", location.getLatitude() + " " + location.getLongitude()); Log.d("Speed",location.getSpeed()+""); Log.d("Past Speed: ", location.getSpeed() +""); currentSpeed = location.getSpeed(); Log.d("Change in velocity",currentSpeed-pastSpeed + "" ); // We have a crash, value should eventually become calculated if(currentSpeed - pastSpeed < -13) { listener.onPossibleCrash(CrashService.this, ActivityManager.getActivity()); // Send push ParsePush push = new ParsePush(); push.setChannel("crash"); push.setMessage("A person may be hurt at " + location.getLatitude() + " latitude, " + location.getLongitude() + " longitude"); push.sendInBackground(); stopLocationListener(); } pastSpeed = currentSpeed; } public void onStatusChanged(String provider, int status, Bundle extras) { Log.d("Status Changed", "has been enabled"); } public void onProviderEnabled(String provider) { Log.d("Enabled", "has been enabled"); } public void onProviderDisabled(String provider) { Log.d("Disabled happened", "has been enabled"); } }; startLocationListener(); } public void stopLocationListener() { locationManager.removeUpdates(locationListener); } public void startLocationListener() { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); } }
UTF-8
Java
3,862
java
CrashService.java
Java
[ { "context": " java.util.concurrent.TimeUnit;\n\n/**\n * Created by Daniel on 5/16/2015.\n */\npublic class CrashService exten", "end": 921, "score": 0.9785194396972656, "start": 915, "tag": "NAME", "value": "Daniel" } ]
null
[]
package io.dispatch.dispatch; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.Service; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.DatabaseUtils; import android.hardware.Sensor; import android.hardware.SensorManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.media.MediaPlayer; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.os.IBinder; import android.os.Vibrator; import android.util.Log; import com.parse.ParsePush; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Created by Daniel on 5/16/2015. */ public class CrashService extends Service { private CrashListener listener; private LocationManager locationManager; private LocationListener locationListener; private float currentSpeed=0; private float pastSpeed=0; @Override public int onStartCommand(Intent intent, int flags, int startId) { if(intent != null) { if (intent.getExtras().containsKey("listener")) { listener = (CrashListener) intent.getExtras().get("listener"); } checkCrash(getApplicationContext()); // listener.onPossibleCrash(this, ActivityManager.getActivity()); } return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { return null; } public void checkCrash(final Context context){ locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { public void onLocationChanged(Location location) { // Called when a new location is found by the network location provider. Log.d("Long/Lat", location.getLatitude() + " " + location.getLongitude()); Log.d("Speed",location.getSpeed()+""); Log.d("Past Speed: ", location.getSpeed() +""); currentSpeed = location.getSpeed(); Log.d("Change in velocity",currentSpeed-pastSpeed + "" ); // We have a crash, value should eventually become calculated if(currentSpeed - pastSpeed < -13) { listener.onPossibleCrash(CrashService.this, ActivityManager.getActivity()); // Send push ParsePush push = new ParsePush(); push.setChannel("crash"); push.setMessage("A person may be hurt at " + location.getLatitude() + " latitude, " + location.getLongitude() + " longitude"); push.sendInBackground(); stopLocationListener(); } pastSpeed = currentSpeed; } public void onStatusChanged(String provider, int status, Bundle extras) { Log.d("Status Changed", "has been enabled"); } public void onProviderEnabled(String provider) { Log.d("Enabled", "has been enabled"); } public void onProviderDisabled(String provider) { Log.d("Disabled happened", "has been enabled"); } }; startLocationListener(); } public void stopLocationListener() { locationManager.removeUpdates(locationListener); } public void startLocationListener() { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); } }
3,862
0.648628
0.645262
116
32.293102
28.243101
146
false
false
0
0
0
0
0
0
0.655172
false
false
9
8fe3ebacd753c4228b1acd8dcce4bc0bd0d5da32
16,114,717,312,122
ddfc8a1447359c2bf0eec8ee9b4fa492b81d0522
/src/server/transfer/AuthenticationTransfer.java
91bce2ee5152173708fcc3ca2e8564399c52cb5c
[]
no_license
ClockWorkTeam/Codice
https://github.com/ClockWorkTeam/Codice
d0ea1230e45a479f93039e9bfdc823161ee10ce9
614ad7478fa714752f5014d22d79aaef5ecda096
refs/heads/master
2021-01-13T14:30:19.617000
2013-03-29T15:22:27
2013-03-29T15:22:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package server.transfer; import java.util.Collection; import javolution.util.FastList; import org.jwebsocket.api.WebSocketConnector; import org.jwebsocket.api.WebSocketPacket; import org.jwebsocket.kit.RawPacket; import org.jwebsocket.kit.WebSocketServerEvent; import org.jwebsocket.listener.WebSocketServerTokenEvent; import org.jwebsocket.listener.WebSocketServerTokenListener; import org.jwebsocket.server.TokenServer; import org.jwebsocket.token.Token; import server.ServerMyTalk; import server.usermanager.*; import server.functionmanager.ContactsManager; import server.shared.User; public class AuthenticationTransfer implements WebSocketServerTokenListener { TokenServer tokenServer; private AuthenticationManager authenticationManager; private UserManager userManager; private Collection<WebSocketConnector> mClients; public AuthenticationTransfer(AuthenticationManager authenticationManager, UserManager userManager){ this.authenticationManager=authenticationManager; this.userManager=userManager; mClients = new FastList<WebSocketConnector>().shared(); } public void setTokenServer(ServerMyTalk server) { tokenServer=server.getTokenServer(); } public void processToken(WebSocketServerTokenEvent event, Token token) { String type= token.getString("type"); WebSocketPacket wspacket=null; if(type.equals("Login")){ User user=authenticationManager.login(token.getString("username"),token.getString("password"),event.getConnector().getRemoteHost().toString()); if(user==null){ wspacket = new RawPacket("{\"risposta\":\"false\",\"name\":\"\",\"surname\":\"\"}"); }else{ wspacket = new RawPacket("{\"risposta\":\"true\", \"name\":\""+user.getName()+"\", \"surname\":\""+user.getSurname()+"\"}"); WebSocketPacket wspacket2=new RawPacket("{\"size\":\""+1+"\", \"username0\":\""+user.getUsername()+"\",\"name0\":\""+user.getName()+"\",\"surname0\":\""+user.getSurname()+"\",\"IP0\":\""+user.getIP()+"\"}"); broadcastToAll(wspacket2); } sendPacket(wspacket, event); } else if(type.equals("SignUp")){ User user = authenticationManager.createUser(token.getString("username"),token.getString("password"), token.getString("name"), token.getString("surname"), event.getConnector().getRemoteHost().toString()); if(user==null){ wspacket = new RawPacket("{\"risposta\":\"false\"}"); }else{ wspacket = new RawPacket("{\"risposta\":\"true\"}"); WebSocketPacket wspacket2=new RawPacket("{\"size\":\""+1+"\", \"username0\":\""+user.getUsername()+"\",\"name0\":\""+user.getName()+"\",\"surname0\":\""+user.getSurname()+"\",\"IP0\":\""+user.getIP()+"\"}"); broadcastToAll(wspacket2); } sendPacket(wspacket, event); } else if(type.equals("getContacts")){ mClients.add(event.getConnector()); ContactsManager contacts= new ContactsManager(); wspacket = new RawPacket(contacts.getAllContacts(userManager.getAllContacts(userManager.getUser(token.getString("username"))))); sendPacket(wspacket, event); } else if(type.equals("Logout")){ boolean ris = authenticationManager.logout(userManager.getUser(token.getString("username"))); if(!ris){ wspacket = new RawPacket("{\"risposta\":\"false\"}"); }else{ User user=userManager.getUser(token.getString("username")); wspacket = new RawPacket("{\"risposta\":\"true\"}"); WebSocketPacket wspacket2=new RawPacket("{\"size\":\""+1+"\", \"username0\":\""+user.getUsername()+"\",\"name0\":\""+user.getName()+"\",\"surname0\":\""+user.getSurname()+"\",\"IP0\":\""+user.getIP()+"\"}"); broadcastToAll(wspacket2); } sendPacket(wspacket, event); } } public void processClosed(WebSocketServerEvent event) { mClients.remove(event.getConnector()); } public void processOpened(WebSocketServerEvent event) { } public void sendPacket(WebSocketPacket packet, WebSocketServerEvent event){ event.sendPacket(packet); } public void broadcastToAll(WebSocketPacket packet) { for (WebSocketConnector lConnector : mClients) { tokenServer.sendPacket(lConnector, packet); } } public void processPacket(WebSocketServerEvent event, WebSocketPacket packet) { } public Collection<WebSocketConnector> getClients(){ return mClients; } }
UTF-8
Java
4,442
java
AuthenticationTransfer.java
Java
[ { "context": "User(token.getString(\"username\"),token.getString(\"password\"), token.getString(\"name\"), token.getString(\"surn", "end": 2234, "score": 0.7087014317512512, "start": 2226, "tag": "PASSWORD", "value": "password" } ]
null
[]
package server.transfer; import java.util.Collection; import javolution.util.FastList; import org.jwebsocket.api.WebSocketConnector; import org.jwebsocket.api.WebSocketPacket; import org.jwebsocket.kit.RawPacket; import org.jwebsocket.kit.WebSocketServerEvent; import org.jwebsocket.listener.WebSocketServerTokenEvent; import org.jwebsocket.listener.WebSocketServerTokenListener; import org.jwebsocket.server.TokenServer; import org.jwebsocket.token.Token; import server.ServerMyTalk; import server.usermanager.*; import server.functionmanager.ContactsManager; import server.shared.User; public class AuthenticationTransfer implements WebSocketServerTokenListener { TokenServer tokenServer; private AuthenticationManager authenticationManager; private UserManager userManager; private Collection<WebSocketConnector> mClients; public AuthenticationTransfer(AuthenticationManager authenticationManager, UserManager userManager){ this.authenticationManager=authenticationManager; this.userManager=userManager; mClients = new FastList<WebSocketConnector>().shared(); } public void setTokenServer(ServerMyTalk server) { tokenServer=server.getTokenServer(); } public void processToken(WebSocketServerTokenEvent event, Token token) { String type= token.getString("type"); WebSocketPacket wspacket=null; if(type.equals("Login")){ User user=authenticationManager.login(token.getString("username"),token.getString("password"),event.getConnector().getRemoteHost().toString()); if(user==null){ wspacket = new RawPacket("{\"risposta\":\"false\",\"name\":\"\",\"surname\":\"\"}"); }else{ wspacket = new RawPacket("{\"risposta\":\"true\", \"name\":\""+user.getName()+"\", \"surname\":\""+user.getSurname()+"\"}"); WebSocketPacket wspacket2=new RawPacket("{\"size\":\""+1+"\", \"username0\":\""+user.getUsername()+"\",\"name0\":\""+user.getName()+"\",\"surname0\":\""+user.getSurname()+"\",\"IP0\":\""+user.getIP()+"\"}"); broadcastToAll(wspacket2); } sendPacket(wspacket, event); } else if(type.equals("SignUp")){ User user = authenticationManager.createUser(token.getString("username"),token.getString("<PASSWORD>"), token.getString("name"), token.getString("surname"), event.getConnector().getRemoteHost().toString()); if(user==null){ wspacket = new RawPacket("{\"risposta\":\"false\"}"); }else{ wspacket = new RawPacket("{\"risposta\":\"true\"}"); WebSocketPacket wspacket2=new RawPacket("{\"size\":\""+1+"\", \"username0\":\""+user.getUsername()+"\",\"name0\":\""+user.getName()+"\",\"surname0\":\""+user.getSurname()+"\",\"IP0\":\""+user.getIP()+"\"}"); broadcastToAll(wspacket2); } sendPacket(wspacket, event); } else if(type.equals("getContacts")){ mClients.add(event.getConnector()); ContactsManager contacts= new ContactsManager(); wspacket = new RawPacket(contacts.getAllContacts(userManager.getAllContacts(userManager.getUser(token.getString("username"))))); sendPacket(wspacket, event); } else if(type.equals("Logout")){ boolean ris = authenticationManager.logout(userManager.getUser(token.getString("username"))); if(!ris){ wspacket = new RawPacket("{\"risposta\":\"false\"}"); }else{ User user=userManager.getUser(token.getString("username")); wspacket = new RawPacket("{\"risposta\":\"true\"}"); WebSocketPacket wspacket2=new RawPacket("{\"size\":\""+1+"\", \"username0\":\""+user.getUsername()+"\",\"name0\":\""+user.getName()+"\",\"surname0\":\""+user.getSurname()+"\",\"IP0\":\""+user.getIP()+"\"}"); broadcastToAll(wspacket2); } sendPacket(wspacket, event); } } public void processClosed(WebSocketServerEvent event) { mClients.remove(event.getConnector()); } public void processOpened(WebSocketServerEvent event) { } public void sendPacket(WebSocketPacket packet, WebSocketServerEvent event){ event.sendPacket(packet); } public void broadcastToAll(WebSocketPacket packet) { for (WebSocketConnector lConnector : mClients) { tokenServer.sendPacket(lConnector, packet); } } public void processPacket(WebSocketServerEvent event, WebSocketPacket packet) { } public Collection<WebSocketConnector> getClients(){ return mClients; } }
4,444
0.6819
0.677172
104
41.721153
45.868847
214
false
false
0
0
0
0
0
0
2.259615
false
false
9
060cf8fbe491538025ed86fef7ac738189b0b372
9,517,647,561,912
9debd8014fc6c489d0dcd212c317edcdd77ecb19
/core/src/test/java/com/seleniumtests/it/stubclasses/StubTestClass.java
61b148610a907f21d8777b155fad29d038e4adab
[ "Apache-2.0" ]
permissive
bhecquet/seleniumRobot
https://github.com/bhecquet/seleniumRobot
ccded5afa6a6be8e90a7388ccad3bb90e3f590aa
7005e70b92d288375d615e8d76af7bf261340e91
refs/heads/master
2023-08-23T17:05:54.029000
2023-06-21T15:09:54
2023-06-21T15:09:54
67,778,824
8
6
Apache-2.0
false
2023-08-02T05:39:58
2016-09-09T07:57:26
2023-02-01T21:51:46
2023-08-02T05:39:57
190,152
7
6
27
Java
false
false
/** * Orignal work: Copyright 2015 www.seleniumtests.com * Modified work: Copyright 2016 www.infotel.com * Copyright 2017-2019 B.Hecquet * * 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.seleniumtests.it.stubclasses; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import org.apache.commons.io.FileUtils; import org.openqa.selenium.WebDriverException; import org.testng.Assert; import org.testng.Reporter; import org.testng.SkipException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.seleniumtests.core.Mask; import com.seleniumtests.core.SeleniumTestsContextManager; import com.seleniumtests.core.TestStepManager; import com.seleniumtests.customexception.DriverExceptions; import com.seleniumtests.driver.screenshots.ScreenShot; import com.seleniumtests.driver.screenshots.SnapshotCheckType; import com.seleniumtests.it.core.aspects.CalcPage; import com.seleniumtests.reporter.info.HyperlinkInfo; import com.seleniumtests.reporter.info.StringInfo; import com.seleniumtests.reporter.logger.Snapshot; import com.seleniumtests.reporter.logger.TestAction; import com.seleniumtests.reporter.logger.TestMessage; import com.seleniumtests.reporter.logger.TestMessage.MessageType; import com.seleniumtests.reporter.logger.TestStep; import com.seleniumtests.util.helper.WaitHelper; import com.seleniumtests.util.logging.ScenarioLogger; public class StubTestClass extends StubParentClass { private static int count = 0; public static boolean failed = false; private boolean maskPassword; @BeforeClass(groups={"stub"}) public void setCount() { WaitHelper.waitForMilliSeconds(100); count = 0; failed = false; } @BeforeMethod(groups={"stub"}) public void set(Method method) { WaitHelper.waitForMilliSeconds(100); logger.info("before count: " + count); maskPassword = SeleniumTestsContextManager.getThreadContext().getMaskedPassword(); } @AfterMethod(groups={"stub"}) public void reset(Method method) { logger.info("after count: " + count); } @Test(groups="stub", description="a test with steps") public void testAndSubActions() throws IOException { TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction("click button", false, new ArrayList<>())); step1.addAction(new TestAction("sendKeys to text field", true, new ArrayList<>())); File tmpImg = File.createTempFile("img", "_with_very_very_very_long_name_to_be_shortened.png"); File tmpHtml = File.createTempFile("html", "_with_very_very_very_long_name_to_be_shortened.html"); ScreenShot screenshot = new ScreenShot(); screenshot.setImagePath("screenshot/" + tmpImg.getName()); screenshot.setHtmlSourcePath("htmls/" + tmpHtml.getName()); FileUtils.copyFile(tmpImg, new File(screenshot.getFullImagePath())); FileUtils.copyFile(tmpHtml, new File(screenshot.getFullHtmlPath())); step1.addSnapshot(new Snapshot(screenshot, "main", SnapshotCheckType.FULL), 1, null); ScreenShot screenshot2 = new ScreenShot(); screenshot2.setImagePath("screenshot/" + tmpImg.getName()); screenshot2.setHtmlSourcePath("htmls/" + tmpHtml.getName()); FileUtils.moveFile(tmpImg, new File(screenshot2.getFullImagePath())); FileUtils.moveFile(tmpHtml, new File(screenshot2.getFullHtmlPath())); step1.addSnapshot(new Snapshot(screenshot2, null, SnapshotCheckType.FULL), 1, null); step1.setActionException(new WebDriverException("driver exception")); TestStep subStep1 = new TestStep("step 1.3: open page", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); subStep1.addAction(new TestAction("click link", false, new ArrayList<>())); subStep1.addMessage(new TestMessage("a message", MessageType.LOG)); subStep1.addAction(new TestAction("sendKeys to password field", false, new ArrayList<>())); step1.addAction(subStep1); WaitHelper.waitForSeconds(3); step1.setDuration(1230L); TestStep step2 = new TestStep("step 2", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step2.setDuration(14030L); TestStepManager.logTestStep(step1); TestStepManager.logTestStep(step2); tmpImg.deleteOnExit(); tmpHtml.deleteOnExit(); } /** * An other test that throws exception */ @Test(groups="stub", dependsOnMethods="testAndSubActions") public void testWithException2() { TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction(String.format("played %d times", count), false, new ArrayList<>())); step1.addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.logTestStep(step1); throw new DriverExceptions("some exception"); } @Test(groups="stub") public void testInError() { TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); TestStepManager.setCurrentRootTestStep(step1); TestStepManager.getParentTestStep().addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.getParentTestStep().addMessage(new TestMessage("click ok", MessageType.INFO)); logger.warn("Some warning message"); logger.info("Some Info message"); logger.error("Some Error message"); ((ScenarioLogger)logger).log("Some log message"); ((ScenarioLogger)logger).logTestValue("key", "we found a value of", "10"); TestStepManager.getParentTestStep().addAction(new TestAction("send keyboard action", false, new ArrayList<>())); TestStepManager.logTestStep(TestStepManager.getCurrentRootTestStep()); Assert.fail("error"); } @Test(groups="stub") public void testSkipped() { throw new SkipException("skip this test"); } @Test(groups="stub") public void testWithException() { count++; TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction(String.format("played %d times", count), false, new ArrayList<>())); step1.addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.logTestStep(step1); throw new DriverExceptions("some exception"); } @DataProvider(name = "data") public Object[][] data() { return new String[][] {new String[] {"data2"}}; } @Test(groups="stub", dataProvider = "data") public void testWithExceptionAndDataProvider(String data) { count++; TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction(String.format("played %d times", count), false, new ArrayList<>())); step1.addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.logTestStep(step1); throw new DriverExceptions("some exception"); } /** * Increase max retry */ @Test(groups="stub") public void testWithExceptionAndMaxRetryIncreased() { count++; TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction(String.format("played %d times", count), false, new ArrayList<>())); step1.addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.logTestStep(step1); try { throw new DriverExceptions("some exception"); } finally { if (count < 3) { increaseMaxRetry(); } } } /** * Increase max retry above limit */ @Test(groups="stub") public void testWithExceptionAndMaxRetryIncreasedWithLimit() { count++; TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction(String.format("played %d times", count), false, new ArrayList<>())); step1.addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.logTestStep(step1); try { throw new DriverExceptions("some exception"); } finally { if (count < 4) { increaseMaxRetry(); } } } /** * Issue #229: test with a step in error but test OK */ @Test(groups="stub") public void testOkWithOneStepFailed() { TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction("first action failed", true, new ArrayList<>())); step1.addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.logTestStep(step1); } /** * Test which fails only on first execution */ @Test(groups="stub") public void testWithExceptionOnFirstExec() { TestStep step1 = new TestStep("step 10", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction(String.format("played %d times", count), false, new ArrayList<>())); step1.addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.logTestStep(step1); if (!failed) { failed = true; throw new DriverExceptions("some exception"); } } /** * Test which fails only on first execution */ @Test(groups="stub") public void testWithSocketTimeoutOnFirstExec() { TestStep step1 = new TestStep("step 10", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction(String.format("played %d times", count), false, new ArrayList<>())); step1.addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.logTestStep(step1); if (!failed) { failed = true; throw new WebDriverException("Session [6919ba25-53b6-4615-bd59-e97399bf1e12] was terminated due to SO_TIMEOUT"); } } @Test(groups="stub", testName="A test which is <OK> é&") public void testOkWithTestName() throws IOException { TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction("click button", false, new ArrayList<>())); step1.addAction(new TestAction("sendKeys to text field", false, new ArrayList<>())); TestStepManager.logTestStep(step1); } @DataProvider(name = "data2") public Object[][] data2() { return new String[][] {new String[] {"data2", "data3"}, new String[] {"data4", "data5"}}; } @DataProvider(name = "data3") public Object[][] data3() { return new Integer[][] {new Integer[] {12, 123456}, new Integer[] {13, 12345}, new Integer[] {14, null} }; } @Test(groups="stub", testName="A test which is OK (${arg0}, ${arg1})", dataProvider = "data2") public void testOkWithTestNameAndDataProvider(String col1, String col2) throws IOException { logger.info(String.format("%s,%s", col1, col2)); } @Test(groups="stub", dataProvider = "data3") public void testOkWithPasswordDataProvider(Integer col1, @Mask Integer sensibleData) throws IOException { logger.info(String.format("%d,%d", col1, sensibleData == null ? -1: sensibleData)); new CalcPage() .add(1, sensibleData); } @Test(groups="stub") public void testOk() throws IOException { TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction("click button", false, new ArrayList<>())); step1.addAction(new TestAction("sendKeys to text field", false, new ArrayList<>())); TestStepManager.logTestStep(step1); } @Test(groups="stub", description="a test with infos") public void testWithInfo1() throws IOException { TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction("click button", false, new ArrayList<>())); step1.addAction(new TestAction("sendKeys to text field", true, new ArrayList<>())); TestStepManager.logTestStep(step1); addTestInfo("bugé <\"ID\">", new StringInfo("12")); } @Test(groups="stub", description="a test with infos") public void testWithInfo2() throws IOException { TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction("click button", false, new ArrayList<>())); step1.addAction(new TestAction("sendKeys to text field", true, new ArrayList<>())); TestStepManager.logTestStep(step1); addTestInfo("user ID", new HyperlinkInfo("12345", "http://foo/bar/12345")); } @Test(groups="stub", dataProvider = "dataset") public void testStandardDataProvider(String col1, String col2) { logger.info(String.format("%s,%s", col1, col2)); } @Test(groups="stub", dataProvider = "datasetSemicolon") public void testStandardDataProviderSemicolon(String col1, String col2) { logger.info(String.format("%s,%s", col1, col2)); } @Test(groups="stub", dataProvider = "datasetWithHeader") public void testStandardDataProviderWithHeader(String col1, String col2) { logger.info(String.format("%s,%s", col1, col2)); } @Test(groups="stub", dataProvider = "datasetSemicolonWithHeader") public void testStandardDataProviderSemicolonWithHeader(String col1, String col2) { logger.info(String.format("%s,%s", col1, col2)); } @Test(groups="stub", dataProvider = "dataset") public void testStandardXlsxDataProvider(String col1, String col2) { logger.info(String.format("%s,%s", col1, col2)); } @Test(groups="stub", dataProvider = "dataset") public void testStandardDataProviderNoFile(String col1, String col2) { logger.info(String.format("%s,%s", col1, col2)); } }
UTF-8
Java
14,393
java
StubTestClass.java
Java
[ { "context": "t 2016 www.infotel.com\r\n * \t\t\t\tCopyright 2017-2019 B.Hecquet\r\n *\r\n * Licensed under the Apache License, Versio", "end": 146, "score": 0.9998618960380554, "start": 137, "tag": "NAME", "value": "B.Hecquet" } ]
null
[]
/** * Orignal work: Copyright 2015 www.seleniumtests.com * Modified work: Copyright 2016 www.infotel.com * Copyright 2017-2019 B.Hecquet * * 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.seleniumtests.it.stubclasses; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import org.apache.commons.io.FileUtils; import org.openqa.selenium.WebDriverException; import org.testng.Assert; import org.testng.Reporter; import org.testng.SkipException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.seleniumtests.core.Mask; import com.seleniumtests.core.SeleniumTestsContextManager; import com.seleniumtests.core.TestStepManager; import com.seleniumtests.customexception.DriverExceptions; import com.seleniumtests.driver.screenshots.ScreenShot; import com.seleniumtests.driver.screenshots.SnapshotCheckType; import com.seleniumtests.it.core.aspects.CalcPage; import com.seleniumtests.reporter.info.HyperlinkInfo; import com.seleniumtests.reporter.info.StringInfo; import com.seleniumtests.reporter.logger.Snapshot; import com.seleniumtests.reporter.logger.TestAction; import com.seleniumtests.reporter.logger.TestMessage; import com.seleniumtests.reporter.logger.TestMessage.MessageType; import com.seleniumtests.reporter.logger.TestStep; import com.seleniumtests.util.helper.WaitHelper; import com.seleniumtests.util.logging.ScenarioLogger; public class StubTestClass extends StubParentClass { private static int count = 0; public static boolean failed = false; private boolean maskPassword; @BeforeClass(groups={"stub"}) public void setCount() { WaitHelper.waitForMilliSeconds(100); count = 0; failed = false; } @BeforeMethod(groups={"stub"}) public void set(Method method) { WaitHelper.waitForMilliSeconds(100); logger.info("before count: " + count); maskPassword = SeleniumTestsContextManager.getThreadContext().getMaskedPassword(); } @AfterMethod(groups={"stub"}) public void reset(Method method) { logger.info("after count: " + count); } @Test(groups="stub", description="a test with steps") public void testAndSubActions() throws IOException { TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction("click button", false, new ArrayList<>())); step1.addAction(new TestAction("sendKeys to text field", true, new ArrayList<>())); File tmpImg = File.createTempFile("img", "_with_very_very_very_long_name_to_be_shortened.png"); File tmpHtml = File.createTempFile("html", "_with_very_very_very_long_name_to_be_shortened.html"); ScreenShot screenshot = new ScreenShot(); screenshot.setImagePath("screenshot/" + tmpImg.getName()); screenshot.setHtmlSourcePath("htmls/" + tmpHtml.getName()); FileUtils.copyFile(tmpImg, new File(screenshot.getFullImagePath())); FileUtils.copyFile(tmpHtml, new File(screenshot.getFullHtmlPath())); step1.addSnapshot(new Snapshot(screenshot, "main", SnapshotCheckType.FULL), 1, null); ScreenShot screenshot2 = new ScreenShot(); screenshot2.setImagePath("screenshot/" + tmpImg.getName()); screenshot2.setHtmlSourcePath("htmls/" + tmpHtml.getName()); FileUtils.moveFile(tmpImg, new File(screenshot2.getFullImagePath())); FileUtils.moveFile(tmpHtml, new File(screenshot2.getFullHtmlPath())); step1.addSnapshot(new Snapshot(screenshot2, null, SnapshotCheckType.FULL), 1, null); step1.setActionException(new WebDriverException("driver exception")); TestStep subStep1 = new TestStep("step 1.3: open page", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); subStep1.addAction(new TestAction("click link", false, new ArrayList<>())); subStep1.addMessage(new TestMessage("a message", MessageType.LOG)); subStep1.addAction(new TestAction("sendKeys to password field", false, new ArrayList<>())); step1.addAction(subStep1); WaitHelper.waitForSeconds(3); step1.setDuration(1230L); TestStep step2 = new TestStep("step 2", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step2.setDuration(14030L); TestStepManager.logTestStep(step1); TestStepManager.logTestStep(step2); tmpImg.deleteOnExit(); tmpHtml.deleteOnExit(); } /** * An other test that throws exception */ @Test(groups="stub", dependsOnMethods="testAndSubActions") public void testWithException2() { TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction(String.format("played %d times", count), false, new ArrayList<>())); step1.addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.logTestStep(step1); throw new DriverExceptions("some exception"); } @Test(groups="stub") public void testInError() { TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); TestStepManager.setCurrentRootTestStep(step1); TestStepManager.getParentTestStep().addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.getParentTestStep().addMessage(new TestMessage("click ok", MessageType.INFO)); logger.warn("Some warning message"); logger.info("Some Info message"); logger.error("Some Error message"); ((ScenarioLogger)logger).log("Some log message"); ((ScenarioLogger)logger).logTestValue("key", "we found a value of", "10"); TestStepManager.getParentTestStep().addAction(new TestAction("send keyboard action", false, new ArrayList<>())); TestStepManager.logTestStep(TestStepManager.getCurrentRootTestStep()); Assert.fail("error"); } @Test(groups="stub") public void testSkipped() { throw new SkipException("skip this test"); } @Test(groups="stub") public void testWithException() { count++; TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction(String.format("played %d times", count), false, new ArrayList<>())); step1.addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.logTestStep(step1); throw new DriverExceptions("some exception"); } @DataProvider(name = "data") public Object[][] data() { return new String[][] {new String[] {"data2"}}; } @Test(groups="stub", dataProvider = "data") public void testWithExceptionAndDataProvider(String data) { count++; TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction(String.format("played %d times", count), false, new ArrayList<>())); step1.addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.logTestStep(step1); throw new DriverExceptions("some exception"); } /** * Increase max retry */ @Test(groups="stub") public void testWithExceptionAndMaxRetryIncreased() { count++; TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction(String.format("played %d times", count), false, new ArrayList<>())); step1.addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.logTestStep(step1); try { throw new DriverExceptions("some exception"); } finally { if (count < 3) { increaseMaxRetry(); } } } /** * Increase max retry above limit */ @Test(groups="stub") public void testWithExceptionAndMaxRetryIncreasedWithLimit() { count++; TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction(String.format("played %d times", count), false, new ArrayList<>())); step1.addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.logTestStep(step1); try { throw new DriverExceptions("some exception"); } finally { if (count < 4) { increaseMaxRetry(); } } } /** * Issue #229: test with a step in error but test OK */ @Test(groups="stub") public void testOkWithOneStepFailed() { TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction("first action failed", true, new ArrayList<>())); step1.addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.logTestStep(step1); } /** * Test which fails only on first execution */ @Test(groups="stub") public void testWithExceptionOnFirstExec() { TestStep step1 = new TestStep("step 10", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction(String.format("played %d times", count), false, new ArrayList<>())); step1.addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.logTestStep(step1); if (!failed) { failed = true; throw new DriverExceptions("some exception"); } } /** * Test which fails only on first execution */ @Test(groups="stub") public void testWithSocketTimeoutOnFirstExec() { TestStep step1 = new TestStep("step 10", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction(String.format("played %d times", count), false, new ArrayList<>())); step1.addAction(new TestAction("click button", false, new ArrayList<>())); TestStepManager.logTestStep(step1); if (!failed) { failed = true; throw new WebDriverException("Session [6919ba25-53b6-4615-bd59-e97399bf1e12] was terminated due to SO_TIMEOUT"); } } @Test(groups="stub", testName="A test which is <OK> é&") public void testOkWithTestName() throws IOException { TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction("click button", false, new ArrayList<>())); step1.addAction(new TestAction("sendKeys to text field", false, new ArrayList<>())); TestStepManager.logTestStep(step1); } @DataProvider(name = "data2") public Object[][] data2() { return new String[][] {new String[] {"data2", "data3"}, new String[] {"data4", "data5"}}; } @DataProvider(name = "data3") public Object[][] data3() { return new Integer[][] {new Integer[] {12, 123456}, new Integer[] {13, 12345}, new Integer[] {14, null} }; } @Test(groups="stub", testName="A test which is OK (${arg0}, ${arg1})", dataProvider = "data2") public void testOkWithTestNameAndDataProvider(String col1, String col2) throws IOException { logger.info(String.format("%s,%s", col1, col2)); } @Test(groups="stub", dataProvider = "data3") public void testOkWithPasswordDataProvider(Integer col1, @Mask Integer sensibleData) throws IOException { logger.info(String.format("%d,%d", col1, sensibleData == null ? -1: sensibleData)); new CalcPage() .add(1, sensibleData); } @Test(groups="stub") public void testOk() throws IOException { TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction("click button", false, new ArrayList<>())); step1.addAction(new TestAction("sendKeys to text field", false, new ArrayList<>())); TestStepManager.logTestStep(step1); } @Test(groups="stub", description="a test with infos") public void testWithInfo1() throws IOException { TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction("click button", false, new ArrayList<>())); step1.addAction(new TestAction("sendKeys to text field", true, new ArrayList<>())); TestStepManager.logTestStep(step1); addTestInfo("bugé <\"ID\">", new StringInfo("12")); } @Test(groups="stub", description="a test with infos") public void testWithInfo2() throws IOException { TestStep step1 = new TestStep("step 1", Reporter.getCurrentTestResult(), new ArrayList<>(), maskPassword); step1.addAction(new TestAction("click button", false, new ArrayList<>())); step1.addAction(new TestAction("sendKeys to text field", true, new ArrayList<>())); TestStepManager.logTestStep(step1); addTestInfo("user ID", new HyperlinkInfo("12345", "http://foo/bar/12345")); } @Test(groups="stub", dataProvider = "dataset") public void testStandardDataProvider(String col1, String col2) { logger.info(String.format("%s,%s", col1, col2)); } @Test(groups="stub", dataProvider = "datasetSemicolon") public void testStandardDataProviderSemicolon(String col1, String col2) { logger.info(String.format("%s,%s", col1, col2)); } @Test(groups="stub", dataProvider = "datasetWithHeader") public void testStandardDataProviderWithHeader(String col1, String col2) { logger.info(String.format("%s,%s", col1, col2)); } @Test(groups="stub", dataProvider = "datasetSemicolonWithHeader") public void testStandardDataProviderSemicolonWithHeader(String col1, String col2) { logger.info(String.format("%s,%s", col1, col2)); } @Test(groups="stub", dataProvider = "dataset") public void testStandardXlsxDataProvider(String col1, String col2) { logger.info(String.format("%s,%s", col1, col2)); } @Test(groups="stub", dataProvider = "dataset") public void testStandardDataProviderNoFile(String col1, String col2) { logger.info(String.format("%s,%s", col1, col2)); } }
14,393
0.714266
0.697658
354
38.652542
33.078072
124
false
false
0
0
0
0
0
0
2.350282
false
false
9
d8c6133465130db3947fcad0c909a9e215ef3711
31,318,901,591,807
e941ed5bdf62fb98269521d984a0cbcbc7fe6ab4
/tugas_1/src/main/java/com/example/model/KeluargaModel.java
70c61a323f1bda7ed9e0db4d540c4d56b71706de
[]
no_license
gigitafazh/APAP
https://github.com/gigitafazh/APAP
7dbe65ca85b7bb4375874fa356cbf632e224d436
3837bbf1e32176ebd90e81fd5dc171bc02598a8d
refs/heads/master
2021-08-23T21:11:43.413000
2017-12-06T15:16:38
2017-12-06T15:16:38
105,964,918
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class KeluargaModel { private int id; private String nomor_kk; private String alamat; private String RT; private String RW; private int id_kelurahan; private int is_tidak_berlaku; private String nama_kelurahan; private String nama_kecamatan; private String nama_kota; }
UTF-8
Java
448
java
KeluargaModel.java
Java
[]
null
[]
package com.example.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class KeluargaModel { private int id; private String nomor_kk; private String alamat; private String RT; private String RW; private int id_kelurahan; private int is_tidak_berlaku; private String nama_kelurahan; private String nama_kecamatan; private String nama_kota; }
448
0.801339
0.801339
22
19.40909
11.002723
33
false
false
0
0
0
0
0
0
1.090909
false
false
9
e2043a2dbea037f49cf58fc3b0ff5e38a7a4be90
11,519,102,295,440
6ebab3f3dbc07987624535a927ba0f5ade766d14
/src/shopping/ShoppingBag.java
74c52a79a2f910a6795ea2fb4951dd648fe6ea78
[]
no_license
miriamdosantos/Java-POO
https://github.com/miriamdosantos/Java-POO
349d564e32eab8cffb7a62170730b206f12a558f
66f9006043a5ed82f85ca3d02434cc0487cb5536
refs/heads/main
2023-05-02T13:50:07.960000
2021-05-13T08:24:19
2021-05-13T08:24:19
366,879,756
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 shopping; import java.util.ArrayList; /** * A simple ShoppingBag * * Stores items in an ArrayList * * Possible to add items * Also can "empty" the bag * * You should NOT need to amend this code at all! * * @author Ken */ public class ShoppingBag { private ArrayList<Item> items; /** * Create a shopping bag by initialising the items to an empty arraylist */ public ShoppingBag(){ items = new ArrayList<Item>(); } /** * Add an item to the shopping bag * @param someItem the item that has been bought */ public void buyItem(Item someItem){ this.items.add(someItem); } /** * create a formatted String containing all the items in the ShoppingBag * @return the formatted String * Also clears the items list */ public String emptyBag(){ String itemList = ""; for(Item item: this.items){ itemList = itemList + item.toString() + "\n"; } this.items.clear(); return itemList; } public double totalPrice (){ ; double total = 0; for (Item item: this.items){ total += item.getPrice(); } return total; } public String toString (){ String toString = ""; for (Item item: items ){ toString += " " + item.getName() + " " + item.getPrice(); } return toString; } }
UTF-8
Java
1,839
java
ShoppingBag.java
Java
[ { "context": "T need to amend this code at all!\r\n * \r\n * @author Ken\r\n */\r\npublic class ShoppingBag {\r\n \r\n priva", "end": 446, "score": 0.9446218013763428, "start": 443, "tag": "NAME", "value": "Ken" } ]
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 shopping; import java.util.ArrayList; /** * A simple ShoppingBag * * Stores items in an ArrayList * * Possible to add items * Also can "empty" the bag * * You should NOT need to amend this code at all! * * @author Ken */ public class ShoppingBag { private ArrayList<Item> items; /** * Create a shopping bag by initialising the items to an empty arraylist */ public ShoppingBag(){ items = new ArrayList<Item>(); } /** * Add an item to the shopping bag * @param someItem the item that has been bought */ public void buyItem(Item someItem){ this.items.add(someItem); } /** * create a formatted String containing all the items in the ShoppingBag * @return the formatted String * Also clears the items list */ public String emptyBag(){ String itemList = ""; for(Item item: this.items){ itemList = itemList + item.toString() + "\n"; } this.items.clear(); return itemList; } public double totalPrice (){ ; double total = 0; for (Item item: this.items){ total += item.getPrice(); } return total; } public String toString (){ String toString = ""; for (Item item: items ){ toString += " " + item.getName() + " " + item.getPrice(); } return toString; } }
1,839
0.513866
0.513322
83
20.156626
18.993011
79
false
false
0
0
0
0
0
0
0.228916
false
false
9
1f9b6d07c54e4f53df716941d8c1d731041efa0c
21,423,296,891,874
2fc8f1ad6b47994789eab060f86a5f45c2485e24
/GroovyLabSrc/de/torstennahm/integrate/sparse/CouldNotEvaluateInfo.java
e683d7b7709b41a302e23d496a000a82eca72c03
[]
no_license
navalsteed/jlabgroovy
https://github.com/navalsteed/jlabgroovy
4648f80008ae1a8eab92ad31697c4f478b4caf4e
28139e98281502d61bf08b0757acf6dc10011801
refs/heads/master
2021-01-17T07:07:49.349000
2014-01-01T19:37:02
2014-01-01T19:37:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Created on Aug 5, 2004 */ package de.torstennahm.integrate.sparse; import de.torstennahm.integrate.IntegrationInfo; import de.torstennahm.integrate.sparse.evaluateindex.Evaluator; import de.torstennahm.integrate.sparse.index.Index; /** * Signifies that an integration index could not be evaluated during the integration process. * * @author Torsten Nahm */ public class CouldNotEvaluateInfo extends IntegrationInfo { public CouldNotEvaluateInfo(Evaluator evaluator, Index index) { super("Could not evaluate an integration index. This error first occurred for the index " + index + ".\n" + "Although integration could be completed, this condition implies slower convergence " + "and error overestimation.\n" + "Please check the index evaluator for possible causes."); } @Override public boolean equals(Object o) { return o.getClass() == CouldNotEvaluateInfo.class; } @Override public int hashCode() { return CouldNotEvaluateInfo.class.hashCode(); } }
UTF-8
Java
1,029
java
CouldNotEvaluateInfo.java
Java
[ { "context": "d during the integration process.\r\n * \r\n * @author Torsten Nahm\r\n */\r\npublic class CouldNotEvaluateInfo extends I", "end": 378, "score": 0.9998580813407898, "start": 366, "tag": "NAME", "value": "Torsten Nahm" } ]
null
[]
/* * Created on Aug 5, 2004 */ package de.torstennahm.integrate.sparse; import de.torstennahm.integrate.IntegrationInfo; import de.torstennahm.integrate.sparse.evaluateindex.Evaluator; import de.torstennahm.integrate.sparse.index.Index; /** * Signifies that an integration index could not be evaluated during the integration process. * * @author <NAME> */ public class CouldNotEvaluateInfo extends IntegrationInfo { public CouldNotEvaluateInfo(Evaluator evaluator, Index index) { super("Could not evaluate an integration index. This error first occurred for the index " + index + ".\n" + "Although integration could be completed, this condition implies slower convergence " + "and error overestimation.\n" + "Please check the index evaluator for possible causes."); } @Override public boolean equals(Object o) { return o.getClass() == CouldNotEvaluateInfo.class; } @Override public int hashCode() { return CouldNotEvaluateInfo.class.hashCode(); } }
1,023
0.730807
0.725947
32
30.15625
31.194059
109
false
false
0
0
0
0
0
0
1.09375
false
false
9
cb3b7589aeff84f0232f4145be2a4f74bd54b00f
27,839,978,021,288
0d7a63fe9f24bfe3ac86ca7e94faf98bc22a8baf
/servers/weinxinFundation/src/weixinFundation/core/menu/MenuUtil.java
6c3341079edbaab68f6c60607b848f3a14d5fbc7
[]
no_license
koalhou/Android
https://github.com/koalhou/Android
cc664ffc6eb085fc2275319fcd7bc50d77288a10
2d11a4d8bd965e3e5e7809422d254459105af9d8
refs/heads/master
2021-01-10T08:28:39.720000
2015-10-22T06:24:32
2015-10-22T06:24:32
44,721,409
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package weixinFundation.core.menu; import net.sf.json.JSONObject; import weixinFundation.core.utils.HttpsUtil; import weixinFundation.core.common.AccessTokenUtil; public class MenuUtil { /** * 创建菜单 * @param appid * @param secret * @return */ public static boolean createMenu(String appid,String secret,String menuDescriptionStr) { if(appid == null) throw new NullPointerException(); if(secret == null) throw new NullPointerException(); String accessToken = AccessTokenUtil.getAccessToken(appid,secret); String urlStr = String .format("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s", accessToken); String resStr = HttpsUtil.post(urlStr, menuDescriptionStr); if (resStr == null) return false; JSONObject json = JSONObject.fromObject(resStr); String errcode = json.getString("errcode"); String errmsg = json.getString("errmsg"); if (errcode.equals("0")) return true; else return false; } }
UTF-8
Java
1,021
java
MenuUtil.java
Java
[]
null
[]
package weixinFundation.core.menu; import net.sf.json.JSONObject; import weixinFundation.core.utils.HttpsUtil; import weixinFundation.core.common.AccessTokenUtil; public class MenuUtil { /** * 创建菜单 * @param appid * @param secret * @return */ public static boolean createMenu(String appid,String secret,String menuDescriptionStr) { if(appid == null) throw new NullPointerException(); if(secret == null) throw new NullPointerException(); String accessToken = AccessTokenUtil.getAccessToken(appid,secret); String urlStr = String .format("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s", accessToken); String resStr = HttpsUtil.post(urlStr, menuDescriptionStr); if (resStr == null) return false; JSONObject json = JSONObject.fromObject(resStr); String errcode = json.getString("errcode"); String errmsg = json.getString("errmsg"); if (errcode.equals("0")) return true; else return false; } }
1,021
0.692004
0.691017
39
23.97436
22.689077
89
false
false
0
0
0
0
0
0
2.025641
false
false
9
257d13b9c73323e350d0f6a55e7f8078aa96ca80
33,122,787,827,542
6b7a45dcc703aa1c4fb8e7900b2db28bfc1f3b19
/android/app/src/main/java/org/us/x42/kyork/idcard/data/CardDataFormat.java
ecaa41027712cb254494a763dd9cefe651d47f4a
[]
no_license
riking/idcard
https://github.com/riking/idcard
a19bb69a43edefdcdade5fb18794b63a3aa8f92d
8cffb655984589c1efcb5d207675a1a04e01f0e9
refs/heads/master
2020-03-22T20:41:48.678000
2018-09-06T21:55:44
2018-09-06T21:55:44
140,623,192
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.us.x42.kyork.idcard.data; import org.us.x42.kyork.idcard.desfire.DESFireProtocol; /** * Data format of the NFC cards. */ public class CardDataFormat { public static final int APPLICATION_ID = 0xFB9852; public static final byte[] APPLICATION_ID_BYTES = new byte[]{(byte) 0xFB, (byte) 0x98, (byte) 0x52}; public static final short SCHEMA_ID = (short)0x0001; /** * Lookup table for the class representing each "file" format on the card. */ public static final class FileFormatInfo { public final Class<? extends CardFile> dfnClass; public final byte fileID; public final int expectedSize; public final boolean isSigned; public final byte fileType; FileFormatInfo(Class<? extends CardFile> dfnClass, byte fileID, int expectedSize, boolean isSigned, byte fileType) { this.dfnClass = dfnClass; this.fileID = fileID; this.expectedSize = expectedSize; this.isSigned = isSigned; this.fileType = fileType; } } public static final FileFormatInfo FORMAT_METADATA = new FileFormatInfo(FileMetadata.class, (byte)0x1, 16, false, DESFireProtocol.FILETYPE_STANDARD); public static final FileFormatInfo FORMAT_USERINFO = new FileFormatInfo(FileUserInfo.class, (byte)0x2, 32, true, DESFireProtocol.FILETYPE_BACKUP); // cantina file..? (possibly encrypted payment information for real-time payments) public static final FileFormatInfo FORMAT_DOORPERMS = new FileFormatInfo(FileDoorPermissions.class, (byte)0x4, 64, true, DESFireProtocol.FILETYPE_BACKUP); public static final FileFormatInfo FORMAT_UPDATE = new FileFormatInfo(FileUpdateData.class, (byte)0x6, 256, false, DESFireProtocol.FILETYPE_STANDARD); public static final FileFormatInfo FORMAT_SIGNATURES = new FileFormatInfo(FileSignatures.class, (byte)0x7, 68 * 5, false, DESFireProtocol.FILETYPE_STANDARD); /** * The files created when creating a new ID card. */ public static final FileFormatInfo[] filesOnCard = { FORMAT_METADATA, FORMAT_USERINFO, FORMAT_DOORPERMS, FORMAT_SIGNATURES, }; }
UTF-8
Java
2,241
java
CardDataFormat.java
Java
[]
null
[]
package org.us.x42.kyork.idcard.data; import org.us.x42.kyork.idcard.desfire.DESFireProtocol; /** * Data format of the NFC cards. */ public class CardDataFormat { public static final int APPLICATION_ID = 0xFB9852; public static final byte[] APPLICATION_ID_BYTES = new byte[]{(byte) 0xFB, (byte) 0x98, (byte) 0x52}; public static final short SCHEMA_ID = (short)0x0001; /** * Lookup table for the class representing each "file" format on the card. */ public static final class FileFormatInfo { public final Class<? extends CardFile> dfnClass; public final byte fileID; public final int expectedSize; public final boolean isSigned; public final byte fileType; FileFormatInfo(Class<? extends CardFile> dfnClass, byte fileID, int expectedSize, boolean isSigned, byte fileType) { this.dfnClass = dfnClass; this.fileID = fileID; this.expectedSize = expectedSize; this.isSigned = isSigned; this.fileType = fileType; } } public static final FileFormatInfo FORMAT_METADATA = new FileFormatInfo(FileMetadata.class, (byte)0x1, 16, false, DESFireProtocol.FILETYPE_STANDARD); public static final FileFormatInfo FORMAT_USERINFO = new FileFormatInfo(FileUserInfo.class, (byte)0x2, 32, true, DESFireProtocol.FILETYPE_BACKUP); // cantina file..? (possibly encrypted payment information for real-time payments) public static final FileFormatInfo FORMAT_DOORPERMS = new FileFormatInfo(FileDoorPermissions.class, (byte)0x4, 64, true, DESFireProtocol.FILETYPE_BACKUP); public static final FileFormatInfo FORMAT_UPDATE = new FileFormatInfo(FileUpdateData.class, (byte)0x6, 256, false, DESFireProtocol.FILETYPE_STANDARD); public static final FileFormatInfo FORMAT_SIGNATURES = new FileFormatInfo(FileSignatures.class, (byte)0x7, 68 * 5, false, DESFireProtocol.FILETYPE_STANDARD); /** * The files created when creating a new ID card. */ public static final FileFormatInfo[] filesOnCard = { FORMAT_METADATA, FORMAT_USERINFO, FORMAT_DOORPERMS, FORMAT_SIGNATURES, }; }
2,241
0.684516
0.665328
52
42.096153
35.213776
114
false
false
0
0
0
0
0
0
0.980769
false
false
9
5dde2974396bca3ba20dc5ac2a13eda122e44c0a
28,217,935,136,442
f930c3bd8b88c8090edf9c8c73ad2a0ff487fe2f
/wifiProject/src/com/waho/service/UserService.java
6aa35c72909ec424f25a7e8547e27289e436b506
[]
no_license
leipeide/WiFiProject
https://github.com/leipeide/WiFiProject
f759544151f8f61e39bd16faa7659073a3d58b40
173a49cbfd9fc2523aca5d984f087fb12f380446
refs/heads/master
2021-07-10T13:42:17.794000
2020-07-23T06:16:55
2020-07-23T06:16:55
177,691,154
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.waho.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.waho.domain.Node; import com.waho.domain.PageBean; import com.waho.domain.User; public interface UserService { /** * 登录服务,返回用户信息和节点列表 map的数据结构为 { user:user Object nodes:[ node Object ] } * * @param username * @param password * @return */ Map<String, Object> login(String username, String password); /** * 根据节点id的字符串返回节点对象 * * @param nodeid * @return */ Node getNodeByIdString(String nodeid); /** * 根据节点id,对节点的开关状态、功率输出百分比进行控制,返回指令发送成功或失败(不代表执行成功和失败,执行结果需要从数据库查询) * * @param nodeid * @param switchState * @param percentage */ Boolean userWriteNodeCmd(String nodeid, String switchState, String percentage); /** * 用户注册,注册成功返回true,注册失败返回false * @param username * @param password * @param email * @return */ Boolean userRegister(String username, String password, String email); /** * 节点重命名,成功返回true,失败返回false * @param nodeid 要修改的节点id * @param nodeName 新的节点名称 * @return */ Boolean userRenameNode(String nodeid, String nodeName); /** * 根据用户id获取节点信息 * @param id * @return */ List<Node> getNodeListByUserId(int id); /** * 根据节点id删除节点的用户id信息 * @param idList * @param userid * @return */ int removeNodeById(List<Integer> idList, int userid); /** * 根据节点id,查找与userid相同的在线节点的webSocket,发送修改wifi名称和密码的指令。返回值为成功发送的指令条数,即成功发送的节点个数。 * @param userid * @param ssid * @param password * @param idList * @return */ int userWriteWifiResetCmd(int userid, String ssid, String password, ArrayList<Integer> idList); /** * 广播控制节点开关和输出功率百分比,返回成功发送的指令条数 * @param idList * @param userid * @param switchState * @param percentage * @return */ int broadcastControl(ArrayList<Integer> idList, int userid, boolean switchState, int percentage); /** * 将节点添加到用户名下。 * @param nodeMac * @param userid * @return */ int addNodeToUser(String nodeMac, int userid); /** * 根据用户id查询用户信息 * @param parseInt * @return */ User getUserMessage(int userid); /** * 修改用户密码 * @param userid * @param newPassword * @return */ boolean updateUserPassword(int userid, String newPassword); /** * 从个人页面返回到home主页面 * @param username * @param password * @return */ Map<String, Object> returnHome(String username, String password); /** * 获得节点,对节点分页显示 * @param id * @param currPage * @return */ PageBean getNodeByUserId(int userid, int currPage); }
UTF-8
Java
3,080
java
UserService.java
Java
[]
null
[]
package com.waho.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.waho.domain.Node; import com.waho.domain.PageBean; import com.waho.domain.User; public interface UserService { /** * 登录服务,返回用户信息和节点列表 map的数据结构为 { user:user Object nodes:[ node Object ] } * * @param username * @param password * @return */ Map<String, Object> login(String username, String password); /** * 根据节点id的字符串返回节点对象 * * @param nodeid * @return */ Node getNodeByIdString(String nodeid); /** * 根据节点id,对节点的开关状态、功率输出百分比进行控制,返回指令发送成功或失败(不代表执行成功和失败,执行结果需要从数据库查询) * * @param nodeid * @param switchState * @param percentage */ Boolean userWriteNodeCmd(String nodeid, String switchState, String percentage); /** * 用户注册,注册成功返回true,注册失败返回false * @param username * @param password * @param email * @return */ Boolean userRegister(String username, String password, String email); /** * 节点重命名,成功返回true,失败返回false * @param nodeid 要修改的节点id * @param nodeName 新的节点名称 * @return */ Boolean userRenameNode(String nodeid, String nodeName); /** * 根据用户id获取节点信息 * @param id * @return */ List<Node> getNodeListByUserId(int id); /** * 根据节点id删除节点的用户id信息 * @param idList * @param userid * @return */ int removeNodeById(List<Integer> idList, int userid); /** * 根据节点id,查找与userid相同的在线节点的webSocket,发送修改wifi名称和密码的指令。返回值为成功发送的指令条数,即成功发送的节点个数。 * @param userid * @param ssid * @param password * @param idList * @return */ int userWriteWifiResetCmd(int userid, String ssid, String password, ArrayList<Integer> idList); /** * 广播控制节点开关和输出功率百分比,返回成功发送的指令条数 * @param idList * @param userid * @param switchState * @param percentage * @return */ int broadcastControl(ArrayList<Integer> idList, int userid, boolean switchState, int percentage); /** * 将节点添加到用户名下。 * @param nodeMac * @param userid * @return */ int addNodeToUser(String nodeMac, int userid); /** * 根据用户id查询用户信息 * @param parseInt * @return */ User getUserMessage(int userid); /** * 修改用户密码 * @param userid * @param newPassword * @return */ boolean updateUserPassword(int userid, String newPassword); /** * 从个人页面返回到home主页面 * @param username * @param password * @return */ Map<String, Object> returnHome(String username, String password); /** * 获得节点,对节点分页显示 * @param id * @param currPage * @return */ PageBean getNodeByUserId(int userid, int currPage); }
3,080
0.684932
0.684932
126
18.698412
20.551626
98
false
false
0
0
0
0
0
0
1.134921
false
false
9
2a07bab3c91c1f411608841926cc63274d981b56
20,383,914,789,014
c3bc6cf2d9d3c41c37679c1d1436c111174ec262
/LevelOrderTraversal.java
1fec749d37b668bf8b265ea3d3e4c73ce698036b
[]
no_license
supreeth18/LeetCode
https://github.com/supreeth18/LeetCode
271096994dae26a0876661493f28f0c8043ecbbc
fa05d9ef3ac25784d625ad239d17cc88dbe588cd
refs/heads/master
2021-01-16T21:21:26.597000
2016-06-24T20:03:39
2016-06-24T20:03:39
61,909,288
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.Leetcode.edu; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /* * Given a binary tree, return the level order traversal of its nodes' values. * (ie, from left to right, level by level). * */ public class LevelOrderTraversal { static class TreeNode { TreeNode left, right; int val; public TreeNode(int val) { this.val = val; } } public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> list = new ArrayList<List<Integer>>(); List<Integer> li = new ArrayList<Integer>(); Queue<TreeNode> q1 = new LinkedList<TreeNode>(); Queue<TreeNode> q2 = new LinkedList<TreeNode>(); if (root == null) return list; q1.add(root); while (!q1.isEmpty()) { root = q1.poll(); if (root.left != null) { q2.add(root.left); } if (root.right != null) { q2.add(root.right); } li.add(root.val); if (q1.isEmpty()) { q1 = q2; q2 = new LinkedList<TreeNode>(); list.add(li); li = new ArrayList<Integer>(); } } return list; } }
UTF-8
Java
1,129
java
LevelOrderTraversal.java
Java
[]
null
[]
package com.Leetcode.edu; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /* * Given a binary tree, return the level order traversal of its nodes' values. * (ie, from left to right, level by level). * */ public class LevelOrderTraversal { static class TreeNode { TreeNode left, right; int val; public TreeNode(int val) { this.val = val; } } public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> list = new ArrayList<List<Integer>>(); List<Integer> li = new ArrayList<Integer>(); Queue<TreeNode> q1 = new LinkedList<TreeNode>(); Queue<TreeNode> q2 = new LinkedList<TreeNode>(); if (root == null) return list; q1.add(root); while (!q1.isEmpty()) { root = q1.poll(); if (root.left != null) { q2.add(root.left); } if (root.right != null) { q2.add(root.right); } li.add(root.val); if (q1.isEmpty()) { q1 = q2; q2 = new LinkedList<TreeNode>(); list.add(li); li = new ArrayList<Integer>(); } } return list; } }
1,129
0.605846
0.596103
52
19.711538
17.955433
79
false
false
0
0
0
0
0
0
2.134615
false
false
9
8c97336fb1d8d012669f98a89df46b2718962a74
25,563,645,359,458
211e0162004b03455839879773c909a4d4868a2f
/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/ASTInfixExpression.java
e216c242d87e60147ee30e520da69d8ea637cea1
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
pmd/pmd
https://github.com/pmd/pmd
460ca96dfcc5d25b5b3e78fc8731593dc6ddf8d3
512d6cbb8d198119a588b84c238ed78d75abda0c
refs/heads/master
2023-09-04T05:58:54.224000
2023-08-31T14:20:57
2023-08-31T14:20:57
4,992,906
4,409
1,671
NOASSERTION
false
2023-09-14T08:13:05
2012-07-11T18:03:00
2023-09-13T12:22:00
2023-09-12T11:10:15
440,287
4,402
1,446
659
Java
false
false
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.Objects; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.java.ast.InternalInterfaces.AtLeastOneChild; import net.sourceforge.pmd.lang.java.ast.InternalInterfaces.BinaryExpressionLike; /** * Represents a binary infix expression. {@linkplain ASTAssignmentExpression Assignment expressions} * are not represented by this node, because they're right-associative. * * <p>This node is used to represent expressions of different precedences. * The {@linkplain BinaryOp operator} is used to differentiate those expressions. * * <pre class="grammar"> * * InfixExpression ::= {@link ASTExpression Expression} {@link BinaryOp} {@link ASTExpression Expression} * * </pre> * * <p>Binary expressions are all left-associative, and are parsed left-recursively. * For example, the expression {@code 1 * 2 * 3 % 4} parses as the following tree: * * <figure> * <img src="doc-files/binaryExpr_70x.svg" /> * </figure> * * <p>In PMD 6.0.x, it would have parsed into the tree: * * <figure> * <img src="doc-files/binaryExpr_60x.svg" /> * </figure> */ public final class ASTInfixExpression extends AbstractJavaExpr implements BinaryExpressionLike, AtLeastOneChild { private BinaryOp operator; ASTInfixExpression(int i) { super(i); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } void setOp(BinaryOp op) { this.operator = Objects.requireNonNull(op); } /** * Returns the right-hand side operand. * * <p>If this is an {@linkplain BinaryOp#INSTANCEOF instanceof expression}, * then the right operand is a {@linkplain ASTTypeExpression TypeExpression}. */ @Override public ASTExpression getRightOperand() { return BinaryExpressionLike.super.getRightOperand(); } /** Returns the operator. */ @Override public @NonNull BinaryOp getOperator() { return operator; } // intentionally left-out @Override public void setImage(String image) { throw new UnsupportedOperationException(); } @Override public String getImage() { return null; } }
UTF-8
Java
2,397
java
ASTInfixExpression.java
Java
[]
null
[]
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.ast; import java.util.Objects; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.java.ast.InternalInterfaces.AtLeastOneChild; import net.sourceforge.pmd.lang.java.ast.InternalInterfaces.BinaryExpressionLike; /** * Represents a binary infix expression. {@linkplain ASTAssignmentExpression Assignment expressions} * are not represented by this node, because they're right-associative. * * <p>This node is used to represent expressions of different precedences. * The {@linkplain BinaryOp operator} is used to differentiate those expressions. * * <pre class="grammar"> * * InfixExpression ::= {@link ASTExpression Expression} {@link BinaryOp} {@link ASTExpression Expression} * * </pre> * * <p>Binary expressions are all left-associative, and are parsed left-recursively. * For example, the expression {@code 1 * 2 * 3 % 4} parses as the following tree: * * <figure> * <img src="doc-files/binaryExpr_70x.svg" /> * </figure> * * <p>In PMD 6.0.x, it would have parsed into the tree: * * <figure> * <img src="doc-files/binaryExpr_60x.svg" /> * </figure> */ public final class ASTInfixExpression extends AbstractJavaExpr implements BinaryExpressionLike, AtLeastOneChild { private BinaryOp operator; ASTInfixExpression(int i) { super(i); } @Override protected <P, R> R acceptVisitor(JavaVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } void setOp(BinaryOp op) { this.operator = Objects.requireNonNull(op); } /** * Returns the right-hand side operand. * * <p>If this is an {@linkplain BinaryOp#INSTANCEOF instanceof expression}, * then the right operand is a {@linkplain ASTTypeExpression TypeExpression}. */ @Override public ASTExpression getRightOperand() { return BinaryExpressionLike.super.getRightOperand(); } /** Returns the operator. */ @Override public @NonNull BinaryOp getOperator() { return operator; } // intentionally left-out @Override public void setImage(String image) { throw new UnsupportedOperationException(); } @Override public String getImage() { return null; } }
2,397
0.691698
0.687526
89
25.932585
30.714634
113
false
false
0
0
0
0
0
0
0.269663
false
false
9
3aeb840736500dc17f12b6f1d3fabc533145e249
858,993,472,989
6025c51991cca34c7f722f37e47d658d26c645d7
/app/src/main/java/ch/epfl/sweng/partyup/SharedAndSavedData.java
48d7a573b67e2e790c1d7357828d9cddcf7bbd31
[]
no_license
mducroux/team-burton
https://github.com/mducroux/team-burton
b4d4abaa06223d8a01b4f55b3b91363dcd8eb2d4
ac36980320b6ef02ee140b446dd4cbde33e4256e
refs/heads/master
2021-09-25T02:03:01.003000
2018-10-16T18:21:44
2018-10-16T18:21:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ch.epfl.sweng.partyup; import android.content.Context; import android.content.SharedPreferences; import ch.epfl.sweng.partyup.dbstore.Party; public class SharedAndSavedData { public static Party connectedParty=null; public static String connectedPartyID=null; /** * read the system to find if we were connected to a party * * @param context a context to access resources. * @return the partyId or null if we were not connected */ public static String getSavedConnectedPartyId(Context context){ SharedPreferences sharedPref = context.getSharedPreferences( context.getString(R.string.data_save_filename), Context.MODE_PRIVATE); return sharedPref.getString(context.getString(R.string.key_pref_connected_party),null); } /** * read the system to find if we were host of a previously connected party * * @param context a context to access resources. * @return true if we were host of the previously connected party */ public static boolean getSavedConnectedIsHost(Context context){ SharedPreferences sharedPref = context.getSharedPreferences( context.getString(R.string.data_save_filename), Context.MODE_PRIVATE); return sharedPref.getBoolean(context.getString(R.string.key_pref_is_host),false); } /** * write the system with info about the party we are connected * * @param context a context to access resources. * @param partyId the ID if the party * @param isHost are we hosting the party? * @return true if the write succeded */ public static boolean setSavedConnectedInfo(Context context, final String partyId, final boolean isHost){ SharedPreferences.Editor sharedPrefEdit = context.getSharedPreferences( context.getString(R.string.data_save_filename), Context.MODE_PRIVATE).edit(); sharedPrefEdit.putString(context.getString(R.string.key_pref_connected_party),partyId); sharedPrefEdit.putBoolean(context.getString(R.string.key_pref_is_host),isHost); return sharedPrefEdit.commit(); } }
UTF-8
Java
2,150
java
SharedAndSavedData.java
Java
[]
null
[]
package ch.epfl.sweng.partyup; import android.content.Context; import android.content.SharedPreferences; import ch.epfl.sweng.partyup.dbstore.Party; public class SharedAndSavedData { public static Party connectedParty=null; public static String connectedPartyID=null; /** * read the system to find if we were connected to a party * * @param context a context to access resources. * @return the partyId or null if we were not connected */ public static String getSavedConnectedPartyId(Context context){ SharedPreferences sharedPref = context.getSharedPreferences( context.getString(R.string.data_save_filename), Context.MODE_PRIVATE); return sharedPref.getString(context.getString(R.string.key_pref_connected_party),null); } /** * read the system to find if we were host of a previously connected party * * @param context a context to access resources. * @return true if we were host of the previously connected party */ public static boolean getSavedConnectedIsHost(Context context){ SharedPreferences sharedPref = context.getSharedPreferences( context.getString(R.string.data_save_filename), Context.MODE_PRIVATE); return sharedPref.getBoolean(context.getString(R.string.key_pref_is_host),false); } /** * write the system with info about the party we are connected * * @param context a context to access resources. * @param partyId the ID if the party * @param isHost are we hosting the party? * @return true if the write succeded */ public static boolean setSavedConnectedInfo(Context context, final String partyId, final boolean isHost){ SharedPreferences.Editor sharedPrefEdit = context.getSharedPreferences( context.getString(R.string.data_save_filename), Context.MODE_PRIVATE).edit(); sharedPrefEdit.putString(context.getString(R.string.key_pref_connected_party),partyId); sharedPrefEdit.putBoolean(context.getString(R.string.key_pref_is_host),isHost); return sharedPrefEdit.commit(); } }
2,150
0.708372
0.708372
59
35.440678
33.939762
109
false
false
0
0
0
0
0
0
0.38983
false
false
9
2ae2d24e528052fc75a5877015277bfc22cc832d
10,969,346,480,580
93934966a4c3a81cc1fc74886e19c1f3c00524fa
/EquipMSServer/src/main/java/cn/unuai/dao/EquipmentDao.java
001e46724d301593d7667054c6d1010283e94991
[]
no_license
unuai/ems
https://github.com/unuai/ems
4523952c55d510578da3b89fc176f73ec8491e22
1c19873f387c2adc48a4e5f7453a412ee43c7963
refs/heads/master
2018-09-29T21:16:02.449000
2018-06-08T15:27:29
2018-06-08T15:27:29
136,363,943
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.unuai.dao; import cn.unuai.entity.EquipmentEntity; import cn.unuai.util.Util; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import java.util.List; /** * Created by SunShuai on 2018/4/26. */ public interface EquipmentDao extends JpaRepository<EquipmentEntity, Long> { public EquipmentEntity save(EquipmentEntity e); @Query(value = "select cast(max(SUBSTR(asset_no ,LENGTH(asset_no)-2)) as unsigned int) from equipment where equip_type=?1", nativeQuery = true) public Integer getMaxAssetNo(int type); @Query("select e from EquipmentEntity e where assetNo=?1") public EquipmentEntity findByAssetNo(String assetNo); @Modifying @Query("update EquipmentEntity e set e.state=?2 where e.id=?1") public void setEquipmentState(int id, int state); @Query(value = "SELECT e.id,e. NAME,e.asset_no," + "( SELECT k. NAME FROM Kind k WHERE k.id = e.equip_type ) AS equipType," + "( SELECT k. NAME FROM Kind k WHERE k.id = e.state ) AS state " + "FROM Equipment e where e.name like ?1 and e.state like ?2 and e.equip_type like ?3 ORDER BY e.asset_no limit ?4,?5", nativeQuery = true) public List getEquipList(String name, String state, String type, int offset, int pageSize); @Query(value = "SELECT count(e.id)" + "FROM equipment e where e.name like ?1 and e.state like ?2 and e.equip_type like ?3", nativeQuery = true) public int getEquipListCount(String name, String state, String type); @Query(value = "select e.id,e. name,e.asset_no,e.factory,f.factoryname, e.buy_date,e.pos,e.price,e.buy_dept,d.deptname,e.use_year,e.image,e.equip_type," + "( select k. name from kind k where k.id = e.equip_type ) as typeName,e.state," + "( select k. name from Kind k where k.id = e.state ) as stateName,e.repaire_cycle " + "from equipment e, factory f,department d " + "where e.id=?1 and e.factory=f.id and e.buy_dept=d.id", nativeQuery = true) public List getEquipmentInfo(int id); @Query(value = "select count(1),(select k2.name from kind k2 where k2.id=e.equip_type) typeName " + "from equipment e,kind k " + "where e.state=k.id " + "group by e.equip_type", nativeQuery = true) public List getTypeCount(); @Query(value = "select count(1) from equipment where state like ?1", nativeQuery = true) public int getEquipmentCountByState(String state); @Query(value = "select sum(price) from EquipmentEntity e") public float getotalAssets(); @Modifying @Query("update EquipmentEntity set lastRepaire = ?1 where assetNo=?2") public void setLastRepaireDate(String date, String assetNo); @Query(value = "select avg(TO_DAYS(g.giveup_date)-TO_DAYS(e.buy_date)) " + "from equipment e,giveup g " + "where e.id=g.equip_id and e.equip_type=?1", nativeQuery = true) public Double getAvgAge(int type); @Query("select e from EquipmentEntity e where id=?1") public EquipmentEntity getOne(int id); }
UTF-8
Java
3,370
java
EquipmentDao.java
Java
[ { "context": ".Query;\n\nimport java.util.List;\n\n/**\n * Created by SunShuai on 2018/4/26.\n */\npublic interface EquipmentDa", "end": 406, "score": 0.7706506848335266, "start": 401, "tag": "USERNAME", "value": "SunSh" }, { "context": ";\n\nimport java.util.List;\n\n/**\n * Created by SunShuai on 2018/4/26.\n */\npublic interface EquipmentDao", "end": 407, "score": 0.5055092573165894, "start": 406, "tag": "NAME", "value": "u" }, { "context": "\n\nimport java.util.List;\n\n/**\n * Created by SunShuai on 2018/4/26.\n */\npublic interface EquipmentDao e", "end": 409, "score": 0.7738577127456665, "start": 407, "tag": "USERNAME", "value": "ai" } ]
null
[]
package cn.unuai.dao; import cn.unuai.entity.EquipmentEntity; import cn.unuai.util.Util; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import java.util.List; /** * Created by SunShuai on 2018/4/26. */ public interface EquipmentDao extends JpaRepository<EquipmentEntity, Long> { public EquipmentEntity save(EquipmentEntity e); @Query(value = "select cast(max(SUBSTR(asset_no ,LENGTH(asset_no)-2)) as unsigned int) from equipment where equip_type=?1", nativeQuery = true) public Integer getMaxAssetNo(int type); @Query("select e from EquipmentEntity e where assetNo=?1") public EquipmentEntity findByAssetNo(String assetNo); @Modifying @Query("update EquipmentEntity e set e.state=?2 where e.id=?1") public void setEquipmentState(int id, int state); @Query(value = "SELECT e.id,e. NAME,e.asset_no," + "( SELECT k. NAME FROM Kind k WHERE k.id = e.equip_type ) AS equipType," + "( SELECT k. NAME FROM Kind k WHERE k.id = e.state ) AS state " + "FROM Equipment e where e.name like ?1 and e.state like ?2 and e.equip_type like ?3 ORDER BY e.asset_no limit ?4,?5", nativeQuery = true) public List getEquipList(String name, String state, String type, int offset, int pageSize); @Query(value = "SELECT count(e.id)" + "FROM equipment e where e.name like ?1 and e.state like ?2 and e.equip_type like ?3", nativeQuery = true) public int getEquipListCount(String name, String state, String type); @Query(value = "select e.id,e. name,e.asset_no,e.factory,f.factoryname, e.buy_date,e.pos,e.price,e.buy_dept,d.deptname,e.use_year,e.image,e.equip_type," + "( select k. name from kind k where k.id = e.equip_type ) as typeName,e.state," + "( select k. name from Kind k where k.id = e.state ) as stateName,e.repaire_cycle " + "from equipment e, factory f,department d " + "where e.id=?1 and e.factory=f.id and e.buy_dept=d.id", nativeQuery = true) public List getEquipmentInfo(int id); @Query(value = "select count(1),(select k2.name from kind k2 where k2.id=e.equip_type) typeName " + "from equipment e,kind k " + "where e.state=k.id " + "group by e.equip_type", nativeQuery = true) public List getTypeCount(); @Query(value = "select count(1) from equipment where state like ?1", nativeQuery = true) public int getEquipmentCountByState(String state); @Query(value = "select sum(price) from EquipmentEntity e") public float getotalAssets(); @Modifying @Query("update EquipmentEntity set lastRepaire = ?1 where assetNo=?2") public void setLastRepaireDate(String date, String assetNo); @Query(value = "select avg(TO_DAYS(g.giveup_date)-TO_DAYS(e.buy_date)) " + "from equipment e,giveup g " + "where e.id=g.equip_id and e.equip_type=?1", nativeQuery = true) public Double getAvgAge(int type); @Query("select e from EquipmentEntity e where id=?1") public EquipmentEntity getOne(int id); }
3,370
0.662611
0.653412
72
45.805557
39.370617
157
false
false
0
0
0
0
0
0
0.902778
false
false
9
c13b34366797f66908f40af45041c37edb96fbfd
10,969,346,483,345
4fcdc84de04ffae414157eded3522518cab93d36
/src/main/java/com/k7/services/NioFileContactService.java
748bc90646dc701b824695308c78241fe760da60
[]
no_license
NSemm/je_dz17
https://github.com/NSemm/je_dz17
53176160d81e25b0ebba9b4c55a384157d4f470d
11c2b54ae8c14899eb3618b01f5c43f4529a7682
refs/heads/master
2023-03-25T09:27:39.208000
2021-03-10T09:57:16
2021-03-10T09:57:16
336,139,922
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.k7.services; import com.k7.contacts.Contact; import com.k7.contacts.ContactType; import lombok.AllArgsConstructor; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @AllArgsConstructor public class NioFileContactService implements ContactService { private String filePath; @Override public void add(Contact c) { try (SeekableByteChannel channel = Files.newByteChannel( Path.of(filePath), StandardOpenOption.APPEND)) { ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.put(new String(c.getName() + "[" + c.getType().toString().toLowerCase() + ":" + c.getValue() + "]\n") .getBytes()); buffer.flip(); channel.write(buffer); buffer.clear(); } catch (IOException e) { e.printStackTrace(); } } @Override public void remove(Integer id) { throw new UnsupportedOperationException("in develop"); } @Override public List<Contact> findByName(String name) { return getContactList().stream() .filter(c -> c.getName().startsWith(name)) .collect(Collectors.toList()); } @Override public List<Contact> findByValue(String value) { return getContactList().stream() .filter(c -> c.getValue().startsWith(value)) .collect(Collectors.toList()); } @Override public List<Contact> getAll() { return getContactList(); } private List<Contact> getContactList() { try (SeekableByteChannel channel = Files.newByteChannel(Path.of(filePath), StandardOpenOption.READ)) { ByteBuffer buffer = ByteBuffer.allocate(1024); String in = ""; List<Contact> contactList = new ArrayList<>(); while (channel.read(buffer) != -1) { buffer.flip(); in += getStringFromBuffer(buffer); String[] strParts = in.split("\n"); for (int i = 0; i < strParts.length - 1; i++) { // System.out.println("strParts[" + i + "]: " + strParts[i]); contactList.add(parse(strParts[i])); } in = strParts[strParts.length - 1]; // System.out.println("in: " + in); buffer.clear(); } if (parse(in) != null) contactList.add(parse(in)); return contactList; } catch ( IOException e) { e.printStackTrace(); } return Collections.emptyList(); } private String getStringFromBuffer(ByteBuffer buffer) { return new String(buffer.array(), buffer.position(), buffer.limit()); } private Contact parse(String user) { Pattern pattern = Pattern.compile("(?:(.+)\\[)(?:(.+):)(?:(.+)\\])"); Matcher matcher = pattern.matcher(user); Contact parsedUser = new Contact(); if ((!matcher.matches())) { System.out.println(user + " - Invalid user!"); return null; } else { parsedUser.setName(matcher.group(1)); parsedUser.setType(ContactType.valueOf(matcher.group(2).toUpperCase())); parsedUser.setValue(matcher.group(3)); } return parsedUser; } }
UTF-8
Java
3,701
java
NioFileContactService.java
Java
[]
null
[]
package com.k7.services; import com.k7.contacts.Contact; import com.k7.contacts.ContactType; import lombok.AllArgsConstructor; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @AllArgsConstructor public class NioFileContactService implements ContactService { private String filePath; @Override public void add(Contact c) { try (SeekableByteChannel channel = Files.newByteChannel( Path.of(filePath), StandardOpenOption.APPEND)) { ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.put(new String(c.getName() + "[" + c.getType().toString().toLowerCase() + ":" + c.getValue() + "]\n") .getBytes()); buffer.flip(); channel.write(buffer); buffer.clear(); } catch (IOException e) { e.printStackTrace(); } } @Override public void remove(Integer id) { throw new UnsupportedOperationException("in develop"); } @Override public List<Contact> findByName(String name) { return getContactList().stream() .filter(c -> c.getName().startsWith(name)) .collect(Collectors.toList()); } @Override public List<Contact> findByValue(String value) { return getContactList().stream() .filter(c -> c.getValue().startsWith(value)) .collect(Collectors.toList()); } @Override public List<Contact> getAll() { return getContactList(); } private List<Contact> getContactList() { try (SeekableByteChannel channel = Files.newByteChannel(Path.of(filePath), StandardOpenOption.READ)) { ByteBuffer buffer = ByteBuffer.allocate(1024); String in = ""; List<Contact> contactList = new ArrayList<>(); while (channel.read(buffer) != -1) { buffer.flip(); in += getStringFromBuffer(buffer); String[] strParts = in.split("\n"); for (int i = 0; i < strParts.length - 1; i++) { // System.out.println("strParts[" + i + "]: " + strParts[i]); contactList.add(parse(strParts[i])); } in = strParts[strParts.length - 1]; // System.out.println("in: " + in); buffer.clear(); } if (parse(in) != null) contactList.add(parse(in)); return contactList; } catch ( IOException e) { e.printStackTrace(); } return Collections.emptyList(); } private String getStringFromBuffer(ByteBuffer buffer) { return new String(buffer.array(), buffer.position(), buffer.limit()); } private Contact parse(String user) { Pattern pattern = Pattern.compile("(?:(.+)\\[)(?:(.+):)(?:(.+)\\])"); Matcher matcher = pattern.matcher(user); Contact parsedUser = new Contact(); if ((!matcher.matches())) { System.out.println(user + " - Invalid user!"); return null; } else { parsedUser.setName(matcher.group(1)); parsedUser.setType(ContactType.valueOf(matcher.group(2).toUpperCase())); parsedUser.setValue(matcher.group(3)); } return parsedUser; } }
3,701
0.576061
0.571197
110
32.654545
23.621807
120
false
false
0
0
0
0
0
0
0.527273
false
false
9
1c80cf6381a82c1a8abea98b2be997e91b1b4e35
12,240,656,815,759
46c688cb2a2079908ed3f1b5b6dd6cc552eefa70
/src/main/java/com/shabloel/recipeapp/model/UnitOfMeasure.java
1ef8a92c77f52a05861baa41a08d55310fba8325
[]
no_license
shabloel/recipe-app
https://github.com/shabloel/recipe-app
f103e6daf5591a8cc9792754f71db2d70cbf65d2
6518efead3b42e57e5b61e594ccecb27da44bca9
refs/heads/master
2023-08-19T18:23:57.593000
2021-10-11T08:51:28
2021-10-11T08:51:28
376,749,299
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.shabloel.recipeapp.model; import lombok.Data; import javax.persistence.*; /** * @author christiaan.griffioen on feb, 2021 */ @Data @Entity @Table(name = "Unit_Of_Measure") public class UnitOfMeasure { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "uom_id") private Long id; @Column(name = "description") private String description; @OneToOne @PrimaryKeyJoinColumn private Ingredient ingredient; }
UTF-8
Java
478
java
UnitOfMeasure.java
Java
[ { "context": "Data;\n\nimport javax.persistence.*;\n\n/**\n * @author christiaan.griffioen on feb, 2021\n */\n@Data\n@Entity\n@Table(name = \"Uni", "end": 124, "score": 0.9989239573478699, "start": 104, "tag": "NAME", "value": "christiaan.griffioen" } ]
null
[]
package com.shabloel.recipeapp.model; import lombok.Data; import javax.persistence.*; /** * @author christiaan.griffioen on feb, 2021 */ @Data @Entity @Table(name = "Unit_Of_Measure") public class UnitOfMeasure { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "uom_id") private Long id; @Column(name = "description") private String description; @OneToOne @PrimaryKeyJoinColumn private Ingredient ingredient; }
478
0.698745
0.690377
26
17.384615
16.048189
55
false
false
0
0
0
0
0
0
0.269231
false
false
9
7e7dd7335377d65e7f5cdac611b19177fb8ec6b6
7,765,300,907,921
9959a9d149b9f704b7ac5ced98895eed2d1655c6
/Ensayo 2/src/main/java/cl/awakelab/ensayo2/dao/ProductoDAO.java
6da691e5ca39bb20cf040a54fbc557819839c6da
[]
no_license
dgpizarro/Awakelab-Ensayo2-PruebaTD
https://github.com/dgpizarro/Awakelab-Ensayo2-PruebaTD
5ac66d7043e08a12792c66a1c339c7505e96801b
64f83b8944709791fa30d4bf743b22c5b8b6145b
refs/heads/master
2022-12-10T14:06:03.509000
2020-09-10T02:24:13
2020-09-10T02:24:13
294,277,437
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cl.awakelab.ensayo2.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import cl.awakelab.ensayo2.model.Producto; public class ProductoDAO { JdbcTemplate template; public void setTemplate(JdbcTemplate template) { this.template = template; } public class ProductoMapper implements RowMapper<Producto> { public Producto mapRow(ResultSet rs, int rowNum) throws SQLException { Producto p = new Producto(); p.setProductoid(rs.getInt(1)); p.setNombre(rs.getString(2)); p.setValor(rs.getInt(3)); return p; } } public List<Producto> listarProductosXCategoria(int id) { String sql = "select productoid, p.nombre, valor from producto p inner join categoria c on" + " (p.categoriaid = c.categoriaid) where p.categoriaid = " + id; return template.query(sql, new ProductoMapper()); } }
UTF-8
Java
1,103
java
ProductoDAO.java
Java
[]
null
[]
package cl.awakelab.ensayo2.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import cl.awakelab.ensayo2.model.Producto; public class ProductoDAO { JdbcTemplate template; public void setTemplate(JdbcTemplate template) { this.template = template; } public class ProductoMapper implements RowMapper<Producto> { public Producto mapRow(ResultSet rs, int rowNum) throws SQLException { Producto p = new Producto(); p.setProductoid(rs.getInt(1)); p.setNombre(rs.getString(2)); p.setValor(rs.getInt(3)); return p; } } public List<Producto> listarProductosXCategoria(int id) { String sql = "select productoid, p.nombre, valor from producto p inner join categoria c on" + " (p.categoriaid = c.categoriaid) where p.categoriaid = " + id; return template.query(sql, new ProductoMapper()); } }
1,103
0.650045
0.645512
36
28.638889
26.687651
99
false
false
0
0
0
0
0
0
0.555556
false
false
9
766e29283ba5ca73d8ad8e2834694d0d2aded029
6,322,191,880,354
6d7416e5831c0a11f328c17996bdedc71c55cf03
/Android/LCTF2016/easy100/myapp/sources/android/support/v7/widget/l.java
fa5d9685f8b2ba779935575ee6095882d9985fde
[]
no_license
Vorblock/myCTF-Study
https://github.com/Vorblock/myCTF-Study
68d166f2170e6c50bd0ff8de5044a67a99b455a2
0add379618cbe67362fe1363142ebb1ad78d45c5
refs/heads/master
2020-03-28T05:36:31.893000
2018-09-19T02:10:57
2018-09-19T02:10:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package android.support.v7.widget; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.database.DataSetObservable; import android.os.AsyncTask; import android.text.TextUtils; import android.util.Log; import android.util.Xml; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; class l extends DataSetObservable { static final boolean a = false; static final String b = l.class.getSimpleName(); static final String c = "historical-records"; static final String d = "historical-record"; static final String e = "activity"; static final String f = "time"; static final String g = "weight"; public static final String h = "activity_choser_model_history.xml"; public static final int i = 50; private static final int m = 5; private static final float n = 1.0f; private static final String o = ".xml"; private static final int p = -1; private static final Object q = new Object(); private static final Map<String, l> r = new HashMap(); private boolean A = false; private f B; final Context j; final String k; boolean l = true; private final Object s = new Object(); private final List<b> t = new ArrayList(); private final List<e> u = new ArrayList(); private Intent v; private c w = new d(); private int x = 50; private boolean y = false; private boolean z = true; public interface a { void setActivityChooserModel(l lVar); } public interface f { boolean a(l lVar, Intent intent); } public final class b implements Comparable<b> { public final ResolveInfo a; public float b; public b(ResolveInfo resolveInfo) { this.a = resolveInfo; } public int hashCode() { return Float.floatToIntBits(this.b) + 31; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } if (Float.floatToIntBits(this.b) != Float.floatToIntBits(((b) obj).b)) { return false; } return true; } /* renamed from: a */ public int compareTo(b bVar) { return Float.floatToIntBits(bVar.b) - Float.floatToIntBits(this.b); } public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("["); stringBuilder.append("resolveInfo:").append(this.a.toString()); stringBuilder.append("; weight:").append(new BigDecimal((double) this.b)); stringBuilder.append("]"); return stringBuilder.toString(); } } public interface c { void a(Intent intent, List<b> list, List<e> list2); } private final class d implements c { private static final float b = 0.95f; private final Map<ComponentName, b> c = new HashMap(); d() { } public void a(Intent intent, List<b> list, List<e> list2) { Map map = this.c; map.clear(); int size = list.size(); for (int i = 0; i < size; i++) { b bVar = (b) list.get(i); bVar.b = 0.0f; map.put(new ComponentName(bVar.a.activityInfo.packageName, bVar.a.activityInfo.name), bVar); } int size2 = list2.size() - 1; float f = l.n; int i2 = size2; while (i2 >= 0) { float f2; e eVar = (e) list2.get(i2); b bVar2 = (b) map.get(eVar.a); if (bVar2 != null) { bVar2.b = (eVar.c * f) + bVar2.b; f2 = b * f; } else { f2 = f; } i2--; f = f2; } Collections.sort(list); } } public static final class e { public final ComponentName a; public final long b; public final float c; public e(String str, long j, float f) { this(ComponentName.unflattenFromString(str), j, f); } public e(ComponentName componentName, long j, float f) { this.a = componentName; this.b = j; this.c = f; } public int hashCode() { return (((((this.a == null ? 0 : this.a.hashCode()) + 31) * 31) + ((int) (this.b ^ (this.b >>> 32)))) * 31) + Float.floatToIntBits(this.c); } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } e eVar = (e) obj; if (this.a == null) { if (eVar.a != null) { return false; } } else if (!this.a.equals(eVar.a)) { return false; } if (this.b != eVar.b) { return false; } if (Float.floatToIntBits(this.c) != Float.floatToIntBits(eVar.c)) { return false; } return true; } public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("["); stringBuilder.append("; activity:").append(this.a); stringBuilder.append("; time:").append(this.b); stringBuilder.append("; weight:").append(new BigDecimal((double) this.c)); stringBuilder.append("]"); return stringBuilder.toString(); } } private final class g extends AsyncTask<Object, Void, Void> { g() { } /* renamed from: a */ public Void doInBackground(Object... objArr) { int i = 0; List list = (List) objArr[0]; String str = (String) objArr[1]; try { OutputStream openFileOutput = l.this.j.openFileOutput(str, 0); XmlSerializer newSerializer = Xml.newSerializer(); try { newSerializer.setOutput(openFileOutput, null); newSerializer.startDocument("UTF-8", Boolean.valueOf(true)); newSerializer.startTag(null, l.c); int size = list.size(); while (i < size) { e eVar = (e) list.remove(0); newSerializer.startTag(null, l.d); newSerializer.attribute(null, l.e, eVar.a.flattenToString()); newSerializer.attribute(null, l.f, String.valueOf(eVar.b)); newSerializer.attribute(null, l.g, String.valueOf(eVar.c)); newSerializer.endTag(null, l.d); i++; } newSerializer.endTag(null, l.c); newSerializer.endDocument(); l.this.l = true; if (openFileOutput != null) { try { openFileOutput.close(); } catch (IOException e) { } } } catch (Throwable e2) { Log.e(l.b, "Error writing historical record file: " + l.this.k, e2); l.this.l = true; if (openFileOutput != null) { try { openFileOutput.close(); } catch (IOException e3) { } } } catch (Throwable e22) { Log.e(l.b, "Error writing historical record file: " + l.this.k, e22); l.this.l = true; if (openFileOutput != null) { try { openFileOutput.close(); } catch (IOException e4) { } } } catch (Throwable e222) { Log.e(l.b, "Error writing historical record file: " + l.this.k, e222); l.this.l = true; if (openFileOutput != null) { try { openFileOutput.close(); } catch (IOException e5) { } } } catch (Throwable th) { l.this.l = true; if (openFileOutput != null) { try { openFileOutput.close(); } catch (IOException e6) { } } } } catch (Throwable e2222) { Log.e(l.b, "Error writing historical record file: " + str, e2222); } return null; } } public static l a(Context context, String str) { l lVar; synchronized (q) { lVar = (l) r.get(str); if (lVar == null) { lVar = new l(context, str); r.put(str, lVar); } } return lVar; } private l(Context context, String str) { this.j = context.getApplicationContext(); if (TextUtils.isEmpty(str) || str.endsWith(o)) { this.k = str; } else { this.k = str + o; } } public void a(Intent intent) { synchronized (this.s) { if (this.v == intent) { return; } this.v = intent; this.A = true; g(); } } public Intent a() { Intent intent; synchronized (this.s) { intent = this.v; } return intent; } public int b() { int size; synchronized (this.s) { g(); size = this.t.size(); } return size; } public ResolveInfo a(int i) { ResolveInfo resolveInfo; synchronized (this.s) { g(); resolveInfo = ((b) this.t.get(i)).a; } return resolveInfo; } public int a(ResolveInfo resolveInfo) { synchronized (this.s) { g(); List list = this.t; int size = list.size(); for (int i = 0; i < size; i++) { if (((b) list.get(i)).a == resolveInfo) { return i; } } return -1; } } public Intent b(int i) { synchronized (this.s) { if (this.v == null) { return null; } g(); b bVar = (b) this.t.get(i); ComponentName componentName = new ComponentName(bVar.a.activityInfo.packageName, bVar.a.activityInfo.name); Intent intent = new Intent(this.v); intent.setComponent(componentName); if (this.B != null) { if (this.B.a(this, new Intent(intent))) { return null; } } a(new e(componentName, System.currentTimeMillis(), (float) n)); return intent; } } public void a(f fVar) { synchronized (this.s) { this.B = fVar; } } public ResolveInfo c() { synchronized (this.s) { g(); if (this.t.isEmpty()) { return null; } ResolveInfo resolveInfo = ((b) this.t.get(0)).a; return resolveInfo; } } public void c(int i) { synchronized (this.s) { float f; g(); b bVar = (b) this.t.get(i); b bVar2 = (b) this.t.get(0); if (bVar2 != null) { f = (bVar2.b - bVar.b) + 5.0f; } else { f = n; } a(new e(new ComponentName(bVar.a.activityInfo.packageName, bVar.a.activityInfo.name), System.currentTimeMillis(), f)); } } private void f() { if (!this.y) { throw new IllegalStateException("No preceding call to #readHistoricalData"); } else if (this.z) { this.z = false; if (!TextUtils.isEmpty(this.k)) { android.support.v4.k.a.a(new g(), new ArrayList(this.u), this.k); } } } /* JADX WARNING: Missing block: B:14:?, code: return; */ public void a(android.support.v7.widget.l.c r3) { /* r2 = this; r1 = r2.s; monitor-enter(r1); r0 = r2.w; Catch:{ all -> 0x0016 } if (r0 != r3) goto L_0x0009; L_0x0007: monitor-exit(r1); Catch:{ all -> 0x0016 } L_0x0008: return; L_0x0009: r2.w = r3; Catch:{ all -> 0x0016 } r0 = r2.h(); Catch:{ all -> 0x0016 } if (r0 == 0) goto L_0x0014; L_0x0011: r2.notifyChanged(); Catch:{ all -> 0x0016 } L_0x0014: monitor-exit(r1); Catch:{ all -> 0x0016 } goto L_0x0008; L_0x0016: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x0016 } throw r0; */ throw new UnsupportedOperationException("Method not decompiled: android.support.v7.widget.l.a(android.support.v7.widget.l$c):void"); } /* JADX WARNING: Missing block: B:14:?, code: return; */ public void d(int r3) { /* r2 = this; r1 = r2.s; monitor-enter(r1); r0 = r2.x; Catch:{ all -> 0x0019 } if (r0 != r3) goto L_0x0009; L_0x0007: monitor-exit(r1); Catch:{ all -> 0x0019 } L_0x0008: return; L_0x0009: r2.x = r3; Catch:{ all -> 0x0019 } r2.k(); Catch:{ all -> 0x0019 } r0 = r2.h(); Catch:{ all -> 0x0019 } if (r0 == 0) goto L_0x0017; L_0x0014: r2.notifyChanged(); Catch:{ all -> 0x0019 } L_0x0017: monitor-exit(r1); Catch:{ all -> 0x0019 } goto L_0x0008; L_0x0019: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x0019 } throw r0; */ throw new UnsupportedOperationException("Method not decompiled: android.support.v7.widget.l.d(int):void"); } public int d() { int i; synchronized (this.s) { i = this.x; } return i; } public int e() { int size; synchronized (this.s) { g(); size = this.u.size(); } return size; } private void g() { int i = i() | j(); k(); if (i != 0) { h(); notifyChanged(); } } private boolean h() { if (this.w == null || this.v == null || this.t.isEmpty() || this.u.isEmpty()) { return false; } this.w.a(this.v, this.t, Collections.unmodifiableList(this.u)); return true; } private boolean i() { if (!this.A || this.v == null) { return false; } this.A = false; this.t.clear(); List queryIntentActivities = this.j.getPackageManager().queryIntentActivities(this.v, 0); int size = queryIntentActivities.size(); for (int i = 0; i < size; i++) { this.t.add(new b((ResolveInfo) queryIntentActivities.get(i))); } return true; } private boolean j() { if (!this.l || !this.z || TextUtils.isEmpty(this.k)) { return false; } this.l = false; this.y = true; l(); return true; } private boolean a(e eVar) { boolean add = this.u.add(eVar); if (add) { this.z = true; k(); f(); h(); notifyChanged(); } return add; } private void k() { int size = this.u.size() - this.x; if (size > 0) { this.z = true; for (int i = 0; i < size; i++) { e eVar = (e) this.u.remove(0); } } } private void l() { try { InputStream openFileInput = this.j.openFileInput(this.k); try { XmlPullParser newPullParser = Xml.newPullParser(); newPullParser.setInput(openFileInput, "UTF-8"); int i = 0; while (i != 1 && i != 2) { i = newPullParser.next(); } if (c.equals(newPullParser.getName())) { List list = this.u; list.clear(); while (true) { int next = newPullParser.next(); if (next == 1) { if (openFileInput != null) { try { openFileInput.close(); return; } catch (IOException e) { return; } } return; } else if (!(next == 3 || next == 4)) { if (d.equals(newPullParser.getName())) { list.add(new e(newPullParser.getAttributeValue(null, e), Long.parseLong(newPullParser.getAttributeValue(null, f)), Float.parseFloat(newPullParser.getAttributeValue(null, g)))); } else { throw new XmlPullParserException("Share records file not well-formed."); } } } } throw new XmlPullParserException("Share records file does not start with historical-records tag."); } catch (Throwable e2) { Log.e(b, "Error reading historical recrod file: " + this.k, e2); if (openFileInput != null) { try { openFileInput.close(); } catch (IOException e3) { } } } catch (Throwable e22) { Log.e(b, "Error reading historical recrod file: " + this.k, e22); if (openFileInput != null) { try { openFileInput.close(); } catch (IOException e4) { } } } catch (Throwable th) { if (openFileInput != null) { try { openFileInput.close(); } catch (IOException e5) { } } } } catch (FileNotFoundException e6) { } } }
UTF-8
Java
19,601
java
l.java
Java
[]
null
[]
package android.support.v7.widget; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.database.DataSetObservable; import android.os.AsyncTask; import android.text.TextUtils; import android.util.Log; import android.util.Xml; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; class l extends DataSetObservable { static final boolean a = false; static final String b = l.class.getSimpleName(); static final String c = "historical-records"; static final String d = "historical-record"; static final String e = "activity"; static final String f = "time"; static final String g = "weight"; public static final String h = "activity_choser_model_history.xml"; public static final int i = 50; private static final int m = 5; private static final float n = 1.0f; private static final String o = ".xml"; private static final int p = -1; private static final Object q = new Object(); private static final Map<String, l> r = new HashMap(); private boolean A = false; private f B; final Context j; final String k; boolean l = true; private final Object s = new Object(); private final List<b> t = new ArrayList(); private final List<e> u = new ArrayList(); private Intent v; private c w = new d(); private int x = 50; private boolean y = false; private boolean z = true; public interface a { void setActivityChooserModel(l lVar); } public interface f { boolean a(l lVar, Intent intent); } public final class b implements Comparable<b> { public final ResolveInfo a; public float b; public b(ResolveInfo resolveInfo) { this.a = resolveInfo; } public int hashCode() { return Float.floatToIntBits(this.b) + 31; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } if (Float.floatToIntBits(this.b) != Float.floatToIntBits(((b) obj).b)) { return false; } return true; } /* renamed from: a */ public int compareTo(b bVar) { return Float.floatToIntBits(bVar.b) - Float.floatToIntBits(this.b); } public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("["); stringBuilder.append("resolveInfo:").append(this.a.toString()); stringBuilder.append("; weight:").append(new BigDecimal((double) this.b)); stringBuilder.append("]"); return stringBuilder.toString(); } } public interface c { void a(Intent intent, List<b> list, List<e> list2); } private final class d implements c { private static final float b = 0.95f; private final Map<ComponentName, b> c = new HashMap(); d() { } public void a(Intent intent, List<b> list, List<e> list2) { Map map = this.c; map.clear(); int size = list.size(); for (int i = 0; i < size; i++) { b bVar = (b) list.get(i); bVar.b = 0.0f; map.put(new ComponentName(bVar.a.activityInfo.packageName, bVar.a.activityInfo.name), bVar); } int size2 = list2.size() - 1; float f = l.n; int i2 = size2; while (i2 >= 0) { float f2; e eVar = (e) list2.get(i2); b bVar2 = (b) map.get(eVar.a); if (bVar2 != null) { bVar2.b = (eVar.c * f) + bVar2.b; f2 = b * f; } else { f2 = f; } i2--; f = f2; } Collections.sort(list); } } public static final class e { public final ComponentName a; public final long b; public final float c; public e(String str, long j, float f) { this(ComponentName.unflattenFromString(str), j, f); } public e(ComponentName componentName, long j, float f) { this.a = componentName; this.b = j; this.c = f; } public int hashCode() { return (((((this.a == null ? 0 : this.a.hashCode()) + 31) * 31) + ((int) (this.b ^ (this.b >>> 32)))) * 31) + Float.floatToIntBits(this.c); } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } e eVar = (e) obj; if (this.a == null) { if (eVar.a != null) { return false; } } else if (!this.a.equals(eVar.a)) { return false; } if (this.b != eVar.b) { return false; } if (Float.floatToIntBits(this.c) != Float.floatToIntBits(eVar.c)) { return false; } return true; } public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("["); stringBuilder.append("; activity:").append(this.a); stringBuilder.append("; time:").append(this.b); stringBuilder.append("; weight:").append(new BigDecimal((double) this.c)); stringBuilder.append("]"); return stringBuilder.toString(); } } private final class g extends AsyncTask<Object, Void, Void> { g() { } /* renamed from: a */ public Void doInBackground(Object... objArr) { int i = 0; List list = (List) objArr[0]; String str = (String) objArr[1]; try { OutputStream openFileOutput = l.this.j.openFileOutput(str, 0); XmlSerializer newSerializer = Xml.newSerializer(); try { newSerializer.setOutput(openFileOutput, null); newSerializer.startDocument("UTF-8", Boolean.valueOf(true)); newSerializer.startTag(null, l.c); int size = list.size(); while (i < size) { e eVar = (e) list.remove(0); newSerializer.startTag(null, l.d); newSerializer.attribute(null, l.e, eVar.a.flattenToString()); newSerializer.attribute(null, l.f, String.valueOf(eVar.b)); newSerializer.attribute(null, l.g, String.valueOf(eVar.c)); newSerializer.endTag(null, l.d); i++; } newSerializer.endTag(null, l.c); newSerializer.endDocument(); l.this.l = true; if (openFileOutput != null) { try { openFileOutput.close(); } catch (IOException e) { } } } catch (Throwable e2) { Log.e(l.b, "Error writing historical record file: " + l.this.k, e2); l.this.l = true; if (openFileOutput != null) { try { openFileOutput.close(); } catch (IOException e3) { } } } catch (Throwable e22) { Log.e(l.b, "Error writing historical record file: " + l.this.k, e22); l.this.l = true; if (openFileOutput != null) { try { openFileOutput.close(); } catch (IOException e4) { } } } catch (Throwable e222) { Log.e(l.b, "Error writing historical record file: " + l.this.k, e222); l.this.l = true; if (openFileOutput != null) { try { openFileOutput.close(); } catch (IOException e5) { } } } catch (Throwable th) { l.this.l = true; if (openFileOutput != null) { try { openFileOutput.close(); } catch (IOException e6) { } } } } catch (Throwable e2222) { Log.e(l.b, "Error writing historical record file: " + str, e2222); } return null; } } public static l a(Context context, String str) { l lVar; synchronized (q) { lVar = (l) r.get(str); if (lVar == null) { lVar = new l(context, str); r.put(str, lVar); } } return lVar; } private l(Context context, String str) { this.j = context.getApplicationContext(); if (TextUtils.isEmpty(str) || str.endsWith(o)) { this.k = str; } else { this.k = str + o; } } public void a(Intent intent) { synchronized (this.s) { if (this.v == intent) { return; } this.v = intent; this.A = true; g(); } } public Intent a() { Intent intent; synchronized (this.s) { intent = this.v; } return intent; } public int b() { int size; synchronized (this.s) { g(); size = this.t.size(); } return size; } public ResolveInfo a(int i) { ResolveInfo resolveInfo; synchronized (this.s) { g(); resolveInfo = ((b) this.t.get(i)).a; } return resolveInfo; } public int a(ResolveInfo resolveInfo) { synchronized (this.s) { g(); List list = this.t; int size = list.size(); for (int i = 0; i < size; i++) { if (((b) list.get(i)).a == resolveInfo) { return i; } } return -1; } } public Intent b(int i) { synchronized (this.s) { if (this.v == null) { return null; } g(); b bVar = (b) this.t.get(i); ComponentName componentName = new ComponentName(bVar.a.activityInfo.packageName, bVar.a.activityInfo.name); Intent intent = new Intent(this.v); intent.setComponent(componentName); if (this.B != null) { if (this.B.a(this, new Intent(intent))) { return null; } } a(new e(componentName, System.currentTimeMillis(), (float) n)); return intent; } } public void a(f fVar) { synchronized (this.s) { this.B = fVar; } } public ResolveInfo c() { synchronized (this.s) { g(); if (this.t.isEmpty()) { return null; } ResolveInfo resolveInfo = ((b) this.t.get(0)).a; return resolveInfo; } } public void c(int i) { synchronized (this.s) { float f; g(); b bVar = (b) this.t.get(i); b bVar2 = (b) this.t.get(0); if (bVar2 != null) { f = (bVar2.b - bVar.b) + 5.0f; } else { f = n; } a(new e(new ComponentName(bVar.a.activityInfo.packageName, bVar.a.activityInfo.name), System.currentTimeMillis(), f)); } } private void f() { if (!this.y) { throw new IllegalStateException("No preceding call to #readHistoricalData"); } else if (this.z) { this.z = false; if (!TextUtils.isEmpty(this.k)) { android.support.v4.k.a.a(new g(), new ArrayList(this.u), this.k); } } } /* JADX WARNING: Missing block: B:14:?, code: return; */ public void a(android.support.v7.widget.l.c r3) { /* r2 = this; r1 = r2.s; monitor-enter(r1); r0 = r2.w; Catch:{ all -> 0x0016 } if (r0 != r3) goto L_0x0009; L_0x0007: monitor-exit(r1); Catch:{ all -> 0x0016 } L_0x0008: return; L_0x0009: r2.w = r3; Catch:{ all -> 0x0016 } r0 = r2.h(); Catch:{ all -> 0x0016 } if (r0 == 0) goto L_0x0014; L_0x0011: r2.notifyChanged(); Catch:{ all -> 0x0016 } L_0x0014: monitor-exit(r1); Catch:{ all -> 0x0016 } goto L_0x0008; L_0x0016: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x0016 } throw r0; */ throw new UnsupportedOperationException("Method not decompiled: android.support.v7.widget.l.a(android.support.v7.widget.l$c):void"); } /* JADX WARNING: Missing block: B:14:?, code: return; */ public void d(int r3) { /* r2 = this; r1 = r2.s; monitor-enter(r1); r0 = r2.x; Catch:{ all -> 0x0019 } if (r0 != r3) goto L_0x0009; L_0x0007: monitor-exit(r1); Catch:{ all -> 0x0019 } L_0x0008: return; L_0x0009: r2.x = r3; Catch:{ all -> 0x0019 } r2.k(); Catch:{ all -> 0x0019 } r0 = r2.h(); Catch:{ all -> 0x0019 } if (r0 == 0) goto L_0x0017; L_0x0014: r2.notifyChanged(); Catch:{ all -> 0x0019 } L_0x0017: monitor-exit(r1); Catch:{ all -> 0x0019 } goto L_0x0008; L_0x0019: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x0019 } throw r0; */ throw new UnsupportedOperationException("Method not decompiled: android.support.v7.widget.l.d(int):void"); } public int d() { int i; synchronized (this.s) { i = this.x; } return i; } public int e() { int size; synchronized (this.s) { g(); size = this.u.size(); } return size; } private void g() { int i = i() | j(); k(); if (i != 0) { h(); notifyChanged(); } } private boolean h() { if (this.w == null || this.v == null || this.t.isEmpty() || this.u.isEmpty()) { return false; } this.w.a(this.v, this.t, Collections.unmodifiableList(this.u)); return true; } private boolean i() { if (!this.A || this.v == null) { return false; } this.A = false; this.t.clear(); List queryIntentActivities = this.j.getPackageManager().queryIntentActivities(this.v, 0); int size = queryIntentActivities.size(); for (int i = 0; i < size; i++) { this.t.add(new b((ResolveInfo) queryIntentActivities.get(i))); } return true; } private boolean j() { if (!this.l || !this.z || TextUtils.isEmpty(this.k)) { return false; } this.l = false; this.y = true; l(); return true; } private boolean a(e eVar) { boolean add = this.u.add(eVar); if (add) { this.z = true; k(); f(); h(); notifyChanged(); } return add; } private void k() { int size = this.u.size() - this.x; if (size > 0) { this.z = true; for (int i = 0; i < size; i++) { e eVar = (e) this.u.remove(0); } } } private void l() { try { InputStream openFileInput = this.j.openFileInput(this.k); try { XmlPullParser newPullParser = Xml.newPullParser(); newPullParser.setInput(openFileInput, "UTF-8"); int i = 0; while (i != 1 && i != 2) { i = newPullParser.next(); } if (c.equals(newPullParser.getName())) { List list = this.u; list.clear(); while (true) { int next = newPullParser.next(); if (next == 1) { if (openFileInput != null) { try { openFileInput.close(); return; } catch (IOException e) { return; } } return; } else if (!(next == 3 || next == 4)) { if (d.equals(newPullParser.getName())) { list.add(new e(newPullParser.getAttributeValue(null, e), Long.parseLong(newPullParser.getAttributeValue(null, f)), Float.parseFloat(newPullParser.getAttributeValue(null, g)))); } else { throw new XmlPullParserException("Share records file not well-formed."); } } } } throw new XmlPullParserException("Share records file does not start with historical-records tag."); } catch (Throwable e2) { Log.e(b, "Error reading historical recrod file: " + this.k, e2); if (openFileInput != null) { try { openFileInput.close(); } catch (IOException e3) { } } } catch (Throwable e22) { Log.e(b, "Error reading historical recrod file: " + this.k, e22); if (openFileInput != null) { try { openFileInput.close(); } catch (IOException e4) { } } } catch (Throwable th) { if (openFileInput != null) { try { openFileInput.close(); } catch (IOException e5) { } } } } catch (FileNotFoundException e6) { } } }
19,601
0.454109
0.437376
622
30.512861
23.255169
208
false
false
0
0
0
0
0
0
0.646302
false
false
9
8a9b5d9f957dd3b7f3589a154a9de35a89bc9dbc
12,008,728,595,020
e7cccbf7e397d71321ed07cc8645d5fad6f38919
/src/P03_Actividad_3/Grupo.java
10a3a508db09108732b51a69850f4453ce21b937
[]
no_license
Victor85bcn/Programacion-2
https://github.com/Victor85bcn/Programacion-2
6b9ab2d21dce7e5cc65204526c46425a5e1d15f8
4d47723ad3d59c117189ad1ae109589a34e5b19e
refs/heads/master
2020-04-15T10:05:23.402000
2019-01-08T06:30:53
2019-01-08T06:30:53
164,579,930
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package P03_Actividad_3; public class Grupo { //Atributos private String nombre; private String estilo; private int integrantes; //Constructores public Grupo(String nombre, String estilo, int integrantes) { super(); this.nombre = nombre; this.estilo = estilo; this.integrantes = integrantes; } //Getters y Setters public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getEstilo() { return estilo; } public void setEstilo(String estilo) { this.estilo = estilo; } public int getIntegrantes() { return integrantes; } public void setIntegrantes(int integrantes) { this.integrantes = integrantes; } //Métodos específicos @Override public String toString() { return "Grupo [nombre=" + nombre + ", estilo=" + estilo + ", integrantes=" + integrantes + "]"; } }
ISO-8859-1
Java
903
java
Grupo.java
Java
[]
null
[]
package P03_Actividad_3; public class Grupo { //Atributos private String nombre; private String estilo; private int integrantes; //Constructores public Grupo(String nombre, String estilo, int integrantes) { super(); this.nombre = nombre; this.estilo = estilo; this.integrantes = integrantes; } //Getters y Setters public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getEstilo() { return estilo; } public void setEstilo(String estilo) { this.estilo = estilo; } public int getIntegrantes() { return integrantes; } public void setIntegrantes(int integrantes) { this.integrantes = integrantes; } //Métodos específicos @Override public String toString() { return "Grupo [nombre=" + nombre + ", estilo=" + estilo + ", integrantes=" + integrantes + "]"; } }
903
0.678135
0.674806
60
14.016666
17.914139
97
false
false
0
0
0
0
0
0
1.283333
false
false
9
1c6cbfd34962f205366a8cd6a23ac8b0a9aeb096
13,477,607,431,294
70ba50828df34403a00c921f02c5e3dd39d4fde7
/src/org/rekdev/lists/ListElement.java
6cae597d1bb2a826fe74ee56ee74859918a61b3c
[]
no_license
robertkuhar/Algorithms
https://github.com/robertkuhar/Algorithms
8a459874ae07e8760011faf5ae8b1a06d19c813e
4f46ee20720559f588e57ae2f60bf3a050ab3332
refs/heads/master
2020-12-25T15:30:15.949000
2016-10-05T19:24:56
2016-10-05T19:24:56
1,501,070
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.rekdev.lists; public class ListElement<T> { private T payload = null; private ListElement<T> next = null; public ListElement( T payload, ListElement<T> next ) { this.payload = payload; this.next = next; } public ListElement( T payload ) { this( payload, null ); } public T getPayload() { return payload; } public void setPayload( T payload ) { this.payload = payload; } public ListElement<T> getNext() { return next; } public void setNext( ListElement<T> next ) { this.next = next; } /** * Analyzes the linked list returning true if a cycle is detected. * * @return true if list traversal results in a cycle; false otherwise */ public boolean hasCycle() { boolean hasCycle = false; ListElement<T> slow = this; ListElement<T> fast = this; int i = 0; while ( !hasCycle && fast != null ) { i++; fast = fast.next; if ( i % 2 == 0 ) { slow = slow.next; } hasCycle = ( slow == fast ); } return hasCycle; } }
UTF-8
Java
1,200
java
ListElement.java
Java
[]
null
[]
package org.rekdev.lists; public class ListElement<T> { private T payload = null; private ListElement<T> next = null; public ListElement( T payload, ListElement<T> next ) { this.payload = payload; this.next = next; } public ListElement( T payload ) { this( payload, null ); } public T getPayload() { return payload; } public void setPayload( T payload ) { this.payload = payload; } public ListElement<T> getNext() { return next; } public void setNext( ListElement<T> next ) { this.next = next; } /** * Analyzes the linked list returning true if a cycle is detected. * * @return true if list traversal results in a cycle; false otherwise */ public boolean hasCycle() { boolean hasCycle = false; ListElement<T> slow = this; ListElement<T> fast = this; int i = 0; while ( !hasCycle && fast != null ) { i++; fast = fast.next; if ( i % 2 == 0 ) { slow = slow.next; } hasCycle = ( slow == fast ); } return hasCycle; } }
1,200
0.525
0.5225
53
21.64151
18.324223
73
false
false
0
0
0
0
0
0
0.415094
false
false
9
fd98d66850fee0ecd1d7c5fccb5ced6cf76bbc28
14,233,521,683,733
7caecfe87b38b74c15865919633c72780df735d1
/src/main/java/com/benz/quizClasses/SetupDao.java
7244a203316a61d35cb23d0b34b844a302d07c87
[]
no_license
cnatsepll/ColorQuizWebApp
https://github.com/cnatsepll/ColorQuizWebApp
3b8a1535935298d5ff01b98dee012ee0887c978f
65e8d61466e4ea92fc36cb87e2d91e0c6c53c371
refs/heads/master
2021-04-15T13:47:13.674000
2018-03-25T02:48:20
2018-03-25T02:48:20
126,377,670
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.benz.quizClasses; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.Map; public interface SetupDao { public List<URL> createFilePathsList(); public void resetQuestionTables(); public Map<Integer, List> fillQuestionsTablesReturnQuestionQuiz(List<URL> filePaths) throws FileNotFoundException, IOException; }
UTF-8
Java
413
java
SetupDao.java
Java
[]
null
[]
package com.benz.quizClasses; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.Map; public interface SetupDao { public List<URL> createFilePathsList(); public void resetQuestionTables(); public Map<Integer, List> fillQuestionsTablesReturnQuestionQuiz(List<URL> filePaths) throws FileNotFoundException, IOException; }
413
0.791768
0.791768
20
19.65
28.712845
128
false
false
0
0
0
0
0
0
1
false
false
9
de968d6ba1337fba1b09748de23bba799b0866c2
14,233,521,683,145
b494822e017dfa68d1dc15a9463b9e517978fa05
/src/com/photoshare/auth/context/AuthSimpleEncoder.java
4575f89d5c9baabea643679c2d10ed397e5bf212
[]
no_license
HaoyuHuang/AuthService
https://github.com/HaoyuHuang/AuthService
1de4613cb809e95f1acaccc65a60e8b0a5f322e1
ec2a0535d50269381fa9e5c18e49789c736a025f
refs/heads/master
2020-06-04T05:39:01.534000
2013-05-15T09:17:08
2013-05-15T09:17:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.photoshare.auth.context; public class AuthSimpleEncoder implements AuthEncoder { @Override public String encode(Response response) throws EncoderException { if (response.getResponse() == null) return ""; char[] a = response.getResponse().toCharArray(); for (int i = 0; i < a.length; i++) { a[i] = (char) (a[i] ^ 't'); } String s = new String(a); return s; } public String encode(String response) { char[] a = response.toCharArray(); for (int i = 0; i < a.length; i++) { a[i] = (char) (a[i] ^ 't'); } String s = new String(a); return s; } }
UTF-8
Java
624
java
AuthSimpleEncoder.java
Java
[]
null
[]
package com.photoshare.auth.context; public class AuthSimpleEncoder implements AuthEncoder { @Override public String encode(Response response) throws EncoderException { if (response.getResponse() == null) return ""; char[] a = response.getResponse().toCharArray(); for (int i = 0; i < a.length; i++) { a[i] = (char) (a[i] ^ 't'); } String s = new String(a); return s; } public String encode(String response) { char[] a = response.toCharArray(); for (int i = 0; i < a.length; i++) { a[i] = (char) (a[i] ^ 't'); } String s = new String(a); return s; } }
624
0.586538
0.583333
29
19.517241
19.545916
66
false
false
0
0
0
0
0
0
1.724138
false
false
9
efdc51fe35df197a4038d9560f7f4411d9422c87
17,205,639,014,211
17e8438486cb3e3073966ca2c14956d3ba9209ea
/dso/tags/4.3.0.1.17/toolkit-impl/src/main/java/com/terracotta/toolkit/factory/impl/BaseDistributedToolkitTypeFactory.java
47a1c26bd4c154894eb25416e0bdf23ab2568521
[]
no_license
sirinath/Terracotta
https://github.com/sirinath/Terracotta
fedfc2c4f0f06c990f94b8b6c3b9c93293334345
00a7662b9cf530dfdb43f2dd821fa559e998c892
refs/heads/master
2021-01-23T05:41:52.414000
2015-07-02T15:21:54
2015-07-02T15:21:54
38,613,711
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. */ package com.terracotta.toolkit.factory.impl; import static com.terracotta.toolkit.config.ConfigUtil.distributeInStripes; import org.terracotta.toolkit.collections.ToolkitMap; import org.terracotta.toolkit.concurrent.locks.ToolkitLock; import org.terracotta.toolkit.config.Configuration; import org.terracotta.toolkit.internal.ToolkitInternal; import org.terracotta.toolkit.store.ToolkitConfigFields; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.tc.logging.TCLogger; import com.tc.logging.TCLogging; import com.tc.platform.PlatformService; import com.terracotta.toolkit.collections.map.AggregateServerMap; import com.terracotta.toolkit.collections.map.InternalToolkitMap; import com.terracotta.toolkit.collections.map.ServerMap; import com.terracotta.toolkit.collections.map.ToolkitCacheImpl; import com.terracotta.toolkit.collections.servermap.api.ServerMapLocalStoreFactory; import com.terracotta.toolkit.config.UnclusteredConfiguration; import com.terracotta.toolkit.config.cache.InternalCacheConfigurationType; import com.terracotta.toolkit.factory.ToolkitObjectFactory; import com.terracotta.toolkit.object.ToolkitObjectStripe; import com.terracotta.toolkit.object.ToolkitObjectStripeImpl; import com.terracotta.toolkit.search.SearchFactory; import com.terracotta.toolkit.type.DistributedClusteredObjectLookup; import com.terracotta.toolkit.type.DistributedToolkitTypeFactory; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Set; import java.util.concurrent.Callable; /** * @author Eugene Shelestovich */ public abstract class BaseDistributedToolkitTypeFactory<K extends Serializable, V extends Serializable> implements DistributedToolkitTypeFactory<ToolkitCacheImpl<K, V>, InternalToolkitMap<K, V>> { private static final TCLogger logger = TCLogging.getLogger(BaseDistributedToolkitTypeFactory.class); private static final UnclusteredConfiguration[] EMPTY_CONFIG_ARRAY = new UnclusteredConfiguration[0]; private static final ServerMap[] EMPTY_SERVER_MAP_ARRAY = new ServerMap[0]; private static final String SEARCH_ATTR_TYPES_MAP_SUFFIX = "searchAttributeTypesMap"; private final SearchFactory searchBuilderFactory; private final ServerMapLocalStoreFactory serverMapLocalStoreFactory; protected BaseDistributedToolkitTypeFactory(SearchFactory searchBuilderFactory, ServerMapLocalStoreFactory serverMapLocalStoreFactory) { this.searchBuilderFactory = searchBuilderFactory; this.serverMapLocalStoreFactory = serverMapLocalStoreFactory; } protected abstract void validateNewConfiguration(Configuration configuration); protected abstract Configuration getDefaultConfiguration(); protected abstract Set<InternalCacheConfigurationType> getAllSupportedConfigs(); @Override public ToolkitCacheImpl<K, V> createDistributedType(final ToolkitInternal toolkit, ToolkitObjectFactory factory, DistributedClusteredObjectLookup<InternalToolkitMap<K, V>> lookup, final String name, ToolkitObjectStripe<InternalToolkitMap<K, V>>[] stripeObjects, Configuration configuration, PlatformService platformService, ToolkitLock configMutationLock) { validateNewConfiguration(configuration); validateExistingClusterWideConfigs(stripeObjects, configuration); Callable<ToolkitMap<String, String>> schemaCreator = new Callable() { @Override public ToolkitMap<String, String> call() throws Exception { return toolkit.getMap(name + '|' + SEARCH_ATTR_TYPES_MAP_SUFFIX, String.class, String.class); } }; AggregateServerMap aggregateServerMap = new AggregateServerMap(factory.getManufacturedToolkitObjectType(), searchBuilderFactory, lookup, name, stripeObjects, configuration, schemaCreator, serverMapLocalStoreFactory, platformService, configMutationLock); return new ToolkitCacheImpl<K, V>(factory, name, aggregateServerMap, platformService, toolkit); } @Override public ToolkitObjectStripe<InternalToolkitMap<K, V>>[] createStripeObjects(final String name, final Configuration config, final int numStripes, PlatformService platformService) { // creating stripe objects for first time ToolkitObjectStripe<InternalToolkitMap<K, V>>[] rv = new ToolkitObjectStripe[numStripes]; Configuration[] stripesConfig = distributeConfigAmongStripes(config, numStripes); for (int i = 0; i < rv.length; i++) { rv[i] = new ToolkitObjectStripeImpl<InternalToolkitMap<K, V>>( stripesConfig[i], getComponentsForStripe(name, stripesConfig[i], platformService)); } return rv; } private ServerMap[] getComponentsForStripe(final String name, final Configuration config, PlatformService platformService) { int numSegments = (Integer)InternalCacheConfigurationType.CONCURRENCY.getValueIfExistsOrDefault(config); if (numSegments <= 0) return EMPTY_SERVER_MAP_ARRAY; final ServerMap[] rv = new ServerMap[numSegments]; final Configuration[] segmentConfigs = distributeConfigAmongStripes(config, numSegments); for (Configuration serverMapConfig : segmentConfigs) { Integer concurrency = (Integer)InternalCacheConfigurationType.CONCURRENCY.getValueIfExists(serverMapConfig); if (concurrency == null) { throw new IllegalArgumentException("Concurrency field missing in config"); } else if (concurrency != 1) { // TODO: write a unit test instead, also check/test for other types throw new AssertionError("Configuration for one ServerMap should have concurrency=1"); } } for (int i = 0; i < rv.length; i++) { rv[i] = new ServerMap(segmentConfigs[i], name, platformService); } return rv; } @Override public void validateExistingLocalInstanceConfig(ToolkitCacheImpl<K, V> existingCache, Configuration newConfig) { final Configuration oldConfig = existingCache.getConfiguration(); for (InternalCacheConfigurationType configType : getAllSupportedConfigs()) { Object existingValue = configType.getValueIfExists(oldConfig); // doing this instead of getExistingValueOrException to report better msg if (existingValue == null && !hasConflictingField(oldConfig, configType.getConfigString())) { throw new IllegalArgumentException('\'' + configType.getConfigString() + "' cannot be null for already existing values in local node"); } else if (configType.getValueIfExists(newConfig) != null) { // only validate if user passed in a value configType.validateExistingMatchesValueFromConfig(existingValue, newConfig); } } } @Override public void validateConfig(Configuration config) { for (InternalCacheConfigurationType configType : getAllSupportedConfigs()) { if (config.hasField(configType.getConfigString())) { configType.validateLegalValue(config.getObjectOrNull(configType.getConfigString())); } } } @Override public Configuration newConfigForCreationInCluster(final Configuration userConfig) { final UnclusteredConfiguration newConfig = new UnclusteredConfiguration(userConfig); final Configuration defaultConfiguration = getDefaultConfiguration(); for (String key : defaultConfiguration.getKeys()) { if (!newConfig.hasField(key) && !newConfig.hasConflictingField(key)) { // add the values from default configuration newConfig.setObject(key, defaultConfiguration.getObjectOrNull(key)); } } return newConfig; } @Override public Configuration newConfigForCreationInLocalNode(String name, ToolkitObjectStripe<InternalToolkitMap<K, V>>[] existingStripedObjects, Configuration userConfig) { final UnclusteredConfiguration newConfig = new UnclusteredConfiguration(userConfig); Collection<Configuration> configurations = getConfigurations(existingStripedObjects); for (InternalCacheConfigurationType configType : getAllSupportedConfigs()) { String field = configType.getConfigString(); Serializable existingValue = configType.getAggregatedConfigValue(configurations); if ((!newConfig.hasField(field) && !newConfig.hasConflictingField(field) && !hasConflictingField(existingStripedObjects[0].getConfiguration(), field))) { // missing in newConfig, merge from existing value configType.setValue(newConfig, existingValue); } else if (configType.acceptOverride() && !existingValue.equals(configType.getValueIfExists(newConfig))) { logger.warn("Overriding configuration value '" + configType.getValueIfExists(newConfig) + "' for field '" + field + "' from TSA with value '" + existingValue + "' for cache '" + name + "'."); configType.setValue(newConfig, existingValue); } } return newConfig; } private boolean hasConflictingField(Configuration config, String name) { // TODO: change this when hasConflictingField is moved in Configuration or AbstractConfiguration return new UnclusteredConfiguration(config).hasConflictingField(name); } protected UnclusteredConfiguration[] distributeConfigAmongStripes(Configuration config, int numberStripes) { if (numberStripes <= 0) return EMPTY_CONFIG_ARRAY; final UnclusteredConfiguration[] configurations = new UnclusteredConfiguration[numberStripes]; for (int i = 0; i < configurations.length; i++) { configurations[i] = new UnclusteredConfiguration(config); } final int overallConcurrency = config.getInt(ToolkitConfigFields.CONCURRENCY_FIELD_NAME); // distribute concurrency across stripes int[] concurrencies = distributeInStripes(overallConcurrency, numberStripes); if (concurrencies.length != numberStripes) { throw new AssertionError(); } for (int i = 0; i < concurrencies.length; i++) { configurations[i].setInt(ToolkitConfigFields.CONCURRENCY_FIELD_NAME, concurrencies[i]); } return configurations; } protected static Collection<Configuration> getConfigurations(final ToolkitObjectStripe[] stripeObjects) { return Lists.transform(Arrays.asList(stripeObjects), new Function<ToolkitObjectStripe, Configuration>() { @Override public Configuration apply(final ToolkitObjectStripe input) { return input.getConfiguration(); } }); } protected void validateExistingClusterWideConfigs(final ToolkitObjectStripe[] stripeObjects, final Configuration newConfig) { Collection<Configuration> configurations = getConfigurations(stripeObjects); for (InternalCacheConfigurationType configType : getAllSupportedConfigs()) { final Object existingValue = configType.getAggregatedConfigValue(configurations); configType.validateExistingMatchesValueFromConfig(existingValue, newConfig); } } }
UTF-8
Java
11,650
java
BaseDistributedToolkitTypeFactory.java
Java
[ { "context": "ort java.util.concurrent.Callable;\n\n/**\n * @author Eugene Shelestovich\n */\npublic abstract class BaseDistributedToolkitT", "end": 1709, "score": 0.999872624874115, "start": 1690, "tag": "NAME", "value": "Eugene Shelestovich" } ]
null
[]
/* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. */ package com.terracotta.toolkit.factory.impl; import static com.terracotta.toolkit.config.ConfigUtil.distributeInStripes; import org.terracotta.toolkit.collections.ToolkitMap; import org.terracotta.toolkit.concurrent.locks.ToolkitLock; import org.terracotta.toolkit.config.Configuration; import org.terracotta.toolkit.internal.ToolkitInternal; import org.terracotta.toolkit.store.ToolkitConfigFields; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.tc.logging.TCLogger; import com.tc.logging.TCLogging; import com.tc.platform.PlatformService; import com.terracotta.toolkit.collections.map.AggregateServerMap; import com.terracotta.toolkit.collections.map.InternalToolkitMap; import com.terracotta.toolkit.collections.map.ServerMap; import com.terracotta.toolkit.collections.map.ToolkitCacheImpl; import com.terracotta.toolkit.collections.servermap.api.ServerMapLocalStoreFactory; import com.terracotta.toolkit.config.UnclusteredConfiguration; import com.terracotta.toolkit.config.cache.InternalCacheConfigurationType; import com.terracotta.toolkit.factory.ToolkitObjectFactory; import com.terracotta.toolkit.object.ToolkitObjectStripe; import com.terracotta.toolkit.object.ToolkitObjectStripeImpl; import com.terracotta.toolkit.search.SearchFactory; import com.terracotta.toolkit.type.DistributedClusteredObjectLookup; import com.terracotta.toolkit.type.DistributedToolkitTypeFactory; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Set; import java.util.concurrent.Callable; /** * @author <NAME> */ public abstract class BaseDistributedToolkitTypeFactory<K extends Serializable, V extends Serializable> implements DistributedToolkitTypeFactory<ToolkitCacheImpl<K, V>, InternalToolkitMap<K, V>> { private static final TCLogger logger = TCLogging.getLogger(BaseDistributedToolkitTypeFactory.class); private static final UnclusteredConfiguration[] EMPTY_CONFIG_ARRAY = new UnclusteredConfiguration[0]; private static final ServerMap[] EMPTY_SERVER_MAP_ARRAY = new ServerMap[0]; private static final String SEARCH_ATTR_TYPES_MAP_SUFFIX = "searchAttributeTypesMap"; private final SearchFactory searchBuilderFactory; private final ServerMapLocalStoreFactory serverMapLocalStoreFactory; protected BaseDistributedToolkitTypeFactory(SearchFactory searchBuilderFactory, ServerMapLocalStoreFactory serverMapLocalStoreFactory) { this.searchBuilderFactory = searchBuilderFactory; this.serverMapLocalStoreFactory = serverMapLocalStoreFactory; } protected abstract void validateNewConfiguration(Configuration configuration); protected abstract Configuration getDefaultConfiguration(); protected abstract Set<InternalCacheConfigurationType> getAllSupportedConfigs(); @Override public ToolkitCacheImpl<K, V> createDistributedType(final ToolkitInternal toolkit, ToolkitObjectFactory factory, DistributedClusteredObjectLookup<InternalToolkitMap<K, V>> lookup, final String name, ToolkitObjectStripe<InternalToolkitMap<K, V>>[] stripeObjects, Configuration configuration, PlatformService platformService, ToolkitLock configMutationLock) { validateNewConfiguration(configuration); validateExistingClusterWideConfigs(stripeObjects, configuration); Callable<ToolkitMap<String, String>> schemaCreator = new Callable() { @Override public ToolkitMap<String, String> call() throws Exception { return toolkit.getMap(name + '|' + SEARCH_ATTR_TYPES_MAP_SUFFIX, String.class, String.class); } }; AggregateServerMap aggregateServerMap = new AggregateServerMap(factory.getManufacturedToolkitObjectType(), searchBuilderFactory, lookup, name, stripeObjects, configuration, schemaCreator, serverMapLocalStoreFactory, platformService, configMutationLock); return new ToolkitCacheImpl<K, V>(factory, name, aggregateServerMap, platformService, toolkit); } @Override public ToolkitObjectStripe<InternalToolkitMap<K, V>>[] createStripeObjects(final String name, final Configuration config, final int numStripes, PlatformService platformService) { // creating stripe objects for first time ToolkitObjectStripe<InternalToolkitMap<K, V>>[] rv = new ToolkitObjectStripe[numStripes]; Configuration[] stripesConfig = distributeConfigAmongStripes(config, numStripes); for (int i = 0; i < rv.length; i++) { rv[i] = new ToolkitObjectStripeImpl<InternalToolkitMap<K, V>>( stripesConfig[i], getComponentsForStripe(name, stripesConfig[i], platformService)); } return rv; } private ServerMap[] getComponentsForStripe(final String name, final Configuration config, PlatformService platformService) { int numSegments = (Integer)InternalCacheConfigurationType.CONCURRENCY.getValueIfExistsOrDefault(config); if (numSegments <= 0) return EMPTY_SERVER_MAP_ARRAY; final ServerMap[] rv = new ServerMap[numSegments]; final Configuration[] segmentConfigs = distributeConfigAmongStripes(config, numSegments); for (Configuration serverMapConfig : segmentConfigs) { Integer concurrency = (Integer)InternalCacheConfigurationType.CONCURRENCY.getValueIfExists(serverMapConfig); if (concurrency == null) { throw new IllegalArgumentException("Concurrency field missing in config"); } else if (concurrency != 1) { // TODO: write a unit test instead, also check/test for other types throw new AssertionError("Configuration for one ServerMap should have concurrency=1"); } } for (int i = 0; i < rv.length; i++) { rv[i] = new ServerMap(segmentConfigs[i], name, platformService); } return rv; } @Override public void validateExistingLocalInstanceConfig(ToolkitCacheImpl<K, V> existingCache, Configuration newConfig) { final Configuration oldConfig = existingCache.getConfiguration(); for (InternalCacheConfigurationType configType : getAllSupportedConfigs()) { Object existingValue = configType.getValueIfExists(oldConfig); // doing this instead of getExistingValueOrException to report better msg if (existingValue == null && !hasConflictingField(oldConfig, configType.getConfigString())) { throw new IllegalArgumentException('\'' + configType.getConfigString() + "' cannot be null for already existing values in local node"); } else if (configType.getValueIfExists(newConfig) != null) { // only validate if user passed in a value configType.validateExistingMatchesValueFromConfig(existingValue, newConfig); } } } @Override public void validateConfig(Configuration config) { for (InternalCacheConfigurationType configType : getAllSupportedConfigs()) { if (config.hasField(configType.getConfigString())) { configType.validateLegalValue(config.getObjectOrNull(configType.getConfigString())); } } } @Override public Configuration newConfigForCreationInCluster(final Configuration userConfig) { final UnclusteredConfiguration newConfig = new UnclusteredConfiguration(userConfig); final Configuration defaultConfiguration = getDefaultConfiguration(); for (String key : defaultConfiguration.getKeys()) { if (!newConfig.hasField(key) && !newConfig.hasConflictingField(key)) { // add the values from default configuration newConfig.setObject(key, defaultConfiguration.getObjectOrNull(key)); } } return newConfig; } @Override public Configuration newConfigForCreationInLocalNode(String name, ToolkitObjectStripe<InternalToolkitMap<K, V>>[] existingStripedObjects, Configuration userConfig) { final UnclusteredConfiguration newConfig = new UnclusteredConfiguration(userConfig); Collection<Configuration> configurations = getConfigurations(existingStripedObjects); for (InternalCacheConfigurationType configType : getAllSupportedConfigs()) { String field = configType.getConfigString(); Serializable existingValue = configType.getAggregatedConfigValue(configurations); if ((!newConfig.hasField(field) && !newConfig.hasConflictingField(field) && !hasConflictingField(existingStripedObjects[0].getConfiguration(), field))) { // missing in newConfig, merge from existing value configType.setValue(newConfig, existingValue); } else if (configType.acceptOverride() && !existingValue.equals(configType.getValueIfExists(newConfig))) { logger.warn("Overriding configuration value '" + configType.getValueIfExists(newConfig) + "' for field '" + field + "' from TSA with value '" + existingValue + "' for cache '" + name + "'."); configType.setValue(newConfig, existingValue); } } return newConfig; } private boolean hasConflictingField(Configuration config, String name) { // TODO: change this when hasConflictingField is moved in Configuration or AbstractConfiguration return new UnclusteredConfiguration(config).hasConflictingField(name); } protected UnclusteredConfiguration[] distributeConfigAmongStripes(Configuration config, int numberStripes) { if (numberStripes <= 0) return EMPTY_CONFIG_ARRAY; final UnclusteredConfiguration[] configurations = new UnclusteredConfiguration[numberStripes]; for (int i = 0; i < configurations.length; i++) { configurations[i] = new UnclusteredConfiguration(config); } final int overallConcurrency = config.getInt(ToolkitConfigFields.CONCURRENCY_FIELD_NAME); // distribute concurrency across stripes int[] concurrencies = distributeInStripes(overallConcurrency, numberStripes); if (concurrencies.length != numberStripes) { throw new AssertionError(); } for (int i = 0; i < concurrencies.length; i++) { configurations[i].setInt(ToolkitConfigFields.CONCURRENCY_FIELD_NAME, concurrencies[i]); } return configurations; } protected static Collection<Configuration> getConfigurations(final ToolkitObjectStripe[] stripeObjects) { return Lists.transform(Arrays.asList(stripeObjects), new Function<ToolkitObjectStripe, Configuration>() { @Override public Configuration apply(final ToolkitObjectStripe input) { return input.getConfiguration(); } }); } protected void validateExistingClusterWideConfigs(final ToolkitObjectStripe[] stripeObjects, final Configuration newConfig) { Collection<Configuration> configurations = getConfigurations(stripeObjects); for (InternalCacheConfigurationType configType : getAllSupportedConfigs()) { final Object existingValue = configType.getAggregatedConfigValue(configurations); configType.validateExistingMatchesValueFromConfig(existingValue, newConfig); } } }
11,637
0.721202
0.720258
224
51.00893
39.610039
149
false
false
0
0
0
0
0
0
0.767857
false
false
9
83f03d0413af3446269ca1d3b1d09d2d432e43d3
6,236,292,567,626
07db4f4192e0fd086c6426fcf18a3d49dbdc52a1
/atlassian-intellij-connector/src/main/java/com/atlassian/theplugin/commons/jira/cache/JIRAServerCache.java
cafe3c7e8b7f28d002f705aef4c450896af6410b
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
brookegravitt/atlassian-connector-for-intellij
https://github.com/brookegravitt/atlassian-connector-for-intellij
1f941d2200669f8f31235c3e2d221d13ac5fe930
ded306aab4dc9cac4384e557eac50564a40658a6
refs/heads/master
2023-06-09T09:26:52.359000
2015-05-27T04:04:40
2015-05-27T04:04:40
96,479,259
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright (C) 2008 Atlassian * * 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.atlassian.theplugin.commons.jira.cache; import com.atlassian.connector.commons.jira.beans.JIRAComponentBean; import com.atlassian.connector.commons.jira.beans.JIRAConstant; import com.atlassian.connector.commons.jira.beans.JIRAFixForVersionBean; import com.atlassian.connector.commons.jira.beans.JIRAIssueTypeBean; import com.atlassian.connector.commons.jira.beans.JIRAPriorityBean; import com.atlassian.connector.commons.jira.beans.JIRAProject; import com.atlassian.connector.commons.jira.beans.JIRAProjectBean; import com.atlassian.connector.commons.jira.beans.JIRAQueryFragment; import com.atlassian.connector.commons.jira.beans.JIRAResolutionBean; import com.atlassian.connector.commons.jira.beans.JIRASecurityLevelBean; import com.atlassian.connector.commons.jira.beans.JIRAStatusBean; import com.atlassian.connector.commons.jira.beans.JIRAVersionBean; import com.atlassian.connector.commons.jira.cache.CacheConstants; import com.atlassian.connector.commons.jira.cache.CachedIconLoader; import com.atlassian.connector.commons.jira.rss.JIRAException; import com.atlassian.theplugin.commons.jira.JiraServerData; import com.atlassian.theplugin.commons.jira.JiraServerFacade; import com.atlassian.theplugin.commons.remoteapi.RemoteApiException; import com.atlassian.theplugin.commons.remoteapi.RemoteApiLoginException; import com.intellij.openapi.util.Pair; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class JIRAServerCache { private static final int VERSION_SPECIAL_VALUES_COUNT = 4; private final JiraServerData jiraServerData; private boolean validServer; private String errorMessage; private List<JIRAProject> projects; private List<JIRAProject> projectsForIssueCreation; private List<JIRAConstant> statuses; private List<JIRAQueryFragment> savedFilters; private List<JIRAPriorityBean> priorities; private List<JIRAResolutionBean> resolutions; private List<JIRAConstant> globalIssueTypes; private List<JIRAConstant> globalSubtaskIssueTypes; private final Map<String, List<JIRAConstant>> issueTypesCache; private final Map<String, List<JIRAConstant>> subtaskIssueTypesCache; private final Map<String, List<JIRAVersionBean>> serverVersionsCache; private final Map<String, List<JIRAComponentBean>> componentsCache; private final HashMap<String, String> usersMap; private HashMap<String, List<JIRASecurityLevelBean>> securityLevels; private final JiraServerFacade jiraServerFacade; public JIRAServerCache(JiraServerData jiraServerData, JiraServerFacade jiraServerFacade) { this.jiraServerFacade = jiraServerFacade; this.issueTypesCache = new HashMap<String, List<JIRAConstant>>(); this.subtaskIssueTypesCache = new HashMap<String, List<JIRAConstant>>(); this.serverVersionsCache = new HashMap<String, List<JIRAVersionBean>>(); this.componentsCache = new HashMap<String, List<JIRAComponentBean>>(); this.jiraServerData = jiraServerData; this.usersMap = new HashMap<String, String>(); this.securityLevels = new HashMap<String, List<JIRASecurityLevelBean>>(); } public JiraServerData getJiraServerData() { return jiraServerData; } public boolean checkServer() throws RemoteApiException { try { jiraServerFacade.testServerConnection(jiraServerData); validServer = true; } catch (RemoteApiLoginException e) { throw e; } catch (RemoteApiException e) { errorMessage = e.getMessage(); throw e; } return validServer; } public List<Pair<String, String>> getUsers() { List<Pair<String, String>> list = new ArrayList<Pair<String, String>>(); for (String userId : usersMap.keySet()) { list.add(new Pair(userId, usersMap.get(userId))); } return list; } public List<JIRASecurityLevelBean> getSecurityLevels(final String projectKey) throws RemoteApiException, JIRAException { if (!securityLevels.containsKey(projectKey)) { securityLevels.put(projectKey, jiraServerFacade.getSecurityLevels(jiraServerData, projectKey)); } return securityLevels.get(projectKey); } public List<JIRAProject> getProjects(boolean fromCacheOnly, boolean forIssueCreation) throws JIRAException { if (forIssueCreation) { if (projectsForIssueCreation == null && !fromCacheOnly) { try { List<JIRAProject> retrieved = jiraServerFacade.getProjectsForIssueCreation(jiraServerData); projectsForIssueCreation = new ArrayList<JIRAProject>(); projectsForIssueCreation.add(new JIRAProjectBean(CacheConstants.ANY_ID, "Any")); projectsForIssueCreation.addAll(retrieved); } catch (JIRAException e) { errorMessage = e.getMessage(); throw e; } } return projectsForIssueCreation; } if (projects == null && !fromCacheOnly) { try { List<JIRAProject> retrieved = jiraServerFacade.getProjects(jiraServerData); projects = new ArrayList<JIRAProject>(); projects.add(new JIRAProjectBean(CacheConstants.ANY_ID, "Any")); projects.addAll(retrieved); } catch (JIRAException e) { errorMessage = e.getMessage(); throw e; } } return forIssueCreation ? projectsForIssueCreation : projects; } public synchronized List<JIRAConstant> getStatuses() throws JIRAException { if (statuses == null) { try { List<JIRAConstant> retrieved = jiraServerFacade.getStatuses(jiraServerData); statuses = new ArrayList<JIRAConstant>(retrieved.size() + 1); statuses.add(new JIRAStatusBean(CacheConstants.ANY_ID, "Any", null)); statuses.addAll(retrieved); for (JIRAConstant status : statuses) { CachedIconLoader.getIcon(status.getIconUrl()); } } catch (JIRAException e) { errorMessage = e.getMessage(); throw e; } } return statuses; } /** * @param project * @param includeAny * @param includeAny * @return list of issue types or empty collection */ public List<JIRAConstant> getIssueTypes(JIRAProject project, boolean includeAny) throws JIRAException { List<JIRAConstant> issueTypes = project == null ? globalIssueTypes : issueTypesCache.get(project.getKey()); if (issueTypes == null) { List<JIRAConstant> retrieved; try { if (project == null || project.getKey() == null) { retrieved = jiraServerFacade.getIssueTypes(jiraServerData); } else { retrieved = jiraServerFacade.getIssueTypesForProject(jiraServerData, project.getId(), project.getKey()); } issueTypes = new ArrayList<JIRAConstant>(retrieved.size()); issueTypes.addAll(retrieved); for (JIRAConstant issueType : issueTypes) { CachedIconLoader.getIcon(issueType.getIconUrl()); } if (project != null) { issueTypesCache.put(project.getKey(), issueTypes); } else { globalIssueTypes = issueTypes; } } catch (JIRAException e) { if (globalIssueTypes != null) { issueTypes = globalIssueTypes; } else { throw e; } } } List<JIRAConstant> result = new ArrayList<JIRAConstant>(); if (includeAny) { result.add(new JIRAIssueTypeBean(CacheConstants.ANY_ID, "Any", null)); } result.addAll(issueTypes); return result; } public List<JIRAConstant> getSubtaskIssueTypes(JIRAProject project) throws JIRAException { List<JIRAConstant> subtaskTypes = project == null ? globalSubtaskIssueTypes : subtaskIssueTypesCache.get(project.getKey()); if (subtaskTypes == null) { List<JIRAConstant> retrieved; try { if (project == null || project.getKey() == null) { retrieved = jiraServerFacade.getSubtaskIssueTypes(jiraServerData); } else { retrieved = jiraServerFacade.getSubtaskIssueTypesForProject(jiraServerData, project.getId(), project.getKey()); } subtaskTypes = new ArrayList<JIRAConstant>(retrieved.size()); subtaskTypes.addAll(retrieved); for (JIRAConstant subtaskType : subtaskTypes) { CachedIconLoader.getIcon(subtaskType.getIconUrl()); } if (project != null) { subtaskIssueTypesCache.put(project.getKey(), subtaskTypes); } else { globalSubtaskIssueTypes = subtaskTypes; } } catch (JIRAException e) { if (globalSubtaskIssueTypes != null) { subtaskTypes = globalSubtaskIssueTypes; } else { errorMessage = e.getMessage(); throw e; } } } return subtaskTypes; } public List<JIRAQueryFragment> getSavedFilters() throws JIRAException { if (savedFilters == null) { try { savedFilters = jiraServerFacade.getSavedFilters(jiraServerData); } catch (JIRAException e) { errorMessage = e.getMessage(); throw e; } } return savedFilters; } public List<JIRAPriorityBean> getPriorities(boolean includeAny) throws JIRAException { if (priorities == null) { try { List<JIRAPriorityBean> retrieved = jiraServerFacade.getPriorities(jiraServerData); priorities = new ArrayList<JIRAPriorityBean>(retrieved.size() + 1); priorities.addAll(retrieved); for (JIRAConstant priority : priorities) { CachedIconLoader.getIcon(priority.getIconUrl()); } } catch (JIRAException e) { errorMessage = e.getMessage(); throw e; } } List<JIRAPriorityBean> result = new ArrayList<JIRAPriorityBean>(); if (includeAny) { result.add(new JIRAPriorityBean(CacheConstants.ANY_ID, -1, "Any", null)); } result.addAll(priorities); return result; } public List<JIRAResolutionBean> getResolutions(boolean includeAnyAndUnknown) throws JIRAException { if (resolutions == null) { try { List<JIRAResolutionBean> retrieved = jiraServerFacade.getResolutions(jiraServerData); resolutions = new ArrayList<JIRAResolutionBean>(retrieved.size()); resolutions.addAll(retrieved); } catch (JIRAException e) { errorMessage = e.getMessage(); throw e; } } List<JIRAResolutionBean> result; result = new ArrayList<JIRAResolutionBean>(); if (includeAnyAndUnknown) { result.add(new JIRAResolutionBean(CacheConstants.ANY_ID, "Any")); result.add(new JIRAResolutionBean(CacheConstants.UNRESOLVED_ID, "Unresolved")); } result.addAll(resolutions); return result; } private List<JIRAVersionBean> getAllVersions(JIRAProject project) throws JIRAException { List<JIRAVersionBean> versions = null; if (project != null) { versions = serverVersionsCache.get(project.getKey()); } if (versions == null) { try { if (project != null && project.getKey() != null) { versions = jiraServerFacade.getVersions(jiraServerData, project.getKey()); Collections.reverse(versions); serverVersionsCache.put(project.getKey(), versions); } else { versions = Collections.emptyList(); } } catch (JIRAException e) { errorMessage = e.getMessage(); throw e; } } return versions; } public List<JIRAVersionBean> getVersions(JIRAProject project, boolean includeSpecialValues) throws JIRAException { List<JIRAVersionBean> versions; if (project != null) { List<JIRAVersionBean> retrieved = getAllVersions(project); if (!retrieved.isEmpty()) { versions = new ArrayList<JIRAVersionBean>(retrieved.size() + VERSION_SPECIAL_VALUES_COUNT); if (includeSpecialValues) { versions.add(new JIRAVersionBean(CacheConstants.ANY_ID, "Any", false)); versions.add(new JIRAVersionBean(CacheConstants.NO_VERSION_ID, "No version", false)); versions.add(new JIRAVersionBean(CacheConstants.UNRELEASED_VERSION_ID, "Unreleased versions", false)); } for (JIRAQueryFragment jiraQueryFragment : retrieved) { if (!((JIRAVersionBean) jiraQueryFragment).isReleased()) { versions.add((JIRAVersionBean) jiraQueryFragment); } } if (includeSpecialValues) { versions.add(new JIRAVersionBean(CacheConstants.RELEASED_VERSION_ID, "Released versions", true)); } for (JIRAQueryFragment jiraQueryFragment : retrieved) { if (((JIRAVersionBean) jiraQueryFragment).isReleased()) { versions.add((JIRAVersionBean) jiraQueryFragment); } } } else { versions = Collections.emptyList(); } } else { versions = Collections.emptyList(); } return versions; } public List<JIRAFixForVersionBean> getFixForVersions(JIRAProject project, boolean includeSpecialValues) throws JIRAException { List<JIRAFixForVersionBean> fixForVersions; if (project != null) { List<JIRAVersionBean> retrieved = getAllVersions(project); if (!retrieved.isEmpty()) { fixForVersions = new ArrayList<JIRAFixForVersionBean>(retrieved.size() + VERSION_SPECIAL_VALUES_COUNT); if (includeSpecialValues) { fixForVersions.add(new JIRAFixForVersionBean(CacheConstants.ANY_ID, "Any", false)); fixForVersions.add(new JIRAFixForVersionBean(CacheConstants.NO_VERSION_ID, "No version", false)); fixForVersions.add(new JIRAFixForVersionBean(CacheConstants.UNRELEASED_VERSION_ID, "Unreleased versions", true)); } for (JIRAVersionBean jiraQueryFragment : retrieved) { if (!jiraQueryFragment.isReleased()) { fixForVersions.add(new JIRAFixForVersionBean(jiraQueryFragment)); } } if (includeSpecialValues) { fixForVersions.add(new JIRAFixForVersionBean(CacheConstants.RELEASED_VERSION_ID, "Released versions", false)); } for (JIRAVersionBean jiraQueryFragment : retrieved) { if (jiraQueryFragment.isReleased()) { fixForVersions.add(new JIRAFixForVersionBean(jiraQueryFragment)); } } } else { fixForVersions = Collections.emptyList(); } } else { fixForVersions = Collections.emptyList(); } return fixForVersions; } public List<JIRAComponentBean> getComponents(JIRAProject project, final boolean includeSpecialValues) throws JIRAException { List<JIRAComponentBean> components = null; if (project != null) { components = componentsCache.get(project.getKey()); } if (components == null) { try { if (project != null && project.getKey() != null) { List<JIRAComponentBean> retrieved = jiraServerFacade.getComponents(jiraServerData, project.getKey()); components = new ArrayList<JIRAComponentBean>(retrieved.size() + 1); if (includeSpecialValues) { components.add(new JIRAComponentBean(CacheConstants.ANY_ID, "Any")); components.add(new JIRAComponentBean(CacheConstants.UNKNOWN_COMPONENT_ID, "Unknown")); } components.addAll(retrieved); componentsCache.put(project.getKey(), components); } else { components = Collections.emptyList(); } } catch (JIRAException e) { errorMessage = e.getMessage(); throw e; } } return components; } public boolean isValidServer() { return validServer; } public String getErrorMessage() { return errorMessage; } public void addUser(String userId, String userName) { usersMap.put(userId, userName); } }
UTF-8
Java
18,449
java
JIRAServerCache.java
Java
[]
null
[]
/** * Copyright (C) 2008 Atlassian * * 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.atlassian.theplugin.commons.jira.cache; import com.atlassian.connector.commons.jira.beans.JIRAComponentBean; import com.atlassian.connector.commons.jira.beans.JIRAConstant; import com.atlassian.connector.commons.jira.beans.JIRAFixForVersionBean; import com.atlassian.connector.commons.jira.beans.JIRAIssueTypeBean; import com.atlassian.connector.commons.jira.beans.JIRAPriorityBean; import com.atlassian.connector.commons.jira.beans.JIRAProject; import com.atlassian.connector.commons.jira.beans.JIRAProjectBean; import com.atlassian.connector.commons.jira.beans.JIRAQueryFragment; import com.atlassian.connector.commons.jira.beans.JIRAResolutionBean; import com.atlassian.connector.commons.jira.beans.JIRASecurityLevelBean; import com.atlassian.connector.commons.jira.beans.JIRAStatusBean; import com.atlassian.connector.commons.jira.beans.JIRAVersionBean; import com.atlassian.connector.commons.jira.cache.CacheConstants; import com.atlassian.connector.commons.jira.cache.CachedIconLoader; import com.atlassian.connector.commons.jira.rss.JIRAException; import com.atlassian.theplugin.commons.jira.JiraServerData; import com.atlassian.theplugin.commons.jira.JiraServerFacade; import com.atlassian.theplugin.commons.remoteapi.RemoteApiException; import com.atlassian.theplugin.commons.remoteapi.RemoteApiLoginException; import com.intellij.openapi.util.Pair; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class JIRAServerCache { private static final int VERSION_SPECIAL_VALUES_COUNT = 4; private final JiraServerData jiraServerData; private boolean validServer; private String errorMessage; private List<JIRAProject> projects; private List<JIRAProject> projectsForIssueCreation; private List<JIRAConstant> statuses; private List<JIRAQueryFragment> savedFilters; private List<JIRAPriorityBean> priorities; private List<JIRAResolutionBean> resolutions; private List<JIRAConstant> globalIssueTypes; private List<JIRAConstant> globalSubtaskIssueTypes; private final Map<String, List<JIRAConstant>> issueTypesCache; private final Map<String, List<JIRAConstant>> subtaskIssueTypesCache; private final Map<String, List<JIRAVersionBean>> serverVersionsCache; private final Map<String, List<JIRAComponentBean>> componentsCache; private final HashMap<String, String> usersMap; private HashMap<String, List<JIRASecurityLevelBean>> securityLevels; private final JiraServerFacade jiraServerFacade; public JIRAServerCache(JiraServerData jiraServerData, JiraServerFacade jiraServerFacade) { this.jiraServerFacade = jiraServerFacade; this.issueTypesCache = new HashMap<String, List<JIRAConstant>>(); this.subtaskIssueTypesCache = new HashMap<String, List<JIRAConstant>>(); this.serverVersionsCache = new HashMap<String, List<JIRAVersionBean>>(); this.componentsCache = new HashMap<String, List<JIRAComponentBean>>(); this.jiraServerData = jiraServerData; this.usersMap = new HashMap<String, String>(); this.securityLevels = new HashMap<String, List<JIRASecurityLevelBean>>(); } public JiraServerData getJiraServerData() { return jiraServerData; } public boolean checkServer() throws RemoteApiException { try { jiraServerFacade.testServerConnection(jiraServerData); validServer = true; } catch (RemoteApiLoginException e) { throw e; } catch (RemoteApiException e) { errorMessage = e.getMessage(); throw e; } return validServer; } public List<Pair<String, String>> getUsers() { List<Pair<String, String>> list = new ArrayList<Pair<String, String>>(); for (String userId : usersMap.keySet()) { list.add(new Pair(userId, usersMap.get(userId))); } return list; } public List<JIRASecurityLevelBean> getSecurityLevels(final String projectKey) throws RemoteApiException, JIRAException { if (!securityLevels.containsKey(projectKey)) { securityLevels.put(projectKey, jiraServerFacade.getSecurityLevels(jiraServerData, projectKey)); } return securityLevels.get(projectKey); } public List<JIRAProject> getProjects(boolean fromCacheOnly, boolean forIssueCreation) throws JIRAException { if (forIssueCreation) { if (projectsForIssueCreation == null && !fromCacheOnly) { try { List<JIRAProject> retrieved = jiraServerFacade.getProjectsForIssueCreation(jiraServerData); projectsForIssueCreation = new ArrayList<JIRAProject>(); projectsForIssueCreation.add(new JIRAProjectBean(CacheConstants.ANY_ID, "Any")); projectsForIssueCreation.addAll(retrieved); } catch (JIRAException e) { errorMessage = e.getMessage(); throw e; } } return projectsForIssueCreation; } if (projects == null && !fromCacheOnly) { try { List<JIRAProject> retrieved = jiraServerFacade.getProjects(jiraServerData); projects = new ArrayList<JIRAProject>(); projects.add(new JIRAProjectBean(CacheConstants.ANY_ID, "Any")); projects.addAll(retrieved); } catch (JIRAException e) { errorMessage = e.getMessage(); throw e; } } return forIssueCreation ? projectsForIssueCreation : projects; } public synchronized List<JIRAConstant> getStatuses() throws JIRAException { if (statuses == null) { try { List<JIRAConstant> retrieved = jiraServerFacade.getStatuses(jiraServerData); statuses = new ArrayList<JIRAConstant>(retrieved.size() + 1); statuses.add(new JIRAStatusBean(CacheConstants.ANY_ID, "Any", null)); statuses.addAll(retrieved); for (JIRAConstant status : statuses) { CachedIconLoader.getIcon(status.getIconUrl()); } } catch (JIRAException e) { errorMessage = e.getMessage(); throw e; } } return statuses; } /** * @param project * @param includeAny * @param includeAny * @return list of issue types or empty collection */ public List<JIRAConstant> getIssueTypes(JIRAProject project, boolean includeAny) throws JIRAException { List<JIRAConstant> issueTypes = project == null ? globalIssueTypes : issueTypesCache.get(project.getKey()); if (issueTypes == null) { List<JIRAConstant> retrieved; try { if (project == null || project.getKey() == null) { retrieved = jiraServerFacade.getIssueTypes(jiraServerData); } else { retrieved = jiraServerFacade.getIssueTypesForProject(jiraServerData, project.getId(), project.getKey()); } issueTypes = new ArrayList<JIRAConstant>(retrieved.size()); issueTypes.addAll(retrieved); for (JIRAConstant issueType : issueTypes) { CachedIconLoader.getIcon(issueType.getIconUrl()); } if (project != null) { issueTypesCache.put(project.getKey(), issueTypes); } else { globalIssueTypes = issueTypes; } } catch (JIRAException e) { if (globalIssueTypes != null) { issueTypes = globalIssueTypes; } else { throw e; } } } List<JIRAConstant> result = new ArrayList<JIRAConstant>(); if (includeAny) { result.add(new JIRAIssueTypeBean(CacheConstants.ANY_ID, "Any", null)); } result.addAll(issueTypes); return result; } public List<JIRAConstant> getSubtaskIssueTypes(JIRAProject project) throws JIRAException { List<JIRAConstant> subtaskTypes = project == null ? globalSubtaskIssueTypes : subtaskIssueTypesCache.get(project.getKey()); if (subtaskTypes == null) { List<JIRAConstant> retrieved; try { if (project == null || project.getKey() == null) { retrieved = jiraServerFacade.getSubtaskIssueTypes(jiraServerData); } else { retrieved = jiraServerFacade.getSubtaskIssueTypesForProject(jiraServerData, project.getId(), project.getKey()); } subtaskTypes = new ArrayList<JIRAConstant>(retrieved.size()); subtaskTypes.addAll(retrieved); for (JIRAConstant subtaskType : subtaskTypes) { CachedIconLoader.getIcon(subtaskType.getIconUrl()); } if (project != null) { subtaskIssueTypesCache.put(project.getKey(), subtaskTypes); } else { globalSubtaskIssueTypes = subtaskTypes; } } catch (JIRAException e) { if (globalSubtaskIssueTypes != null) { subtaskTypes = globalSubtaskIssueTypes; } else { errorMessage = e.getMessage(); throw e; } } } return subtaskTypes; } public List<JIRAQueryFragment> getSavedFilters() throws JIRAException { if (savedFilters == null) { try { savedFilters = jiraServerFacade.getSavedFilters(jiraServerData); } catch (JIRAException e) { errorMessage = e.getMessage(); throw e; } } return savedFilters; } public List<JIRAPriorityBean> getPriorities(boolean includeAny) throws JIRAException { if (priorities == null) { try { List<JIRAPriorityBean> retrieved = jiraServerFacade.getPriorities(jiraServerData); priorities = new ArrayList<JIRAPriorityBean>(retrieved.size() + 1); priorities.addAll(retrieved); for (JIRAConstant priority : priorities) { CachedIconLoader.getIcon(priority.getIconUrl()); } } catch (JIRAException e) { errorMessage = e.getMessage(); throw e; } } List<JIRAPriorityBean> result = new ArrayList<JIRAPriorityBean>(); if (includeAny) { result.add(new JIRAPriorityBean(CacheConstants.ANY_ID, -1, "Any", null)); } result.addAll(priorities); return result; } public List<JIRAResolutionBean> getResolutions(boolean includeAnyAndUnknown) throws JIRAException { if (resolutions == null) { try { List<JIRAResolutionBean> retrieved = jiraServerFacade.getResolutions(jiraServerData); resolutions = new ArrayList<JIRAResolutionBean>(retrieved.size()); resolutions.addAll(retrieved); } catch (JIRAException e) { errorMessage = e.getMessage(); throw e; } } List<JIRAResolutionBean> result; result = new ArrayList<JIRAResolutionBean>(); if (includeAnyAndUnknown) { result.add(new JIRAResolutionBean(CacheConstants.ANY_ID, "Any")); result.add(new JIRAResolutionBean(CacheConstants.UNRESOLVED_ID, "Unresolved")); } result.addAll(resolutions); return result; } private List<JIRAVersionBean> getAllVersions(JIRAProject project) throws JIRAException { List<JIRAVersionBean> versions = null; if (project != null) { versions = serverVersionsCache.get(project.getKey()); } if (versions == null) { try { if (project != null && project.getKey() != null) { versions = jiraServerFacade.getVersions(jiraServerData, project.getKey()); Collections.reverse(versions); serverVersionsCache.put(project.getKey(), versions); } else { versions = Collections.emptyList(); } } catch (JIRAException e) { errorMessage = e.getMessage(); throw e; } } return versions; } public List<JIRAVersionBean> getVersions(JIRAProject project, boolean includeSpecialValues) throws JIRAException { List<JIRAVersionBean> versions; if (project != null) { List<JIRAVersionBean> retrieved = getAllVersions(project); if (!retrieved.isEmpty()) { versions = new ArrayList<JIRAVersionBean>(retrieved.size() + VERSION_SPECIAL_VALUES_COUNT); if (includeSpecialValues) { versions.add(new JIRAVersionBean(CacheConstants.ANY_ID, "Any", false)); versions.add(new JIRAVersionBean(CacheConstants.NO_VERSION_ID, "No version", false)); versions.add(new JIRAVersionBean(CacheConstants.UNRELEASED_VERSION_ID, "Unreleased versions", false)); } for (JIRAQueryFragment jiraQueryFragment : retrieved) { if (!((JIRAVersionBean) jiraQueryFragment).isReleased()) { versions.add((JIRAVersionBean) jiraQueryFragment); } } if (includeSpecialValues) { versions.add(new JIRAVersionBean(CacheConstants.RELEASED_VERSION_ID, "Released versions", true)); } for (JIRAQueryFragment jiraQueryFragment : retrieved) { if (((JIRAVersionBean) jiraQueryFragment).isReleased()) { versions.add((JIRAVersionBean) jiraQueryFragment); } } } else { versions = Collections.emptyList(); } } else { versions = Collections.emptyList(); } return versions; } public List<JIRAFixForVersionBean> getFixForVersions(JIRAProject project, boolean includeSpecialValues) throws JIRAException { List<JIRAFixForVersionBean> fixForVersions; if (project != null) { List<JIRAVersionBean> retrieved = getAllVersions(project); if (!retrieved.isEmpty()) { fixForVersions = new ArrayList<JIRAFixForVersionBean>(retrieved.size() + VERSION_SPECIAL_VALUES_COUNT); if (includeSpecialValues) { fixForVersions.add(new JIRAFixForVersionBean(CacheConstants.ANY_ID, "Any", false)); fixForVersions.add(new JIRAFixForVersionBean(CacheConstants.NO_VERSION_ID, "No version", false)); fixForVersions.add(new JIRAFixForVersionBean(CacheConstants.UNRELEASED_VERSION_ID, "Unreleased versions", true)); } for (JIRAVersionBean jiraQueryFragment : retrieved) { if (!jiraQueryFragment.isReleased()) { fixForVersions.add(new JIRAFixForVersionBean(jiraQueryFragment)); } } if (includeSpecialValues) { fixForVersions.add(new JIRAFixForVersionBean(CacheConstants.RELEASED_VERSION_ID, "Released versions", false)); } for (JIRAVersionBean jiraQueryFragment : retrieved) { if (jiraQueryFragment.isReleased()) { fixForVersions.add(new JIRAFixForVersionBean(jiraQueryFragment)); } } } else { fixForVersions = Collections.emptyList(); } } else { fixForVersions = Collections.emptyList(); } return fixForVersions; } public List<JIRAComponentBean> getComponents(JIRAProject project, final boolean includeSpecialValues) throws JIRAException { List<JIRAComponentBean> components = null; if (project != null) { components = componentsCache.get(project.getKey()); } if (components == null) { try { if (project != null && project.getKey() != null) { List<JIRAComponentBean> retrieved = jiraServerFacade.getComponents(jiraServerData, project.getKey()); components = new ArrayList<JIRAComponentBean>(retrieved.size() + 1); if (includeSpecialValues) { components.add(new JIRAComponentBean(CacheConstants.ANY_ID, "Any")); components.add(new JIRAComponentBean(CacheConstants.UNKNOWN_COMPONENT_ID, "Unknown")); } components.addAll(retrieved); componentsCache.put(project.getKey(), components); } else { components = Collections.emptyList(); } } catch (JIRAException e) { errorMessage = e.getMessage(); throw e; } } return components; } public boolean isValidServer() { return validServer; } public String getErrorMessage() { return errorMessage; } public void addUser(String userId, String userName) { usersMap.put(userId, userName); } }
18,449
0.608217
0.607513
450
39.995556
31.721777
131
true
false
0
0
0
0
0
0
0.584444
false
false
9
4346dd7366b5c7295a214dbcf74984a1e3152049
20,289,425,568,720
6dd290e5d8eb8c2bb14c16f277d997db26df497d
/examples/src/main/java/org/example/example/example1/MongoDatabase.java
303fe120f729a0e557d99825ee99afd6f15344f3
[]
no_license
JeffreyDeveloper/syringe
https://github.com/JeffreyDeveloper/syringe
f472d683a468f42ef31ea0cda73412c7105e3b39
c3faeca5b6b1fe474060bb01fa2d2a008e0cd02e
refs/heads/master
2022-11-26T18:20:41.130000
2020-07-25T03:13:40
2020-07-25T03:13:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.example.example.example1; public class MongoDatabase implements Database { @Override public User find(int userId) { System.out.println("Searching user in MongoDB"); // find user... return null; } @Override public void save(User user) { System.out.println("Saving user in MongoDB"); // save user... } @Override public void remove(int userId) { System.out.println("Removing user from MongoDB"); // remove user... } }
UTF-8
Java
524
java
MongoDatabase.java
Java
[]
null
[]
package org.example.example.example1; public class MongoDatabase implements Database { @Override public User find(int userId) { System.out.println("Searching user in MongoDB"); // find user... return null; } @Override public void save(User user) { System.out.println("Saving user in MongoDB"); // save user... } @Override public void remove(int userId) { System.out.println("Removing user from MongoDB"); // remove user... } }
524
0.603053
0.601145
24
20.833334
18.992689
57
false
false
0
0
0
0
0
0
0.208333
false
false
9
8362b4357f933feba534f710993f0aec88030925
3,487,513,508,247
53ba62d6ca53235ef83114b09dc06190b7cdac3f
/app/src/main/java/com/umbrella/umbrella/DatabaseUserRepo.java
a918b2c98bdb301e520551c76788b89a9dcec280
[]
no_license
CSCI3130-12/umbrella
https://github.com/CSCI3130-12/umbrella
c72f04ebd74996f04072c4b0b9f6bb58486031a3
5aa5f3026036e379043e99f4847004fb758d5182
refs/heads/master
2021-05-09T14:53:26.334000
2018-04-13T00:55:13
2018-04-13T00:55:13
119,075,089
1
1
null
false
2018-04-13T00:55:14
2018-01-26T16:26:07
2018-04-13T00:46:39
2018-04-13T00:55:14
835
1
0
5
HTML
false
null
package com.umbrella.umbrella; import android.text.method.SingleLineTransformationMethod; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.CompletableFuture; /** * Created by samdoiron on 2018-04-09. */ class DatabaseUserRepo implements StudentRepo { private final DatabaseCourseRepo courseRepo; private DatabaseReference lectureLabDB; private DatabaseReference courseDB; private DatabaseReference studentDB; public DatabaseUserRepo(DatabaseReference dbReference) { studentDB = dbReference.child("Users").child("Student"); lectureLabDB = dbReference.child("Semester").child("Courses").child("Lectures Labs Tutorials"); courseRepo = new DatabaseCourseRepo(dbReference); } @Override public void updateRegistration(Student student) { try { ArrayList<String> newLabCRNs = new ArrayList<>(); for (LectureLab lab : student.getRegistration()) { newLabCRNs.add(lab.getCRN()); } HashMap<String, Object> update = new HashMap<>(); update.put("LectureLabSet", newLabCRNs); studentDB.child(student.getUsername()).updateChildren(update); } catch (Exception e) { e.printStackTrace(); } } @Override public CompletableFuture<Student> getByUsername(String username) { CompletableFuture<Student> futureStudent = new CompletableFuture<>(); studentDB.child(username).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { try { buildStudent(dataSnapshot).thenAccept(student -> { System.out.println("Built student " + student.getUsername()); futureStudent.complete(student); }); } catch (Exception e) { e.printStackTrace(); } } @Override public void onCancelled(DatabaseError databaseError) { } }); return futureStudent; } private CompletableFuture<Student> buildStudent(DataSnapshot studentSnapshot) { try { DataSnapshot coursesData = studentSnapshot.child("CourseSet"); DataSnapshot lectureLabsData = studentSnapshot.child("LectureLabSet"); CompletableFuture<CourseSet> courseSetFuture = loadStudentCourses(coursesData); courseSetFuture.thenAccept(f -> { System.out.println("got course set"); }); CompletableFuture<LectureLabSet> lectureLabSetFuture = loadStudentLectureLabs(lectureLabsData); lectureLabSetFuture.thenAccept(f -> { System.out.println("got lecture lab set"); }); System.out.println("waiting for both"); return CompletableFuture.allOf(courseSetFuture, lectureLabSetFuture) .thenApply(x -> { System.out.println("loaded student dependants"); LectureLabSet lectureLabs = lectureLabSetFuture.join(); CourseSet courseSet = courseSetFuture.join(); return new Student( studentSnapshot.child("Name").getValue(String.class), studentSnapshot.child("Password").getValue(String.class), courseSet, lectureLabs ); }); } catch (Exception e) { e.printStackTrace(); return null; } } private CompletableFuture<LectureLabSet> loadStudentLectureLabs(DataSnapshot lectureLabs) { LectureLabSet labs = new LectureLabSet(); ArrayList<CompletableFuture<LectureLab>> futures = new ArrayList<>(); for (DataSnapshot course : lectureLabs.getChildren()) { String crn = course.getValue(String.class); System.out.println("ADD"); CompletableFuture<LectureLab> future = loadLectureLab(crn); future.thenAccept(x -> System.out.println("RESOLVE")); futures.add(future); } return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])) .thenApply(x -> { System.out.println("load student lecture labs done"); // Bug: Never reached futures.stream().map(CompletableFuture::join).forEach(labs::add); return labs; }); } private CompletableFuture<LectureLab> loadLectureLab(String crn) { CompletableFuture<LectureLab> futureLectureLab = new CompletableFuture<>(); DatabaseReference data = lectureLabDB.child(crn); data.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot labSnapshot) { System.out.println("Loaded a lecture lab"); buildLectureLab(labSnapshot).thenAccept(lectureLab -> { System.out.println("Built the lecture lab for " + lectureLab.getCourse().getCourseName()); futureLectureLab.complete(lectureLab); }); } @Override public void onCancelled(DatabaseError databaseError) { } }); return futureLectureLab; } private CompletableFuture<LectureLab> buildLectureLab(DataSnapshot labSnapshot) { return courseRepo.getCourse(labSnapshot.child("CourseID").getValue(String.class)).thenApply(course -> { System.out.println("Got course for lecture lab"); try { return new LectureLab( course, labSnapshot.child("CRN").getValue(String.class), labSnapshot.child("Instructor").getValue(String.class), labSnapshot.child("Location").getValue(String.class), labSnapshot.child("Max Students").getValue(Integer.class), 0 ); } catch (Exception e) { e.printStackTrace(); return null; } }); } private CompletableFuture<CourseSet> loadStudentCourses(DataSnapshot courses) { CourseSet courseSet = new CourseSet(); ArrayList<CompletableFuture<Course>> futures = new ArrayList<>(); for (DataSnapshot course : courses.getChildren()) { String courseID = course.getValue(String.class); futures.add(courseRepo.getCourse(courseID)); } return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])) .thenApply(x -> { futures.stream().map(CompletableFuture::join).forEach(courseSet::add); return courseSet; }); } }
UTF-8
Java
7,284
java
DatabaseUserRepo.java
Java
[ { "context": "l.concurrent.CompletableFuture;\n\n/**\n * Created by samdoiron on 2018-04-09.\n */\n\nclass DatabaseUserRepo implem", "end": 434, "score": 0.9995654225349426, "start": 425, "tag": "USERNAME", "value": "samdoiron" } ]
null
[]
package com.umbrella.umbrella; import android.text.method.SingleLineTransformationMethod; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.CompletableFuture; /** * Created by samdoiron on 2018-04-09. */ class DatabaseUserRepo implements StudentRepo { private final DatabaseCourseRepo courseRepo; private DatabaseReference lectureLabDB; private DatabaseReference courseDB; private DatabaseReference studentDB; public DatabaseUserRepo(DatabaseReference dbReference) { studentDB = dbReference.child("Users").child("Student"); lectureLabDB = dbReference.child("Semester").child("Courses").child("Lectures Labs Tutorials"); courseRepo = new DatabaseCourseRepo(dbReference); } @Override public void updateRegistration(Student student) { try { ArrayList<String> newLabCRNs = new ArrayList<>(); for (LectureLab lab : student.getRegistration()) { newLabCRNs.add(lab.getCRN()); } HashMap<String, Object> update = new HashMap<>(); update.put("LectureLabSet", newLabCRNs); studentDB.child(student.getUsername()).updateChildren(update); } catch (Exception e) { e.printStackTrace(); } } @Override public CompletableFuture<Student> getByUsername(String username) { CompletableFuture<Student> futureStudent = new CompletableFuture<>(); studentDB.child(username).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { try { buildStudent(dataSnapshot).thenAccept(student -> { System.out.println("Built student " + student.getUsername()); futureStudent.complete(student); }); } catch (Exception e) { e.printStackTrace(); } } @Override public void onCancelled(DatabaseError databaseError) { } }); return futureStudent; } private CompletableFuture<Student> buildStudent(DataSnapshot studentSnapshot) { try { DataSnapshot coursesData = studentSnapshot.child("CourseSet"); DataSnapshot lectureLabsData = studentSnapshot.child("LectureLabSet"); CompletableFuture<CourseSet> courseSetFuture = loadStudentCourses(coursesData); courseSetFuture.thenAccept(f -> { System.out.println("got course set"); }); CompletableFuture<LectureLabSet> lectureLabSetFuture = loadStudentLectureLabs(lectureLabsData); lectureLabSetFuture.thenAccept(f -> { System.out.println("got lecture lab set"); }); System.out.println("waiting for both"); return CompletableFuture.allOf(courseSetFuture, lectureLabSetFuture) .thenApply(x -> { System.out.println("loaded student dependants"); LectureLabSet lectureLabs = lectureLabSetFuture.join(); CourseSet courseSet = courseSetFuture.join(); return new Student( studentSnapshot.child("Name").getValue(String.class), studentSnapshot.child("Password").getValue(String.class), courseSet, lectureLabs ); }); } catch (Exception e) { e.printStackTrace(); return null; } } private CompletableFuture<LectureLabSet> loadStudentLectureLabs(DataSnapshot lectureLabs) { LectureLabSet labs = new LectureLabSet(); ArrayList<CompletableFuture<LectureLab>> futures = new ArrayList<>(); for (DataSnapshot course : lectureLabs.getChildren()) { String crn = course.getValue(String.class); System.out.println("ADD"); CompletableFuture<LectureLab> future = loadLectureLab(crn); future.thenAccept(x -> System.out.println("RESOLVE")); futures.add(future); } return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])) .thenApply(x -> { System.out.println("load student lecture labs done"); // Bug: Never reached futures.stream().map(CompletableFuture::join).forEach(labs::add); return labs; }); } private CompletableFuture<LectureLab> loadLectureLab(String crn) { CompletableFuture<LectureLab> futureLectureLab = new CompletableFuture<>(); DatabaseReference data = lectureLabDB.child(crn); data.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot labSnapshot) { System.out.println("Loaded a lecture lab"); buildLectureLab(labSnapshot).thenAccept(lectureLab -> { System.out.println("Built the lecture lab for " + lectureLab.getCourse().getCourseName()); futureLectureLab.complete(lectureLab); }); } @Override public void onCancelled(DatabaseError databaseError) { } }); return futureLectureLab; } private CompletableFuture<LectureLab> buildLectureLab(DataSnapshot labSnapshot) { return courseRepo.getCourse(labSnapshot.child("CourseID").getValue(String.class)).thenApply(course -> { System.out.println("Got course for lecture lab"); try { return new LectureLab( course, labSnapshot.child("CRN").getValue(String.class), labSnapshot.child("Instructor").getValue(String.class), labSnapshot.child("Location").getValue(String.class), labSnapshot.child("Max Students").getValue(Integer.class), 0 ); } catch (Exception e) { e.printStackTrace(); return null; } }); } private CompletableFuture<CourseSet> loadStudentCourses(DataSnapshot courses) { CourseSet courseSet = new CourseSet(); ArrayList<CompletableFuture<Course>> futures = new ArrayList<>(); for (DataSnapshot course : courses.getChildren()) { String courseID = course.getValue(String.class); futures.add(courseRepo.getCourse(courseID)); } return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])) .thenApply(x -> { futures.stream().map(CompletableFuture::join).forEach(courseSet::add); return courseSet; }); } }
7,284
0.596513
0.595277
175
40.622856
29.861309
111
false
false
0
0
0
0
0
0
0.497143
false
false
9
2fc2bf87083c1fa13ba0db888ded80c2ebfa05d1
33,629,593,985,220
649bca6a86656fd83970742fc0e952b6a552f617
/src/shoppingg/LoginSuccess.java
360228e37dde1f127ab2bbce1b62cfa3abfe8c99
[]
no_license
mathysaru/shopping
https://github.com/mathysaru/shopping
a2aa46dc699b4b4f998576d4ed19041d7bbc5a8b
249746d15be6b10daafbbd0644b4b78641066057
refs/heads/master
2023-08-04T13:38:40.643000
2021-09-04T15:41:25
2021-09-04T15:41:25
403,094,432
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package shoppingg; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class LoginSuccess extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { Cookie[] mycookie=req.getCookies(); res.setContentType("text/html"); PrintWriter out=res.getWriter(); String book=req.getParameter("book"); out.print("<h2>welcome "+mycookie[0].getValue()+"</h2><hr>"); out.print("<h3>Thank you for purchasing book:"+book+"</h3><hr>"); out.print("<h3>Rs.250 debited from credit card: "+mycookie[1].getValue()); out.close(); } }
UTF-8
Java
674
java
LoginSuccess.java
Java
[]
null
[]
package shoppingg; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class LoginSuccess extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { Cookie[] mycookie=req.getCookies(); res.setContentType("text/html"); PrintWriter out=res.getWriter(); String book=req.getParameter("book"); out.print("<h2>welcome "+mycookie[0].getValue()+"</h2><hr>"); out.print("<h3>Thank you for purchasing book:"+book+"</h3><hr>"); out.print("<h3>Rs.250 debited from credit card: "+mycookie[1].getValue()); out.close(); } }
674
0.72997
0.71365
24
27.083334
27.658508
106
false
false
0
0
0
0
0
0
0.75
false
false
9
093e09745678ccaf3f072590e62d8a0d25b58d39
33,595,234,250,678
98368deb114a0ade0f2314271846efb58810e317
/trust-rnt-admin/src/main/java/com/trust/config/KaptchText.java
2efedbc1dc1a2a89e4d5d087bc8f6af94863c2ef
[]
no_license
bestchendong/psychic-winner
https://github.com/bestchendong/psychic-winner
9ef35089c718e81a8cd4735662f0169bed25e3ff
a089b454697075072c2ac2edbf14455e32d65e69
refs/heads/master
2020-03-14T01:37:13.590000
2018-04-28T08:12:40
2018-04-28T08:12:40
131,381,425
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.trust.config; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.geom.Line2D; import java.awt.image.BufferedImage; import java.util.Random; import com.google.code.kaptcha.BackgroundProducer; import com.google.code.kaptcha.GimpyEngine; import com.google.code.kaptcha.Producer; import com.google.code.kaptcha.text.TextProducer; import com.google.code.kaptcha.util.Configurable; /** * @Author Yangcb * @Descrintion 自定义实现验证码字符串 * @Date create 2018-02-25 15:45 * @Version 1.0 */ public class KaptchText extends Configurable implements TextProducer { private int width = 100; private int height = 40; /** * Create an image which will have written a distorted text. * * @param text * the distorted characters * @return image with the text */ public BufferedImage createImage(String text) { GimpyEngine gimpyEngine = getConfig().getObscurificatorImpl(); BackgroundProducer backgroundProducer = getConfig().getBackgroundImpl(); boolean isBorderDrawn = getConfig().isBorderDrawn(); this.width = getConfig().getWidth(); this.height = getConfig().getHeight(); BufferedImage bi = renderWord(text, width, height); bi = gimpyEngine.getDistortedImage(bi); bi = backgroundProducer.addBackground(bi); Graphics2D graphics = bi.createGraphics(); if (isBorderDrawn) { drawBox(graphics); } return bi; } private void drawBox(Graphics2D graphics) { Color borderColor = getConfig().getBorderColor(); int borderThickness = getConfig().getBorderThickness(); graphics.setColor(borderColor); if (borderThickness != 1) { BasicStroke stroke = new BasicStroke((float) borderThickness); graphics.setStroke(stroke); } Line2D line1 = new Line2D.Double(0, 0, 0, width); graphics.draw(line1); Line2D line2 = new Line2D.Double(0, 0, width, 0); graphics.draw(line2); line2 = new Line2D.Double(0, height - 1, width, height - 1); graphics.draw(line2); line2 = new Line2D.Double(width - 1, height - 1, width - 1, 0); graphics.draw(line2); } /** * @return the text to be drawn */ public String createText() { return getConfig().getTextProducerImpl().getText(); } public BufferedImage renderWord(String word, int width, int height) { int fontSize = getConfig().getTextProducerFontSize(); Font[] fonts = getConfig().getTextProducerFonts(fontSize); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2D = image.createGraphics(); RenderingHints hints = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)); g2D.setRenderingHints(hints); FontRenderContext frc = g2D.getFontRenderContext(); Random random = new Random(); int startPosY = (height - fontSize) / 5 + fontSize; char[] wordChars = word.toCharArray(); Font[] chosenFonts = new Font[wordChars.length]; int [] charWidths = new int[wordChars.length]; int widthNeeded = 0; for (int i = 0; i < wordChars.length; i++) { chosenFonts[i] = fonts[random.nextInt(fonts.length)]; char[] charToDraw = new char[]{ wordChars[i] }; GlyphVector gv = chosenFonts[i].createGlyphVector(frc, charToDraw); charWidths[i] = (int)gv.getVisualBounds().getWidth(); if (i > 0) { widthNeeded = widthNeeded + 2; } widthNeeded = widthNeeded + charWidths[i]; } int startPosX = (width - widthNeeded) / 2; for (int i = 0; i < wordChars.length; i++) { g2D.setColor(getColor()); g2D.setFont(chosenFonts[i]); char[] charToDraw = new char[] { wordChars[i] }; g2D.drawChars(charToDraw, 0, charToDraw.length, startPosX, startPosY); startPosX = startPosX + (int) charWidths[i] ; } return image; } /** * 生成随机颜色 * @return */ private Color getColor(){ Random random = new Random(); int red = random.nextInt(255); int green = random.nextInt(255); int blue = random.nextInt(255); return new Color(red, green, blue); } @Override /** * @return the random text */ public String getText() { int length = getConfig().getTextProducerCharLength(); char[] chars = getConfig().getTextProducerCharString(); Random rand = new Random(); StringBuffer text = new StringBuffer(); for (int i = 0; i < length; i++) { text.append(chars[rand.nextInt(chars.length)]); } return text.toString(); } }
UTF-8
Java
5,389
java
KaptchText.java
Java
[ { "context": "gle.code.kaptcha.util.Configurable;\n/**\n * @Author Yangcb\n * @Descrintion 自定义实现验证码字符串\n * @Date create 2018-", "end": 583, "score": 0.9996974468231201, "start": 577, "tag": "USERNAME", "value": "Yangcb" } ]
null
[]
package com.trust.config; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.geom.Line2D; import java.awt.image.BufferedImage; import java.util.Random; import com.google.code.kaptcha.BackgroundProducer; import com.google.code.kaptcha.GimpyEngine; import com.google.code.kaptcha.Producer; import com.google.code.kaptcha.text.TextProducer; import com.google.code.kaptcha.util.Configurable; /** * @Author Yangcb * @Descrintion 自定义实现验证码字符串 * @Date create 2018-02-25 15:45 * @Version 1.0 */ public class KaptchText extends Configurable implements TextProducer { private int width = 100; private int height = 40; /** * Create an image which will have written a distorted text. * * @param text * the distorted characters * @return image with the text */ public BufferedImage createImage(String text) { GimpyEngine gimpyEngine = getConfig().getObscurificatorImpl(); BackgroundProducer backgroundProducer = getConfig().getBackgroundImpl(); boolean isBorderDrawn = getConfig().isBorderDrawn(); this.width = getConfig().getWidth(); this.height = getConfig().getHeight(); BufferedImage bi = renderWord(text, width, height); bi = gimpyEngine.getDistortedImage(bi); bi = backgroundProducer.addBackground(bi); Graphics2D graphics = bi.createGraphics(); if (isBorderDrawn) { drawBox(graphics); } return bi; } private void drawBox(Graphics2D graphics) { Color borderColor = getConfig().getBorderColor(); int borderThickness = getConfig().getBorderThickness(); graphics.setColor(borderColor); if (borderThickness != 1) { BasicStroke stroke = new BasicStroke((float) borderThickness); graphics.setStroke(stroke); } Line2D line1 = new Line2D.Double(0, 0, 0, width); graphics.draw(line1); Line2D line2 = new Line2D.Double(0, 0, width, 0); graphics.draw(line2); line2 = new Line2D.Double(0, height - 1, width, height - 1); graphics.draw(line2); line2 = new Line2D.Double(width - 1, height - 1, width - 1, 0); graphics.draw(line2); } /** * @return the text to be drawn */ public String createText() { return getConfig().getTextProducerImpl().getText(); } public BufferedImage renderWord(String word, int width, int height) { int fontSize = getConfig().getTextProducerFontSize(); Font[] fonts = getConfig().getTextProducerFonts(fontSize); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2D = image.createGraphics(); RenderingHints hints = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)); g2D.setRenderingHints(hints); FontRenderContext frc = g2D.getFontRenderContext(); Random random = new Random(); int startPosY = (height - fontSize) / 5 + fontSize; char[] wordChars = word.toCharArray(); Font[] chosenFonts = new Font[wordChars.length]; int [] charWidths = new int[wordChars.length]; int widthNeeded = 0; for (int i = 0; i < wordChars.length; i++) { chosenFonts[i] = fonts[random.nextInt(fonts.length)]; char[] charToDraw = new char[]{ wordChars[i] }; GlyphVector gv = chosenFonts[i].createGlyphVector(frc, charToDraw); charWidths[i] = (int)gv.getVisualBounds().getWidth(); if (i > 0) { widthNeeded = widthNeeded + 2; } widthNeeded = widthNeeded + charWidths[i]; } int startPosX = (width - widthNeeded) / 2; for (int i = 0; i < wordChars.length; i++) { g2D.setColor(getColor()); g2D.setFont(chosenFonts[i]); char[] charToDraw = new char[] { wordChars[i] }; g2D.drawChars(charToDraw, 0, charToDraw.length, startPosX, startPosY); startPosX = startPosX + (int) charWidths[i] ; } return image; } /** * 生成随机颜色 * @return */ private Color getColor(){ Random random = new Random(); int red = random.nextInt(255); int green = random.nextInt(255); int blue = random.nextInt(255); return new Color(red, green, blue); } @Override /** * @return the random text */ public String getText() { int length = getConfig().getTextProducerCharLength(); char[] chars = getConfig().getTextProducerCharString(); Random rand = new Random(); StringBuffer text = new StringBuffer(); for (int i = 0; i < length; i++) { text.append(chars[rand.nextInt(chars.length)]); } return text.toString(); } }
5,389
0.604482
0.590289
170
30.5
22.671892
82
false
false
0
0
0
0
0
0
0.670588
false
false
9
1aa6442ed927b4195aeb2ae10c84598176025649
23,046,794,576,652
a36b61d81690bed3d81f49898e508c797a4bbae7
/src/com/system/Info.java
b79f89ac66c6c2271ff944f848b9e69d9625a0d4
[]
no_license
KemasRaihan/DiscInformationSystem
https://github.com/KemasRaihan/DiscInformationSystem
ab8304675fcbc986a340168d01cbe885f7ba730a
9950fcbe61010a32da3794c6992b594ec31e5192
refs/heads/main
2023-04-21T11:54:55.199000
2021-04-22T18:45:43
2021-04-22T18:45:43
324,469,457
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.system; import java.util.InputMismatchException; import java.util.Scanner; import java.util.Vector; public class Info { public static Vector<DiscFile> allDiscFiles = new Vector<DiscFile>(); public static void launchMenu(Scanner input) { boolean keepUsing = true; while (keepUsing) { System.out.println("\nDisc Information Management"); System.out.println("-----------------------------\n"); System.out.println("1. Add New Music CD."); System.out.println("2. Add New Game Disc"); System.out.println("3. Search Disc."); System.out.println("4. Remove Disc."); System.out.println("5. Rename Text File."); System.out.println("6. Display Details in Reverse Order."); System.out.print("\nEnter your choice: "); boolean DiscIsMusic; boolean validInput; do { validInput = true; String userInput = input.nextLine(); switch (userInput) { case "1": addNewDisc(input, DiscIsMusic = true); break; case "2": addNewDisc(input, DiscIsMusic = false); break; case "3": printSearchedDiscDetails(input); break; case "4": removeDisc(input); break; case "5": renameFileFromVector(input); break; case "6": if(allDiscFiles.size()==0) System.out.println("\nThere are no discs currently in your list. Please add a disc to display their details.\n"); else displayDetailsInReverseOrder(allDiscFiles.size()); break; default: System.out.println("Invalid input. Please try again."); validInput=false; } }while(!validInput); } } public static void addNewDisc(Scanner input, boolean DiscIsMusic) { System.out.println("\nAdd New Disc"); System.out.println("------------------"); System.out.print("\nEnter CD title: "); String titleInput = input.nextLine(); String genreInput = new Genre().selectGenre(input, DiscIsMusic); System.out.println("\nEnter the release date. "); String releaseDateInput = new ReleaseDate().getValidDate(input); input.nextLine(); // consume newline leftover String filename = "disc"+Integer.toString(allDiscFiles.size() + 1); if (DiscIsMusic) { // goes to this path if user wants to add a music CD and adds details only exclusive to music CDs System.out.print("\nEnter name of artist: "); String artistInput = input.nextLine(); System.out.print("\nEnter number of songs: "); int numberOfSongsInput = new NumberHandling().enterPositiveInteger(input); System.out.print("\nEnter duration (in minutes): "); int durationInput = new NumberHandling().enterPositiveInteger(input); Music newMusicCD = new Music(titleInput, releaseDateInput, genreInput, artistInput, numberOfSongsInput, durationInput); DiscFile<Music> newDiscFile = new DiscFile<Music>(newMusicCD, newMusicCD.getTitle(), newMusicCD.getFullDetails(), filename); input.nextLine(); // consume newline leftover allDiscFiles.add(newDiscFile); System.out.println("\nMusic CD details successfully added."); } else { // goes to this path if user wants to add a game disc and adds details only exclusive to game discs String ratingInput = new Rating().selectPEGIRating(input); input.nextLine(); // consume newline leftover System.out.print("\nEnter platform: "); String platformInput = input.nextLine(); Game newGameDisc = new Game(titleInput, releaseDateInput, genreInput, ratingInput, platformInput); DiscFile<Game> newDiscFile = new DiscFile<Game>(newGameDisc, newGameDisc.getTitle(), newGameDisc.getFullDetails(), filename); allDiscFiles.add(newDiscFile); System.out.println("\nGame disc details successfully added.\n"); } } private static DiscFile searchDiscFileByTitle(String title) { DiscFile desiredFile = null; for (DiscFile discFile : allDiscFiles) if (discFile.getDiscTitle().toUpperCase().equals(title.toUpperCase())) desiredFile = discFile; return desiredFile; } private static String checkIfTitleExists(Scanner input){ boolean validDisc=false; String title=""; while(!validDisc) { System.out.print("Enter title: "); String titleInput = input.nextLine(); DiscFile discFile = searchDiscFileByTitle(titleInput); if (discFile != null) { validDisc = true; title = discFile.getDiscTitle(); } else System.out.println("Disc is not found. Please try again."); } return title; } private static String EnterYOrN(Scanner input, String message){ String userInput=""; boolean validInput; do{ validInput=true; System.out.print(message); userInput=input.nextLine().toUpperCase(); if(!userInput.equals("Y") && !userInput.equals("N")){ // if the user does not enter 'Y' or 'N' the loop will prompt to user to enter again until they enter either one validInput=false; System.out.println("Invalid input. Please try again"); } }while(!validInput); return userInput; } private static void printSearchedDiscDetails(Scanner input){ boolean searchAnotherDisc = true; while(searchAnotherDisc) { System.out.println("\nSearch Disc"); System.out.println("------------"); String title = checkIfTitleExists(input); System.out.println("\n"+searchDiscFileByTitle(title).readDiscDetailsFromFile()+"\n"); String userInput = EnterYOrN(input, "Would you like to search another disc (Y/N)? "); if (userInput.equals("N")) searchAnotherDisc = false; } } private static void removeDisc(Scanner input) { boolean deleteAnotherDisc = true; while (deleteAnotherDisc) { System.out.println("\nRemove Disc"); System.out.println("-------------"); String title = checkIfTitleExists(input); DiscFile fileToDelete = searchDiscFileByTitle(title); String deleteThis = EnterYOrN(input, "Are you sure you would like to delete the following disc (Y/N): \n\n"+fileToDelete.readDiscDetailsFromFile()+"\n\nEnter your choice: "); if (deleteThis.equals("Y")) { fileToDelete.deleteFile(); allDiscFiles.remove(fileToDelete); } String userInput = EnterYOrN(input, "Would you like to delete another disc (Y/N)? "); if (userInput.equals("N")) deleteAnotherDisc = false; } } private static void renameFileFromVector(Scanner input){ boolean renameAnotherFile = true; while(renameAnotherFile) { System.out.println("\nRename file"); System.out.println("------------"); String title = checkIfTitleExists(input); searchDiscFileByTitle(title).renameFile(input); String userInput = EnterYOrN(input, "Would you like to rename another file (Y/N)? "); if (userInput.equals("N")) renameAnotherFile = false; } } private static int displayDetailsInReverseOrder(int n){ if(n==0) return 0; else { System.out.print("\n"+allDiscFiles.get(n - 1).readDiscDetailsFromFile()+"\n"); return displayDetailsInReverseOrder(n - 1); } } }
UTF-8
Java
8,484
java
Info.java
Java
[]
null
[]
package com.system; import java.util.InputMismatchException; import java.util.Scanner; import java.util.Vector; public class Info { public static Vector<DiscFile> allDiscFiles = new Vector<DiscFile>(); public static void launchMenu(Scanner input) { boolean keepUsing = true; while (keepUsing) { System.out.println("\nDisc Information Management"); System.out.println("-----------------------------\n"); System.out.println("1. Add New Music CD."); System.out.println("2. Add New Game Disc"); System.out.println("3. Search Disc."); System.out.println("4. Remove Disc."); System.out.println("5. Rename Text File."); System.out.println("6. Display Details in Reverse Order."); System.out.print("\nEnter your choice: "); boolean DiscIsMusic; boolean validInput; do { validInput = true; String userInput = input.nextLine(); switch (userInput) { case "1": addNewDisc(input, DiscIsMusic = true); break; case "2": addNewDisc(input, DiscIsMusic = false); break; case "3": printSearchedDiscDetails(input); break; case "4": removeDisc(input); break; case "5": renameFileFromVector(input); break; case "6": if(allDiscFiles.size()==0) System.out.println("\nThere are no discs currently in your list. Please add a disc to display their details.\n"); else displayDetailsInReverseOrder(allDiscFiles.size()); break; default: System.out.println("Invalid input. Please try again."); validInput=false; } }while(!validInput); } } public static void addNewDisc(Scanner input, boolean DiscIsMusic) { System.out.println("\nAdd New Disc"); System.out.println("------------------"); System.out.print("\nEnter CD title: "); String titleInput = input.nextLine(); String genreInput = new Genre().selectGenre(input, DiscIsMusic); System.out.println("\nEnter the release date. "); String releaseDateInput = new ReleaseDate().getValidDate(input); input.nextLine(); // consume newline leftover String filename = "disc"+Integer.toString(allDiscFiles.size() + 1); if (DiscIsMusic) { // goes to this path if user wants to add a music CD and adds details only exclusive to music CDs System.out.print("\nEnter name of artist: "); String artistInput = input.nextLine(); System.out.print("\nEnter number of songs: "); int numberOfSongsInput = new NumberHandling().enterPositiveInteger(input); System.out.print("\nEnter duration (in minutes): "); int durationInput = new NumberHandling().enterPositiveInteger(input); Music newMusicCD = new Music(titleInput, releaseDateInput, genreInput, artistInput, numberOfSongsInput, durationInput); DiscFile<Music> newDiscFile = new DiscFile<Music>(newMusicCD, newMusicCD.getTitle(), newMusicCD.getFullDetails(), filename); input.nextLine(); // consume newline leftover allDiscFiles.add(newDiscFile); System.out.println("\nMusic CD details successfully added."); } else { // goes to this path if user wants to add a game disc and adds details only exclusive to game discs String ratingInput = new Rating().selectPEGIRating(input); input.nextLine(); // consume newline leftover System.out.print("\nEnter platform: "); String platformInput = input.nextLine(); Game newGameDisc = new Game(titleInput, releaseDateInput, genreInput, ratingInput, platformInput); DiscFile<Game> newDiscFile = new DiscFile<Game>(newGameDisc, newGameDisc.getTitle(), newGameDisc.getFullDetails(), filename); allDiscFiles.add(newDiscFile); System.out.println("\nGame disc details successfully added.\n"); } } private static DiscFile searchDiscFileByTitle(String title) { DiscFile desiredFile = null; for (DiscFile discFile : allDiscFiles) if (discFile.getDiscTitle().toUpperCase().equals(title.toUpperCase())) desiredFile = discFile; return desiredFile; } private static String checkIfTitleExists(Scanner input){ boolean validDisc=false; String title=""; while(!validDisc) { System.out.print("Enter title: "); String titleInput = input.nextLine(); DiscFile discFile = searchDiscFileByTitle(titleInput); if (discFile != null) { validDisc = true; title = discFile.getDiscTitle(); } else System.out.println("Disc is not found. Please try again."); } return title; } private static String EnterYOrN(Scanner input, String message){ String userInput=""; boolean validInput; do{ validInput=true; System.out.print(message); userInput=input.nextLine().toUpperCase(); if(!userInput.equals("Y") && !userInput.equals("N")){ // if the user does not enter 'Y' or 'N' the loop will prompt to user to enter again until they enter either one validInput=false; System.out.println("Invalid input. Please try again"); } }while(!validInput); return userInput; } private static void printSearchedDiscDetails(Scanner input){ boolean searchAnotherDisc = true; while(searchAnotherDisc) { System.out.println("\nSearch Disc"); System.out.println("------------"); String title = checkIfTitleExists(input); System.out.println("\n"+searchDiscFileByTitle(title).readDiscDetailsFromFile()+"\n"); String userInput = EnterYOrN(input, "Would you like to search another disc (Y/N)? "); if (userInput.equals("N")) searchAnotherDisc = false; } } private static void removeDisc(Scanner input) { boolean deleteAnotherDisc = true; while (deleteAnotherDisc) { System.out.println("\nRemove Disc"); System.out.println("-------------"); String title = checkIfTitleExists(input); DiscFile fileToDelete = searchDiscFileByTitle(title); String deleteThis = EnterYOrN(input, "Are you sure you would like to delete the following disc (Y/N): \n\n"+fileToDelete.readDiscDetailsFromFile()+"\n\nEnter your choice: "); if (deleteThis.equals("Y")) { fileToDelete.deleteFile(); allDiscFiles.remove(fileToDelete); } String userInput = EnterYOrN(input, "Would you like to delete another disc (Y/N)? "); if (userInput.equals("N")) deleteAnotherDisc = false; } } private static void renameFileFromVector(Scanner input){ boolean renameAnotherFile = true; while(renameAnotherFile) { System.out.println("\nRename file"); System.out.println("------------"); String title = checkIfTitleExists(input); searchDiscFileByTitle(title).renameFile(input); String userInput = EnterYOrN(input, "Would you like to rename another file (Y/N)? "); if (userInput.equals("N")) renameAnotherFile = false; } } private static int displayDetailsInReverseOrder(int n){ if(n==0) return 0; else { System.out.print("\n"+allDiscFiles.get(n - 1).readDiscDetailsFromFile()+"\n"); return displayDetailsInReverseOrder(n - 1); } } }
8,484
0.559642
0.55752
205
40.390244
38.224674
186
false
false
0
0
0
0
0
0
0.658537
false
false
9
03256f648104fd528f5ca1c7e00819f03f8540dd
11,330,123,727,460
caea867c8a37bde4f3ee410fef56256a8a3a6338
/sparrow-api/src/main/java/com/github/nnest/sparrow/command/document/query/fulltext/Match.java
31b1c3d944c9bd4ac933e065c02611d76b338c25
[ "MIT" ]
permissive
nnest/sparrow
https://github.com/nnest/sparrow
4052167adb0d9e8f58f2beaf77ee9771b4633210
80a16856a809f5ac60dc4e132e6d5f32e81ea76c
refs/heads/master
2021-01-12T03:09:19.871000
2017-03-10T01:58:17
2017-03-10T01:58:17
78,167,026
2
1
null
false
2017-01-11T07:12:14
2017-01-06T02:37:29
2017-01-06T10:50:19
2017-01-11T06:06:40
96
0
1
0
Java
null
null
/** * */ package com.github.nnest.sparrow.command.document.query.fulltext; import java.math.BigDecimal; import com.github.nnest.sparrow.command.document.query.DefaultExampleType; import com.github.nnest.sparrow.command.document.query.ExampleType; import com.github.nnest.sparrow.command.document.query.attrs.ExampleTextConjunction; import com.github.nnest.sparrow.command.document.query.attrs.ZeroTermsQuery; import com.github.nnest.sparrow.command.document.query.attrs.fuzzy.Fuzziness; import com.github.nnest.sparrow.command.document.query.attrs.rewrite.Rewrite; import com.github.nnest.sparrow.command.document.query.attrs.shouldmatch.MinimumShouldMatch; /** * Match basic, in elastic search, the {@code match} api. * * @author brad.wu * @since 0.0.1 * @version 0.0.1 */ public class Match extends AbstractSingleMatch<Match> { private ExampleTextConjunction conjunction = null; private MinimumShouldMatch minimumShouldMatch = null; private Fuzziness fuzziness = null; private ZeroTermsQuery zeroTermsQuery = null; private BigDecimal cutoffFrequency = null; private Boolean lenient = null; private Integer prefixLength = null; private Integer maxExpansions = null; private Rewrite rewrite = null; private Boolean transpositions = null; public Match(String exampleText) { super(exampleText); } /** * (non-Javadoc) * * @see com.github.nnest.sparrow.command.document.query.Example#getExampleType() */ @Override public ExampleType getExampleType() { return DefaultExampleType.MATCH; } /** * @return the conjunction */ public ExampleTextConjunction getConjunction() { return conjunction; } /** * @param conjunction * the conjunction to set * @return this */ public Match with(ExampleTextConjunction conjunction) { assert conjunction != null : "Conjunction cannot be null."; this.conjunction = conjunction; return this; } /** * @return the minimumShouldMatch */ public MinimumShouldMatch getMinimumShouldMatch() { return minimumShouldMatch; } /** * @param minimumShouldMatch * the miuimumShouldMatch to set * @return this */ public Match with(MinimumShouldMatch minimumShouldMatch) { assert minimumShouldMatch != null : "Minimum should match cannot be null."; this.minimumShouldMatch = minimumShouldMatch; return this; } /** * @return the fuzziness */ public Fuzziness getFuzziness() { return fuzziness; } /** * @param fuzziness * the fuzziness to set * @return this */ public Match with(Fuzziness fuzziness) { assert fuzziness != null : "Fuzziness cannot be null."; this.fuzziness = fuzziness; return this; } /** * @return the zeroTermsQuery */ public ZeroTermsQuery getZeroTermsQuery() { return zeroTermsQuery; } /** * @param zeroTermsQuery * the zeroTermsQuery to set * @return this */ public Match with(ZeroTermsQuery zeroTermsQuery) { assert zeroTermsQuery != null : "Zero terms query cannot be null."; this.zeroTermsQuery = zeroTermsQuery; return this; } /** * @return the cutoffFrequency */ public BigDecimal getCutoffFrequency() { return cutoffFrequency; } /** * @param cutoffFrequency * the cutoffFrequency to set * @return this */ public Match withCutoffFrequency(BigDecimal cutoffFrequency) { assert cutoffFrequency != null : "Cutoff frequence cannot be null."; double v = cutoffFrequency.doubleValue(); assert v >= 0 : "Cutoff frequence must in range [0, 1) or absolute if greater or equal to 1.0."; this.cutoffFrequency = cutoffFrequency; return this; } /** * @return the lenient */ public Boolean getLenient() { return lenient; } /** * @param lenient * the lenient to set * @return this */ public Match withLenient(Boolean lenient) { assert lenient != null : "Lenient cannot be null"; this.lenient = lenient; return this; } /** * @return the prefixLength */ public Integer getPrefixLength() { return prefixLength; } /** * @param prefixLength * the prefixLength to set * @return this */ public Match withPrefixLength(Integer prefixLength) { assert prefixLength != null && prefixLength >= 0 : "Prefix length cannot be null, and must be zero or positive."; this.prefixLength = prefixLength; return this; } /** * @return the maxExpansions */ public Integer getMaxExpansions() { return maxExpansions; } /** * @param maxExpansions * the maxExpansions to set * @return this */ public Match withMaxExpansions(Integer maxExpansions) { assert maxExpansions != null && maxExpansions >= 0 : "Max expansions cannot be null, and must be zero or positive."; this.maxExpansions = maxExpansions; return this; } /** * @return the rewrite */ public Rewrite getRewrite() { return rewrite; } /** * @param rewrite * the rewrite to set * @return this */ public Match with(Rewrite rewrite) { assert rewrite != null : "Rewrite cannot be null."; this.rewrite = rewrite; return this; } /** * @return the transpositions */ public Boolean getTranspositions() { return transpositions; } /** * @param transpositions * the transpositions to set * @return this */ public Match withTranspositions(Boolean transpositions) { assert transpositions != null : "Transpositions cannot be null."; this.transpositions = transpositions; return this; } }
UTF-8
Java
5,476
java
Match.java
Java
[ { "context": "stic search, the {@code match} api.\n * \n * @author brad.wu\n * @since 0.0.1\n * @version 0.0.1\n */\npublic clas", "end": 748, "score": 0.8644841313362122, "start": 741, "tag": "USERNAME", "value": "brad.wu" } ]
null
[]
/** * */ package com.github.nnest.sparrow.command.document.query.fulltext; import java.math.BigDecimal; import com.github.nnest.sparrow.command.document.query.DefaultExampleType; import com.github.nnest.sparrow.command.document.query.ExampleType; import com.github.nnest.sparrow.command.document.query.attrs.ExampleTextConjunction; import com.github.nnest.sparrow.command.document.query.attrs.ZeroTermsQuery; import com.github.nnest.sparrow.command.document.query.attrs.fuzzy.Fuzziness; import com.github.nnest.sparrow.command.document.query.attrs.rewrite.Rewrite; import com.github.nnest.sparrow.command.document.query.attrs.shouldmatch.MinimumShouldMatch; /** * Match basic, in elastic search, the {@code match} api. * * @author brad.wu * @since 0.0.1 * @version 0.0.1 */ public class Match extends AbstractSingleMatch<Match> { private ExampleTextConjunction conjunction = null; private MinimumShouldMatch minimumShouldMatch = null; private Fuzziness fuzziness = null; private ZeroTermsQuery zeroTermsQuery = null; private BigDecimal cutoffFrequency = null; private Boolean lenient = null; private Integer prefixLength = null; private Integer maxExpansions = null; private Rewrite rewrite = null; private Boolean transpositions = null; public Match(String exampleText) { super(exampleText); } /** * (non-Javadoc) * * @see com.github.nnest.sparrow.command.document.query.Example#getExampleType() */ @Override public ExampleType getExampleType() { return DefaultExampleType.MATCH; } /** * @return the conjunction */ public ExampleTextConjunction getConjunction() { return conjunction; } /** * @param conjunction * the conjunction to set * @return this */ public Match with(ExampleTextConjunction conjunction) { assert conjunction != null : "Conjunction cannot be null."; this.conjunction = conjunction; return this; } /** * @return the minimumShouldMatch */ public MinimumShouldMatch getMinimumShouldMatch() { return minimumShouldMatch; } /** * @param minimumShouldMatch * the miuimumShouldMatch to set * @return this */ public Match with(MinimumShouldMatch minimumShouldMatch) { assert minimumShouldMatch != null : "Minimum should match cannot be null."; this.minimumShouldMatch = minimumShouldMatch; return this; } /** * @return the fuzziness */ public Fuzziness getFuzziness() { return fuzziness; } /** * @param fuzziness * the fuzziness to set * @return this */ public Match with(Fuzziness fuzziness) { assert fuzziness != null : "Fuzziness cannot be null."; this.fuzziness = fuzziness; return this; } /** * @return the zeroTermsQuery */ public ZeroTermsQuery getZeroTermsQuery() { return zeroTermsQuery; } /** * @param zeroTermsQuery * the zeroTermsQuery to set * @return this */ public Match with(ZeroTermsQuery zeroTermsQuery) { assert zeroTermsQuery != null : "Zero terms query cannot be null."; this.zeroTermsQuery = zeroTermsQuery; return this; } /** * @return the cutoffFrequency */ public BigDecimal getCutoffFrequency() { return cutoffFrequency; } /** * @param cutoffFrequency * the cutoffFrequency to set * @return this */ public Match withCutoffFrequency(BigDecimal cutoffFrequency) { assert cutoffFrequency != null : "Cutoff frequence cannot be null."; double v = cutoffFrequency.doubleValue(); assert v >= 0 : "Cutoff frequence must in range [0, 1) or absolute if greater or equal to 1.0."; this.cutoffFrequency = cutoffFrequency; return this; } /** * @return the lenient */ public Boolean getLenient() { return lenient; } /** * @param lenient * the lenient to set * @return this */ public Match withLenient(Boolean lenient) { assert lenient != null : "Lenient cannot be null"; this.lenient = lenient; return this; } /** * @return the prefixLength */ public Integer getPrefixLength() { return prefixLength; } /** * @param prefixLength * the prefixLength to set * @return this */ public Match withPrefixLength(Integer prefixLength) { assert prefixLength != null && prefixLength >= 0 : "Prefix length cannot be null, and must be zero or positive."; this.prefixLength = prefixLength; return this; } /** * @return the maxExpansions */ public Integer getMaxExpansions() { return maxExpansions; } /** * @param maxExpansions * the maxExpansions to set * @return this */ public Match withMaxExpansions(Integer maxExpansions) { assert maxExpansions != null && maxExpansions >= 0 : "Max expansions cannot be null, and must be zero or positive."; this.maxExpansions = maxExpansions; return this; } /** * @return the rewrite */ public Rewrite getRewrite() { return rewrite; } /** * @param rewrite * the rewrite to set * @return this */ public Match with(Rewrite rewrite) { assert rewrite != null : "Rewrite cannot be null."; this.rewrite = rewrite; return this; } /** * @return the transpositions */ public Boolean getTranspositions() { return transpositions; } /** * @param transpositions * the transpositions to set * @return this */ public Match withTranspositions(Boolean transpositions) { assert transpositions != null : "Transpositions cannot be null."; this.transpositions = transpositions; return this; } }
5,476
0.698868
0.696494
242
21.628099
22.85894
98
false
false
0
0
0
0
0
0
1.256198
false
false
9
2b1d4e3880708a523cb7fa3a1a67d7856e5925fe
4,707,284,209,305
1e6d00fb0b454ccf690e571a0bfda456c21329f7
/src/main/java/com/reimia/bianli/BianLiErJinZhi.java
f0595e02fd9c778d728476e2e2ece4cfdea0e825
[]
no_license
Reimia/mdzz
https://github.com/Reimia/mdzz
b24bcc6c072aacf964674a14d3bad6bb97d37bf4
9932235b2719ee073e327e0d15f813c5a18e6630
refs/heads/master
2022-06-30T10:59:52.848000
2021-04-20T02:57:27
2021-04-20T02:57:27
216,738,268
0
0
null
false
2022-06-17T02:47:09
2019-10-22T06:23:51
2021-04-20T03:03:48
2022-06-17T02:47:08
171
0
0
5
Java
false
false
package com.reimia.bianli; import java.io.*; import java.util.Arrays; public class BianLiErJinZhi { public static void main(String[] args) { String path = "D:\\bianliceshi";//要遍历的路径 String path2 = "D:\\bianliceshi.txt";//输出文件地址(如果没有则创建) File file = new File(path); File fileOut = new File(path2); if (fileOut.exists()) { if (fileOut.delete()){ System.out.println("文件已存在,将删除后重新创建"); //如果输出文件存在则删除文件 } } func(file, fileOut); } private static void func(File file, File fileOut) { File[] fs = file.listFiles(); assert fs != null; for (File f : fs) { if (f.isDirectory()) //若是目录,则递归打印该目录下的文件 { func(f, fileOut); } if (f.isFile()) //若是文件,直接打印 { System.out.println(f);//输出绝对路径 try { int length = (int) f.length(); FileInputStream fis = new FileInputStream(f); FileOutputStream fos = new FileOutputStream(fileOut, true); BufferedInputStream in = new BufferedInputStream(fis); ByteArrayOutputStream out = new ByteArrayOutputStream(length); byte[] temp = new byte[length]; while (in.read(temp) != -1) { out.write(temp); } byte[] content = out.toByteArray(); System.out.println(Arrays.toString(content));//打印写入内容 fos.write(content);//写入 in.close(); out.close(); fos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); } } } } }
UTF-8
Java
2,132
java
BianLiErJinZhi.java
Java
[]
null
[]
package com.reimia.bianli; import java.io.*; import java.util.Arrays; public class BianLiErJinZhi { public static void main(String[] args) { String path = "D:\\bianliceshi";//要遍历的路径 String path2 = "D:\\bianliceshi.txt";//输出文件地址(如果没有则创建) File file = new File(path); File fileOut = new File(path2); if (fileOut.exists()) { if (fileOut.delete()){ System.out.println("文件已存在,将删除后重新创建"); //如果输出文件存在则删除文件 } } func(file, fileOut); } private static void func(File file, File fileOut) { File[] fs = file.listFiles(); assert fs != null; for (File f : fs) { if (f.isDirectory()) //若是目录,则递归打印该目录下的文件 { func(f, fileOut); } if (f.isFile()) //若是文件,直接打印 { System.out.println(f);//输出绝对路径 try { int length = (int) f.length(); FileInputStream fis = new FileInputStream(f); FileOutputStream fos = new FileOutputStream(fileOut, true); BufferedInputStream in = new BufferedInputStream(fis); ByteArrayOutputStream out = new ByteArrayOutputStream(length); byte[] temp = new byte[length]; while (in.read(temp) != -1) { out.write(temp); } byte[] content = out.toByteArray(); System.out.println(Arrays.toString(content));//打印写入内容 fos.write(content);//写入 in.close(); out.close(); fos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); } } } } }
2,132
0.444898
0.443367
57
32.385963
21.191486
82
false
false
0
0
0
0
0
0
0.561404
false
false
9
8ba970e205e70bdeb3758248afcc877038664a83
26,809,185,924,023
2a49b84a98f53a55077a4d303ab7e00a0a7f05b1
/src/main/java/com/example/tangoDemo/service/impl/TangoCardServiceImpl.java
126bf1df9f70aa9fc89c37692459c9684b94468a
[]
no_license
arpitsharma11/tango-demo
https://github.com/arpitsharma11/tango-demo
c1cf92c80c670290d0823afa3b67b130d89968d4
968e5b15b6d088df7403952b79b6063709c90605
refs/heads/master
2022-12-21T07:18:46.531000
2019-10-29T09:36:57
2019-10-29T09:36:57
217,979,893
0
0
null
false
2020-10-13T17:02:26
2019-10-28T06:26:46
2019-10-29T09:37:21
2020-10-13T17:02:24
58
0
0
1
Java
false
false
package com.example.tangoDemo.service.impl; import com.example.tangoDemo.pojo.*; import com.example.tangoDemo.service.TangoCardService; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.core.annotation.Order; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.client.support.BasicAuthenticationInterceptor; import org.springframework.web.client.RestTemplate; public class TangoCardServiceImpl implements TangoCardService { private RestTemplate restTemplate = new RestTemplate(); private String tangoCardBaseUrl = "https://integration-api.tangocard.com/raas/v2/"; public TangoCardServiceImpl(){ restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("ZeMoSo Sandbox","dh$w!fiFuNtsVeNeuPuS!QOyvOncdLVwvtHdgVAcsU$UI")); } @Override public CatalogResponse catalogs(){ CatalogResponse response =restTemplate.getForObject(tangoCardBaseUrl + "catalogs", CatalogResponse.class); return response; } @Override public OrderResponse orderGiftCard(OrderRequest request){ HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); ObjectMapper mappper = new ObjectMapper(); try { String requestJson = mappper.writeValueAsString(request); HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers); ResponseEntity<OrderResponse> res = restTemplate.postForEntity(tangoCardBaseUrl + "orders",entity,OrderResponse.class); return res.getBody(); //return res; } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } @Override public OrderHistoryResponse retrievePastOrder(){ OrderHistoryResponse res = restTemplate.getForObject(tangoCardBaseUrl + "orders",OrderHistoryResponse.class); return res; } }
UTF-8
Java
2,161
java
TangoCardServiceImpl.java
Java
[]
null
[]
package com.example.tangoDemo.service.impl; import com.example.tangoDemo.pojo.*; import com.example.tangoDemo.service.TangoCardService; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.core.annotation.Order; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.client.support.BasicAuthenticationInterceptor; import org.springframework.web.client.RestTemplate; public class TangoCardServiceImpl implements TangoCardService { private RestTemplate restTemplate = new RestTemplate(); private String tangoCardBaseUrl = "https://integration-api.tangocard.com/raas/v2/"; public TangoCardServiceImpl(){ restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("ZeMoSo Sandbox","dh$w!fiFuNtsVeNeuPuS!QOyvOncdLVwvtHdgVAcsU$UI")); } @Override public CatalogResponse catalogs(){ CatalogResponse response =restTemplate.getForObject(tangoCardBaseUrl + "catalogs", CatalogResponse.class); return response; } @Override public OrderResponse orderGiftCard(OrderRequest request){ HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); ObjectMapper mappper = new ObjectMapper(); try { String requestJson = mappper.writeValueAsString(request); HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers); ResponseEntity<OrderResponse> res = restTemplate.postForEntity(tangoCardBaseUrl + "orders",entity,OrderResponse.class); return res.getBody(); //return res; } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } @Override public OrderHistoryResponse retrievePastOrder(){ OrderHistoryResponse res = restTemplate.getForObject(tangoCardBaseUrl + "orders",OrderHistoryResponse.class); return res; } }
2,161
0.738547
0.738084
56
37.589287
35.435947
145
false
false
0
0
0
0
0
0
0.625
false
false
9
40145fd2f5e5242a4390fb58f6cb9a5e7309d546
37,675,453,138,085
1abacbd52979dbfe37c0db55452eee5b8b403676
/src/stringManipulations.java
40c31def4d3cac70bb0ff393efc816cc7a6758e8
[]
no_license
revathysoundar/StringOperations
https://github.com/revathysoundar/StringOperations
b6a6d74622e32d0f3ef1b30cb0437135ef975b87
5de31d4c8ef99077cd6e644ff73de45446843d98
refs/heads/master
2020-09-22T11:45:55.391000
2016-08-30T14:32:38
2016-08-30T14:32:38
66,950,016
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Arrays; import java.util.Scanner; import java.lang.StringBuilder; public class stringManipulations { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); String firstName = "Revathy"; String lastName = "Raja"; String fullName = firstName + " " + lastName; System.out.println("My Full Name is " + fullName); System.out.println("Enter your name"); String name = sc.nextLine(); if(name.equals("David") || name.equalsIgnoreCase("David")) { System.out.println("You're the instructor"); System.out.println("Starts with Dav"); } else { System.out.println("You're a student"); } char firstChar = name.charAt(0); System.out.println("First Character " + firstChar); int lenOfString = name.length(); for(int i = 0; i < lenOfString; i++) { if(name.charAt(i) == 'f') { System.out.println("Contains f"); } } String sentence = "She sells seashells by the seashore." ; String sentence1 = sentence.replace('s', 'S'); System.out.println("Sentence Before Replace: " + sentence ); System.out.println("Sentence After Replace: " + sentence1 ); System.out.println("Sentence Before Replace: " + sentence ); String sentence2 = sentence.replace("ell", "oo"); System.out.println("Sentence After ell Replace: " + sentence2); int lenOfSentence = sentence.length(); System.out.println("Length of sentence: " + lenOfSentence); String lowerCase = sentence.toLowerCase(); System.out.println("Sentence lower case: " + lowerCase ); ///////////////////////////////// String word1 = "Hello World"; System.out.println(word1); char ch = word1.charAt(1); System.out.println(ch); System.out.println(word1.indexOf('l')); System.out.println(word1.startsWith("Hello")); System.out.println(word1.endsWith("World")); System.out.println(word1.length()); System.out.println(word1.lastIndexOf('l')); String word2 = word1.replace('l', '5'); System.out.println(name.contains("f")); System.out.println(word1); System.out.println(word2); System.out.println(word1.substring(7,10)); System.out.println(word1.substring(6)); //System.out.println(Arrays.asList(word1.spilt(" ")); StringBuffer fullNameBuffer = new StringBuffer(); fullNameBuffer.append(firstName); fullNameBuffer.append(" "); fullNameBuffer.append(lastName); System.out.println(fullNameBuffer); String phrase = "Grant Chirpus loves Detroit"; System.out.println(phrase.substring(0, 5)); // prints "Grant" System.out.println(phrase.substring(6, 13)); // prints "Chirpus" System.out.println(phrase.substring(14, 19)); // prints "loves" System.out.println(phrase.substring(20)); // prints "Detroit" sc.close(); } }
UTF-8
Java
2,825
java
stringManipulations.java
Java
[ { "context": " new Scanner(System.in);\n\t\t\n\t\tString firstName = \"Revathy\";\n\t\tString lastName = \"Raja\";\n\t\tString fullName =", "end": 273, "score": 0.9998468160629272, "start": 266, "tag": "NAME", "value": "Revathy" }, { "context": "tring firstName = \"Revathy\";\n\t\tString lastName = \"Raja\";\n\t\tString fullName = firstName + \" \" + lastName;", "end": 301, "score": 0.9998363256454468, "start": 297, "tag": "NAME", "value": "Raja" }, { "context": "if(name.equals(\"David\") || name.equalsIgnoreCase(\"David\"))\n\t\t{\n\t\t\tSystem.out.println(\"You're the instruct", "end": 537, "score": 0.6283642649650574, "start": 532, "tag": "NAME", "value": "David" }, { "context": "e instructor\");\n\t\t\tSystem.out.println(\"Starts with Dav\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tSystem.out.println(\"You're a", "end": 631, "score": 0.9986013174057007, "start": 628, "tag": "NAME", "value": "Dav" }, { "context": "fer = new StringBuffer();\n\t\tfullNameBuffer.append(firstName);\n\t\tfullNameBuffer.append(\" \");\n\t\tfullNameBuffer.", "end": 2332, "score": 0.9900858998298645, "start": 2323, "tag": "NAME", "value": "firstName" }, { "context": "llNameBuffer.append(\" \");\n\t\tfullNameBuffer.append(lastName);\n\t\tSystem.out.println(fullNameBuffer);\n\t\t\n\t\tStri", "end": 2397, "score": 0.994755744934082, "start": 2389, "tag": "NAME", "value": "lastName" }, { "context": "ut.println(fullNameBuffer);\n\t\t\n\t\tString phrase = \"Grant Chirpus loves Detroit\";\n\t\tSystem.out.println(phrase.subst", "end": 2473, "score": 0.9995592832565308, "start": 2460, "tag": "NAME", "value": "Grant Chirpus" }, { "context": "Buffer);\n\t\t\n\t\tString phrase = \"Grant Chirpus loves Detroit\";\n\t\tSystem.out.println(phrase.substring(0, 5)); /", "end": 2487, "score": 0.9990217089653015, "start": 2480, "tag": "NAME", "value": "Detroit" }, { "context": "m.out.println(phrase.substring(0, 5)); // prints \"Grant\"\n\t\tSystem.out.println(phrase.substring(6, 13)); /", "end": 2552, "score": 0.9993857741355896, "start": 2547, "tag": "NAME", "value": "Grant" }, { "context": ".out.println(phrase.substring(6, 13)); // prints \"Chirpus\"\n\t\tSystem.out.println(phrase.substring(14, 19)); ", "end": 2619, "score": 0.9987097382545471, "start": 2612, "tag": "NAME", "value": "Chirpus" }, { "context": "tem.out.println(phrase.substring(20)); // prints \"Detroit\"\n\t\t\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t", "end": 2749, "score": 0.9974417090415955, "start": 2742, "tag": "NAME", "value": "Detroit" } ]
null
[]
import java.util.Arrays; import java.util.Scanner; import java.lang.StringBuilder; public class stringManipulations { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); String firstName = "Revathy"; String lastName = "Raja"; String fullName = firstName + " " + lastName; System.out.println("My Full Name is " + fullName); System.out.println("Enter your name"); String name = sc.nextLine(); if(name.equals("David") || name.equalsIgnoreCase("David")) { System.out.println("You're the instructor"); System.out.println("Starts with Dav"); } else { System.out.println("You're a student"); } char firstChar = name.charAt(0); System.out.println("First Character " + firstChar); int lenOfString = name.length(); for(int i = 0; i < lenOfString; i++) { if(name.charAt(i) == 'f') { System.out.println("Contains f"); } } String sentence = "She sells seashells by the seashore." ; String sentence1 = sentence.replace('s', 'S'); System.out.println("Sentence Before Replace: " + sentence ); System.out.println("Sentence After Replace: " + sentence1 ); System.out.println("Sentence Before Replace: " + sentence ); String sentence2 = sentence.replace("ell", "oo"); System.out.println("Sentence After ell Replace: " + sentence2); int lenOfSentence = sentence.length(); System.out.println("Length of sentence: " + lenOfSentence); String lowerCase = sentence.toLowerCase(); System.out.println("Sentence lower case: " + lowerCase ); ///////////////////////////////// String word1 = "Hello World"; System.out.println(word1); char ch = word1.charAt(1); System.out.println(ch); System.out.println(word1.indexOf('l')); System.out.println(word1.startsWith("Hello")); System.out.println(word1.endsWith("World")); System.out.println(word1.length()); System.out.println(word1.lastIndexOf('l')); String word2 = word1.replace('l', '5'); System.out.println(name.contains("f")); System.out.println(word1); System.out.println(word2); System.out.println(word1.substring(7,10)); System.out.println(word1.substring(6)); //System.out.println(Arrays.asList(word1.spilt(" ")); StringBuffer fullNameBuffer = new StringBuffer(); fullNameBuffer.append(firstName); fullNameBuffer.append(" "); fullNameBuffer.append(lastName); System.out.println(fullNameBuffer); String phrase = "<NAME> loves Detroit"; System.out.println(phrase.substring(0, 5)); // prints "Grant" System.out.println(phrase.substring(6, 13)); // prints "Chirpus" System.out.println(phrase.substring(14, 19)); // prints "loves" System.out.println(phrase.substring(20)); // prints "Detroit" sc.close(); } }
2,818
0.664425
0.650973
106
25.650944
22.134256
66
false
false
0
0
0
0
0
0
2.471698
false
false
9
7e2bec9a68aabbc0789b9f62384163c46d379ccf
37,056,977,854,164
b64b7749e68967d24ce5e1e8bfb6d3755290b25c
/assignment_9_may_2019/ReverseString.java
2f22cefe4680f0237662b32becc16a48e776d310
[]
no_license
hussham786/IBM_Assignment
https://github.com/hussham786/IBM_Assignment
17cc29314558deedbe5a5199ce7b522976a5f0dd
66499a302c90fe561c776bac8bcf59b2d4a7929c
refs/heads/master
2020-05-18T01:20:26.838000
2019-06-28T06:50:10
2019-06-28T06:50:10
184,088,181
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; class ReverseString{ public static void main(String[] args) { String str = ""; Scanner sc = new Scanner(System.in); System.out.println("Enter a String: "); str = sc.nextLine(); System.out.println("The reverse of the string is: " + new ReverseString().reverseString(str)); } String reverseString(String str){ String reverseStr = ""; for (int i = str.length() - 1; i >= 0 ; i--) { reverseStr = reverseStr + str.charAt(i); } return reverseStr; } }
UTF-8
Java
519
java
ReverseString.java
Java
[]
null
[]
import java.util.Scanner; class ReverseString{ public static void main(String[] args) { String str = ""; Scanner sc = new Scanner(System.in); System.out.println("Enter a String: "); str = sc.nextLine(); System.out.println("The reverse of the string is: " + new ReverseString().reverseString(str)); } String reverseString(String str){ String reverseStr = ""; for (int i = str.length() - 1; i >= 0 ; i--) { reverseStr = reverseStr + str.charAt(i); } return reverseStr; } }
519
0.630058
0.626204
20
24.049999
23.068323
96
false
false
0
0
0
0
0
0
1.9
false
false
9
132c4d1b6736efd67a48050ff16dbb441538fbdf
34,883,724,412,402
abc97e6bea930d47504b1fed9580affb0d57ddb5
/Desktop/Projects/POS/app/src/main/java/com/walkover/pos/SalesAndInvoicePackage/SalesProductUtils/SalesProductBean.java
a30eb355063d60c3de33c72a3ba4184cfe575860
[]
no_license
saurabhsharma30/POS
https://github.com/saurabhsharma30/POS
5b4b80fb1d5fc061cb2cf2e4cdcdce5a6db01597
94072b4ade7b176168862fed0a7ed58906d3cf22
refs/heads/master
2021-01-20T07:40:34.976000
2017-03-04T12:20:29
2017-03-04T12:20:30
83,891,579
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.walkover.pos.SalesAndInvoicePackage.SalesProductUtils; /** * Created by saurabh on 1/3/17. */ public class SalesProductBean { private String inventory_stock_id; private String inventory_category_id; private String company_id; private String product_name; private String product_pic; private String product_code; private String barcode_no; private String stock_type; private String description; private String cost_price; private String sell_price; private String opening_quantity; private String current_quantity; private String discount; private String tax; private String location; public String getInventory_stock_id() { return inventory_stock_id; } public void setInventory_stock_id(String inventory_stock_id) { this.inventory_stock_id = inventory_stock_id; } public String getInventory_category_id() { return inventory_category_id; } public void setInventory_category_id(String inventory_category_id) { this.inventory_category_id = inventory_category_id; } public String getCompany_id() { return company_id; } public void setCompany_id(String company_id) { this.company_id = company_id; } public String getProduct_name() { return product_name; } public void setProduct_name(String product_name) { this.product_name = product_name; } public String getProduct_pic() { return product_pic; } public void setProduct_pic(String product_pic) { this.product_pic = product_pic; } public String getProduct_code() { return product_code; } public void setProduct_code(String product_code) { this.product_code = product_code; } public String getBarcode_no() { return barcode_no; } public void setBarcode_no(String barcode_no) { this.barcode_no = barcode_no; } public String getStock_type() { return stock_type; } public void setStock_type(String stock_type) { this.stock_type = stock_type; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCost_price() { return cost_price; } public void setCost_price(String cost_price) { this.cost_price = cost_price; } public String getSell_price() { return sell_price; } public void setSell_price(String sell_price) { this.sell_price = sell_price; } public String getOpening_quantity() { return opening_quantity; } public void setOpening_quantity(String opening_quantity) { this.opening_quantity = opening_quantity; } public String getCurrent_quantity() { return current_quantity; } public void setCurrent_quantity(String current_quantity) { this.current_quantity = current_quantity; } public String getDiscount() { return discount; } public void setDiscount(String discount) { this.discount = discount; } public String getTax() { return tax; } public void setTax(String tax) { this.tax = tax; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } }
UTF-8
Java
3,479
java
SalesProductBean.java
Java
[ { "context": "voicePackage.SalesProductUtils;\n\n/**\n * Created by saurabh on 1/3/17.\n */\n\npublic class SalesProductBean {\n\n", "end": 93, "score": 0.9994643330574036, "start": 86, "tag": "USERNAME", "value": "saurabh" } ]
null
[]
package com.walkover.pos.SalesAndInvoicePackage.SalesProductUtils; /** * Created by saurabh on 1/3/17. */ public class SalesProductBean { private String inventory_stock_id; private String inventory_category_id; private String company_id; private String product_name; private String product_pic; private String product_code; private String barcode_no; private String stock_type; private String description; private String cost_price; private String sell_price; private String opening_quantity; private String current_quantity; private String discount; private String tax; private String location; public String getInventory_stock_id() { return inventory_stock_id; } public void setInventory_stock_id(String inventory_stock_id) { this.inventory_stock_id = inventory_stock_id; } public String getInventory_category_id() { return inventory_category_id; } public void setInventory_category_id(String inventory_category_id) { this.inventory_category_id = inventory_category_id; } public String getCompany_id() { return company_id; } public void setCompany_id(String company_id) { this.company_id = company_id; } public String getProduct_name() { return product_name; } public void setProduct_name(String product_name) { this.product_name = product_name; } public String getProduct_pic() { return product_pic; } public void setProduct_pic(String product_pic) { this.product_pic = product_pic; } public String getProduct_code() { return product_code; } public void setProduct_code(String product_code) { this.product_code = product_code; } public String getBarcode_no() { return barcode_no; } public void setBarcode_no(String barcode_no) { this.barcode_no = barcode_no; } public String getStock_type() { return stock_type; } public void setStock_type(String stock_type) { this.stock_type = stock_type; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCost_price() { return cost_price; } public void setCost_price(String cost_price) { this.cost_price = cost_price; } public String getSell_price() { return sell_price; } public void setSell_price(String sell_price) { this.sell_price = sell_price; } public String getOpening_quantity() { return opening_quantity; } public void setOpening_quantity(String opening_quantity) { this.opening_quantity = opening_quantity; } public String getCurrent_quantity() { return current_quantity; } public void setCurrent_quantity(String current_quantity) { this.current_quantity = current_quantity; } public String getDiscount() { return discount; } public void setDiscount(String discount) { this.discount = discount; } public String getTax() { return tax; } public void setTax(String tax) { this.tax = tax; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } }
3,479
0.639552
0.638402
153
21.738562
19.624172
72
false
false
0
0
0
0
0
0
0.320261
false
false
9
8d221b9534a6211b3efc29e73776beb802db6c01
37,108,517,461,227
4b46c6f657002ec51099b3cada094f79b3b1fe7d
/app/src/main/java/com/display/cctest/activity/WelcomeActivity.java
cf13292e03db8eb51f93a40f33673fa0e816e7be
[]
no_license
display822/CCtest
https://github.com/display822/CCtest
b3ea359a2773c4963b9c701366a82d7c65231cad
8073ed4f009ba00f0cb2e2bc0a015e19ed93bf37
refs/heads/master
2018-02-06T19:36:07.759000
2017-10-22T17:45:08
2017-10-22T17:45:08
95,633,313
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.display.cctest.activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import com.display.cctest.R; import java.util.Timer; import java.util.TimerTask; /** * Created by chenlie on 2017/6/28. * */ public class WelcomeActivity extends BaseActivity{ Timer timer; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //三秒后跳转 timer = new Timer(); timer.schedule(new MyTimer(), 2500); } @Override protected int getContentResId() { return R.layout.activity_welcome_layout; } class MyTimer extends TimerTask{ @Override public void run() { startActivity(new Intent(WelcomeActivity.this, ZeroActivity.class)); timer.cancel(); finish(); } } }
UTF-8
Java
914
java
WelcomeActivity.java
Java
[ { "context": "er;\nimport java.util.TimerTask;\n\n/**\n * Created by chenlie on 2017/6/28.\n *\n */\n\npublic class WelcomeActivit", "end": 247, "score": 0.9996334910392761, "start": 240, "tag": "USERNAME", "value": "chenlie" } ]
null
[]
package com.display.cctest.activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import com.display.cctest.R; import java.util.Timer; import java.util.TimerTask; /** * Created by chenlie on 2017/6/28. * */ public class WelcomeActivity extends BaseActivity{ Timer timer; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //三秒后跳转 timer = new Timer(); timer.schedule(new MyTimer(), 2500); } @Override protected int getContentResId() { return R.layout.activity_welcome_layout; } class MyTimer extends TimerTask{ @Override public void run() { startActivity(new Intent(WelcomeActivity.this, ZeroActivity.class)); timer.cancel(); finish(); } } }
914
0.653761
0.641593
43
20.023256
19.693569
80
false
false
0
0
0
0
0
0
0.395349
false
false
9
cca6dc50ee5a2e903cc68fbee19d680b8686e109
27,273,042,394,964
15b071636a0ecdceed3235debae315ae58e77429
/src/solutions/CBar/LecteurFichier.java
c741c6b281c7ad8be939a5c3f0b4a08c076b3907
[]
no_license
PengBAI/TpChoco
https://github.com/PengBAI/TpChoco
65f6cb1c27c418f1ba54af92944823870353fe22
dcdfcf6e6476f53586e16173ff2c47a2b5d09bbc
refs/heads/master
2016-09-05T21:59:26
2014-12-12T13:08:11
2014-12-12T13:08:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package solutions.CBar; /* * LecteurFichier.java * * Created on 6 février 2007, 16:28 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ import java.util.*; import java.io.*; public class LecteurFichier { protected String nomFic; public int[] instance; // créer une methode GetInstance protected int nbjobs; public LecteurFichier(String nFic) { nomFic = nFic; instance = null; nbjobs=0; } public int GetNbJobs() { return nbjobs; } public int[] convert() { try { BufferedReader in = new BufferedReader(new FileReader(nomFic)); // ouvre le fichier String line; int i = 0; line = in.readLine() ; if (line != null) { nbjobs=Integer.parseInt(line); instance = new int[nbjobs]; while ((line = in.readLine()) != null) { // lit la première ligne du fichier : = null si on est à la fin du fichier StringTokenizer st = new StringTokenizer(line, " "); // Rq st peut être vue comme une liste de chaines de caractères séparées par le token " " int taille = st.countTokens(); // nb de listes int j = 0; while(taille > 0){ int val = Integer.parseInt(st.nextToken()); //renvoie la string sur laquelle on pointe et passe à la suivante instance[j] = val; j++; taille--; } i++; } } else System.out.println("vide !!!"); in.close(); } catch (Exception e) { e.printStackTrace(); System.out.println("Erreur fichier"); } System.out.println("------------------------------------------------"); for(int i=0; i<1; i++){ for(int j=0; j<nbjobs; j++) System.out.print(instance[j]+" "); System.out.println(); } System.out.println(); System.out.println("------------------------------------------------"); return instance; } }
ISO-8859-1
Java
2,304
java
LecteurFichier.java
Java
[]
null
[]
package solutions.CBar; /* * LecteurFichier.java * * Created on 6 février 2007, 16:28 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ import java.util.*; import java.io.*; public class LecteurFichier { protected String nomFic; public int[] instance; // créer une methode GetInstance protected int nbjobs; public LecteurFichier(String nFic) { nomFic = nFic; instance = null; nbjobs=0; } public int GetNbJobs() { return nbjobs; } public int[] convert() { try { BufferedReader in = new BufferedReader(new FileReader(nomFic)); // ouvre le fichier String line; int i = 0; line = in.readLine() ; if (line != null) { nbjobs=Integer.parseInt(line); instance = new int[nbjobs]; while ((line = in.readLine()) != null) { // lit la première ligne du fichier : = null si on est à la fin du fichier StringTokenizer st = new StringTokenizer(line, " "); // Rq st peut être vue comme une liste de chaines de caractères séparées par le token " " int taille = st.countTokens(); // nb de listes int j = 0; while(taille > 0){ int val = Integer.parseInt(st.nextToken()); //renvoie la string sur laquelle on pointe et passe à la suivante instance[j] = val; j++; taille--; } i++; } } else System.out.println("vide !!!"); in.close(); } catch (Exception e) { e.printStackTrace(); System.out.println("Erreur fichier"); } System.out.println("------------------------------------------------"); for(int i=0; i<1; i++){ for(int j=0; j<nbjobs; j++) System.out.print(instance[j]+" "); System.out.println(); } System.out.println(); System.out.println("------------------------------------------------"); return instance; } }
2,304
0.471895
0.464924
81
27.308641
28.695353
134
false
false
0
0
0
0
0
0
0.580247
false
false
9
fa2d6a0caafd1fef57da15a1f6e7ef08b62c39cf
19,928,648,315,177
aa7d47fa0d3a2b9c6fa573b91ff16daeffcc547c
/nycemoves-file-upload/src/main/java/com/nyce/moves/controller/UploadController.java
e5777b22aa1859446ca658ba165f7b6bce3ffc8a
[]
no_license
mmehrotra/nyce-moves-1.0
https://github.com/mmehrotra/nyce-moves-1.0
a9cdf7f181cf42da57d7fa9f8e567c11c838d6d7
6bd549b9d3841b9c57e5d3e6ae2c37296112c2ff
refs/heads/master
2020-04-24T16:30:47.959000
2019-06-17T09:19:00
2019-06-17T09:19:00
172,109,966
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nyce.moves.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.nyce.moves.common.ApplicationConstants; import com.nyce.moves.model.FileObject; import com.nyce.moves.model.ResponseTemplate; import com.nyce.moves.model.UploadFileResponse; import com.nyce.moves.model.ResponseTemplate.StatusEnum; import com.nyce.moves.service.AmazonClient; @RestController public class UploadController { private AmazonClient amazonClient; @Autowired UploadController(AmazonClient amazonClient) { this.amazonClient = amazonClient; } @RequestMapping("/service-status") public ResponseTemplate uploadStatus() { ResponseTemplate responseTemplate = new ResponseTemplate(); responseTemplate.setCode(ApplicationConstants.SUCCESS_CODE_11001); responseTemplate.setStatus(StatusEnum.SUCCESS); responseTemplate.setMessage("File upload service is running"); return responseTemplate; } @RequestMapping(method = RequestMethod.POST, value = "/players/{playerId}/uploadFile") public UploadFileResponse uploadFile(@RequestPart(value = "file") MultipartFile file, @PathVariable Long playerId, @RequestHeader String fileType) { UploadFileResponse uploadFileResponse = new UploadFileResponse(); uploadFileResponse.setCode(ApplicationConstants.SUCCESS_CODE_11001); uploadFileResponse.setStatus(UploadFileResponse.StatusEnum.SUCCESS); uploadFileResponse.setMessage("File has been loaded successfully"); FileObject fileObject = new FileObject(); fileObject = this.amazonClient.uploadFile(file, playerId, fileType, fileObject); uploadFileResponse.setFileObject(fileObject); return uploadFileResponse; } @RequestMapping(method = RequestMethod.POST, value = "/players/temp/uploadFile") public UploadFileResponse uploadTempFile(@RequestPart(value = "file") MultipartFile file, @RequestHeader String fileType) { UploadFileResponse uploadFileResponse = new UploadFileResponse(); uploadFileResponse.setCode(ApplicationConstants.SUCCESS_CODE_11001); uploadFileResponse.setStatus(UploadFileResponse.StatusEnum.SUCCESS); uploadFileResponse.setMessage("File has been loaded successfully"); FileObject fileObject = new FileObject(); fileObject = this.amazonClient.uploadFile(file, 0L, fileType, fileObject); uploadFileResponse.setFileObject(fileObject); return uploadFileResponse; } @RequestMapping(method = RequestMethod.DELETE, value = "/deleteFile") public ResponseTemplate deleteFile(@RequestPart(value = "url") String fileUrl) { this.amazonClient.deleteFileFromS3Bucket(fileUrl); ResponseTemplate responseTemplate = new ResponseTemplate(); responseTemplate.setCode(ApplicationConstants.SUCCESS_CODE_11001); responseTemplate.setStatus(StatusEnum.SUCCESS); responseTemplate.setMessage("File has been deleted successfully with url [" + fileUrl + "]"); return responseTemplate; } }
UTF-8
Java
3,295
java
UploadController.java
Java
[]
null
[]
package com.nyce.moves.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.nyce.moves.common.ApplicationConstants; import com.nyce.moves.model.FileObject; import com.nyce.moves.model.ResponseTemplate; import com.nyce.moves.model.UploadFileResponse; import com.nyce.moves.model.ResponseTemplate.StatusEnum; import com.nyce.moves.service.AmazonClient; @RestController public class UploadController { private AmazonClient amazonClient; @Autowired UploadController(AmazonClient amazonClient) { this.amazonClient = amazonClient; } @RequestMapping("/service-status") public ResponseTemplate uploadStatus() { ResponseTemplate responseTemplate = new ResponseTemplate(); responseTemplate.setCode(ApplicationConstants.SUCCESS_CODE_11001); responseTemplate.setStatus(StatusEnum.SUCCESS); responseTemplate.setMessage("File upload service is running"); return responseTemplate; } @RequestMapping(method = RequestMethod.POST, value = "/players/{playerId}/uploadFile") public UploadFileResponse uploadFile(@RequestPart(value = "file") MultipartFile file, @PathVariable Long playerId, @RequestHeader String fileType) { UploadFileResponse uploadFileResponse = new UploadFileResponse(); uploadFileResponse.setCode(ApplicationConstants.SUCCESS_CODE_11001); uploadFileResponse.setStatus(UploadFileResponse.StatusEnum.SUCCESS); uploadFileResponse.setMessage("File has been loaded successfully"); FileObject fileObject = new FileObject(); fileObject = this.amazonClient.uploadFile(file, playerId, fileType, fileObject); uploadFileResponse.setFileObject(fileObject); return uploadFileResponse; } @RequestMapping(method = RequestMethod.POST, value = "/players/temp/uploadFile") public UploadFileResponse uploadTempFile(@RequestPart(value = "file") MultipartFile file, @RequestHeader String fileType) { UploadFileResponse uploadFileResponse = new UploadFileResponse(); uploadFileResponse.setCode(ApplicationConstants.SUCCESS_CODE_11001); uploadFileResponse.setStatus(UploadFileResponse.StatusEnum.SUCCESS); uploadFileResponse.setMessage("File has been loaded successfully"); FileObject fileObject = new FileObject(); fileObject = this.amazonClient.uploadFile(file, 0L, fileType, fileObject); uploadFileResponse.setFileObject(fileObject); return uploadFileResponse; } @RequestMapping(method = RequestMethod.DELETE, value = "/deleteFile") public ResponseTemplate deleteFile(@RequestPart(value = "url") String fileUrl) { this.amazonClient.deleteFileFromS3Bucket(fileUrl); ResponseTemplate responseTemplate = new ResponseTemplate(); responseTemplate.setCode(ApplicationConstants.SUCCESS_CODE_11001); responseTemplate.setStatus(StatusEnum.SUCCESS); responseTemplate.setMessage("File has been deleted successfully with url [" + fileUrl + "]"); return responseTemplate; } }
3,295
0.816995
0.810319
82
39.195122
32.838272
149
false
false
0
0
0
0
0
0
1.573171
false
false
9
f04b491ef3c11c9e1f1b95431c9c45e6729ca54e
38,508,676,797,264
503ed8ce78f9e3504bae16fbb6eae5102f1fe838
/Trabajo-fin-master-us/src/main/java/es/us/master/base/usuario/model/Usuario.java
f12389e6a0052b4d55a799f33b04d15afc07efd9
[]
no_license
alemarcha/ApiRestPFMMovil
https://github.com/alemarcha/ApiRestPFMMovil
74055de226020b9eb5af514c3ae7d5edda82c674
9caeda6f165e49d6cbc20b5b0a70f9323acfa53a
refs/heads/master
2020-05-19T08:53:28.246000
2015-09-03T18:20:30
2015-09-03T18:20:30
38,390,559
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package es.us.master.base.usuario.model; //Generated 03-jul-2015 20:05:13 by Hibernate Tools 4.3.1 import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; /** * Usuario generated by hbm2java */ @Entity @Table(name = "USUARIO", schema = "C##ALEMARCHA") public class Usuario implements java.io.Serializable { private static final long serialVersionUID = -4622445748644156283L; private BigDecimal id; private String nombre; private String password; public Usuario() { } public Usuario(BigDecimal id, String nombre, String password) { this.id = id; this.nombre = nombre; this.password = password; } @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "my_seq_gen") @SequenceGenerator(name = "my_seq_gen", sequenceName = "sequence_usuario") @Column(name = "ID", unique = true, nullable = false, precision = 22, scale = 0) public BigDecimal getId() { return this.id; } public void setId(BigDecimal id) { this.id = id; } @Column(name = "NOMBRE", nullable = false, length = 45) public String getNombre() { return this.nombre; } public void setNombre(String nombre) { this.nombre = nombre; } @Column(name = "PASSWORD", nullable = false, length = 120) public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Usuario other = (Usuario) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
UTF-8
Java
2,151
java
Usuario.java
Java
[ { "context": "s.id = id;\n\tthis.nombre = nombre;\n\tthis.password = password;\n }\n\n @Id\n @GeneratedValue(strategy = Ge", "end": 855, "score": 0.9993065595626831, "start": 847, "tag": "PASSWORD", "value": "password" }, { "context": "id setPassword(String password) {\n\tthis.password = password;\n }\n\n @Override\n public int hashCode() {", "end": 1623, "score": 0.983569324016571, "start": 1615, "tag": "PASSWORD", "value": "password" } ]
null
[]
package es.us.master.base.usuario.model; //Generated 03-jul-2015 20:05:13 by Hibernate Tools 4.3.1 import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; /** * Usuario generated by hbm2java */ @Entity @Table(name = "USUARIO", schema = "C##ALEMARCHA") public class Usuario implements java.io.Serializable { private static final long serialVersionUID = -4622445748644156283L; private BigDecimal id; private String nombre; private String password; public Usuario() { } public Usuario(BigDecimal id, String nombre, String password) { this.id = id; this.nombre = nombre; this.password = <PASSWORD>; } @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "my_seq_gen") @SequenceGenerator(name = "my_seq_gen", sequenceName = "sequence_usuario") @Column(name = "ID", unique = true, nullable = false, precision = 22, scale = 0) public BigDecimal getId() { return this.id; } public void setId(BigDecimal id) { this.id = id; } @Column(name = "NOMBRE", nullable = false, length = 45) public String getNombre() { return this.nombre; } public void setNombre(String nombre) { this.nombre = nombre; } @Column(name = "PASSWORD", nullable = false, length = 120) public String getPassword() { return this.password; } public void setPassword(String password) { this.password = <PASSWORD>; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Usuario other = (Usuario) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
2,155
0.671316
0.649465
89
23.168539
20.656765
84
false
false
0
0
0
0
0
0
0.820225
false
false
9
a7ae1baabd53bbecc84c2f7ccc8bc55bf4f56d78
29,789,893,224,625
052cff99fad6400ae598349378e95286e44cacef
/src/main/java/com/duyj/mybatis/mapper2/BMapper.java
b38970b54040feeea8873fb3053fed32bb080707
[]
no_license
dyj2012/myTest
https://github.com/dyj2012/myTest
6c3271c5693fee5d13f7d3fea362572af26036b8
3306ff91305dc23b9a44c96326006b5e1d7a8ff5
refs/heads/master
2022-12-21T06:43:12.659000
2020-12-29T02:24:10
2020-12-29T02:24:10
144,830,501
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.duyj.mybatis.mapper2; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; @Mapper public interface BMapper { // @Select("select 'bbb'") String query(); }
UTF-8
Java
213
java
BMapper.java
Java
[]
null
[]
package com.duyj.mybatis.mapper2; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; @Mapper public interface BMapper { // @Select("select 'bbb'") String query(); }
213
0.741784
0.737089
11
18.454546
16.902737
44
false
false
0
0
0
0
0
0
0.363636
false
false
9
462ad27fa930e652325fc029bde65f7f0e8dba99
2,723,009,280,017
954109e9c4552e8e9161578d6c12daf4e0e6feef
/src/main/java/com/gcn/heco/schedule/listener/ScheduleEventListner.java
4ffeb621f9d3284b1c3535d2a1756d887818aad7
[]
no_license
rahul-me/heco
https://github.com/rahul-me/heco
7c79669142cc4b4cc376edd958f98ad60f2f2082
61fca82834fac79ca7c397d7cd41dce8304e5cb4
refs/heads/master
2022-01-22T23:01:59.483000
2022-01-11T10:41:53
2022-01-11T10:41:53
250,859,866
0
0
null
false
2022-01-11T10:42:46
2020-03-28T17:56:37
2022-01-11T08:14:57
2022-01-11T10:42:06
38
0
0
0
Java
false
false
package com.gcn.heco.schedule.listener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.gcn.heco.app.model.NocMiSchedule; import com.gcn.heco.constant.Constant; import com.gcn.heco.database.model.MiSchedule; import com.gcn.heco.database.service.IMiDBService; import com.gcn.heco.schedule.container.ScheduleContainer; @Component public class ScheduleEventListner implements IScheduleEventListener { static Logger logger = LoggerFactory.getLogger(ScheduleEventListner.class); @Autowired private ScheduleContainer scheduleContainer; @Autowired private IMiDBService iMiDBService; @Override public void afterPost(MiSchedule miSchedule, NocMiSchedule nocMiSchedule) { if(nocMiSchedule != null){ Integer miId = nocMiSchedule.getManualInstrScheduleId(); logger.info("heco: Response from NOC for post request for schedule having id "+miSchedule.getId()); if(miId != null){ miSchedule.setScheduleId(miId); scheduleContainer.addActiveSchedule(miSchedule); logger.info("heco: Schedule having id "+miSchedule.getId()+" has been added to active schedule list"); } } else { logger.warn("heco: Troble getting response from NOC for post request for schedule having id "+miSchedule.getId()); } } @Override public void afterCancel(MiSchedule miSchedule, NocMiSchedule nocMiSchedule) { if(nocMiSchedule != null && miSchedule != null){ logger.info("heco: Response from NOC for cancel request for schedule having id "+miSchedule.getId()); miSchedule.setStatus(Constant.MI_STATUS_CANCELLED); MiSchedule miSchedule2 = iMiDBService.getById(miSchedule.getId()); if(miSchedule2 != null) { iMiDBService.saveOrUpdate(miSchedule); } } } }
UTF-8
Java
1,828
java
ScheduleEventListner.java
Java
[]
null
[]
package com.gcn.heco.schedule.listener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.gcn.heco.app.model.NocMiSchedule; import com.gcn.heco.constant.Constant; import com.gcn.heco.database.model.MiSchedule; import com.gcn.heco.database.service.IMiDBService; import com.gcn.heco.schedule.container.ScheduleContainer; @Component public class ScheduleEventListner implements IScheduleEventListener { static Logger logger = LoggerFactory.getLogger(ScheduleEventListner.class); @Autowired private ScheduleContainer scheduleContainer; @Autowired private IMiDBService iMiDBService; @Override public void afterPost(MiSchedule miSchedule, NocMiSchedule nocMiSchedule) { if(nocMiSchedule != null){ Integer miId = nocMiSchedule.getManualInstrScheduleId(); logger.info("heco: Response from NOC for post request for schedule having id "+miSchedule.getId()); if(miId != null){ miSchedule.setScheduleId(miId); scheduleContainer.addActiveSchedule(miSchedule); logger.info("heco: Schedule having id "+miSchedule.getId()+" has been added to active schedule list"); } } else { logger.warn("heco: Troble getting response from NOC for post request for schedule having id "+miSchedule.getId()); } } @Override public void afterCancel(MiSchedule miSchedule, NocMiSchedule nocMiSchedule) { if(nocMiSchedule != null && miSchedule != null){ logger.info("heco: Response from NOC for cancel request for schedule having id "+miSchedule.getId()); miSchedule.setStatus(Constant.MI_STATUS_CANCELLED); MiSchedule miSchedule2 = iMiDBService.getById(miSchedule.getId()); if(miSchedule2 != null) { iMiDBService.saveOrUpdate(miSchedule); } } } }
1,828
0.772429
0.770241
53
33.490566
32.233009
117
false
false
0
0
0
0
0
0
1.924528
false
false
9
b5606d3d5b751ce84e6fc50ce0322a87675aeaac
16,209,206,644,123
603b7f6274d96f3556542268c4dd7e3458ff6384
/app/src/main/java/e_commerce/e_commerce/LocationFromMap.java
6b863d7fc1ac971791e693d50e3ce168b73d929c
[]
no_license
Aravind-Suresh/mangoSeed
https://github.com/Aravind-Suresh/mangoSeed
62db5417a161cb7179673d51c04bdd1050ccbd0e
34c5ed2557d3a09b5166b195a5ce890b1d616409
refs/heads/master
2021-01-23T20:45:46.292000
2015-05-10T23:05:41
2015-05-10T23:05:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package e_commerce.e_commerce; /** * Created by Suganprabu on 17-04-2015. */ import android.app.ProgressDialog; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.FragmentActivity; import android.util.Log; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import java.util.Calendar; public class LocationFromMap extends FragmentActivity implements OnMapReadyCallback, LocationListener { MapFragment mapfragment; public static double[] location = new double[2]; //location[0] is lat and location[1] is long public static LocationManager locationManager; private ProgressDialog p1; private boolean locationChanged=false; private Handler locUpdateHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_location); p1=new ProgressDialog(LocationFromMap.this); if(location==null) { location[0] = 1000.0; location[1] = 1000.0; } locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { p1.setCancelable(true); p1.setTitle("Getting location..."); p1.show(); Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if(location != null && location.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) { LocationFromMap.location[0] = location.getLatitude(); LocationFromMap.location[1] = location.getLongitude(); Log.i("Lat", String.valueOf(LocationFromMap.location[0])); Log.i("Long", String.valueOf(LocationFromMap.location[1])); Log.i("Location Accuracy", String.valueOf(location.getAccuracy())); if (p1.isShowing()) { p1.hide(); p1.dismiss(); } locationChanged=true; Message msg = new Message(); msg.arg1=1; locUpdateHandler.sendMessage(msg); finish(); } else { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); } /*locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,new LocationListener() { @Override public void onLocationChanged(Location location) { LocationFromMap.location[0] = location.getLatitude(); LocationFromMap.location[1] = location.getLongitude(); Log.i("Lat", String.valueOf(LocationFromMap.location[0])); Log.i("Long", String.valueOf(LocationFromMap.location[1])); Log.i("Location Accuracy", String.valueOf(location.getAccuracy())); // locationManager.removeUpdates(myLocationListener); if (p1.isShowing()) { p1.hide(); p1.dismiss(); } locationChanged=true; Message msg = new Message(); msg.arg1=1; locUpdateHandler.sendMessage(msg); finish(); *//*if(locationChanged==true){ if(gmap!=null) gmap.addMarker(new MarkerOptions() .position(new LatLng(LocationFromMap.location[0],LocationFromMap.location[1])) .title("Marker")); }*//* } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } });*/ } if(!LoginActivity.prefs.getString("Latitude","").equals("")&&!LoginActivity.prefs.getString("Longitude","").equals("")) { location[0] = Double.parseDouble(LoginActivity.prefs.getString("Latitude","")); location[1] = Double.parseDouble(LoginActivity.prefs.getString("Longitude","")); Log.i("Latitude", String.valueOf(location[0])); Log.i("Longitude", String.valueOf(location[1])); } if(!p1.isShowing()) { mapfragment = (MapFragment) getFragmentManager().findFragmentById(R.id.googleMap); mapfragment.getMapAsync(this); } } @Override public void onMapReady(final GoogleMap map){ Log.i("Location[0]",String.valueOf(LocationFromMap.location[0])); Log.i("Location[1]", String.valueOf(LocationFromMap.location[1])); if((LocationFromMap.location[0]==1000.0&&LocationFromMap.location[1]==1000.0) || (LocationFromMap.location[0]==0.0&&LocationFromMap.location[1]==0.0)){ map.addMarker(new MarkerOptions() .position(new LatLng(12.9915, 80.2336)) .title("Marker")); Log.i("Latitude","12.9915"); Log.i("Longitude","80.2336"); } else{ map.addMarker(new MarkerOptions() .position(new LatLng(LocationFromMap.location[0], LocationFromMap.location[1])) .title("Marker")); } locUpdateHandler = new Handler() { public void handleMessage(Message msg) { if (msg.arg1 == 1) { map.addMarker(new MarkerOptions() .position(new LatLng(LocationFromMap.location[0],LocationFromMap.location[1])) .title("Marker")); CameraUpdateFactory.newLatLng(new LatLng(LocationFromMap.location[0],LocationFromMap.location[1])); } } }; map.setIndoorEnabled(false); map.setBuildingsEnabled(true); map.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { if (MainActivity.internetConnection.isConnectingToInternet() == true) { map.clear(); map.addMarker(new MarkerOptions() .position(latLng) .title("Marker")); LocationFromMap.location[0] = latLng.latitude; LocationFromMap.location[1] = latLng.longitude; LoginActivity.prefs.edit().putString("Latitude",String.valueOf(location[0])).apply(); LoginActivity.prefs.edit().putString("Longitude",String.valueOf(location[1])).apply(); LoginActivity.prefs.edit().putString("Latitude",String.valueOf(location[0])).commit(); LoginActivity.prefs.edit().putString("Longitude",String.valueOf(location[1])).commit(); } } }); map.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() { @Override public void onMapLongClick(LatLng latLng) { if (MainActivity.internetConnection.isConnectingToInternet() == true) { map.clear(); map.addMarker(new MarkerOptions() .position(latLng) .title("Marker")); LocationFromMap.location[0] = latLng.latitude; LocationFromMap.location[1] = latLng.longitude; LoginActivity.prefs.edit().putString("Latitude",String.valueOf(location[0])).apply(); LoginActivity.prefs.edit().putString("Longitude",String.valueOf(location[1])).apply(); LoginActivity.prefs.edit().putString("Latitude",String.valueOf(location[0])).commit(); LoginActivity.prefs.edit().putString("Longitude",String.valueOf(location[1])).commit(); Message msg = new Message(); msg.arg1=1; msg.arg2=1; Master.locationHandler.sendMessage(msg); if(Master.locationDialog!=null && Master.locationDialog.isShowing()) { Master.locationDialog.hide(); Master.locationDialog.dismiss(); } finish(); } } }); map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() { @Override public void onMarkerDragStart(Marker marker) { } @Override public void onMarkerDrag(Marker marker) { } @Override public void onMarkerDragEnd(Marker marker) { if (MainActivity.internetConnection.isConnectingToInternet() == true) { map.clear(); map.addMarker(new MarkerOptions() .position(marker.getPosition()) .title("Marker")); LocationFromMap.location[0] = marker.getPosition().latitude; LocationFromMap.location[1] = marker.getPosition().longitude; LoginActivity.prefs.edit().putString("Latitude",String.valueOf(location[0])).apply(); LoginActivity.prefs.edit().putString("Longitude",String.valueOf(location[1])).apply(); LoginActivity.prefs.edit().putString("Latitude",String.valueOf(location[0])).commit(); LoginActivity.prefs.edit().putString("Longitude",String.valueOf(location[1])).commit(); } } }); } @Override public void onBackPressed(){ super.onBackPressed(); Message msg = new Message(); msg.arg1=1; msg.arg2=1; Master.locationHandler.sendMessage(msg); if(Master.locationDialog!=null && Master.locationDialog.isShowing()) { Master.locationDialog.hide(); Master.locationDialog.dismiss(); } } public void onLocationChanged(Location location) { if(location!=null){ locationManager.removeUpdates(this); LocationFromMap.location[0] = location.getLatitude(); LocationFromMap.location[1] = location.getLongitude(); Log.i("Lat", String.valueOf(LocationFromMap.location[0])); Log.i("Long", String.valueOf(LocationFromMap.location[1])); Log.i("Location Accuracy", String.valueOf(location.getAccuracy())); // locationManager.removeUpdates(myLocationListener); if (p1.isShowing()) { p1.hide(); p1.dismiss(); } locationChanged=true; Message msg = new Message(); msg.arg1=1; locUpdateHandler.sendMessage(msg); finish(); } } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } /* @Override public void onLocationChanged(android.location.Location loc) { Location.location[0] = loc.getLatitude(); Location.location[1] = loc.getLongitude(); Log.i("Lat",String.valueOf(Location.location[0])); Log.i("Long",String.valueOf(Location.location[1])); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { }*/ /*@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_location, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); }*/ }
UTF-8
Java
13,221
java
LocationFromMap.java
Java
[ { "context": "package e_commerce.e_commerce;\n\n/**\n * Created by Suganprabu on 17-04-2015.\n */\n\nimport android.app.ProgressDi", "end": 60, "score": 0.9814824461936951, "start": 50, "tag": "NAME", "value": "Suganprabu" } ]
null
[]
package e_commerce.e_commerce; /** * Created by Suganprabu on 17-04-2015. */ import android.app.ProgressDialog; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.FragmentActivity; import android.util.Log; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import java.util.Calendar; public class LocationFromMap extends FragmentActivity implements OnMapReadyCallback, LocationListener { MapFragment mapfragment; public static double[] location = new double[2]; //location[0] is lat and location[1] is long public static LocationManager locationManager; private ProgressDialog p1; private boolean locationChanged=false; private Handler locUpdateHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_location); p1=new ProgressDialog(LocationFromMap.this); if(location==null) { location[0] = 1000.0; location[1] = 1000.0; } locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { p1.setCancelable(true); p1.setTitle("Getting location..."); p1.show(); Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if(location != null && location.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) { LocationFromMap.location[0] = location.getLatitude(); LocationFromMap.location[1] = location.getLongitude(); Log.i("Lat", String.valueOf(LocationFromMap.location[0])); Log.i("Long", String.valueOf(LocationFromMap.location[1])); Log.i("Location Accuracy", String.valueOf(location.getAccuracy())); if (p1.isShowing()) { p1.hide(); p1.dismiss(); } locationChanged=true; Message msg = new Message(); msg.arg1=1; locUpdateHandler.sendMessage(msg); finish(); } else { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); } /*locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,new LocationListener() { @Override public void onLocationChanged(Location location) { LocationFromMap.location[0] = location.getLatitude(); LocationFromMap.location[1] = location.getLongitude(); Log.i("Lat", String.valueOf(LocationFromMap.location[0])); Log.i("Long", String.valueOf(LocationFromMap.location[1])); Log.i("Location Accuracy", String.valueOf(location.getAccuracy())); // locationManager.removeUpdates(myLocationListener); if (p1.isShowing()) { p1.hide(); p1.dismiss(); } locationChanged=true; Message msg = new Message(); msg.arg1=1; locUpdateHandler.sendMessage(msg); finish(); *//*if(locationChanged==true){ if(gmap!=null) gmap.addMarker(new MarkerOptions() .position(new LatLng(LocationFromMap.location[0],LocationFromMap.location[1])) .title("Marker")); }*//* } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } });*/ } if(!LoginActivity.prefs.getString("Latitude","").equals("")&&!LoginActivity.prefs.getString("Longitude","").equals("")) { location[0] = Double.parseDouble(LoginActivity.prefs.getString("Latitude","")); location[1] = Double.parseDouble(LoginActivity.prefs.getString("Longitude","")); Log.i("Latitude", String.valueOf(location[0])); Log.i("Longitude", String.valueOf(location[1])); } if(!p1.isShowing()) { mapfragment = (MapFragment) getFragmentManager().findFragmentById(R.id.googleMap); mapfragment.getMapAsync(this); } } @Override public void onMapReady(final GoogleMap map){ Log.i("Location[0]",String.valueOf(LocationFromMap.location[0])); Log.i("Location[1]", String.valueOf(LocationFromMap.location[1])); if((LocationFromMap.location[0]==1000.0&&LocationFromMap.location[1]==1000.0) || (LocationFromMap.location[0]==0.0&&LocationFromMap.location[1]==0.0)){ map.addMarker(new MarkerOptions() .position(new LatLng(12.9915, 80.2336)) .title("Marker")); Log.i("Latitude","12.9915"); Log.i("Longitude","80.2336"); } else{ map.addMarker(new MarkerOptions() .position(new LatLng(LocationFromMap.location[0], LocationFromMap.location[1])) .title("Marker")); } locUpdateHandler = new Handler() { public void handleMessage(Message msg) { if (msg.arg1 == 1) { map.addMarker(new MarkerOptions() .position(new LatLng(LocationFromMap.location[0],LocationFromMap.location[1])) .title("Marker")); CameraUpdateFactory.newLatLng(new LatLng(LocationFromMap.location[0],LocationFromMap.location[1])); } } }; map.setIndoorEnabled(false); map.setBuildingsEnabled(true); map.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { if (MainActivity.internetConnection.isConnectingToInternet() == true) { map.clear(); map.addMarker(new MarkerOptions() .position(latLng) .title("Marker")); LocationFromMap.location[0] = latLng.latitude; LocationFromMap.location[1] = latLng.longitude; LoginActivity.prefs.edit().putString("Latitude",String.valueOf(location[0])).apply(); LoginActivity.prefs.edit().putString("Longitude",String.valueOf(location[1])).apply(); LoginActivity.prefs.edit().putString("Latitude",String.valueOf(location[0])).commit(); LoginActivity.prefs.edit().putString("Longitude",String.valueOf(location[1])).commit(); } } }); map.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() { @Override public void onMapLongClick(LatLng latLng) { if (MainActivity.internetConnection.isConnectingToInternet() == true) { map.clear(); map.addMarker(new MarkerOptions() .position(latLng) .title("Marker")); LocationFromMap.location[0] = latLng.latitude; LocationFromMap.location[1] = latLng.longitude; LoginActivity.prefs.edit().putString("Latitude",String.valueOf(location[0])).apply(); LoginActivity.prefs.edit().putString("Longitude",String.valueOf(location[1])).apply(); LoginActivity.prefs.edit().putString("Latitude",String.valueOf(location[0])).commit(); LoginActivity.prefs.edit().putString("Longitude",String.valueOf(location[1])).commit(); Message msg = new Message(); msg.arg1=1; msg.arg2=1; Master.locationHandler.sendMessage(msg); if(Master.locationDialog!=null && Master.locationDialog.isShowing()) { Master.locationDialog.hide(); Master.locationDialog.dismiss(); } finish(); } } }); map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() { @Override public void onMarkerDragStart(Marker marker) { } @Override public void onMarkerDrag(Marker marker) { } @Override public void onMarkerDragEnd(Marker marker) { if (MainActivity.internetConnection.isConnectingToInternet() == true) { map.clear(); map.addMarker(new MarkerOptions() .position(marker.getPosition()) .title("Marker")); LocationFromMap.location[0] = marker.getPosition().latitude; LocationFromMap.location[1] = marker.getPosition().longitude; LoginActivity.prefs.edit().putString("Latitude",String.valueOf(location[0])).apply(); LoginActivity.prefs.edit().putString("Longitude",String.valueOf(location[1])).apply(); LoginActivity.prefs.edit().putString("Latitude",String.valueOf(location[0])).commit(); LoginActivity.prefs.edit().putString("Longitude",String.valueOf(location[1])).commit(); } } }); } @Override public void onBackPressed(){ super.onBackPressed(); Message msg = new Message(); msg.arg1=1; msg.arg2=1; Master.locationHandler.sendMessage(msg); if(Master.locationDialog!=null && Master.locationDialog.isShowing()) { Master.locationDialog.hide(); Master.locationDialog.dismiss(); } } public void onLocationChanged(Location location) { if(location!=null){ locationManager.removeUpdates(this); LocationFromMap.location[0] = location.getLatitude(); LocationFromMap.location[1] = location.getLongitude(); Log.i("Lat", String.valueOf(LocationFromMap.location[0])); Log.i("Long", String.valueOf(LocationFromMap.location[1])); Log.i("Location Accuracy", String.valueOf(location.getAccuracy())); // locationManager.removeUpdates(myLocationListener); if (p1.isShowing()) { p1.hide(); p1.dismiss(); } locationChanged=true; Message msg = new Message(); msg.arg1=1; locUpdateHandler.sendMessage(msg); finish(); } } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } /* @Override public void onLocationChanged(android.location.Location loc) { Location.location[0] = loc.getLatitude(); Location.location[1] = loc.getLongitude(); Log.i("Lat",String.valueOf(Location.location[0])); Log.i("Long",String.valueOf(Location.location[1])); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { }*/ /*@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_location, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); }*/ }
13,221
0.574465
0.562514
365
35.221916
32.452412
159
false
false
0
0
0
0
0
0
0.547945
false
false
9
03f784fb5be588752d515fda9721371b1df37520
7,146,825,638,606
e68e09d4542e9f3d73fee963f15160917b70bdce
/src/main/java/com/example/uhf_bt/NumberTool.java
2fbdde3a1b92686879c3a3b26a54692efe07dbf1
[]
no_license
trytomo/electron_reader
https://github.com/trytomo/electron_reader
c81fb9cdfa29ba3641d82529266aca4ea71bb9eb
2d73b8524d2c06379d69353066f3e724465101d8
refs/heads/main
2023-08-17T17:34:18.303000
2021-10-05T14:43:53
2021-10-05T14:43:53
413,851,163
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.uhf_bt; import java.math.BigDecimal; public class NumberTool { public static double getPointDouble(int point, double val) { BigDecimal bd = new BigDecimal(val); return bd.setScale(point, BigDecimal.ROUND_HALF_UP).doubleValue(); } public static double getPointDouble(int point, int val) { BigDecimal bd = new BigDecimal(val); return bd.setScale(point, BigDecimal.ROUND_HALF_UP).doubleValue(); } public static double getPointDouble(int point, long val) { BigDecimal bd = new BigDecimal(val); return bd.setScale(point, BigDecimal.ROUND_HALF_UP).doubleValue(); } public static double getPointDouble(int point, String val) { BigDecimal bd = new BigDecimal(val); return bd.setScale(point, BigDecimal.ROUND_HALF_UP).doubleValue(); } }
UTF-8
Java
778
java
NumberTool.java
Java
[]
null
[]
package com.example.uhf_bt; import java.math.BigDecimal; public class NumberTool { public static double getPointDouble(int point, double val) { BigDecimal bd = new BigDecimal(val); return bd.setScale(point, BigDecimal.ROUND_HALF_UP).doubleValue(); } public static double getPointDouble(int point, int val) { BigDecimal bd = new BigDecimal(val); return bd.setScale(point, BigDecimal.ROUND_HALF_UP).doubleValue(); } public static double getPointDouble(int point, long val) { BigDecimal bd = new BigDecimal(val); return bd.setScale(point, BigDecimal.ROUND_HALF_UP).doubleValue(); } public static double getPointDouble(int point, String val) { BigDecimal bd = new BigDecimal(val); return bd.setScale(point, BigDecimal.ROUND_HALF_UP).doubleValue(); } }
778
0.748072
0.748072
26
28.923077
27.007011
68
false
false
0
0
0
0
0
0
1.615385
false
false
9
f4ae9e13b70052150a89ead62a55252515141932
13,065,290,567,174
c8eb512a4b7d363179c2238fcfd03155ed93033b
/redback/branches/redback-1.3-Mx/redback-authentication/redback-authentication-api/src/main/java/org/codehaus/plexus/redback/authentication/TokenBasedAuthenticationDataSource.java
0956e5d115bd530bedc1330a457aa94439f6558e
[ "Apache-2.0" ]
permissive
codehaus/redback
https://github.com/codehaus/redback
8600e04ee00835bc382b2e67fbf5fc99a1b094a2
50337e936e0bb7dae502dd302dd40a1afa7e56cf
refs/heads/master
2023-07-20T01:31:45.917000
2014-03-30T00:37:48
2014-03-30T00:37:48
36,526,388
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.codehaus.plexus.redback.authentication; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; /* * Copyright 2001-2006 The Codehaus. * * 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. */ /** * TokenBasedAuthenticationDataSource * * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a> * @version $Id$ * */ @Service("authenticationDataSource#token") @Scope("prototype") public class TokenBasedAuthenticationDataSource implements AuthenticationDataSource { private String token; private String principal; private boolean enforcePasswordChange = true; public TokenBasedAuthenticationDataSource( String principal ) { this.principal = principal; } public TokenBasedAuthenticationDataSource() { } public String getPrincipal() { return principal; } public String getToken() { return token; } public void setPrincipal( String principal ) { this.principal = principal; } public void setToken( String token ) { this.token = token; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append( "TokenBasedAuthenticationDataSource[" ); sb.append( "principal=" ).append( principal ); sb.append( ",token=" ).append( token ); sb.append( ']' ); return sb.toString(); } public void setEnforcePasswordChange( boolean enforcePasswordChange ) { this.enforcePasswordChange = enforcePasswordChange; } public boolean isEnforcePasswordChange() { return enforcePasswordChange; } }
UTF-8
Java
2,209
java
TokenBasedAuthenticationDataSource.java
Java
[ { "context": "ticationDataSource \n *\n * @author <a href=\"mailto:joakim@erdfelt.com\">Joakim Erdfelt</a>\n * @version $Id$\n * \n */\n@Ser", "end": 849, "score": 0.9999284744262695, "start": 831, "tag": "EMAIL", "value": "joakim@erdfelt.com" }, { "context": " *\n * @author <a href=\"mailto:joakim@erdfelt.com\">Joakim Erdfelt</a>\n * @version $Id$\n * \n */\n@Service(\"authentica", "end": 865, "score": 0.999894917011261, "start": 851, "tag": "NAME", "value": "Joakim Erdfelt" } ]
null
[]
package org.codehaus.plexus.redback.authentication; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; /* * Copyright 2001-2006 The Codehaus. * * 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. */ /** * TokenBasedAuthenticationDataSource * * @author <a href="mailto:<EMAIL>"><NAME></a> * @version $Id$ * */ @Service("authenticationDataSource#token") @Scope("prototype") public class TokenBasedAuthenticationDataSource implements AuthenticationDataSource { private String token; private String principal; private boolean enforcePasswordChange = true; public TokenBasedAuthenticationDataSource( String principal ) { this.principal = principal; } public TokenBasedAuthenticationDataSource() { } public String getPrincipal() { return principal; } public String getToken() { return token; } public void setPrincipal( String principal ) { this.principal = principal; } public void setToken( String token ) { this.token = token; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append( "TokenBasedAuthenticationDataSource[" ); sb.append( "principal=" ).append( principal ); sb.append( ",token=" ).append( token ); sb.append( ']' ); return sb.toString(); } public void setEnforcePasswordChange( boolean enforcePasswordChange ) { this.enforcePasswordChange = enforcePasswordChange; } public boolean isEnforcePasswordChange() { return enforcePasswordChange; } }
2,190
0.681304
0.675871
88
24.102272
23.962111
75
false
false
0
0
0
0
0
0
0.284091
false
false
9
cedaa0ebdb0b35577a359566f343c866c725ffbf
24,386,824,345,050
1694190e0f77d4a3bf924a960c95ccb7e169ee1e
/fp_home/fp_https/.svn/pristine/ee/ee4cf893b4f246b942653078cbcf85c76c999dc4.svn-base
fe8f714a875b56929daaef2fbb077761be16aa38
[]
no_license
hilda2018/fpWork
https://github.com/hilda2018/fpWork
f7e8887e288c467ff486c3ef6b8d1ea5b88f9954
07f7ab55951f30e00b55ce8998ea88303caffc38
refs/heads/master
2020-03-17T00:49:39.515000
2018-05-12T10:06:03
2018-05-12T10:06:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fresh.service.impl; import java.util.List; import com.fresh.dao.CountDao; import com.fresh.dao.SellerDao; import com.fresh.dao.ServiceDao; import com.fresh.model.ResultCount; import com.fresh.model.Users; import com.fresh.service.ServiceService; import com.google.inject.Inject; public class ServiceServiceImpl implements ServiceService { @Inject private CountDao countDao; @Inject private ServiceDao serviceDao; /** * 获取服务商信息 */ public List<Users> getServiceList(Integer pagestart,Integer pagesize,String serviceTypeStr,String companyNameStr){ List<Users> list = serviceDao.getServiceList(pagestart, pagesize, serviceTypeStr,companyNameStr); return list; } /** * 获取服务商总数 */ public List<ResultCount> getServiceCount(String serviceTypeStr,String companyNameStr){ List<ResultCount> list=countDao.getServiceCount(serviceTypeStr,companyNameStr); return list; } /** * 获取首页服务商信息 */ public List<Users> getServiceListIndex(){ return serviceDao.getServiceListIndex(); } }
UTF-8
Java
1,065
ee4cf893b4f246b942653078cbcf85c76c999dc4.svn-base
Java
[]
null
[]
package com.fresh.service.impl; import java.util.List; import com.fresh.dao.CountDao; import com.fresh.dao.SellerDao; import com.fresh.dao.ServiceDao; import com.fresh.model.ResultCount; import com.fresh.model.Users; import com.fresh.service.ServiceService; import com.google.inject.Inject; public class ServiceServiceImpl implements ServiceService { @Inject private CountDao countDao; @Inject private ServiceDao serviceDao; /** * 获取服务商信息 */ public List<Users> getServiceList(Integer pagestart,Integer pagesize,String serviceTypeStr,String companyNameStr){ List<Users> list = serviceDao.getServiceList(pagestart, pagesize, serviceTypeStr,companyNameStr); return list; } /** * 获取服务商总数 */ public List<ResultCount> getServiceCount(String serviceTypeStr,String companyNameStr){ List<ResultCount> list=countDao.getServiceCount(serviceTypeStr,companyNameStr); return list; } /** * 获取首页服务商信息 */ public List<Users> getServiceListIndex(){ return serviceDao.getServiceListIndex(); } }
1,065
0.778214
0.778214
41
23.853659
28.193201
115
false
false
0
0
0
0
0
0
1.365854
false
false
9
ec6556258bfa22e6ec35dd14e29c290a29cf0517
17,437,567,268,282
07746277668b6c17b1d6a14fc26d838d0ddb0c5d
/src/LRUCache_146/LRUCache.java
a2c77ad57632f6b19a0f7d208c37383ce13b0206
[]
no_license
Drafthj/leetcode
https://github.com/Drafthj/leetcode
69628246d6d27c8693e9c4443c5b8d8ff7ce8f9d
bd592260721959ecd619eb83fe2fa2c6df6770b1
refs/heads/master
2020-12-24T12:33:48.812000
2016-12-21T07:30:09
2016-12-21T07:30:09
72,980,925
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package LRUCache_146; import java.util.HashMap; /** * Created by drafthj on 2016/12/4 1:56. */ public class LRUCache { class DNode{ public DNode(int key, int value) { this.key = key; this.value = value; } int key; int value; DNode next; DNode prev; } private DNode head; private DNode tail; private void list(){ DNode f = head; while (f!=null){ System.out.println(f.value); f = f.next; } } private void addFirst(DNode d){ if(head == null){ head = d; tail = d; }else { head.prev = d; d.next = head; head = d; } } private void remove(DNode node){ DNode prev = node.prev; DNode next = node.next; if(prev == null){ head = next; }else { prev.next = next; node.prev = null; } if(next == null){ tail = prev; }else { next.prev = prev; node.next = null; } } private HashMap<Integer,DNode> cache; private int count; private int capacity; public LRUCache(int capacity) { this.capacity = capacity; cache = new HashMap<>(capacity); } public int get(int key) { DNode node = cache.get(key); if(node!=null){ remove(node); addFirst(node); return node.value; } return -1; } public void set(int key, int value) { DNode old = cache.get(key); DNode node = new DNode(key,value); if(old!=null){ cache.put(key,node); remove(old); addFirst(node); }else { if(count<capacity){ cache.put(key,node); }else { cache.remove(tail.key); remove(tail); cache.put(key,node); } addFirst(node); count++; } } }
UTF-8
Java
2,079
java
LRUCache.java
Java
[ { "context": "146;\n\nimport java.util.HashMap;\n\n/**\n * Created by drafthj on 2016/12/4 1:56.\n */\npublic class LRUCache {\n ", "end": 75, "score": 0.9997029900550842, "start": 68, "tag": "USERNAME", "value": "drafthj" } ]
null
[]
package LRUCache_146; import java.util.HashMap; /** * Created by drafthj on 2016/12/4 1:56. */ public class LRUCache { class DNode{ public DNode(int key, int value) { this.key = key; this.value = value; } int key; int value; DNode next; DNode prev; } private DNode head; private DNode tail; private void list(){ DNode f = head; while (f!=null){ System.out.println(f.value); f = f.next; } } private void addFirst(DNode d){ if(head == null){ head = d; tail = d; }else { head.prev = d; d.next = head; head = d; } } private void remove(DNode node){ DNode prev = node.prev; DNode next = node.next; if(prev == null){ head = next; }else { prev.next = next; node.prev = null; } if(next == null){ tail = prev; }else { next.prev = prev; node.next = null; } } private HashMap<Integer,DNode> cache; private int count; private int capacity; public LRUCache(int capacity) { this.capacity = capacity; cache = new HashMap<>(capacity); } public int get(int key) { DNode node = cache.get(key); if(node!=null){ remove(node); addFirst(node); return node.value; } return -1; } public void set(int key, int value) { DNode old = cache.get(key); DNode node = new DNode(key,value); if(old!=null){ cache.put(key,node); remove(old); addFirst(node); }else { if(count<capacity){ cache.put(key,node); }else { cache.remove(tail.key); remove(tail); cache.put(key,node); } addFirst(node); count++; } } }
2,079
0.449254
0.44252
93
21.354839
11.749761
42
false
false
0
0
0
0
0
0
0.580645
false
false
9
8217e95e40371ed663d4540714f43cfb96c37368
19,533,511,264,068
d04033fd37275c75fa8d268c8acd415ea8226bc3
/teste-marte-elo7/exploration/Movement.java
912a0afd417cfcdc9dec4a84ad1c009f6aeec12c
[]
no_license
vkadaiski/teste-marte-elo7
https://github.com/vkadaiski/teste-marte-elo7
12dd9dcade5c614cd17d10e91885fd820bd74583
07173d5cf2815f6c1853061487abeb9c55838df8
refs/heads/master
2023-03-12T05:20:31.034000
2021-03-01T18:58:49
2021-03-01T18:58:49
343,524,755
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package exploration; public enum Movement { MOVE_FORWARD('M'), LEFT('L'), RIGHT('R'); private final char shortCode; Movement(char code) { this.shortCode = code; } public char getMovementCode() { return this.shortCode; } public static Movement getMovement(char shortCode) { for (Movement m : Movement.values()) { if (m.shortCode == shortCode) return m; } throw new IllegalArgumentException(); } /* Realizando a movimentação da sonda */ public void doMovement(Probe probe) { Direction dir = probe.getDirection(); switch (this) { case MOVE_FORWARD: probe.setDirection(dir.moveFoward()); Position current_position = probe.getPosition(); Position new_position = current_position.changePosition(probe, dir); probe.setPosition(new_position); break; case LEFT: probe.setDirection(dir.turnLeft()); break; case RIGHT: probe.setDirection(dir.turnRight()); break; default: throw new IllegalArgumentException(); } } }
UTF-8
Java
1,086
java
Movement.java
Java
[]
null
[]
package exploration; public enum Movement { MOVE_FORWARD('M'), LEFT('L'), RIGHT('R'); private final char shortCode; Movement(char code) { this.shortCode = code; } public char getMovementCode() { return this.shortCode; } public static Movement getMovement(char shortCode) { for (Movement m : Movement.values()) { if (m.shortCode == shortCode) return m; } throw new IllegalArgumentException(); } /* Realizando a movimentação da sonda */ public void doMovement(Probe probe) { Direction dir = probe.getDirection(); switch (this) { case MOVE_FORWARD: probe.setDirection(dir.moveFoward()); Position current_position = probe.getPosition(); Position new_position = current_position.changePosition(probe, dir); probe.setPosition(new_position); break; case LEFT: probe.setDirection(dir.turnLeft()); break; case RIGHT: probe.setDirection(dir.turnRight()); break; default: throw new IllegalArgumentException(); } } }
1,086
0.631919
0.631919
46
22.586956
19.074883
76
false
false
0
0
0
0
0
0
0.456522
false
false
9
cf7632b510a2fa9b72efec81ce6b538f029f241a
9,818,295,309,115
a134aa0d111507c1660b8ab59b832bafd9f6dc5a
/src/main/java/bryzhatov/projects/shop/Application.java
94b223de21336d6e90643f51672f4d5a2fb81e35
[]
no_license
bryzhatov/shop
https://github.com/bryzhatov/shop
2751663c429a565a0a4eaec464ad0ed85d31bd14
275b3bb4f8da28277cb735570dd848259678e910
refs/heads/master
2020-05-04T09:33:32.459000
2019-04-02T12:14:24
2019-04-02T12:14:24
179,070,556
0
0
null
false
2019-04-02T15:43:50
2019-04-02T12:13:56
2019-04-02T12:14:35
2019-04-02T15:41:07
5
0
0
1
Java
false
null
package bryzhatov.projects.shop; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author Dmitry Bryzhatov * @since 2019-04-01 */ @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class); } }
UTF-8
Java
365
java
Application.java
Java
[ { "context": "toconfigure.SpringBootApplication;\n\n/**\n * @author Dmitry Bryzhatov\n * @since 2019-04-01\n */\n@SpringBootApplication\np", "end": 186, "score": 0.9998794198036194, "start": 170, "tag": "NAME", "value": "Dmitry Bryzhatov" } ]
null
[]
package bryzhatov.projects.shop; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author <NAME> * @since 2019-04-01 */ @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class); } }
355
0.761644
0.739726
15
23.333334
21.057592
68
false
false
0
0
0
0
0
0
0.266667
false
false
9
0c2325890f1f2965d8cfe6e787ca357745890186
32,332,513,864,634
e6b7422693815f7302ccc55e0dd7fcacfa868145
/springcloudalibabastudy/cloud-api/src/main/java/com/lsg/cloudapi/user/fallback/AccountClientFallbackFactory.java
73b8174549ecad5888c985b0e9ce3b0e12a08c13
[]
no_license
leishuiguang/study-netty
https://github.com/leishuiguang/study-netty
504f9034780c50a4fcc70ec79945a9221cd662c7
8ab4a30ef0638cb006b62ad078aede8fe6c8245d
refs/heads/main
2023-04-16T01:34:29.066000
2021-04-28T11:30:22
2021-04-28T11:30:22
353,332,588
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lsg.cloudapi.user.fallback; import com.lsg.cloudapi.user.AccountClient; import com.lsg.cloudcommon.result.Result; import com.lsg.cloudcommon.result.ResultCode; import feign.hystrix.FallbackFactory; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; @Component @Slf4j public class AccountClientFallbackFactory implements FallbackFactory<AccountClient> { @Override public AccountClient create(Throwable throwable) { log.error("服务调用异常,异常信息:{}", throwable.getMessage()); return param -> Result.failure(ResultCode.SERVICE_ERROR); } }
UTF-8
Java
628
java
AccountClientFallbackFactory.java
Java
[]
null
[]
package com.lsg.cloudapi.user.fallback; import com.lsg.cloudapi.user.AccountClient; import com.lsg.cloudcommon.result.Result; import com.lsg.cloudcommon.result.ResultCode; import feign.hystrix.FallbackFactory; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; @Component @Slf4j public class AccountClientFallbackFactory implements FallbackFactory<AccountClient> { @Override public AccountClient create(Throwable throwable) { log.error("服务调用异常,异常信息:{}", throwable.getMessage()); return param -> Result.failure(ResultCode.SERVICE_ERROR); } }
628
0.783113
0.778146
19
30.789474
25.259869
85
false
false
0
0
0
0
0
0
0.526316
false
false
9
ad6c59cb59b96bc045ff4e55d87b876bef5e0862
13,151,189,871,485
f08191da262305786287bd1a4a41671a1c1960f7
/MiuiSystemUI/umi/systemui/miui/statusbar/analytics/$$Lambda$SystemUIStat$4yQkEBi0C_T1qgydx0AUvJ0g7c.java
858a303bf4c16bc788a680a61a4c4fb9d921d8e1
[]
no_license
lmjssjj/arsc_compare
https://github.com/lmjssjj/arsc_compare
f75acb947d890503defb9189e78e7019cb9b58e4
bf5ce3bb50f6b1595d373cd159f83b6b800dff37
refs/heads/master
2022-11-11T02:42:10.896000
2020-07-08T00:46:54
2020-07-08T00:46:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.android.systemui.miui.statusbar.analytics; import com.android.systemui.statusbar.NotificationData; import java.util.function.Function; /* renamed from: com.android.systemui.miui.statusbar.analytics.-$$Lambda$SystemUIStat$4y-QkEBi0C_T1qgydx0AUvJ0g7c reason: invalid class name */ /* compiled from: lambda */ public final /* synthetic */ class $$Lambda$SystemUIStat$4yQkEBi0C_T1qgydx0AUvJ0g7c implements Function { public static final /* synthetic */ $$Lambda$SystemUIStat$4yQkEBi0C_T1qgydx0AUvJ0g7c INSTANCE = new $$Lambda$SystemUIStat$4yQkEBi0C_T1qgydx0AUvJ0g7c(); private /* synthetic */ $$Lambda$SystemUIStat$4yQkEBi0C_T1qgydx0AUvJ0g7c() { } public final Object apply(Object obj) { return ((NotificationData.Entry) obj).notification; } }
UTF-8
Java
785
java
$$Lambda$SystemUIStat$4yQkEBi0C_T1qgydx0AUvJ0g7c.java
Java
[]
null
[]
package com.android.systemui.miui.statusbar.analytics; import com.android.systemui.statusbar.NotificationData; import java.util.function.Function; /* renamed from: com.android.systemui.miui.statusbar.analytics.-$$Lambda$SystemUIStat$4y-QkEBi0C_T1qgydx0AUvJ0g7c reason: invalid class name */ /* compiled from: lambda */ public final /* synthetic */ class $$Lambda$SystemUIStat$4yQkEBi0C_T1qgydx0AUvJ0g7c implements Function { public static final /* synthetic */ $$Lambda$SystemUIStat$4yQkEBi0C_T1qgydx0AUvJ0g7c INSTANCE = new $$Lambda$SystemUIStat$4yQkEBi0C_T1qgydx0AUvJ0g7c(); private /* synthetic */ $$Lambda$SystemUIStat$4yQkEBi0C_T1qgydx0AUvJ0g7c() { } public final Object apply(Object obj) { return ((NotificationData.Entry) obj).notification; } }
785
0.765605
0.727389
17
45.176472
48.969662
155
false
false
0
0
0
0
0
0
0.294118
false
false
9
3cb9f2aba14792d693c6b1b04dccfd5b205fb3e0
29,703,993,843,042
926bc9d0c33e94b57f97ddd0a7387ff3bf42c954
/src/domain/MiniBar.java
d75e6e4e44755bfc3626ed962467fbc3963eaa14
[]
no_license
marce-ldv/Hotel-V2
https://github.com/marce-ldv/Hotel-V2
fb8843b452734e99c11b8b1b306865e5924f2419
081462b4343e81aeccef31ac0c1ccab8066eb58e
refs/heads/master
2021-09-17T08:12:43.393000
2018-06-29T12:23:44
2018-06-29T12:23:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package domain; import java.util.ArrayList; import org.json.JSONException; import org.json.JSONObject; import exepciones.ComidaInexistenteException; import exepciones.NoHaySuficienteComidaException; public class MiniBar <T extends Servicio> { private ArrayList<Servicio> servicios; // constructores public MiniBar() { servicios = new ArrayList<Servicio>(); } public MiniBar(ArrayList<Servicio> serviciosRecib) { servicios = serviciosRecib; } //metodos public void agregarServicios (String nombre, int precio, int cantidad) { Servicio b = new Servicio (nombre, precio, cantidad); servicios.add(b); } /** * este metodo da la comida al pasajero y retorna el costo de lo que el mismo consumio * * * @return costoTotalComida * */ public float darServicioToPasajeroYretornaCosto (String nombreComida, int cantidadComida) throws NoHaySuficienteComidaException,ComidaInexistenteException { float costoTotalComida = 0; for(Servicio e: servicios) // se recorre el array por completo { if(nombreComida.equals(e.getNombre())) { if(e.getCantidad() >= cantidadComida) // si la cantidad de alimentos es mayor o igual a la que piede el pasajero { costoTotalComida = cantidadComida * e.getValor(); // el costo total sera la cantidad de productos que pidio por el precio del mismo e.setCantidad(e.getCantidad() - cantidadComida); // se modifica la cantidad de la comida que pidio } else { System.out.println("Solo hay " + e.getCantidad() + " " + e.getNombre()); // esto deberia ser una excepcion throw new NoHaySuficienteComidaException("Excepcion"); } } else { throw new ComidaInexistenteException("Excepcion"); // esto tambien deberia ser una excepcion } } return costoTotalComida; } public void listarElementos(ArrayList<Servicio> arr) { int i = 0; for(i = 0; arr.size() < i; i++) { System.out.print(" |"+arr.get(i)+"|"); } } public JSONObject getFormatoJSON() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("alimentos", servicios); return jsonObject; } @Override public String toString() { return "MiniBar [alimentos=" + servicios + "]"; } }
UTF-8
Java
2,290
java
MiniBar.java
Java
[]
null
[]
package domain; import java.util.ArrayList; import org.json.JSONException; import org.json.JSONObject; import exepciones.ComidaInexistenteException; import exepciones.NoHaySuficienteComidaException; public class MiniBar <T extends Servicio> { private ArrayList<Servicio> servicios; // constructores public MiniBar() { servicios = new ArrayList<Servicio>(); } public MiniBar(ArrayList<Servicio> serviciosRecib) { servicios = serviciosRecib; } //metodos public void agregarServicios (String nombre, int precio, int cantidad) { Servicio b = new Servicio (nombre, precio, cantidad); servicios.add(b); } /** * este metodo da la comida al pasajero y retorna el costo de lo que el mismo consumio * * * @return costoTotalComida * */ public float darServicioToPasajeroYretornaCosto (String nombreComida, int cantidadComida) throws NoHaySuficienteComidaException,ComidaInexistenteException { float costoTotalComida = 0; for(Servicio e: servicios) // se recorre el array por completo { if(nombreComida.equals(e.getNombre())) { if(e.getCantidad() >= cantidadComida) // si la cantidad de alimentos es mayor o igual a la que piede el pasajero { costoTotalComida = cantidadComida * e.getValor(); // el costo total sera la cantidad de productos que pidio por el precio del mismo e.setCantidad(e.getCantidad() - cantidadComida); // se modifica la cantidad de la comida que pidio } else { System.out.println("Solo hay " + e.getCantidad() + " " + e.getNombre()); // esto deberia ser una excepcion throw new NoHaySuficienteComidaException("Excepcion"); } } else { throw new ComidaInexistenteException("Excepcion"); // esto tambien deberia ser una excepcion } } return costoTotalComida; } public void listarElementos(ArrayList<Servicio> arr) { int i = 0; for(i = 0; arr.size() < i; i++) { System.out.print(" |"+arr.get(i)+"|"); } } public JSONObject getFormatoJSON() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("alimentos", servicios); return jsonObject; } @Override public String toString() { return "MiniBar [alimentos=" + servicios + "]"; } }
2,290
0.686463
0.685153
103
21.223301
31.825657
155
false
false
0
0
0
0
0
0
2.116505
false
false
9
8cac62e063ad9eba623e670212d2e2914fe12975
687,194,792,388
fe470beecb228be29389479480c90c13dfdf1e35
/Decimal64/src/decimal64/HexadecimalConverter.java
8cfabe8106f5895e9902445da7cab5c57fee7117
[]
no_license
jhayfelix/ArchorgCaseStudy
https://github.com/jhayfelix/ArchorgCaseStudy
bba25d8bcdee8ab14984ff27b60d6e48c70b651d
773ad658c60444fa9ba1f05b8c39a22fdc4ea79c
refs/heads/master
2021-01-10T09:04:46.432000
2016-03-19T12:14:13
2016-03-19T12:14:13
54,264,086
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 decimal64; /** * * @author John JP Andres */ public class HexadecimalConverter { String hexadecimal = "hey"; double decimal; HexadecimalConverter(){} public double HextoDecimal(){ hexadecimal = hexadecimal.toUpperCase(); try{ decimal = Integer.parseInt(hexadecimal, 16); } catch(NumberFormatException ne){ System.out.println("Invalid Input"); setBye(); } finally{ } //returns string decimal return decimal; } public double HextoDecimal(String hexadecimal){ this.hexadecimal = hexadecimal.toUpperCase(); try{ decimal = Integer.parseInt(this.hexadecimal, 16); } catch(NumberFormatException ne){ System.out.println("Invalid Input"); setBye(); } finally{ } //returns string decimal return decimal; } public void setBye(){ this.hexadecimal = "stop"; this.decimal = 0; } public void setToNull(){ this.hexadecimal = ""; this.decimal = 0; } public void setString(String s){ this.hexadecimal = s; } public String getHexadecimal() { return hexadecimal; } public void setHexadecimal(String hexadecimal) { this.hexadecimal = hexadecimal; } public double getDecimal() { return decimal; } public void setDecimal(double decimal) { this.decimal = decimal; } }
UTF-8
Java
1,850
java
HexadecimalConverter.java
Java
[ { "context": " editor.\n */\npackage decimal64;\n\n/**\n *\n * @author John JP Andres\n */\npublic class HexadecimalConverter {\n \n ", "end": 237, "score": 0.9687889218330383, "start": 223, "tag": "NAME", "value": "John JP Andres" } ]
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 decimal64; /** * * @author <NAME> */ public class HexadecimalConverter { String hexadecimal = "hey"; double decimal; HexadecimalConverter(){} public double HextoDecimal(){ hexadecimal = hexadecimal.toUpperCase(); try{ decimal = Integer.parseInt(hexadecimal, 16); } catch(NumberFormatException ne){ System.out.println("Invalid Input"); setBye(); } finally{ } //returns string decimal return decimal; } public double HextoDecimal(String hexadecimal){ this.hexadecimal = hexadecimal.toUpperCase(); try{ decimal = Integer.parseInt(this.hexadecimal, 16); } catch(NumberFormatException ne){ System.out.println("Invalid Input"); setBye(); } finally{ } //returns string decimal return decimal; } public void setBye(){ this.hexadecimal = "stop"; this.decimal = 0; } public void setToNull(){ this.hexadecimal = ""; this.decimal = 0; } public void setString(String s){ this.hexadecimal = s; } public String getHexadecimal() { return hexadecimal; } public void setHexadecimal(String hexadecimal) { this.hexadecimal = hexadecimal; } public double getDecimal() { return decimal; } public void setDecimal(double decimal) { this.decimal = decimal; } }
1,842
0.543243
0.538919
88
20.022728
17.691149
79
false
false
0
0
0
0
0
0
0.306818
false
false
9
df73d9c7f91bcfc4e6fd20b81e717117d1aa1ac2
17,746,804,928,526
d5a9989a97b833052a8041511d11ef34b23b0dac
/OpenFinance/src/com/buildsoftware/openfinance/finance/view/ConsultaPessoaBean.java
adac33c4dfe0917aa6c6339d0a3c6837035a38ce
[]
no_license
Brenomorais/JEE_OpenFinance
https://github.com/Brenomorais/JEE_OpenFinance
f4e29a37026169d4c9732f392957391deb27e49b
8bc29e5eba29c9e356729849c0da83a19d9d9a50
refs/heads/master
2021-04-15T17:25:39.442000
2018-03-26T16:47:18
2018-03-26T16:47:18
126,639,174
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.buildsoftware.openfinance.finance.view; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import com.buildsoftware.openfinance.finance.model.Pessoa; import com.buildsoftware.openfinance.finance.repository.Pessoas; import com.buildsoftware.openfinance.finance.service.GestaoPessoas; import com.buildsoftware.openfinance.finance.service.RegraNegocioException; import com.buildsoftware.openfinance.finance.util.FacesUtil; import com.buildsoftware.openfinance.finance.util.Repositorios; @ManagedBean public class ConsultaPessoaBean implements Serializable{ private static final long serialVersionUID = 1L; private List<Pessoa> pessoas = new ArrayList<Pessoa>(); private Pessoa pessoaSelecionada; private Pessoa pessoa = new Pessoa(); private Repositorios repositorios = new Repositorios(); @PostConstruct public void inicializar(){ Pessoas pessoas = this.repositorios.getPessoas(); this.pessoas = pessoas.todasPessoas(); } public void excluir(){ GestaoPessoas gestaoPessoas = new GestaoPessoas(this.repositorios.getPessoas()); try { gestaoPessoas.excluir(this.pessoaSelecionada); this.inicializar(); FacesUtil.adicionarMensagem(FacesMessage.SEVERITY_ERROR,"Pessoa excluída com sucesso!"); } catch (RegraNegocioException e) { FacesUtil.adicionarMensagem(FacesMessage.SEVERITY_ERROR,e.getMessage()); } } public List<Pessoa> getPessoas() { return pessoas; } public void setPessoas(List<Pessoa> pessoas) { this.pessoas = pessoas; } public Pessoa getPessoaSelecionada() { return pessoaSelecionada; } public void setPessoaSelecionada(Pessoa pessoaSelecionada) { this.pessoaSelecionada = pessoaSelecionada; } public Repositorios getRepositorios() { return repositorios; } public void setRepositorios(Repositorios repositorios) { this.repositorios = repositorios; } public void setPessoa(Pessoa pessoa){ this.pessoa = pessoa; } public Pessoa getPessoa(){ return pessoa; } }
ISO-8859-1
Java
2,122
java
ConsultaPessoaBean.java
Java
[]
null
[]
package com.buildsoftware.openfinance.finance.view; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import com.buildsoftware.openfinance.finance.model.Pessoa; import com.buildsoftware.openfinance.finance.repository.Pessoas; import com.buildsoftware.openfinance.finance.service.GestaoPessoas; import com.buildsoftware.openfinance.finance.service.RegraNegocioException; import com.buildsoftware.openfinance.finance.util.FacesUtil; import com.buildsoftware.openfinance.finance.util.Repositorios; @ManagedBean public class ConsultaPessoaBean implements Serializable{ private static final long serialVersionUID = 1L; private List<Pessoa> pessoas = new ArrayList<Pessoa>(); private Pessoa pessoaSelecionada; private Pessoa pessoa = new Pessoa(); private Repositorios repositorios = new Repositorios(); @PostConstruct public void inicializar(){ Pessoas pessoas = this.repositorios.getPessoas(); this.pessoas = pessoas.todasPessoas(); } public void excluir(){ GestaoPessoas gestaoPessoas = new GestaoPessoas(this.repositorios.getPessoas()); try { gestaoPessoas.excluir(this.pessoaSelecionada); this.inicializar(); FacesUtil.adicionarMensagem(FacesMessage.SEVERITY_ERROR,"Pessoa excluída com sucesso!"); } catch (RegraNegocioException e) { FacesUtil.adicionarMensagem(FacesMessage.SEVERITY_ERROR,e.getMessage()); } } public List<Pessoa> getPessoas() { return pessoas; } public void setPessoas(List<Pessoa> pessoas) { this.pessoas = pessoas; } public Pessoa getPessoaSelecionada() { return pessoaSelecionada; } public void setPessoaSelecionada(Pessoa pessoaSelecionada) { this.pessoaSelecionada = pessoaSelecionada; } public Repositorios getRepositorios() { return repositorios; } public void setRepositorios(Repositorios repositorios) { this.repositorios = repositorios; } public void setPessoa(Pessoa pessoa){ this.pessoa = pessoa; } public Pessoa getPessoa(){ return pessoa; } }
2,122
0.78595
0.785479
73
28.054794
24.790569
91
false
false
0
0
0
0
0
0
1.616438
false
false
9
d9ab0ee4b3982deecc8c0eef68cf6a1a4f4caaa0
15,659,450,768,574
e95ce056444f381e314330de8daa48baec8b6555
/web/src/main/java/com/example/web/utils/StringUtils.java
29d310f8756fcd2da286dc1312726f02377cbebc
[]
no_license
hatran1568/spring-api-web
https://github.com/hatran1568/spring-api-web
bae88270a26385eb75d3ed20ea0126542013bb50
b7864738071f0afbad0400536d066a1e9b263f28
refs/heads/main
2023-08-11T15:07:33.965000
2021-09-24T10:25:11
2021-09-24T10:25:11
408,740,702
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.web.utils; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringUtils extends org.springframework.util.StringUtils { public static String snakeCaseToCamelCase(String strInput) { StringTokenizer token = new StringTokenizer(strInput, "_"); StringBuilder str = new StringBuilder(token.nextToken()); while (token.hasMoreTokens()) { String s = token.nextToken(); str.append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)); } return str.toString(); } public static String camelCaseToSnakeCase(String strInput) { Matcher m = Pattern.compile("(?<=[a-z])[A-Z]").matcher(strInput); String result = m.replaceAll(match -> "_" + match.group().toLowerCase()); return result; } public static String camelCaseToSnakeCaseNumber(String strInput) { Matcher m = Pattern.compile("(?<=[a-z0-9])[A-Z]").matcher(strInput); String result = m.replaceAll(match -> "_" + match.group().toLowerCase()); return result; } public static boolean isNumeric(String strNum) { if (strNum == null) { return false; } try { int d = Integer.parseInt(strNum); } catch (NumberFormatException nfe) { return false; } return true; } }
UTF-8
Java
1,417
java
StringUtils.java
Java
[]
null
[]
package com.example.web.utils; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringUtils extends org.springframework.util.StringUtils { public static String snakeCaseToCamelCase(String strInput) { StringTokenizer token = new StringTokenizer(strInput, "_"); StringBuilder str = new StringBuilder(token.nextToken()); while (token.hasMoreTokens()) { String s = token.nextToken(); str.append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)); } return str.toString(); } public static String camelCaseToSnakeCase(String strInput) { Matcher m = Pattern.compile("(?<=[a-z])[A-Z]").matcher(strInput); String result = m.replaceAll(match -> "_" + match.group().toLowerCase()); return result; } public static String camelCaseToSnakeCaseNumber(String strInput) { Matcher m = Pattern.compile("(?<=[a-z0-9])[A-Z]").matcher(strInput); String result = m.replaceAll(match -> "_" + match.group().toLowerCase()); return result; } public static boolean isNumeric(String strNum) { if (strNum == null) { return false; } try { int d = Integer.parseInt(strNum); } catch (NumberFormatException nfe) { return false; } return true; } }
1,417
0.623853
0.62103
42
32.738094
27.395741
82
false
false
0
0
0
0
0
0
0.47619
false
false
9
8336352fc9b1f14cb777801fee3881fe30d86b1f
3,702,261,853,265
91203bfd7716426436cb1df6385eec0875793325
/src/snapcode/util/SamplesPane.java
bda235b073e762e3d8d6eb2ce865475212571df9
[]
no_license
reportmill/SnapCode
https://github.com/reportmill/SnapCode
9a228bd59dcc94ee00132eedf1c8cd2f39e9d3fa
59cc1e66242ba59ea4dc9d16bd76b7919708fabd
refs/heads/master
2023-09-01T14:26:40.570000
2023-08-29T16:18:30
2023-08-29T16:18:30
66,491,728
8
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package snapcode.util; import snap.geom.Pos; import snap.geom.Size; import snap.geom.VPos; import snap.gfx.*; import snap.util.StringUtils; import snap.view.*; import snap.viewx.DialogBox; import snap.viewx.DialogSheet; import snap.web.WebResponse; import snap.web.WebURL; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; /** * A class to show samples. */ public class SamplesPane extends ViewOwner { // A consumer for resulting URL private Consumer<WebURL> _handler; // The selected index private int _selIndex; // The dialog box private DialogSheet _dialogSheet; // The shared document names private static String[] _docNames; // The shared document images private static Image[] _docImages; // Constants private static final String SAMPLES_ROOT = "https://reportmill.com/SnapCode/Samples/"; private static final String SAMPLES_EXT = ".jepl"; private static final String SAMPLES_LABEL = "Select a Java REPL file:"; private static final Size DOC_SIZE = new Size(130, 102); private static final Effect SHADOW = new ShadowEffect(20, Color.GRAY, 0, 0); private static final Effect SHADOW_SEL = new ShadowEffect(20, Color.get("#038ec3"), 0, 0); private static final Color CONTENT_FILL = new Color(.98, .98, 1d); /** * Shows the samples pane. */ public void showSamples(ViewOwner anOwner, Consumer<WebURL> aHandler) { View view = anOwner.getUI(); _handler = aHandler; _dialogSheet = new DialogSheet(); _dialogSheet.setContent(getUI()); _dialogSheet.showConfirmDialog(view); _dialogSheet.addPropChangeListener(pc -> dialogBoxClosed(), DialogBox.Showing_Prop); } /** * Called when dialog box closed. */ private void dialogBoxClosed() { // If cancelled, just return if (_dialogSheet.isCancelled()) return; // Get selected URL and send to handler WebURL url = getDocURL(_selIndex); runLater(() -> _handler.accept(url)); } /** * Creates UI. */ @Override protected View createUI() { // Create main ColView to hold RowViews for samples ColView colView = new ColView(); colView.setName("ItemColView"); colView.setSpacing(10); colView.setPadding(15, 15, 15, 15); colView.setAlign(Pos.TOP_CENTER); colView.setFillWidth(true); colView.setFill(CONTENT_FILL); colView.setBorder(Color.GRAY, 1); colView.setPrefWidth(640); // Add loading label Label loadLabel = new Label("Loading..."); loadLabel.setFont(Font.Arial16.deriveFont(32).getBold()); loadLabel.setTextFill(Color.GRAY); colView.addChild(loadLabel); // Create ScrollView ScrollView scrollView = new ScrollView(colView); scrollView.setPrefHeight(450); // Create "Select template" label Label selectLabel = new Label(SAMPLES_LABEL); selectLabel.setFont(Font.Arial16.deriveFont(20).getBold()); // Create HeaderRow to hold SelectLabel RowView headerRow = new RowView(); headerRow.addChild(selectLabel); // Create top level col view to hold HeaderRow and ColView ColView boxView = new ColView(); boxView.setSpacing(8); boxView.setFillWidth(true); boxView.setChildren(headerRow, scrollView); // Return return boxView; } /** * Initialize UI. */ @Override protected void initUI() { if (_docNames == null) loadIndexFile(); else buildUI(); } /** * Starts loading. */ private void loadIndexFile() { WebURL url = WebURL.getURL(SAMPLES_ROOT + "index.txt"); url.getResponseAndCall(resp -> indexFileLoaded(resp)); } /** * Loads content. */ private void indexFileLoaded(WebResponse aResp) { // If response is bogus, report it if (aResp.getCode() != WebResponse.OK) { runLater(() -> indexFileLoadFailed(aResp)); return; } // Get text and break into lines String text = aResp.getText(); String[] lines = text.split("\\s*\n\\s*"); // Get names list from lines List<String> docNamesList = new ArrayList<>(); for (String line : lines) { line = line.trim(); if (line.length() > 0) docNamesList.add(line); } // Get DocNames from list _docNames = docNamesList.toArray(new String[0]); _docImages = new Image[_docNames.length]; // Rebuild UI runLater(() -> buildUI()); } /** * Loads failure condition. */ private void indexFileLoadFailed(WebResponse aResp) { // Get error string and TextArea String str = "Failed to load index file.\n" + "Response code: " + aResp.getCodeString() + "\n" + "Exception: " + aResp.getException(); TextArea textArea = new TextArea(); textArea.setText(str); // Add to ColView ColView colView = getView("ItemColView", ColView.class); colView.setAlign(Pos.CENTER); colView.addChild(textArea); } /** * Loads samples. */ private void buildUI() { // Get ItemColView and remove children ColView colView = getView("ItemColView", ColView.class); colView.removeChildren(); // Create RowViews RowView rowView = null; for (int i = 0; i < _docNames.length; i++) { // Create/add new RowView for every three samples if (i % 3 == 0) { rowView = new RowView(); rowView.setAlign(Pos.CENTER); colView.addChild(rowView); } // Create/add new ItemBox for index View itemBox = createItemBox(i); rowView.addChild(itemBox); } // Make sure all row views and image boxes are owned by ui for (View child : colView.getChildren()) child.setOwner(this); // Load images loadImagesInBackground(); } /** * Creates an item box for given index. */ private ColView createItemBox(int anIndex) { // Create ImageViewX for sample ImageView imageView = new ImageView(); imageView.setPrefSize(DOC_SIZE); imageView.setName("ImageView" + anIndex); // Create label for sample String name = getDocName(anIndex); String labelText = name.replace('_', ' '); Label label = new Label(labelText); label.setFont(Font.Arial13); label.setPadding(3, 4, 3, 4); label.setLeanY(VPos.BOTTOM); // Create/add ItemBox for Sample and add ImageView + Label ColView itemBox = new ColView(); itemBox.setPrefSize(200, 200); itemBox.setAlign(Pos.CENTER); itemBox.setPadding(0, 0, 8, 0); itemBox.setName("ItemBox" + anIndex); itemBox.addEventHandler(e -> itemBoxWasPressed(itemBox, e), MousePress); itemBox.setChildren(imageView, label); setItemBoxSelected(itemBox, anIndex == 0); // Return return itemBox; } /** * Configures an item box. */ private void setItemBoxSelected(ColView itemBox, boolean isSelected) { // Set ImageView.Effect ImageView imageView = (ImageView) itemBox.getChild(0); imageView.setEffect(isSelected ? SHADOW_SEL : SHADOW); // Set Label Fill and TextFill Label oldLabel = (Label) itemBox.getChild(1); oldLabel.setFill(isSelected ? Color.BLUE : null); oldLabel.setTextFill(isSelected ? Color.WHITE : null); } /** * Called when template ItemBox is clicked. */ private void itemBoxWasPressed(ColView anItemBox, ViewEvent anEvent) { // Get name and index of pressed ItemBox String name = anItemBox.getName(); int index = StringUtils.intValue(name); // Set attributes of current selection back to normal ColView oldItemBox = getView("ItemBox" + _selIndex, ColView.class); setItemBoxSelected(oldItemBox, false); // Set attributes of new selection to selected effect setItemBoxSelected(anItemBox, true); // Set new index _selIndex = index; // If double-click, confirm dialog box if (anEvent.getClickCount() > 1) _dialogSheet.confirm(); } /** * Returns the number of docs. */ private static int getDocCount() { return _docNames.length; } /** * Returns the doc name at index. */ private static String getDocName(int anIndex) { return _docNames[anIndex]; } /** * Returns the doc url at given index. */ private static WebURL getDocURL(int anIndex) { // Get document name, URL string and URL String name = getDocName(anIndex); String urls = SAMPLES_ROOT + name + '/' + name + SAMPLES_EXT; WebURL url = WebURL.getURL(urls); return url; } /** * Returns the doc thumnail image at given index. */ private Image getDocImage(int anIndex) { // If image already set, just return Image image = _docImages[anIndex]; if (image != null) return image; // Get image name, URL string, and URL String name = getDocName(anIndex); String urls = SAMPLES_ROOT + name + '/' + name + ".png"; WebURL imgURL = WebURL.getURL(urls); // Create Image. Then make sure image is loaded by requesting Image.Native. image = _docImages[anIndex] = Image.getImageForSource(imgURL); image.getNative(); return image; } /** * Loads the thumbnail image for each sample in background thread. */ private void loadImagesInBackground() { new Thread(() -> loadImages()).start(); } /** * Loads the thumbnail image for each sample in background thread. */ private void loadImages() { // Iterate over sample names and load/set images for (int i = 0; i < getDocCount(); i++) { int index = i; Image img = getDocImage(i); runLater(() -> setImage(img, index)); } } /** * Called after an image is loaded to set in ImageView in app thread. */ private void setImage(Image anImg, int anIndex) { String name = "ImageView" + anIndex; ImageView iview = getView(name, ImageView.class); iview.setImage(anImg); iview.setPrefSize(-1, -1); } /** * Animate SampleButton. */ public static void startSamplesButtonAnim(View samplesButton) { // Configure anim ViewAnim anim = samplesButton.getAnim(0); anim.getAnim(400).setScale(1.3).getAnim(800).setScale(1.1).getAnim(1200).setScale(1.3).getAnim(1600).setScale(1.0) .getAnim(2400).setRotate(360); anim.setLoopCount(3).play(); } /** * Stops SampleButton animation. */ public static void stopSamplesButtonAnim(View samplesButton) { samplesButton.getAnim(0).finish(); } }
UTF-8
Java
11,307
java
SamplesPane.java
Java
[ { "context": "nal String SAMPLES_ROOT = \"https://reportmill.com/SnapCode/Samples/\";\n private static final String SAMPLE", "end": 882, "score": 0.8157917261123657, "start": 874, "tag": "USERNAME", "value": "SnapCode" } ]
null
[]
package snapcode.util; import snap.geom.Pos; import snap.geom.Size; import snap.geom.VPos; import snap.gfx.*; import snap.util.StringUtils; import snap.view.*; import snap.viewx.DialogBox; import snap.viewx.DialogSheet; import snap.web.WebResponse; import snap.web.WebURL; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; /** * A class to show samples. */ public class SamplesPane extends ViewOwner { // A consumer for resulting URL private Consumer<WebURL> _handler; // The selected index private int _selIndex; // The dialog box private DialogSheet _dialogSheet; // The shared document names private static String[] _docNames; // The shared document images private static Image[] _docImages; // Constants private static final String SAMPLES_ROOT = "https://reportmill.com/SnapCode/Samples/"; private static final String SAMPLES_EXT = ".jepl"; private static final String SAMPLES_LABEL = "Select a Java REPL file:"; private static final Size DOC_SIZE = new Size(130, 102); private static final Effect SHADOW = new ShadowEffect(20, Color.GRAY, 0, 0); private static final Effect SHADOW_SEL = new ShadowEffect(20, Color.get("#038ec3"), 0, 0); private static final Color CONTENT_FILL = new Color(.98, .98, 1d); /** * Shows the samples pane. */ public void showSamples(ViewOwner anOwner, Consumer<WebURL> aHandler) { View view = anOwner.getUI(); _handler = aHandler; _dialogSheet = new DialogSheet(); _dialogSheet.setContent(getUI()); _dialogSheet.showConfirmDialog(view); _dialogSheet.addPropChangeListener(pc -> dialogBoxClosed(), DialogBox.Showing_Prop); } /** * Called when dialog box closed. */ private void dialogBoxClosed() { // If cancelled, just return if (_dialogSheet.isCancelled()) return; // Get selected URL and send to handler WebURL url = getDocURL(_selIndex); runLater(() -> _handler.accept(url)); } /** * Creates UI. */ @Override protected View createUI() { // Create main ColView to hold RowViews for samples ColView colView = new ColView(); colView.setName("ItemColView"); colView.setSpacing(10); colView.setPadding(15, 15, 15, 15); colView.setAlign(Pos.TOP_CENTER); colView.setFillWidth(true); colView.setFill(CONTENT_FILL); colView.setBorder(Color.GRAY, 1); colView.setPrefWidth(640); // Add loading label Label loadLabel = new Label("Loading..."); loadLabel.setFont(Font.Arial16.deriveFont(32).getBold()); loadLabel.setTextFill(Color.GRAY); colView.addChild(loadLabel); // Create ScrollView ScrollView scrollView = new ScrollView(colView); scrollView.setPrefHeight(450); // Create "Select template" label Label selectLabel = new Label(SAMPLES_LABEL); selectLabel.setFont(Font.Arial16.deriveFont(20).getBold()); // Create HeaderRow to hold SelectLabel RowView headerRow = new RowView(); headerRow.addChild(selectLabel); // Create top level col view to hold HeaderRow and ColView ColView boxView = new ColView(); boxView.setSpacing(8); boxView.setFillWidth(true); boxView.setChildren(headerRow, scrollView); // Return return boxView; } /** * Initialize UI. */ @Override protected void initUI() { if (_docNames == null) loadIndexFile(); else buildUI(); } /** * Starts loading. */ private void loadIndexFile() { WebURL url = WebURL.getURL(SAMPLES_ROOT + "index.txt"); url.getResponseAndCall(resp -> indexFileLoaded(resp)); } /** * Loads content. */ private void indexFileLoaded(WebResponse aResp) { // If response is bogus, report it if (aResp.getCode() != WebResponse.OK) { runLater(() -> indexFileLoadFailed(aResp)); return; } // Get text and break into lines String text = aResp.getText(); String[] lines = text.split("\\s*\n\\s*"); // Get names list from lines List<String> docNamesList = new ArrayList<>(); for (String line : lines) { line = line.trim(); if (line.length() > 0) docNamesList.add(line); } // Get DocNames from list _docNames = docNamesList.toArray(new String[0]); _docImages = new Image[_docNames.length]; // Rebuild UI runLater(() -> buildUI()); } /** * Loads failure condition. */ private void indexFileLoadFailed(WebResponse aResp) { // Get error string and TextArea String str = "Failed to load index file.\n" + "Response code: " + aResp.getCodeString() + "\n" + "Exception: " + aResp.getException(); TextArea textArea = new TextArea(); textArea.setText(str); // Add to ColView ColView colView = getView("ItemColView", ColView.class); colView.setAlign(Pos.CENTER); colView.addChild(textArea); } /** * Loads samples. */ private void buildUI() { // Get ItemColView and remove children ColView colView = getView("ItemColView", ColView.class); colView.removeChildren(); // Create RowViews RowView rowView = null; for (int i = 0; i < _docNames.length; i++) { // Create/add new RowView for every three samples if (i % 3 == 0) { rowView = new RowView(); rowView.setAlign(Pos.CENTER); colView.addChild(rowView); } // Create/add new ItemBox for index View itemBox = createItemBox(i); rowView.addChild(itemBox); } // Make sure all row views and image boxes are owned by ui for (View child : colView.getChildren()) child.setOwner(this); // Load images loadImagesInBackground(); } /** * Creates an item box for given index. */ private ColView createItemBox(int anIndex) { // Create ImageViewX for sample ImageView imageView = new ImageView(); imageView.setPrefSize(DOC_SIZE); imageView.setName("ImageView" + anIndex); // Create label for sample String name = getDocName(anIndex); String labelText = name.replace('_', ' '); Label label = new Label(labelText); label.setFont(Font.Arial13); label.setPadding(3, 4, 3, 4); label.setLeanY(VPos.BOTTOM); // Create/add ItemBox for Sample and add ImageView + Label ColView itemBox = new ColView(); itemBox.setPrefSize(200, 200); itemBox.setAlign(Pos.CENTER); itemBox.setPadding(0, 0, 8, 0); itemBox.setName("ItemBox" + anIndex); itemBox.addEventHandler(e -> itemBoxWasPressed(itemBox, e), MousePress); itemBox.setChildren(imageView, label); setItemBoxSelected(itemBox, anIndex == 0); // Return return itemBox; } /** * Configures an item box. */ private void setItemBoxSelected(ColView itemBox, boolean isSelected) { // Set ImageView.Effect ImageView imageView = (ImageView) itemBox.getChild(0); imageView.setEffect(isSelected ? SHADOW_SEL : SHADOW); // Set Label Fill and TextFill Label oldLabel = (Label) itemBox.getChild(1); oldLabel.setFill(isSelected ? Color.BLUE : null); oldLabel.setTextFill(isSelected ? Color.WHITE : null); } /** * Called when template ItemBox is clicked. */ private void itemBoxWasPressed(ColView anItemBox, ViewEvent anEvent) { // Get name and index of pressed ItemBox String name = anItemBox.getName(); int index = StringUtils.intValue(name); // Set attributes of current selection back to normal ColView oldItemBox = getView("ItemBox" + _selIndex, ColView.class); setItemBoxSelected(oldItemBox, false); // Set attributes of new selection to selected effect setItemBoxSelected(anItemBox, true); // Set new index _selIndex = index; // If double-click, confirm dialog box if (anEvent.getClickCount() > 1) _dialogSheet.confirm(); } /** * Returns the number of docs. */ private static int getDocCount() { return _docNames.length; } /** * Returns the doc name at index. */ private static String getDocName(int anIndex) { return _docNames[anIndex]; } /** * Returns the doc url at given index. */ private static WebURL getDocURL(int anIndex) { // Get document name, URL string and URL String name = getDocName(anIndex); String urls = SAMPLES_ROOT + name + '/' + name + SAMPLES_EXT; WebURL url = WebURL.getURL(urls); return url; } /** * Returns the doc thumnail image at given index. */ private Image getDocImage(int anIndex) { // If image already set, just return Image image = _docImages[anIndex]; if (image != null) return image; // Get image name, URL string, and URL String name = getDocName(anIndex); String urls = SAMPLES_ROOT + name + '/' + name + ".png"; WebURL imgURL = WebURL.getURL(urls); // Create Image. Then make sure image is loaded by requesting Image.Native. image = _docImages[anIndex] = Image.getImageForSource(imgURL); image.getNative(); return image; } /** * Loads the thumbnail image for each sample in background thread. */ private void loadImagesInBackground() { new Thread(() -> loadImages()).start(); } /** * Loads the thumbnail image for each sample in background thread. */ private void loadImages() { // Iterate over sample names and load/set images for (int i = 0; i < getDocCount(); i++) { int index = i; Image img = getDocImage(i); runLater(() -> setImage(img, index)); } } /** * Called after an image is loaded to set in ImageView in app thread. */ private void setImage(Image anImg, int anIndex) { String name = "ImageView" + anIndex; ImageView iview = getView(name, ImageView.class); iview.setImage(anImg); iview.setPrefSize(-1, -1); } /** * Animate SampleButton. */ public static void startSamplesButtonAnim(View samplesButton) { // Configure anim ViewAnim anim = samplesButton.getAnim(0); anim.getAnim(400).setScale(1.3).getAnim(800).setScale(1.1).getAnim(1200).setScale(1.3).getAnim(1600).setScale(1.0) .getAnim(2400).setRotate(360); anim.setLoopCount(3).play(); } /** * Stops SampleButton animation. */ public static void stopSamplesButtonAnim(View samplesButton) { samplesButton.getAnim(0).finish(); } }
11,307
0.599275
0.589635
382
28.602095
23.211384
122
false
false
0
0
0
0
0
0
0.510471
false
false
9
dedcac3d98457d97c50808f439186172ecd2f060
25,469,156,121,430
200a207ed990bf2b427160f7e9a2b5690be65788
/src/main/java/net/minecraft/entity/ai/EntityAISit.java
4b764bc11a15a7b4d3df2b9ee4e8b4efa2afbd27
[ "WTFPL" ]
permissive
8MiYile/HomoCraftServer
https://github.com/8MiYile/HomoCraftServer
8fae0e35a82267dbac023531c63903a293861e71
06c52bccad746256a08f78bfc56ae9e4c847445c
refs/heads/master
2021-02-07T20:55:22.127000
2020-05-06T10:01:49
2020-05-06T10:01:49
244,075,912
13
8
WTFPL
false
2020-10-13T19:58:13
2020-03-01T02:49:30
2020-05-12T07:41:59
2020-10-13T19:58:12
16,170
12
4
4
Java
false
false
package net.minecraft.entity.ai; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityTameable; public class EntityAISit extends EntityAIBase { private final EntityTameable tameable; private boolean isSitting; public EntityAISit(EntityTameable entityIn) { this.tameable = entityIn; this.setMutexBits(5); } public boolean shouldExecute() { if (!this.tameable.isTamed()) { // return false; return this.isSitting && this.tameable.getAttackTarget() == null; // CraftBukkit - Allow sitting for wild animals } else if (this.tameable.isInWater()) { return false; } else if (!this.tameable.onGround) { return false; } else { EntityLivingBase entitylivingbase = this.tameable.getOwner(); if (entitylivingbase == null) { return true; } else { return this.tameable.getDistanceSq(entitylivingbase) < 144.0D && entitylivingbase.getRevengeTarget() != null ? false : this.isSitting; } } } public void startExecuting() { this.tameable.getNavigator().clearPath(); this.tameable.setSitting(true); } public void resetTask() { this.tameable.setSitting(false); } public void setSitting(boolean sitting) { this.isSitting = sitting; } }
UTF-8
Java
1,532
java
EntityAISit.java
Java
[]
null
[]
package net.minecraft.entity.ai; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityTameable; public class EntityAISit extends EntityAIBase { private final EntityTameable tameable; private boolean isSitting; public EntityAISit(EntityTameable entityIn) { this.tameable = entityIn; this.setMutexBits(5); } public boolean shouldExecute() { if (!this.tameable.isTamed()) { // return false; return this.isSitting && this.tameable.getAttackTarget() == null; // CraftBukkit - Allow sitting for wild animals } else if (this.tameable.isInWater()) { return false; } else if (!this.tameable.onGround) { return false; } else { EntityLivingBase entitylivingbase = this.tameable.getOwner(); if (entitylivingbase == null) { return true; } else { return this.tameable.getDistanceSq(entitylivingbase) < 144.0D && entitylivingbase.getRevengeTarget() != null ? false : this.isSitting; } } } public void startExecuting() { this.tameable.getNavigator().clearPath(); this.tameable.setSitting(true); } public void resetTask() { this.tameable.setSitting(false); } public void setSitting(boolean sitting) { this.isSitting = sitting; } }
1,532
0.578982
0.575718
62
23.725807
27.171598
150
false
false
0
0
0
0
0
0
0.290323
false
false
9
af1e3519a35593031bf916064deeb84e6667bfd3
25,469,156,120,548
fe30da1fd2e8345fa479fa63838459e405b25dd7
/app/src/main/java/com/chensd/funnydemo/adapter/RecyclerAdapter.java
d8427b0f4e04a3ae9a667f297914bd6a99a7e4ba
[]
no_license
chenshandong/Rxjava-retrofit-mvp
https://github.com/chenshandong/Rxjava-retrofit-mvp
6c6278a4341feacfb413f0332570f3b51cc97666
65218b516645dd6c1c806c1c46da973dcdb94c72
refs/heads/master
2021-01-22T02:48:31.052000
2017-02-06T16:05:16
2017-02-06T16:05:16
81,072,326
7
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.chensd.funnydemo.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.chensd.funnydemo.R; import com.chensd.funnydemo.model.ImageInfo; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by chen on 2017/1/16. */ public class RecyclerAdapter extends RecyclerView.Adapter { private List<ImageInfo> list; private OnItemClickListener listener; public Object getItem(int position){ return list.get(position); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycleritem_layout, null); return new DeBounceViewHolder(view); } @Override public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) { if (listener != null){ holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onItemClick(v, holder.getLayoutPosition()); } }); } DeBounceViewHolder deBounceViewHolder = (DeBounceViewHolder) holder; Glide.with(holder.itemView.getContext()).load(list.get(position).getImage_url()) .placeholder(R.drawable.loading).thumbnail(0.1f).diskCacheStrategy(DiskCacheStrategy.SOURCE) .into(deBounceViewHolder.imageView); deBounceViewHolder.textView.setText(list.get(position).getDescription()); } @Override public int getItemCount() { return list == null ? 0 : list.size(); } public void setImages(List<ImageInfo> list) { this.list = list; notifyDataSetChanged(); } class DeBounceViewHolder extends RecyclerView.ViewHolder { @Bind(R.id.recycler_img) ImageView imageView; @Bind(R.id.description_tv) TextView textView; public DeBounceViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } public void setOnItemClickListener(OnItemClickListener listener){ this.listener = listener; } public interface OnItemClickListener{ void onItemClick(View v, int position); } }
UTF-8
Java
2,588
java
RecyclerAdapter.java
Java
[ { "context": "import butterknife.ButterKnife;\n\n/**\n * Created by chen on 2017/1/16.\n */\npublic class RecyclerAdapter ex", "end": 516, "score": 0.9839801788330078, "start": 512, "tag": "USERNAME", "value": "chen" } ]
null
[]
package com.chensd.funnydemo.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.chensd.funnydemo.R; import com.chensd.funnydemo.model.ImageInfo; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by chen on 2017/1/16. */ public class RecyclerAdapter extends RecyclerView.Adapter { private List<ImageInfo> list; private OnItemClickListener listener; public Object getItem(int position){ return list.get(position); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycleritem_layout, null); return new DeBounceViewHolder(view); } @Override public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) { if (listener != null){ holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onItemClick(v, holder.getLayoutPosition()); } }); } DeBounceViewHolder deBounceViewHolder = (DeBounceViewHolder) holder; Glide.with(holder.itemView.getContext()).load(list.get(position).getImage_url()) .placeholder(R.drawable.loading).thumbnail(0.1f).diskCacheStrategy(DiskCacheStrategy.SOURCE) .into(deBounceViewHolder.imageView); deBounceViewHolder.textView.setText(list.get(position).getDescription()); } @Override public int getItemCount() { return list == null ? 0 : list.size(); } public void setImages(List<ImageInfo> list) { this.list = list; notifyDataSetChanged(); } class DeBounceViewHolder extends RecyclerView.ViewHolder { @Bind(R.id.recycler_img) ImageView imageView; @Bind(R.id.description_tv) TextView textView; public DeBounceViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } public void setOnItemClickListener(OnItemClickListener listener){ this.listener = listener; } public interface OnItemClickListener{ void onItemClick(View v, int position); } }
2,588
0.680448
0.676198
87
28.747126
26.932106
108
false
false
0
0
0
0
0
0
0.448276
false
false
9
a76ee4e85a5beafd970515b695e64e789b07cd9e
29,789,893,233,993
d4ff607043a9ab2510da1a2eff2825af551fbbda
/src/test/java/com/codecool/ipbinary/model/BinaryIntegerTest.java
95ed388575af2fc2632d1d9b9edcdb172aeafddd
[]
no_license
CodecoolBP20161/sdt-week3-binary
https://github.com/CodecoolBP20161/sdt-week3-binary
1072b2ebd0042f0632e643786a1210e9fb93ea49
05ab1eade422a4df5bfb272342454d7f8256cb27
refs/heads/master
2020-06-11T13:00:45.487000
2016-12-05T19:49:25
2016-12-05T19:49:25
75,660,229
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.codecool.ipbinary.model; import org.junit.Test; import static junit.framework.TestCase.assertEquals; /** * @author kovacsa */ public class BinaryIntegerTest { @Test public void testGetStringValue() { assertEquals("11111110", new BinaryInteger(254).getStringValue()); assertEquals("00000001", new BinaryInteger(1).getStringValue()); } @Test(expected = RuntimeException.class) public void testBigNumber(){ new BinaryInteger(1000); } }
UTF-8
Java
503
java
BinaryIntegerTest.java
Java
[ { "context": "t.framework.TestCase.assertEquals;\n\n/**\n * @author kovacsa\n */\npublic class BinaryIntegerTest {\n\n @Test\n ", "end": 138, "score": 0.9995723962783813, "start": 131, "tag": "USERNAME", "value": "kovacsa" } ]
null
[]
package com.codecool.ipbinary.model; import org.junit.Test; import static junit.framework.TestCase.assertEquals; /** * @author kovacsa */ public class BinaryIntegerTest { @Test public void testGetStringValue() { assertEquals("11111110", new BinaryInteger(254).getStringValue()); assertEquals("00000001", new BinaryInteger(1).getStringValue()); } @Test(expected = RuntimeException.class) public void testBigNumber(){ new BinaryInteger(1000); } }
503
0.691849
0.644135
26
18.384615
22.602037
74
false
false
0
0
0
0
0
0
0.307692
false
false
9
7ed4ff97d1028a960e5d3f19756d4c81633a8e7a
28,398,323,810,936
2a11a5fb1205e9cfba069f566c2d0e5f435f8e56
/src/main/java/com/boldseas/porscheshop/events/EventBusBean.java
e6d5f81078482acb26b10a53878f323af3874215
[]
no_license
lilingling3/porshe-shop
https://github.com/lilingling3/porshe-shop
949bf7e4f5bd4147e97d25e1b00cff1c64f0f3c3
256d9f6bff3164f25e536bdca7f1a6ad038ad04a
refs/heads/master
2020-03-27T07:21:04.745000
2018-08-26T13:48:18
2018-08-26T13:48:18
146,184,349
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.boldseas.porscheshop.events; import com.google.common.eventbus.AsyncEventBus; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import java.util.UUID; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; /** * @author fei.ye * @version 2018/5/23. */ @Component public class EventBusBean { @Bean public AsyncEventBus asynceventbus(){ ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(2, new BasicThreadFactory.Builder().namingPattern("porsche-shop-event-bus-" + UUID.randomUUID()).daemon(true).build()); return new AsyncEventBus(executorService); } }
UTF-8
Java
810
java
EventBusBean.java
Java
[ { "context": "rrent.ScheduledThreadPoolExecutor;\n\n/**\n * @author fei.ye\n * @version 2018/5/23.\n */\n@Component\npublic clas", "end": 412, "score": 0.9908952116966248, "start": 406, "tag": "USERNAME", "value": "fei.ye" } ]
null
[]
package com.boldseas.porscheshop.events; import com.google.common.eventbus.AsyncEventBus; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import java.util.UUID; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; /** * @author fei.ye * @version 2018/5/23. */ @Component public class EventBusBean { @Bean public AsyncEventBus asynceventbus(){ ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(2, new BasicThreadFactory.Builder().namingPattern("porsche-shop-event-bus-" + UUID.randomUUID()).daemon(true).build()); return new AsyncEventBus(executorService); } }
810
0.772839
0.761728
25
31.4
31.616451
132
false
false
0
0
0
0
0
0
0.44
false
false
9
22aae5a6846e6ce805d19e4dbf5fe499d16f31a9
2,602,750,233,983
793a9768feb30207902fbc67d2a2b5cc3d93a4ed
/test/tmanager/object/database/AgentTest.java
deeb974138e8950b83a14b02f9491d1a275b1afb
[]
no_license
zerohouse/tmanager
https://github.com/zerohouse/tmanager
d4d53d8591a54f2cb44fd290f2d7e4c2a6b1e017
2d4cb940886efe195f23b8df5ca6b01fcdbd2ea3
refs/heads/master
2021-01-10T20:04:50.636000
2015-01-30T09:54:15
2015-01-30T09:54:15
29,671,073
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package tmanager.object.database; import java.util.Date; import org.junit.Test; import easyjdbc.query.QueryExecuter; public class AgentTest { @Test public void test() { QueryExecuter qe = new QueryExecuter(); Date from = new Date(); from.setTime(from.getTime() - 60*60*1000*24*30000); Date to = new Date(); Agent agent = qe.get(Agent.class, "play"); agent.getSchedulesAndLines(qe, from, to, 0); System.out.println(agent); System.out.println(from); System.out.println(to); System.out.println(qe.getList(Line.class, "agentId=? and time between ? and ?", "jobbank", from, to)); System.out.println(qe.getList(Schedule.class, "agentId=? and startTime between ? and ? and endTime between ? and ?", "lol", from, to, from, to)); } }
UTF-8
Java
760
java
AgentTest.java
Java
[]
null
[]
package tmanager.object.database; import java.util.Date; import org.junit.Test; import easyjdbc.query.QueryExecuter; public class AgentTest { @Test public void test() { QueryExecuter qe = new QueryExecuter(); Date from = new Date(); from.setTime(from.getTime() - 60*60*1000*24*30000); Date to = new Date(); Agent agent = qe.get(Agent.class, "play"); agent.getSchedulesAndLines(qe, from, to, 0); System.out.println(agent); System.out.println(from); System.out.println(to); System.out.println(qe.getList(Line.class, "agentId=? and time between ? and ?", "jobbank", from, to)); System.out.println(qe.getList(Schedule.class, "agentId=? and startTime between ? and ? and endTime between ? and ?", "lol", from, to, from, to)); } }
760
0.692105
0.671053
28
26.142857
32.478249
147
false
false
0
0
0
0
0
0
2
false
false
9
e4d967c3077bd820cb4234d92df059b32f90c99f
11,020,886,130,837
1cca1c6b1ab097d46dc658298233948b17de360d
/cshop-search/cshop-search-service/src/main/java/com/javachen/cshop/domain/SearchRequest.java
da5f19eabacb7ada89b18cc5d11832405d633d84
[]
no_license
tanbinh123/cshop
https://github.com/tanbinh123/cshop
992dbddc5252b1582752ceacad9f61b3e94fdeb0
a8e54e94c7e8495b84e9cd88267976f1d8df0b22
refs/heads/master
2022-02-22T10:07:51.365000
2019-08-19T17:17:05
2019-08-19T17:17:05
459,664,452
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.javachen.cshop.domain; import lombok.Data; import java.util.Map; @Data public class SearchRequest { /** * 搜索条件 */ private String key; /** * 当前页 */ private Integer page = 1; private Integer size = 20; /** * 排序字段 */ private String sortBy; /** * 是否降序 */ private Boolean descending; /** * 过滤字段 */ private Map<String, String> filter; }
UTF-8
Java
484
java
SearchRequest.java
Java
[]
null
[]
package com.javachen.cshop.domain; import lombok.Data; import java.util.Map; @Data public class SearchRequest { /** * 搜索条件 */ private String key; /** * 当前页 */ private Integer page = 1; private Integer size = 20; /** * 排序字段 */ private String sortBy; /** * 是否降序 */ private Boolean descending; /** * 过滤字段 */ private Map<String, String> filter; }
484
0.526906
0.520179
36
11.388889
11.304565
39
false
false
0
0
0
0
0
0
0.277778
false
false
9
6bc7bab9ec24e38ba944197607470ba10fd813c2
7,567,732,431,462
8bb37ad038734b55fe6a37702bae5a14c681f583
/gson/src/test/java/io/jeti/gson/SerializeTest.java
cb1c709e48a142d2d5d7ec95fef7f8818dd163d2
[]
no_license
jeti/gson
https://github.com/jeti/gson
6b919561bb4a7ce71acfb6298d1002f3613a2b4d
e0feebb2f6923fee8e5ec08ec7bc2c536e405508
refs/heads/master
2021-07-08T00:42:38.576000
2017-10-04T10:06:41
2017-10-04T10:06:41
105,511,785
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.jeti.gson; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.junit.Test; public class SerializeTest { @Test public void test() throws Exception { /* Fill the village with idiots. */ int n = 4; List<Idiot> idiots = new ArrayList<>(); for (int i = 0; i < n; i++) { idiots.add(new Idiot("Name: " + i, "Nickname: " + i, i, i + 1)); } /* Now create a village */ Village village = new Village(idiots, new float[] { 1f, 2f, 3f, 4f }); /* * Finally, try to serialize, and deserialize the village, then check * whether the deserialized object is equal to the original object. */ GsonSerializer gsonSerializer = new GsonSerializer(); String serialized = gsonSerializer.toString(village); Village dVillage = (Village) gsonSerializer.fromString(serialized); TestCase.assertEquals(village, dVillage); System.out.println("Serialized object: "); System.out.println(serialized); System.out.println("Original object: "); System.out.println(village.toString()); System.out.println("Deserialized object: "); System.out.println(dVillage.toString()); /* * Note that the deserialized object clearly won't be the same instance * as the original object. So if you are curious, you can uncomment the * following line just to show that it will fail. * * <pre><code>TestCase.assertEquals(village,dVillage);</code></pre> */ } }
UTF-8
Java
1,622
java
SerializeTest.java
Java
[]
null
[]
package io.jeti.gson; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.junit.Test; public class SerializeTest { @Test public void test() throws Exception { /* Fill the village with idiots. */ int n = 4; List<Idiot> idiots = new ArrayList<>(); for (int i = 0; i < n; i++) { idiots.add(new Idiot("Name: " + i, "Nickname: " + i, i, i + 1)); } /* Now create a village */ Village village = new Village(idiots, new float[] { 1f, 2f, 3f, 4f }); /* * Finally, try to serialize, and deserialize the village, then check * whether the deserialized object is equal to the original object. */ GsonSerializer gsonSerializer = new GsonSerializer(); String serialized = gsonSerializer.toString(village); Village dVillage = (Village) gsonSerializer.fromString(serialized); TestCase.assertEquals(village, dVillage); System.out.println("Serialized object: "); System.out.println(serialized); System.out.println("Original object: "); System.out.println(village.toString()); System.out.println("Deserialized object: "); System.out.println(dVillage.toString()); /* * Note that the deserialized object clearly won't be the same instance * as the original object. So if you are curious, you can uncomment the * following line just to show that it will fail. * * <pre><code>TestCase.assertEquals(village,dVillage);</code></pre> */ } }
1,622
0.614057
0.609741
49
32.122448
27.286562
79
false
false
0
0
0
0
0
0
0.714286
false
false
9