hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e188ead3bfaa264a957cac8f8f1d5021ad7ee39 | 1,747 | java | Java | src/main/java/com/jillesvangurp/iterables/FilteringIterable.java | jillesvangurp/iterables-support | a0a967d82fb7d8d5504a50eb19d5e7f1541b2771 | [
"MIT"
] | null | null | null | src/main/java/com/jillesvangurp/iterables/FilteringIterable.java | jillesvangurp/iterables-support | a0a967d82fb7d8d5504a50eb19d5e7f1541b2771 | [
"MIT"
] | 1 | 2019-05-20T10:45:44.000Z | 2019-05-20T10:53:09.000Z | src/main/java/com/jillesvangurp/iterables/FilteringIterable.java | jillesvangurp/iterables-support | a0a967d82fb7d8d5504a50eb19d5e7f1541b2771 | [
"MIT"
] | null | null | null | 29.116667 | 83 | 0.482541 | 10,439 | package com.jillesvangurp.iterables;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Filter the elements in an Iterable using a {@link Filter}.
*
* @param <T> the type that is filtered
*/
public class FilteringIterable<T> implements Iterable<T> {
private final Iterable<T> iterable;
private final Filter<T> filter;
public FilteringIterable(Iterable<T> iterable, Filter<T> filter) {
this.iterable = iterable;
this.filter = filter;
}
@Override
public Iterator<T> iterator() {
final Iterator<T> iterator = iterable.iterator();
return new Iterator<T>() {
T next = null;
@Override
public boolean hasNext() {
while (iterator.hasNext() && next == null) {
T candidate = iterator.next();
try {
if (filter.passes(candidate)) {
next = candidate;
}
} catch (PermanentlyFailToPassException e) {
// special poison pill to force the iterator to abort
return false;
}
}
return next != null;
}
@Override
public T next() {
if (hasNext()) {
T result = next;
next = null;
return result;
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove is not supported");
}
};
}
}
|
3e188ec8577643f2891d938867e736604eb895c6 | 1,287 | java | Java | AndroidStudio/answers/assignments/fundamentals/2nd/ControllerAssignment3/app/src/main/java/jp/mixi/assignment/controller/adv/TitleFragment.java | harus2rock/AndroidTraining | b10a35143295d0e4b2248502f46d659631680c71 | [
"Apache-2.0"
] | 746 | 2015-01-03T01:36:11.000Z | 2022-03-23T10:14:26.000Z | AndroidStudio/answers/assignments/fundamentals/2nd/ControllerAssignment3/app/src/main/java/jp/mixi/assignment/controller/adv/TitleFragment.java | harus2rock/AndroidTraining | b10a35143295d0e4b2248502f46d659631680c71 | [
"Apache-2.0"
] | 108 | 2015-01-01T12:28:45.000Z | 2022-01-21T05:04:17.000Z | AndroidStudio/answers/assignments/fundamentals/2nd/ControllerAssignment3/app/src/main/java/jp/mixi/assignment/controller/adv/TitleFragment.java | harus2rock/AndroidTraining | b10a35143295d0e4b2248502f46d659631680c71 | [
"Apache-2.0"
] | 314 | 2015-01-02T08:12:22.000Z | 2022-01-21T05:06:13.000Z | 26.265306 | 75 | 0.683761 | 10,440 | package jp.mixi.assignment.controller.adv;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {@link Fragment} subclass.
* Use the {@link TitleFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class TitleFragment extends Fragment {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment TitleLabelFragment.
*/
public static TitleFragment newInstance() {
TitleFragment fragment = new TitleFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
public TitleFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_title, container, false);
}
}
|
3e188ecc50aaa5cdfd846b64d14bc93e345b9f89 | 280 | java | Java | app/src/main/java/com/lt/integrate/frame/demo/listener/HttpsListenerInterface.java | LeWaves/Seconds-frameWork | 6754fbdb1d20c582a75c79f89cee604151b2de78 | [
"MIT"
] | 1 | 2018-01-05T09:40:57.000Z | 2018-01-05T09:40:57.000Z | app/src/main/java/com/lt/integrate/frame/demo/listener/HttpsListenerInterface.java | LeWaves/App-FrameWork | 6754fbdb1d20c582a75c79f89cee604151b2de78 | [
"MIT"
] | null | null | null | app/src/main/java/com/lt/integrate/frame/demo/listener/HttpsListenerInterface.java | LeWaves/App-FrameWork | 6754fbdb1d20c582a75c79f89cee604151b2de78 | [
"MIT"
] | null | null | null | 18.666667 | 55 | 0.735714 | 10,441 | package com.lt.integrate.frame.demo.listener;
import android.view.View;
import java.util.List;
/**
* Created by iclick on 2017/9/26.
*/
public interface HttpsListenerInterface {
void onSucessHttps(List<Object> list,String data );
void onErrorHttps(String error );
}
|
3e188f66c198032dec1327b82b4bd64265d08e36 | 3,583 | java | Java | algorithms.complexities.ide/src-gen/algorithms/complexities/ide/contentassist/antlr/ComplexitiesParser.java | vicegd/algorithms.complexities | d51b15b6216336b28db634317ca2bf9afcc2244a | [
"MIT"
] | null | null | null | algorithms.complexities.ide/src-gen/algorithms/complexities/ide/contentassist/antlr/ComplexitiesParser.java | vicegd/algorithms.complexities | d51b15b6216336b28db634317ca2bf9afcc2244a | [
"MIT"
] | null | null | null | algorithms.complexities.ide/src-gen/algorithms/complexities/ide/contentassist/antlr/ComplexitiesParser.java | vicegd/algorithms.complexities | d51b15b6216336b28db634317ca2bf9afcc2244a | [
"MIT"
] | null | null | null | 49.082192 | 126 | 0.808261 | 10,442 | /*
* generated by Xtext 2.12.0
*/
package algorithms.complexities.ide.contentassist.antlr;
import algorithms.complexities.ide.contentassist.antlr.internal.InternalComplexitiesParser;
import algorithms.complexities.services.ComplexitiesGrammarAccess;
import com.google.inject.Inject;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.xtext.AbstractElement;
import org.eclipse.xtext.ide.editor.contentassist.antlr.AbstractContentAssistParser;
public class ComplexitiesParser extends AbstractContentAssistParser {
@Inject
private ComplexitiesGrammarAccess grammarAccess;
private Map<AbstractElement, String> nameMappings;
@Override
protected InternalComplexitiesParser createParser() {
InternalComplexitiesParser result = new InternalComplexitiesParser(null);
result.setGrammarAccess(grammarAccess);
return result;
}
@Override
protected String getRuleName(AbstractElement element) {
if (nameMappings == null) {
nameMappings = new HashMap<AbstractElement, String>() {
private static final long serialVersionUID = 1L;
{
put(grammarAccess.getCalculationAccess().getAlternatives(), "rule__Calculation__Alternatives");
put(grammarAccess.getComplexityAccess().getAlternatives_2(), "rule__Complexity__Alternatives_2");
put(grammarAccess.getTimeUnitsAccess().getAlternatives(), "rule__TimeUnits__Alternatives");
put(grammarAccess.getModelAccess().getGroup(), "rule__Model__Group__0");
put(grammarAccess.getExecutionTimesAccess().getGroup(), "rule__ExecutionTimes__Group__0");
put(grammarAccess.getSizesAccess().getGroup(), "rule__Sizes__Group__0");
put(grammarAccess.getComplexityAccess().getGroup(), "rule__Complexity__Group__0");
put(grammarAccess.getModelAccess().getCalculationsAssignment_1(), "rule__Model__CalculationsAssignment_1");
put(grammarAccess.getExecutionTimesAccess().getComplexityAssignment_3(), "rule__ExecutionTimes__ComplexityAssignment_3");
put(grammarAccess.getExecutionTimesAccess().getTime1Assignment_7(), "rule__ExecutionTimes__Time1Assignment_7");
put(grammarAccess.getExecutionTimesAccess().getTime1UnitAssignment_8(), "rule__ExecutionTimes__Time1UnitAssignment_8");
put(grammarAccess.getExecutionTimesAccess().getSize1Assignment_12(), "rule__ExecutionTimes__Size1Assignment_12");
put(grammarAccess.getExecutionTimesAccess().getTime2UnitAssignment_16(), "rule__ExecutionTimes__Time2UnitAssignment_16");
put(grammarAccess.getExecutionTimesAccess().getSize2Assignment_20(), "rule__ExecutionTimes__Size2Assignment_20");
put(grammarAccess.getSizesAccess().getComplexityAssignment_3(), "rule__Sizes__ComplexityAssignment_3");
put(grammarAccess.getSizesAccess().getSize1Assignment_7(), "rule__Sizes__Size1Assignment_7");
put(grammarAccess.getSizesAccess().getTime1Assignment_11(), "rule__Sizes__Time1Assignment_11");
put(grammarAccess.getSizesAccess().getTime1UnitAssignment_12(), "rule__Sizes__Time1UnitAssignment_12");
put(grammarAccess.getSizesAccess().getTime2Assignment_18(), "rule__Sizes__Time2Assignment_18");
put(grammarAccess.getSizesAccess().getTime2UnitAssignment_19(), "rule__Sizes__Time2UnitAssignment_19");
}
};
}
return nameMappings.get(element);
}
@Override
protected String[] getInitialHiddenTokens() {
return new String[] { "RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT" };
}
public ComplexitiesGrammarAccess getGrammarAccess() {
return this.grammarAccess;
}
public void setGrammarAccess(ComplexitiesGrammarAccess grammarAccess) {
this.grammarAccess = grammarAccess;
}
}
|
3e188f8e3f9cfee88577c8e4e2f1beac12bce452 | 15,434 | java | Java | caliper/src/main/java/com/google/caliper/options/ParsedOptions.java | Aexyn/caliper | 5edf5db29d06243d3ef7754cd433601edbb9fdb7 | [
"Apache-2.0"
] | null | null | null | caliper/src/main/java/com/google/caliper/options/ParsedOptions.java | Aexyn/caliper | 5edf5db29d06243d3ef7754cd433601edbb9fdb7 | [
"Apache-2.0"
] | 1 | 2018-09-21T23:06:43.000Z | 2018-09-21T23:06:43.000Z | caliper/src/main/java/com/google/caliper/options/ParsedOptions.java | Aexyn/caliper | 5edf5db29d06243d3ef7754cd433601edbb9fdb7 | [
"Apache-2.0"
] | null | null | null | 38.297767 | 100 | 0.564857 | 10,443 | /*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.caliper.options;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.MINUTES;
import com.google.caliper.options.CommandLineParser.Leftovers;
import com.google.caliper.options.CommandLineParser.Option;
import com.google.caliper.util.InvalidCommandException;
import com.google.caliper.util.ShortDuration;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Ordering;
import java.io.File;
import java.util.List;
import java.util.Map;
final class ParsedOptions implements CaliperOptions {
public static ParsedOptions from(String[] args) throws InvalidCommandException {
ParsedOptions options = new ParsedOptions();
CommandLineParser<ParsedOptions> parser = CommandLineParser.forClass(ParsedOptions.class);
try {
parser.parseAndInject(args, options);
} catch (InvalidCommandException e) {
e.setUsage(USAGE);
throw e;
}
return options;
}
private ParsedOptions() {
}
// --------------------------------------------------------------------------
// Dry run -- simple boolean, needs to be checked in some methods
// --------------------------------------------------------------------------
@Option({"-n", "--dry-run"})
private boolean dryRun;
@Override public boolean dryRun() {
return dryRun;
}
private void dryRunIncompatible(String optionName) throws InvalidCommandException {
// This only works because CLP does field injection before method injection
if (dryRun) {
throw new InvalidCommandException("Option not available in dry-run mode: " + optionName);
}
}
// --------------------------------------------------------------------------
// Delimiter -- injected early so methods can use it
// --------------------------------------------------------------------------
@Option({"-d", "--delimiter"})
private String delimiter = ",";
private ImmutableSet<String> split(String string) {
return ImmutableSet.copyOf(Splitter.on(delimiter).split(string));
}
// --------------------------------------------------------------------------
// Benchmark method names to run
// --------------------------------------------------------------------------
private ImmutableSet<String> benchmarkNames = ImmutableSet.of();
@Option({"-b", "--benchmark"})
private void setBenchmarkNames(String benchmarksString) {
benchmarkNames = split(benchmarksString);
}
@Override public ImmutableSet<String> benchmarkMethodNames() {
return benchmarkNames;
}
// --------------------------------------------------------------------------
// Print configuration?
// --------------------------------------------------------------------------
@Option({"-p", "--print-config"})
private boolean printConfiguration = false;
@Override public boolean printConfiguration() {
return printConfiguration;
}
// --------------------------------------------------------------------------
// Trials
// --------------------------------------------------------------------------
private int trials = 1;
@Option({"-t", "--trials"})
private void setTrials(int trials) throws InvalidCommandException {
dryRunIncompatible("trials");
if (trials < 1) {
throw new InvalidCommandException("trials must be at least 1: " + trials);
}
this.trials = trials;
}
@Override public int trialsPerScenario() {
return trials;
}
// --------------------------------------------------------------------------
// Time limit
// --------------------------------------------------------------------------
private ShortDuration runTime = ShortDuration.of(5, MINUTES);
@Option({"-l", "--time-limit"})
private void setTimeLimit(String timeLimitString) throws InvalidCommandException {
try {
this.runTime = ShortDuration.valueOf(timeLimitString);
} catch (IllegalArgumentException e) {
throw new InvalidCommandException("Invalid time limit: " + timeLimitString);
}
}
@Override public ShortDuration timeLimit() {
return runTime;
}
// --------------------------------------------------------------------------
// Run name
// --------------------------------------------------------------------------
private String runName = "";
@Option({"-r", "--run-name"})
private void setRunName(String runName) {
this.runName = checkNotNull(runName);
}
@Override public String runName() {
return runName;
}
// --------------------------------------------------------------------------
// VM specifications
// --------------------------------------------------------------------------
private ImmutableSet<String> vmNames = ImmutableSet.of();
@Option({"-m", "--vm"})
private void setVms(String vmsString) throws InvalidCommandException {
dryRunIncompatible("vm");
vmNames = split(vmsString);
}
@Override public ImmutableSet<String> vmNames() {
return vmNames;
}
// --------------------------------------------------------------------------
// Measuring instruments to use
// --------------------------------------------------------------------------
private static final ImmutableSet<String> DEFAULT_INSTRUMENT_NAMES =
new ImmutableSet.Builder<String>()
.add("allocation")
.add("runtime")
.build();
private ImmutableSet<String> instrumentNames = DEFAULT_INSTRUMENT_NAMES;
@Option({"-i", "--instrument"})
private void setInstruments(String instrumentsString) {
instrumentNames = split(instrumentsString);
}
@Override public ImmutableSet<String> instrumentNames() {
return instrumentNames;
}
// --------------------------------------------------------------------------
// Benchmark parameters
// --------------------------------------------------------------------------
private Multimap<String, String> mutableUserParameters = ArrayListMultimap.create();
@Option("-D")
private void addParameterSpec(String nameAndValues) throws InvalidCommandException {
addToMultimap(nameAndValues, mutableUserParameters);
}
@Override public ImmutableSetMultimap<String, String> userParameters() {
// de-dup values, but keep in order
return new ImmutableSetMultimap.Builder<String, String>()
.orderKeysBy(Ordering.natural())
.putAll(mutableUserParameters)
.build();
}
// --------------------------------------------------------------------------
// VM arguments
// --------------------------------------------------------------------------
private Multimap<String, String> mutableVmArguments = ArrayListMultimap.create();
@Option("-J")
private void addVmArgumentsSpec(String nameAndValues) throws InvalidCommandException {
dryRunIncompatible("-J");
addToMultimap(nameAndValues, mutableVmArguments);
}
@Override public ImmutableSetMultimap<String, String> vmArguments() {
// de-dup values, but keep in order
return new ImmutableSetMultimap.Builder<String, String>()
.orderKeysBy(Ordering.natural())
.putAll(mutableVmArguments)
.build();
}
// --------------------------------------------------------------------------
// VM arguments
// --------------------------------------------------------------------------
private final Map<String, String> mutableConfigPropertes = Maps.newHashMap();
@Option("-C")
private void addConfigProperty(String nameAndValue) throws InvalidCommandException {
List<String> tokens = splitProperty(nameAndValue);
mutableConfigPropertes.put(tokens.get(0), tokens.get(1));
}
@Override public ImmutableMap<String, String> configProperties() {
return ImmutableMap.copyOf(mutableConfigPropertes);
}
// --------------------------------------------------------------------------
// Location of .caliper
// --------------------------------------------------------------------------
private File caliperDirectory = new File(System.getProperty("user.home"), ".caliper");
@Option({"--directory"})
private void setCaliperDirectory(String path) {
caliperDirectory = new File(path);
}
@Override public File caliperDirectory() {
return caliperDirectory;
}
// --------------------------------------------------------------------------
// Location of config.properties
// --------------------------------------------------------------------------
private Optional<File> caliperConfigFile = Optional.absent();
@Option({"-c", "--config"})
private void setCaliperConfigFile(String filename) {
caliperConfigFile = Optional.of(new File(filename));
}
@Override public File caliperConfigFile() {
return caliperConfigFile.or(new File(caliperDirectory, "config.properties"));
}
// --------------------------------------------------------------------------
// Leftover - benchmark class name
// --------------------------------------------------------------------------
private String benchmarkClassName;
@Leftovers
private void setLeftovers(ImmutableList<String> leftovers) throws InvalidCommandException {
if (leftovers.isEmpty()) {
throw new InvalidCommandException("No benchmark class specified");
}
if (leftovers.size() > 1) {
throw new InvalidCommandException("Extra stuff, expected only class name: " + leftovers);
}
this.benchmarkClassName = leftovers.get(0);
}
@Override public String benchmarkClassName() {
return benchmarkClassName;
}
// --------------------------------------------------------------------------
// Helper methods
// --------------------------------------------------------------------------
private static List<String> splitProperty(String propertyString) throws InvalidCommandException {
List<String> tokens = ImmutableList.copyOf(Splitter.on('=').limit(2).split(propertyString));
if (tokens.size() != 2) {
throw new InvalidCommandException("no '=' found in: " + propertyString);
}
return tokens;
}
private void addToMultimap(String nameAndValues, Multimap<String, String> multimap)
throws InvalidCommandException {
List<String> tokens = splitProperty(nameAndValues);
String name = tokens.get(0);
String values = tokens.get(1);
if (multimap.containsKey(name)) {
throw new InvalidCommandException("multiple parameter sets for: " + name);
}
multimap.putAll(name, split(values));
}
@Override public String toString() {
return Objects.toStringHelper(this)
.add("benchmarkClassName", this.benchmarkClassName())
.add("benchmarkMethodNames", this.benchmarkMethodNames())
.add("benchmarkParameters", this.userParameters())
.add("dryRun", this.dryRun())
.add("instrumentNames", this.instrumentNames())
.add("vms", this.vmNames())
.add("vmArguments", this.vmArguments())
.add("trials", this.trialsPerScenario())
.add("printConfig", this.printConfiguration())
.add("delimiter", this.delimiter)
.add("caliperConfigFile", this.caliperConfigFile)
.toString();
}
// --------------------------------------------------------------------------
// Usage
// --------------------------------------------------------------------------
// TODO(kevinb): kinda nice if CommandLineParser could autogenerate most of this...
// TODO(kevinb): a test could actually check that we don't exceed 79 columns.
private static final ImmutableList<String> USAGE = ImmutableList.of(
"Usage:",
" java com.google.caliper.runner.CaliperMain <benchmark_class_name> [options...]",
"",
"Options:",
" -h, --help print this message",
" -n, --dry-run instead of measuring, execute a single rep for each scenario",
" in-process",
" -b, --benchmark comma-separated list of benchmark methods to run; 'foo' is",
" an alias for 'timeFoo' (default: all found in class)",
" -m, --vm comma-separated list of VMs to test on; possible values are",
" configured in Caliper's configuration file (default:",
" whichever VM caliper itself is running in, only)",
" -i, --instrument comma-separated list of measuring instruments to use; possible ",
" values are configured in Caliper's configuration file ",
" (default: \"" + Joiner.on(",").join(DEFAULT_INSTRUMENT_NAMES) + "\")",
" -t, --trials number of independent trials to peform per benchmark scenario; ",
" a positive integer (default: 1)",
" -l, --time-limit maximum length of time allowed for a single trial; use 0 to allow ",
" trials to run indefinitely. (default: 30s) ",
" -r, --run-name a user-friendly string used to identify the run",
" -p, --print-config print the effective configuration that will be used by Caliper",
" -d, --delimiter separator used in options that take multiple values (default: ',')",
" -c, --config location of Caliper's configuration file (default:",
" $HOME/.caliper/config.properties)",
" --directory location of Caliper's configuration and data directory ",
" (default: $HOME/.caliper)",
"",
" -Dparam=val1,val2,...",
" Specifies the values to inject into the 'param' field of the benchmark",
" class; if multiple values or parameters are specified in this way, caliper",
" will try all possible combinations.",
"",
// commented out until this flag is fixed
// " -JdisplayName='vm arg list choice 1,vm arg list choice 2,...'",
// " Specifies alternate sets of VM arguments to pass. As with any variable,",
// " caliper will test all possible combinations. Example:",
// " -Jmemory='-Xms32m -Xmx32m,-Xms512m -Xmx512m'",
// "",
" -CconfigProperty=value",
" Specifies a value for any property that could otherwise be specified in ",
" $HOME/.caliper/config.properties. Properties specified on the command line",
" will override those specified in the file.",
"",
"See http://code.google.com/p/caliper/wiki/CommandLineOptions for more details.",
"");
}
|
3e188fb62f38eea7f9b2061c5ef51d56e2f108e9 | 8,814 | java | Java | src/main/java/org/olat/resource/accesscontrol/provider/paypal/ui/PaypalMasterAccountController.java | JHDSonline/OpenOLAT | 449e1f1753162aac458dda15a6baac146ecbdb16 | [
"Apache-2.0"
] | 191 | 2018-03-29T09:55:44.000Z | 2022-03-23T06:42:12.000Z | src/main/java/org/olat/resource/accesscontrol/provider/paypal/ui/PaypalMasterAccountController.java | JHDSonline/OpenOLAT | 449e1f1753162aac458dda15a6baac146ecbdb16 | [
"Apache-2.0"
] | 68 | 2018-05-11T06:19:00.000Z | 2022-01-25T18:03:26.000Z | src/main/java/org/olat/resource/accesscontrol/provider/paypal/ui/PaypalMasterAccountController.java | JHDSonline/OpenOLAT | 449e1f1753162aac458dda15a6baac146ecbdb16 | [
"Apache-2.0"
] | 139 | 2018-04-27T09:46:11.000Z | 2022-03-27T08:52:50.000Z | 33.942308 | 128 | 0.746856 | 10,444 | /**
* OLAT - Online Learning and Training<br>
* http://www.olat.org
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Copyright (c) frentix GmbH<br>
* http://www.frentix.com<br>
* <p>
*/
package org.olat.resource.accesscontrol.provider.paypal.ui;
import java.math.BigDecimal;
import java.net.UnknownHostException;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.form.flexible.FormItem;
import org.olat.core.gui.components.form.flexible.FormItemContainer;
import org.olat.core.gui.components.form.flexible.elements.FormLink;
import org.olat.core.gui.components.form.flexible.elements.MultipleSelectionElement;
import org.olat.core.gui.components.form.flexible.elements.SingleSelection;
import org.olat.core.gui.components.form.flexible.elements.TextElement;
import org.olat.core.gui.components.form.flexible.impl.FormBasicController;
import org.olat.core.gui.components.form.flexible.impl.FormEvent;
import org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer;
import org.olat.core.gui.components.link.Link;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.util.StringHelper;
import org.olat.resource.accesscontrol.AccessControlModule;
import org.olat.resource.accesscontrol.provider.paypal.PaypalModule;
import org.olat.resource.accesscontrol.provider.paypal.manager.PaypalManager;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* Description:<br>
* Set the account settings
*
* <P>
* Initial Date: 26 mai 2011 <br>
*
* @author srosse, kenaa@example.com, http://www.frentix.com
*/
public class PaypalMasterAccountController extends FormBasicController {
private TextElement usernameEl;
private TextElement passwordEl;
private TextElement signatureEl;
private TextElement applicationIdEl;
private TextElement firstReceiverEl;
private TextElement deviceIpEl;
private TextElement vatNumberEl;
private TextElement vatRateEl;
private MultipleSelectionElement vatEnabledEl;
private SingleSelection currencyEl;
private FormLink checkButton;
@Autowired
private PaypalModule paypalModule;
@Autowired
private PaypalManager paypalManager;
@Autowired
private AccessControlModule acModule;
private static final String[] vatKeys = new String[]{"on"};
private final String[] vatValues;
private static final String[] currencies = new String[] {
"",
"AUD",
"CAD",
"CZK",
"DKK",
"EUR",
"HKD",
"HUF",
"ILS",
"JPY",
"MXN",
"NOK",
"NZD",
"PHP",
"PLN",
"GBP",
"SGD",
"SEK",
"CHF",
"TWD",
"THB",
"TRY",
"USD"
};
public PaypalMasterAccountController(UserRequest ureq, WindowControl wControl) {
super(ureq, wControl);
vatValues = new String[]{ translate("vat.on") };
initForm(ureq);
}
@Override
protected void doDispose() {
//
}
@Override
protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) {
setFormTitle("paypal.config.title");
setFormWarning("paypal.config.deprecated");
if(acModule.isPaypalEnabled()) {
setFormDescription("paypal.config.description");
setFormContextHelp("PayPal Configuration");
currencyEl = uifactory.addDropdownSingleselect("currency", "currency", formLayout, currencies, currencies, null);
String currency = paypalModule.getPaypalCurrency();
if(StringHelper.containsNonWhitespace(currency)) {
currencyEl.select(currency, true);
} else {
currencyEl.select("", true);
}
vatEnabledEl = uifactory.addCheckboxesHorizontal("vat.enabled", "vat.enabled", formLayout, vatKeys, vatValues);
vatEnabledEl.addActionListener(FormEvent.ONCHANGE);
if(acModule.isVatEnabled()) {
vatEnabledEl.select(vatKeys[0], true);
}
String vatNr = acModule.getVatNumber();
vatNumberEl = uifactory.addTextElement("vat.nr", "vat.nr", 255, vatNr, formLayout);
BigDecimal vatRate = acModule.getVat();
String vatRateStr = vatRate == null ? "" : vatRate.toPlainString();
vatRateEl = uifactory.addTextElement("vat.rate", "vat.rate", 5, vatRateStr, formLayout);
vatRateEl.setDisplaySize(5);
uifactory.addSpacerElement("paypal-space", formLayout, false);
String firstReceiver = paypalModule.getPaypalFirstReceiverEmailAddress();
firstReceiverEl = uifactory.addTextElement("first-receiver", "paypal.config.first.receiver", 255, firstReceiver, formLayout);
String userId = paypalModule.getPaypalSecurityUserId();
usernameEl = uifactory.addTextElement("api-username", "paypal.config.username", 255, userId, formLayout);
passwordEl = uifactory.addPasswordElement("api-password", "paypal.config.password", 255, "", formLayout);
passwordEl.setExampleKey("paypal.config.password.expl", null);
passwordEl.setAutocomplete("new-password");
String signature = paypalModule.getPaypalSecuritySignature();
signatureEl = uifactory.addTextElement("api-signature", "paypal.config.signature", 255, signature, formLayout);
String applicationId = paypalModule.getPaypalApplicationId();
uifactory.addSpacerElement("paypal-space2", formLayout, false);
applicationIdEl = uifactory.addTextElement("application-id", "paypal.config.application.id", 255, applicationId, formLayout);
try {
deviceIpEl = uifactory.addTextElement("device-ip", "paypal.config.device.ip", 255, "", formLayout);
String deviceIp = paypalModule.getDeviceIpAddress();
deviceIpEl.setValue(deviceIp);
} catch (UnknownHostException e) {
logError("", e);
}
final FormLayoutContainer buttonGroupLayout = FormLayoutContainer.createButtonLayout("buttonLayout", getTranslator());
formLayout.add(buttonGroupLayout);
checkButton = uifactory.addFormLink("paypal.check", buttonGroupLayout, Link.BUTTON);
uifactory.addFormSubmitButton("save", buttonGroupLayout);
} else {
String fxSupport = "efpyi@example.com";
setFormWarning("paypal.config.disabled.warning", new String[]{fxSupport});
}
}
@Override
protected void formOK(UserRequest ureq) {
boolean vatEnabled = vatEnabledEl.isMultiselect() && vatEnabledEl.isSelected(0);
acModule.setVatEnabled(vatEnabled);
String vatNr = vatNumberEl.getValue();
acModule.setVatNumber(vatNr);
String vatRate = vatRateEl.getValue();
if(StringHelper.containsNonWhitespace(vatRate)) {
try {
acModule.setVat(new BigDecimal(vatRate));
} catch (Exception e) {
//error
vatRateEl.setErrorKey("", null);
}
} else {
acModule.setVat(BigDecimal.ZERO);
}
String currency = currencyEl.isOneSelected() ? currencyEl.getSelectedKey() : "";
paypalModule.setPaypalCurrency(currency);
String userId = usernameEl.getValue();
if(StringHelper.containsNonWhitespace(userId)) {
paypalModule.setPaypalSecurityUserId(userId);
}
String password = passwordEl.getValue();
if(StringHelper.containsNonWhitespace(password)) {
paypalModule.setPaypalSecurityPassword(password);
}
String signature = signatureEl.getValue();
if(StringHelper.containsNonWhitespace(signature)) {
paypalModule.setPaypalSecuritySignature(signature);
}
String applicationId = applicationIdEl.getValue();
if(StringHelper.containsNonWhitespace(applicationId)) {
paypalModule.setPaypalApplicationId(applicationId);
}
String deviceIp = deviceIpEl.getValue();
if(StringHelper.containsNonWhitespace(deviceIp)) {
paypalModule.setDeviceIpAddress(deviceIp);
}
String firstReceiver = firstReceiverEl.getValue();
if(StringHelper.containsNonWhitespace(firstReceiver)) {
paypalModule.setPaypalFirstReceiverEmailAddress(firstReceiver);
}
showInfo("paypal.config.saved");
}
@Override
protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) {
if(source == checkButton) {
checkCredentials();
} else if (source == vatEnabledEl) {
if (vatEnabledEl.isSelected(0)) {
vatNumberEl.setEnabled(true);
vatRateEl.setEnabled(true);
} else {
vatNumberEl.setEnabled(false);
vatRateEl.setEnabled(false);
vatRateEl.setValue(null);
}
}
super.formInnerEvent(ureq, source, event);
}
private void checkCredentials() {
if(paypalManager.convertCurrency()) {
showInfo("paypal.config.success");
} else {
showError("paypal.config.error");
}
}
} |
3e1890dc6e885d11d3995f9e127d1944517b7a31 | 5,869 | java | Java | src/java/Servlets/UsuarioServlet.java | csalgadolizana/MisOfertasWeb | bc54ed3cb277a89f388950676ab2a84d2232b5ca | [
"MIT"
] | null | null | null | src/java/Servlets/UsuarioServlet.java | csalgadolizana/MisOfertasWeb | bc54ed3cb277a89f388950676ab2a84d2232b5ca | [
"MIT"
] | null | null | null | src/java/Servlets/UsuarioServlet.java | csalgadolizana/MisOfertasWeb | bc54ed3cb277a89f388950676ab2a84d2232b5ca | [
"MIT"
] | null | null | null | 39.389262 | 123 | 0.645596 | 10,445 | /*
* 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 Servlets;
import servicios.Cliente;
import servicios.Persona;
import servicios.Usuario;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.simple.JSONObject;
/**
*
* @author PC-Cristopher
*/
public class UsuarioServlet extends HttpServlet {
JSONObject jObj;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String accion = request.getParameter("accion");
System.err.println("ClienteServlet ->" + accion);
switch (accion) {
case "getDataSession":
getMyData(request, response);
break;
case "destroySession":
destroySession(request, response);
break;
default:
// response.sendRedirect("index.html");
break;
}
}
private void destroySession(HttpServletRequest request, HttpServletResponse response) throws IOException {
HttpSession session = request.getSession(true);
session.invalidate();
jObj = new JSONObject();
jObj.put("sesion", "destroyed");
PrintWriter out = response.getWriter();
response.setContentType("Content-Type: application/json");
out.println(jObj);
}
private void getMyData(HttpServletRequest request, HttpServletResponse response) throws IOException {
HttpSession session = request.getSession(true);
Cliente cliente = (Cliente) session.getAttribute("cliente");
Usuario usuario = (Usuario) session.getAttribute("trabajador");
jObj = new JSONObject();
if (cliente != null) {
System.out.println("cliente " + cliente.getPersonaIdpersona().getNombre());
jObj.put("sesion", "1");
jObj.put("nombre", cliente.getPersonaIdpersona().getNombre());
jObj.put("correo", cliente.getPersonaIdpersona().getApellidos());
jObj.put("rut", cliente.getPersonaIdpersona().getRut());
jObj.put("apellido", cliente.getPersonaIdpersona().getApellidos());
jObj.put("sexo", cliente.getPersonaIdpersona().getSexoIdSexo().getIdSexo().intValue());
jObj.put("correo", cliente.getCorreo());
jObj.put("telefono", cliente.getTelefono().intValue());
jObj.put("aceptaInformativo", cliente.getAceptaInformativo());
System.out.println("aceptaInformativo " + cliente.getAceptaInformativo());
jObj.put("idCiudad", cliente.getCiudadIdCiudad().getIdCiudad().intValue());
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date fecha = cliente.getFechaNacimiento().toGregorianCalendar().getTime();
System.err.println("sdf.format(fecha) " + cliente.getFechaNacimiento().getYear());
System.err.println("sdf.format(fecha) " + sdf.format(fecha));
jObj.put("fecha", sdf.format(fecha));
} else {
if (usuario != null) {
jObj.put("sesion", "1");
jObj.put("nombre", usuario.getPersonaIdpersona().getNombre());
jObj.put("correo", usuario.getPersonaIdpersona().getApellidos());
jObj.put("sexo", usuario.getPersonaIdpersona().getSexoIdSexo().getIdSexo().intValue());
jObj.put("correo", usuario.getCorreo());
} else {
jObj.put("sesion", "nula");
}
}
// jObj.put("correo", cliente.getPersonaIdpersona().getNombre() + "");
// jObj.put("correo", usuario.getPersonaIdpersona().getNombre() + "");
PrintWriter out = response.getWriter();
response.setContentType("Content-Type: application/json");
out.println(jObj);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
3e1892247eb42de7324706aa29c4f925085a060e | 148 | java | Java | Auth/src/main/java/com/auth/mapper/RoleMapper.java | EtachGu/OAuth2SSO | 521eeebcf0f638383d90020e95821be26dacff4b | [
"MIT"
] | 2 | 2019-03-24T06:02:06.000Z | 2019-03-25T02:07:12.000Z | Auth/src/main/java/com/auth/mapper/RoleMapper.java | EtachGu/OAuth2SSO | 521eeebcf0f638383d90020e95821be26dacff4b | [
"MIT"
] | null | null | null | Auth/src/main/java/com/auth/mapper/RoleMapper.java | EtachGu/OAuth2SSO | 521eeebcf0f638383d90020e95821be26dacff4b | [
"MIT"
] | null | null | null | 21.142857 | 50 | 0.797297 | 10,446 | package com.auth.mapper;
import com.auth.entity.Role;
import tk.mybatis.mapper.common.Mapper;
public interface RoleMapper extends Mapper<Role> {
} |
3e1892e14c558d57b33e473e76465d9b38bc8ffe | 1,007 | java | Java | src/main/java/com/github/crimsondawn45/basicshields/object/BasicShieldEnchantment.java | ogpaulw/Basic-Shields-Fabric | dc1d92e91bed751a59d266543a1aec2fc116558f | [
"CC0-1.0"
] | 3 | 2022-01-09T10:10:13.000Z | 2022-03-27T03:31:42.000Z | src/main/java/com/github/crimsondawn45/basicshields/object/BasicShieldEnchantment.java | ogpaulw/Basic-Shields-Fabric | dc1d92e91bed751a59d266543a1aec2fc116558f | [
"CC0-1.0"
] | 32 | 2021-12-31T23:22:02.000Z | 2022-03-25T18:39:31.000Z | src/main/java/com/github/crimsondawn45/basicshields/object/BasicShieldEnchantment.java | ogpaulw/Basic-Shields-Fabric | dc1d92e91bed751a59d266543a1aec2fc116558f | [
"CC0-1.0"
] | 2 | 2022-02-11T12:27:34.000Z | 2022-03-21T20:03:24.000Z | 27.972222 | 113 | 0.718967 | 10,447 | package com.github.crimsondawn45.basicshields.object;
import com.github.crimsondawn45.basicshields.initializers.BasicShields;
import com.github.crimsondawn45.fabricshieldlib.lib.object.FabricShieldEnchantment;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
public class BasicShieldEnchantment extends FabricShieldEnchantment {
private int maxLevel;
private String name;
private Identifier id;
public BasicShieldEnchantment(String name,Rarity weight, boolean isTreasure, boolean isCurse, int maxLevel) {
super(weight, isTreasure, isCurse);
this.maxLevel = maxLevel;
this.name = name;
this.id = new Identifier(BasicShields.MOD_ID, this.name);
Registry.register(Registry.ENCHANTMENT, this.id, this);
}
@Override
public int getMaxLevel() {
return this.maxLevel;
}
public String getName() {
return this.name;
}
public Identifier id() {
return this.id;
}
}
|
3e18935c369ff28daa483ebf2f49918c00da1f96 | 12,598 | java | Java | src/main/java/com/ning/billing/recurly/model/RecurlyUnitCurrency.java | demetrio812/recurly-java-library | 7e1ee6310bcb736d2a629a4b9d44c7846c934b99 | [
"Apache-2.0"
] | 27 | 2015-01-16T08:06:16.000Z | 2022-02-22T22:43:50.000Z | src/main/java/com/ning/billing/recurly/model/RecurlyUnitCurrency.java | demetrio812/recurly-java-library | 7e1ee6310bcb736d2a629a4b9d44c7846c934b99 | [
"Apache-2.0"
] | 277 | 2015-01-02T14:46:22.000Z | 2022-03-11T10:29:53.000Z | src/main/java/com/ning/billing/recurly/model/RecurlyUnitCurrency.java | demetrio812/recurly-java-library | 7e1ee6310bcb736d2a629a4b9d44c7846c934b99 | [
"Apache-2.0"
] | 78 | 2015-01-12T20:33:11.000Z | 2022-02-22T22:43:52.000Z | 33.240106 | 109 | 0.653834 | 10,448 | /*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2015 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.billing.recurly.model;
import java.util.Map;
import com.google.common.base.Objects;
import javax.annotation.Nullable;
import javax.xml.bind.annotation.XmlElement;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class RecurlyUnitCurrency {
// United States Dollars
@XmlElement(name = "USD")
private Integer unitAmountUSD;
// Australian Dollars
@XmlElement(name = "AUD")
private Integer unitAmountAUD;
@XmlElement(name = "JPY")
private Integer unitAmountJPY;
// Canadian Dollars
@XmlElement(name = "CAD")
private Integer unitAmountCAD;
// Euros
@XmlElement(name = "EUR")
private Integer unitAmountEUR;
// British Pounds
@XmlElement(name = "GBP")
private Integer unitAmountGBP;
// Czech Korunas
@XmlElement(name = "CZK")
private Integer unitAmountCZK;
// Danish Krones
@XmlElement(name = "DKK")
private Integer unitAmountDKK;
// Hungarian Forints
@XmlElement(name = "HUF")
private Integer unitAmountHUF;
// Indian Rupees
@XmlElement(name = "INR")
private Integer unitAmountINR;
// Norwegian Krones
@XmlElement(name = "NOK")
private Integer unitAmountNOK;
// New Zealand Dollars
@XmlElement(name = "NZD")
private Integer unitAmountNZD;
// Polish Zloty
@XmlElement(name = "PLN")
private Integer unitAmountPLN;
// Singapore Dollars
@XmlElement(name = "SGD")
private Integer unitAmountSGD;
// Swedish Kronas
@XmlElement(name = "SEK")
private Integer unitAmountSEK;
// Swiss Francs
@XmlElement(name = "CHF")
private Integer unitAmountCHF;
// South African Rand
@XmlElement(name = "ZAR")
private Integer unitAmountZAR;
public static RecurlyUnitCurrency build(@Nullable final Object unitAmountInCents) {
if (RecurlyObject.isNull(unitAmountInCents)) {
return null;
}
if (unitAmountInCents instanceof RecurlyUnitCurrency) {
return (RecurlyUnitCurrency) unitAmountInCents;
}
final RecurlyUnitCurrency recurlyUnitCurrency = new RecurlyUnitCurrency();
if (unitAmountInCents instanceof Map) {
final Map amounts = (Map) unitAmountInCents;
recurlyUnitCurrency.setUnitAmountUSD(amounts.get("USD"));
recurlyUnitCurrency.setUnitAmountAUD(amounts.get("AUD"));
recurlyUnitCurrency.setUnitAmountCAD(amounts.get("CAD"));
recurlyUnitCurrency.setUnitAmountEUR(amounts.get("EUR"));
recurlyUnitCurrency.setUnitAmountGBP(amounts.get("GBP"));
recurlyUnitCurrency.setUnitAmountCZK(amounts.get("CZK"));
recurlyUnitCurrency.setUnitAmountDKK(amounts.get("DKK"));
recurlyUnitCurrency.setUnitAmountHUF(amounts.get("HUF"));
recurlyUnitCurrency.setUnitAmountNOK(amounts.get("NOK"));
recurlyUnitCurrency.setUnitAmountNZD(amounts.get("NZD"));
recurlyUnitCurrency.setUnitAmountPLN(amounts.get("PLN"));
recurlyUnitCurrency.setUnitAmountSGD(amounts.get("SGD"));
recurlyUnitCurrency.setUnitAmountSEK(amounts.get("SEK"));
recurlyUnitCurrency.setUnitAmountCHF(amounts.get("CHF"));
recurlyUnitCurrency.setUnitAmountZAR(amounts.get("ZAR"));
recurlyUnitCurrency.setUnitAmountJPY(amounts.get("JPY"));
recurlyUnitCurrency.setUnitAmountINR(amounts.get("INR"));
}
return recurlyUnitCurrency;
}
public Integer getUnitAmountUSD() {
return unitAmountUSD;
}
public void setUnitAmountUSD(final Object unitAmountUSD) {
this.unitAmountUSD = RecurlyObject.integerOrNull(unitAmountUSD);
}
public Integer getUnitAmountAUD() {
return unitAmountAUD;
}
public void setUnitAmountAUD(final Object unitAmountAUD) {
this.unitAmountAUD = RecurlyObject.integerOrNull(unitAmountAUD);
}
public Integer getUnitAmountCAD() {
return unitAmountCAD;
}
public void setUnitAmountCAD(final Object unitAmountCAD) {
this.unitAmountCAD = RecurlyObject.integerOrNull(unitAmountCAD);
}
public Integer getUnitAmountEUR() {
return unitAmountEUR;
}
public void setUnitAmountEUR(final Object unitAmountEUR) {
this.unitAmountEUR = RecurlyObject.integerOrNull(unitAmountEUR);
}
public Integer getUnitAmountGBP() {
return unitAmountGBP;
}
public void setUnitAmountGBP(final Object unitAmountGBP) {
this.unitAmountGBP = RecurlyObject.integerOrNull(unitAmountGBP);
}
public Integer getUnitAmountCZK() {
return unitAmountCZK;
}
public void setUnitAmountCZK(final Object unitAmountCZK) {
this.unitAmountCZK = RecurlyObject.integerOrNull(unitAmountCZK);
}
public Integer getUnitAmountDKK() {
return unitAmountDKK;
}
public void setUnitAmountDKK(final Object unitAmountDKK) {
this.unitAmountDKK = RecurlyObject.integerOrNull(unitAmountDKK);
}
public Integer getUnitAmountHUF() {
return unitAmountHUF;
}
public void setUnitAmountHUF(final Object unitAmountHUF) {
this.unitAmountHUF = RecurlyObject.integerOrNull(unitAmountHUF);
}
public Integer getUnitAmountINR() {
return unitAmountINR;
}
public void setUnitAmountINR(final Object unitAmountINR) {
this.unitAmountINR = RecurlyObject.integerOrNull(unitAmountINR);
}
public Integer getUnitAmountNOK() {
return unitAmountNOK;
}
public void setUnitAmountNOK(final Object unitAmountNOK) {
this.unitAmountNOK = RecurlyObject.integerOrNull(unitAmountNOK);
}
public Integer getUnitAmountJPY() {
return unitAmountJPY;
}
public void setUnitAmountJPY(final Object unitAmountJPY) {
this.unitAmountJPY = RecurlyObject.integerOrNull(unitAmountJPY);
}
public Integer getUnitAmountNZD() {
return unitAmountNZD;
}
public void setUnitAmountNZD(final Object unitAmountNZD) {
this.unitAmountNZD = RecurlyObject.integerOrNull(unitAmountNZD);
}
public Integer getUnitAmountPLN() {
return unitAmountPLN;
}
public void setUnitAmountPLN(final Object unitAmountPLN) {
this.unitAmountPLN = RecurlyObject.integerOrNull(unitAmountPLN);
}
public Integer getUnitAmountSGD() {
return unitAmountSGD;
}
public void setUnitAmountSGD(final Object unitAmountSGD) {
this.unitAmountSGD = RecurlyObject.integerOrNull(unitAmountSGD);
}
public Integer getUnitAmountSEK() {
return unitAmountSEK;
}
public void setUnitAmountSEK(final Object unitAmountSEK) {
this.unitAmountSEK = RecurlyObject.integerOrNull(unitAmountSEK);
}
public Integer getUnitAmountCHF() {
return unitAmountCHF;
}
public void setUnitAmountCHF(final Object unitAmountCHF) {
this.unitAmountCHF = RecurlyObject.integerOrNull(unitAmountCHF);
}
public Integer getUnitAmountZAR() {
return unitAmountZAR;
}
public void setUnitAmountZAR(final Object unitAmountZAR) {
this.unitAmountZAR = RecurlyObject.integerOrNull(unitAmountZAR);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("RecurlyUnitCurrency");
sb.append("{unitAmountUSD=").append(unitAmountUSD);
sb.append(", unitAmountAUD=").append(unitAmountAUD);
sb.append(", unitAmountCAD=").append(unitAmountCAD);
sb.append(", unitAmountEUR=").append(unitAmountEUR);
sb.append(", unitAmountGBP=").append(unitAmountGBP);
sb.append(", unitAmountCZK=").append(unitAmountCZK);
sb.append(", unitAmountDKK=").append(unitAmountDKK);
sb.append(", unitAmountHUF=").append(unitAmountHUF);
sb.append(", unitAmountNOK=").append(unitAmountNOK);
sb.append(", unitAmountNZD=").append(unitAmountNZD);
sb.append(", unitAmountPLN=").append(unitAmountPLN);
sb.append(", unitAmountSGD=").append(unitAmountSGD);
sb.append(", unitAmountSEK=").append(unitAmountSEK);
sb.append(", unitAmountCHF=").append(unitAmountCHF);
sb.append(", unitAmountZAR=").append(unitAmountZAR);
sb.append(", unitAmountJPY=").append(unitAmountJPY);
sb.append(", unitAmountINR=").append(unitAmountINR);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final RecurlyUnitCurrency that = (RecurlyUnitCurrency) o;
if (unitAmountAUD != null ? !unitAmountAUD.equals(that.unitAmountAUD) : that.unitAmountAUD != null) {
return false;
}
if (unitAmountCAD != null ? !unitAmountCAD.equals(that.unitAmountCAD) : that.unitAmountCAD != null) {
return false;
}
if (unitAmountCHF != null ? !unitAmountCHF.equals(that.unitAmountCHF) : that.unitAmountCHF != null) {
return false;
}
if (unitAmountCZK != null ? !unitAmountCZK.equals(that.unitAmountCZK) : that.unitAmountCZK != null) {
return false;
}
if (unitAmountDKK != null ? !unitAmountDKK.equals(that.unitAmountDKK) : that.unitAmountDKK != null) {
return false;
}
if (unitAmountEUR != null ? !unitAmountEUR.equals(that.unitAmountEUR) : that.unitAmountEUR != null) {
return false;
}
if (unitAmountGBP != null ? !unitAmountGBP.equals(that.unitAmountGBP) : that.unitAmountGBP != null) {
return false;
}
if (unitAmountHUF != null ? !unitAmountHUF.equals(that.unitAmountHUF) : that.unitAmountHUF != null) {
return false;
}
if (unitAmountNOK != null ? !unitAmountNOK.equals(that.unitAmountNOK) : that.unitAmountNOK != null) {
return false;
}
if (unitAmountNZD != null ? !unitAmountNZD.equals(that.unitAmountNZD) : that.unitAmountNZD != null) {
return false;
}
if (unitAmountPLN != null ? !unitAmountPLN.equals(that.unitAmountPLN) : that.unitAmountPLN != null) {
return false;
}
if (unitAmountSEK != null ? !unitAmountSEK.equals(that.unitAmountSEK) : that.unitAmountSEK != null) {
return false;
}
if (unitAmountSGD != null ? !unitAmountSGD.equals(that.unitAmountSGD) : that.unitAmountSGD != null) {
return false;
}
if (unitAmountUSD != null ? !unitAmountUSD.equals(that.unitAmountUSD) : that.unitAmountUSD != null) {
return false;
}
if (unitAmountZAR != null ? !unitAmountZAR.equals(that.unitAmountZAR) : that.unitAmountZAR != null) {
return false;
}
if (unitAmountJPY != null ? !unitAmountJPY.equals(that.unitAmountJPY) : that.unitAmountJPY != null) {
return false;
}
if (unitAmountINR != null ? !unitAmountINR.equals(that.unitAmountINR) : that.unitAmountINR != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
return Objects.hashCode(
unitAmountUSD,
unitAmountCAD,
unitAmountAUD,
unitAmountEUR,
unitAmountGBP,
unitAmountCZK,
unitAmountDKK,
unitAmountHUF,
unitAmountNOK,
unitAmountNZD,
unitAmountPLN,
unitAmountSGD,
unitAmountSEK,
unitAmountCHF,
unitAmountZAR,
unitAmountJPY,
unitAmountINR
);
}
}
|
3e189378fd3ad7334bae76a4ef0f6523b0aeba7a | 1,728 | java | Java | src/main/java/fr/ritaly/dungeonmaster/actuator/HasActuators.java | laurentd75/yadmjc | 70f23697bf6060ae2dceccbd0bc9ac92b6c6d29f | [
"Apache-2.0"
] | 4 | 2016-11-24T16:25:43.000Z | 2019-04-05T06:57:14.000Z | src/main/java/fr/ritaly/dungeonmaster/actuator/HasActuators.java | laurentd75/yadmjc | 70f23697bf6060ae2dceccbd0bc9ac92b6c6d29f | [
"Apache-2.0"
] | 1 | 2020-11-21T14:58:26.000Z | 2020-11-22T13:08:56.000Z | src/main/java/fr/ritaly/dungeonmaster/actuator/HasActuators.java | laurentd75/yadmjc | 70f23697bf6060ae2dceccbd0bc9ac92b6c6d29f | [
"Apache-2.0"
] | 6 | 2017-01-14T20:36:50.000Z | 2021-04-04T16:41:36.000Z | 34.039216 | 73 | 0.714286 | 10,449 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package fr.ritaly.dungeonmaster.actuator;
/**
* An object which handles an {@link Actuator} per trigger type.
*
* @author <a href="mailto:lyhxr@example.com">Francois RITALY</a>
*/
public interface HasActuators {
/**
* Returnt the {@link Actuator} mapped to the given trigger type.
*
* @param triggerType
* a {@link TriggerType}. Can't be null.
* @return an {@link Actuator} or null if none is mapped to the given
* trigger type.
*/
public Actuator getActuator(TriggerType triggerType);
/**
* Sets the {@link Actuator} mapped to the given trigger type.
*
* @param triggerType
* an {@link TriggerType}.
* @param actuator
* an {@link Actuator}.
*/
public void setActuator(TriggerType triggerType, Actuator actuator);
public void addActuator(TriggerType triggerType, Actuator actuator);
public void clearActuator(TriggerType triggerType);
} |
3e18940fd1e5e82ba34372d60a9e351acd1ea644 | 1,194 | java | Java | casadocodigo/src/main/java/br/com/casadocodigo/controllers/EstadoController.java | HennanGadelha/orange-talents-05-template-casa-do-codigo | 86fe4078513ff9b1e4b0ec87a5fe829e409bdbe0 | [
"Apache-2.0"
] | null | null | null | casadocodigo/src/main/java/br/com/casadocodigo/controllers/EstadoController.java | HennanGadelha/orange-talents-05-template-casa-do-codigo | 86fe4078513ff9b1e4b0ec87a5fe829e409bdbe0 | [
"Apache-2.0"
] | null | null | null | casadocodigo/src/main/java/br/com/casadocodigo/controllers/EstadoController.java | HennanGadelha/orange-talents-05-template-casa-do-codigo | 86fe4078513ff9b1e4b0ec87a5fe829e409bdbe0 | [
"Apache-2.0"
] | null | null | null | 27.767442 | 92 | 0.832496 | 10,450 | package br.com.casadocodigo.controllers;
import br.com.casadocodigo.config.validacoes.ValidacaoEstadoPorPais;
import br.com.casadocodigo.dtos.dtosRequest.EstadoDto;
import br.com.casadocodigo.models.Estado;
import br.com.casadocodigo.repositories.EstadoRepository;
import br.com.casadocodigo.repositories.PaisRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RestController
@RequestMapping("/estados")
public class EstadoController {
@Autowired
EstadoRepository estadoRepository;
@Autowired
PaisRepository paisRepository;
@Autowired
ValidacaoEstadoPorPais validacaoEstadoPorPais;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addValidators(validacaoEstadoPorPais);
}
@PostMapping
public ResponseEntity<EstadoDto> cadastrarEstado(@RequestBody @Valid EstadoDto estadoDto) {
Estado estado = estadoDto.converterEstadoDtoParaEstado(estadoDto, paisRepository);
estadoRepository.save(estado);
return ResponseEntity.ok().body(estadoDto);
}
}
|
3e1894efcc536c067edb8bac882b9667b8d64bea | 505 | java | Java | Collection/src/linkedlist/linkedlist_search.java | engineerscodes/JavaWorkSpaceHUB | 576fc0c0417c33948110d408ce0fd010706abbf3 | [
"MIT"
] | 4 | 2020-09-02T16:13:58.000Z | 2022-02-01T00:05:08.000Z | Collection/src/linkedlist/linkedlist_search.java | engineerscodes/JavaWorkSpaceHUB | 576fc0c0417c33948110d408ce0fd010706abbf3 | [
"MIT"
] | null | null | null | Collection/src/linkedlist/linkedlist_search.java | engineerscodes/JavaWorkSpaceHUB | 576fc0c0417c33948110d408ce0fd010706abbf3 | [
"MIT"
] | 5 | 2020-09-05T11:51:47.000Z | 2021-10-01T07:23:41.000Z | 16.290323 | 52 | 0.657426 | 10,451 | /**
*
*/
package linkedlist;
import java.util.*;
/**
* @author M.NAVEEN
RANDOM CODER'S
*
*/
public class linkedlist_search
{
static linkedlist l;
static Scanner nav;
public linkedlist_search()
{
l=new linkedlist();
nav=new Scanner(System.in);
}
public static void main(String[] args)
{
linkedlist_search ls=new linkedlist_search();
l.add();
System.out.println("Enter the element in search");
int ele=nav.nextInt();
System.out.println(l.d.contains(ele));
}
}
|
3e18951e37234d781beef110a6a53a9fe05c3fab | 1,703 | java | Java | spartanizer-plugin/src/main/java/il/org/spartan/spartanizer/research/nanos/CachingPattern.java | SpartanRefactoring/spartanizer | 158ab742d27dca1b42edb0b9858ae8753f4b22d1 | [
"MIT"
] | 76 | 2016-09-20T00:30:39.000Z | 2017-05-02T13:09:24.000Z | spartanizer-plugin/src/main/java/il/org/spartan/spartanizer/research/nanos/CachingPattern.java | mittelman/spartan-refactoring | 158ab742d27dca1b42edb0b9858ae8753f4b22d1 | [
"MIT"
] | 1,190 | 2016-09-06T21:23:25.000Z | 2017-05-01T20:48:00.000Z | spartanizer-plugin/src/main/java/il/org/spartan/spartanizer/research/nanos/CachingPattern.java | SpartanRefactoring/spartan-refactoring | 158ab742d27dca1b42edb0b9858ae8753f4b22d1 | [
"MIT"
] | 61 | 2016-09-07T07:13:02.000Z | 2017-01-20T11:59:26.000Z | 37.021739 | 109 | 0.741632 | 10,452 | package il.org.spartan.spartanizer.research.nanos;
import static il.org.spartan.spartanizer.ast.navigate.step.parent;
import static il.org.spartan.spartanizer.research.TipperFactory.statementsPattern;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.IfStatement;
import il.org.spartan.spartanizer.ast.safety.az;
import il.org.spartan.spartanizer.research.UserDefinedTipper;
import il.org.spartan.spartanizer.research.nanos.common.NanoPatternTipper;
import il.org.spartan.spartanizer.tipping.Tip;
/** A field which is initialized only on first reference
* @author Ori Marcovitch
* @since Jan 8, 2017 */
public final class CachingPattern extends NanoPatternTipper<IfStatement> {
private static final long serialVersionUID = 0x6135435DBF185EC8L;
private static final UserDefinedTipper<Block> tipper = //
statementsPattern("if($X1 == null)$X1 = $X2;return $X1;", //
"return $X1!=null?$X1:($X1=$X2);", //
"Caching pattern: rewrite as return of ternary");
@Override public boolean canTip(final IfStatement x) {
return tipper.check(az.block(parent(x)));
}
@Override public Tip pattern(final IfStatement $) {
return tipper.tip(az.block(parent($)));
}
@Override public Category category() {
return Category.Field;
}
@Override public String description() {
return "A field which its value is defined by an expression which is evaluated only on the first access";
}
@Override public String technicalName() {
return "IfX₁IsNullInitializeWithX₂ReturnX₁";
}
@Override public String example() {
return tipper.pattern();
}
@Override public String symbolycReplacement() {
return tipper.replacement();
}
}
|
3e1896421affadb8a9dd30354b5632ac918c19f1 | 3,605 | java | Java | OpenAMASE/src/Core/avtas/data/DelimetedReader.java | afrl-rq/OpenAMASE | f5d0c856ea01335e96ac98157cfd0777fa00195f | [
"NASA-1.3"
] | 23 | 2018-01-12T02:22:50.000Z | 2022-01-27T18:06:01.000Z | OpenAMASE/src/Core/avtas/data/DelimetedReader.java | sahabi/OpenAMASE | b50f5a71265a1f1644c49cce2161b40b108c65fe | [
"NASA-1.3"
] | 7 | 2017-06-23T16:26:16.000Z | 2021-05-27T16:49:08.000Z | OpenAMASE/src/Core/avtas/data/DelimetedReader.java | sahabi/OpenAMASE | b50f5a71265a1f1644c49cce2161b40b108c65fe | [
"NASA-1.3"
] | 32 | 2017-07-10T21:18:50.000Z | 2021-11-22T14:38:31.000Z | 31.902655 | 105 | 0.568932 | 10,453 | // ===============================================================================
// Authors: AFRL/RQQD
// Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division
//
// Copyright (c) 2017 Government of the United State of America, as represented by
// the Secretary of the Air Force. No copyright is claimed in the United States under
// Title 17, U.S. Code. All Other Rights Reserved.
// ===============================================================================
package avtas.data;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Implements a File reader that automatically handles files delimeters
* @author AFRL/RQQD
*/
public class DelimetedReader {
BufferedReader reader = null;
String delimeter = "\t";
File file = null;
public DelimetedReader(File f, String delimeter) {
try {
this.file = f;
this.delimeter = delimeter;
this.reader = new BufferedReader(new FileReader(file));
} catch (IOException ex) {
Logger.getLogger(DelimetedReader.class.getName()).log(Level.SEVERE, null, ex);
}
}
/** Attempts to read the requested line. If the line is beyond the end of the file, then
* this returns null. Note: To make sequential reads on the file, it is more efficient to
* reset the reader and call readNextLine().
*
* This does not affect the position of the default reader (the one used by readNextLine())
*
* @param row the row number to read (starting with zero)
* @return an array of strings representing the values at the requested row.
*/
public String[] readLine(int row) {
try {
BufferedReader tmpReader = new BufferedReader(new FileReader(file));
for (int i = 0; i < row; i++) {
tmpReader.readLine();
}
String rowVal = tmpReader.readLine();
return rowVal.split(delimeter);
} catch (IOException ex) {
Logger.getLogger(DelimetedReader.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
/** Attempts to read the next line of data. If the reader is at the end of the file, this
* returns null.
* @return an array of strings representing the data read
*/
public String[] readNextLine() {
try {
String line = reader.readLine();
if (line == null ) {
return null;
}
return line.split(delimeter);
} catch (IOException ex) {
Logger.getLogger(DelimetedReader.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
/** Sets the reader to the requested row */
public void setReader(int row) {
try {
reader.reset();
for (int i = 0; i < row; i++) {
reader.readLine();
}
} catch (IOException ex) {
Logger.getLogger(DelimetedReader.class.getName()).log(Level.SEVERE, null, ex);
}
}
/** Cleans up resources */
public void close() {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(DelimetedReader.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/* Distribution A. Approved for public release.
* Case: #88ABW-2015-4601. Date: 24 Sep 2015. */ |
3e189667e30fb2ccdd740e822e21720475e817b0 | 4,983 | java | Java | shardingsphere-sql-parser/shardingsphere-sql-parser-binder/src/main/java/org/apache/shardingsphere/sql/parser/binder/metadata/column/ColumnMetaDataLoader.java | forachange/sharding-jdbc | d44ee3ba864b001bf4f02f6a13bcad918f7d0ec2 | [
"Apache-2.0"
] | 2 | 2020-07-17T09:46:21.000Z | 2020-07-17T09:46:29.000Z | shardingsphere-sql-parser/shardingsphere-sql-parser-binder/src/main/java/org/apache/shardingsphere/sql/parser/binder/metadata/column/ColumnMetaDataLoader.java | forachange/sharding-jdbc | d44ee3ba864b001bf4f02f6a13bcad918f7d0ec2 | [
"Apache-2.0"
] | null | null | null | shardingsphere-sql-parser/shardingsphere-sql-parser-binder/src/main/java/org/apache/shardingsphere/sql/parser/binder/metadata/column/ColumnMetaDataLoader.java | forachange/sharding-jdbc | d44ee3ba864b001bf4f02f6a13bcad918f7d0ec2 | [
"Apache-2.0"
] | 1 | 2020-12-07T07:55:06.000Z | 2020-12-07T07:55:06.000Z | 44.097345 | 161 | 0.671884 | 10,454 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.sql.parser.binder.metadata.column;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import org.apache.shardingsphere.sql.parser.binder.metadata.util.JdbcUtil;
/**
* Column meta data loader.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class ColumnMetaDataLoader {
private static final String COLUMN_NAME = "COLUMN_NAME";
private static final String DATA_TYPE = "DATA_TYPE";
private static final String TYPE_NAME = "TYPE_NAME";
/**
* Load column meta data list.
*
* @param connection connection
* @param table table name
* @param databaseType database type
* @return column meta data list
* @throws SQLException SQL exception
*/
public static Collection<ColumnMetaData> load(final Connection connection, final String table, final String databaseType) throws SQLException {
Collection<ColumnMetaData> result = new LinkedList<>();
Collection<String> primaryKeys = loadPrimaryKeys(connection, table, databaseType);
List<String> columnNames = new ArrayList<>();
List<Integer> columnTypes = new ArrayList<>();
List<String> columnTypeNames = new ArrayList<>();
List<Boolean> isPrimaryKeys = new ArrayList<>();
List<Boolean> isCaseSensitives = new ArrayList<>();
try (ResultSet resultSet = connection.getMetaData().getColumns(connection.getCatalog(), JdbcUtil.getSchema(connection, databaseType), table, "%")) {
while (resultSet.next()) {
String columnName = resultSet.getString(COLUMN_NAME);
columnTypes.add(resultSet.getInt(DATA_TYPE));
columnTypeNames.add(resultSet.getString(TYPE_NAME));
isPrimaryKeys.add(primaryKeys.contains(columnName));
columnNames.add(columnName);
}
}
try (ResultSet resultSet = connection.createStatement().executeQuery(generateEmptyResultSQL(table, databaseType))) {
for (String each : columnNames) {
isCaseSensitives.add(resultSet.getMetaData().isCaseSensitive(resultSet.findColumn(each)));
}
}
for (int i = 0; i < columnNames.size(); i++) {
// TODO load auto generated from database meta data
result.add(new ColumnMetaData(columnNames.get(i), columnTypes.get(i), columnTypeNames.get(i), isPrimaryKeys.get(i), false, isCaseSensitives.get(i)));
}
return result;
}
private static String generateEmptyResultSQL(final String table, final String databaseType) {
// TODO consider add a getDialectDelimeter() interface in parse module
String delimiterLeft;
String delimiterRight;
if ("MySQL".equals(databaseType) || "MariaDB".equals(databaseType)) {
delimiterLeft = "`";
delimiterRight = "`";
} else if ("Oracle".equals(databaseType) || "PostgreSQL".equals(databaseType) || "H2".equals(databaseType) || "SQL92".equals(databaseType)) {
delimiterLeft = "\"";
delimiterRight = "\"";
} else if ("SQLServer".equals(databaseType)) {
delimiterLeft = "[";
delimiterRight = "]";
} else {
delimiterLeft = "";
delimiterRight = "";
}
return "SELECT * FROM " + delimiterLeft + table + delimiterRight + " WHERE 1 != 1";
}
private static Collection<String> loadPrimaryKeys(final Connection connection, final String table, final String databaseType) throws SQLException {
Collection<String> result = new HashSet<>();
try (ResultSet resultSet = connection.getMetaData().getPrimaryKeys(connection.getCatalog(), JdbcUtil.getSchema(connection, databaseType), table)) {
while (resultSet.next()) {
result.add(resultSet.getString(COLUMN_NAME));
}
}
return result;
}
}
|
3e18967a9adbccc2dac4030f93e70dbd8b347f89 | 4,239 | java | Java | src/main/java/com/github/nosan/embedded/cassandra/cql/CqlDataSet.java | eugenediatlov/embedded-cassandra | 0ecb21ac27a07be49ff4b78fe947671337a6f4ff | [
"Apache-2.0"
] | 64 | 2018-06-26T14:38:54.000Z | 2022-03-17T02:09:57.000Z | src/main/java/com/github/nosan/embedded/cassandra/cql/CqlDataSet.java | eugenediatlov/embedded-cassandra | 0ecb21ac27a07be49ff4b78fe947671337a6f4ff | [
"Apache-2.0"
] | 133 | 2018-07-09T13:47:28.000Z | 2022-03-31T11:52:34.000Z | src/main/java/com/github/nosan/embedded/cassandra/cql/CqlDataSet.java | eugenediatlov/embedded-cassandra | 0ecb21ac27a07be49ff4b78fe947671337a6f4ff | [
"Apache-2.0"
] | 15 | 2018-07-23T12:55:31.000Z | 2022-03-14T16:48:22.000Z | 30.717391 | 85 | 0.72352 | 10,455 | /*
* Copyright 2020-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.github.nosan.embedded.cassandra.cql;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import com.github.nosan.embedded.cassandra.commons.ClassPathResource;
import com.github.nosan.embedded.cassandra.commons.Resource;
/**
* {@link CqlDataSet} represents the set of {@link CqlScript}.
*
* @author Dmytro Nosan
* @see CqlScript
* @see DefaultCqlDataSet
* @since 4.0.1
*/
@FunctionalInterface
public interface CqlDataSet extends CqlScript {
/**
* Creates {@link CqlDataSet} with the specified resource names and default charset.
*
* @param names the resource names
* @return a new {@link CqlDataSet}
*/
static CqlDataSet ofClassPaths(String... names) {
return ofClassPaths(Charset.defaultCharset(), names);
}
/**
* Creates {@link CqlDataSet} with the specified resource names and charset.
*
* @param names the resource names
* @param charset the encoding to use
* @return a new {@link CqlDataSet}
*/
static CqlDataSet ofClassPaths(Charset charset, String... names) {
Objects.requireNonNull(charset, "Charset must not be null");
Objects.requireNonNull(names, "Classpath resources must not be null");
return new DefaultCqlDataSet(Arrays.stream(names)
.map(ClassPathResource::new)
.map(resource -> new ResourceCqlScript(resource, charset))
.collect(Collectors.toList()));
}
/**
* Creates {@link CqlDataSet} with the specified resources and default charset.
*
* @param resources the resources to use
* @return a new {@link CqlDataSet}
*/
static CqlDataSet ofResources(Resource... resources) {
return ofResources(Charset.defaultCharset(), resources);
}
/**
* Creates {@link CqlDataSet} with the specified resources and charset.
*
* @param resources the resources to use
* @param charset the encoding to use
* @return a new {@link CqlDataSet}
*/
static CqlDataSet ofResources(Charset charset, Resource... resources) {
Objects.requireNonNull(charset, "Charset must not be null");
Objects.requireNonNull(resources, "Resources must not be null");
return new DefaultCqlDataSet(Arrays.stream(resources)
.map(resource -> new ResourceCqlScript(resource, charset))
.collect(Collectors.toList()));
}
/**
* Creates {@link CqlDataSet} with the specified CQL scripts.
*
* @param scripts the scripts to use
* @return a new {@link CqlDataSet}
*/
static CqlDataSet ofScripts(CqlScript... scripts) {
Objects.requireNonNull(scripts, "Cql Scripts must not be null");
List<CqlScript> result = new ArrayList<>();
for (CqlScript script : scripts) {
if (script instanceof CqlDataSet) {
result.addAll(((CqlDataSet) script).getScripts());
}
else {
result.add(script);
}
}
return new DefaultCqlDataSet(result);
}
/**
* Performs the given {@code callback} for each script of the {@link CqlDataSet}.
*
* @param callback The action to be performed for each script
*/
default void forEachScript(Consumer<? super CqlScript> callback) {
Objects.requireNonNull(callback, "Callback must not be null");
getScripts().forEach(callback);
}
@Override
default List<String> getStatements() {
List<String> statements = new ArrayList<>();
forEachScript(script -> statements.addAll(script.getStatements()));
return Collections.unmodifiableList(statements);
}
/**
* Gets {@code CQL} scripts.
*
* @return {@code CQL} scripts (never null)
*/
List<? extends CqlScript> getScripts();
}
|
3e18972cabe6a2cd5175f767043d8e32d2d96684 | 1,007 | java | Java | 1.JavaSyntax/src/com/javarush/task/pro/task09/task0914/Solution.java | rfedorenkov/JavaRushTasks | 1ab103fa3bf50a0bd955b5b71bac5131969ef738 | [
"MIT"
] | null | null | null | 1.JavaSyntax/src/com/javarush/task/pro/task09/task0914/Solution.java | rfedorenkov/JavaRushTasks | 1ab103fa3bf50a0bd955b5b71bac5131969ef738 | [
"MIT"
] | null | null | null | 1.JavaSyntax/src/com/javarush/task/pro/task09/task0914/Solution.java | rfedorenkov/JavaRushTasks | 1ab103fa3bf50a0bd955b5b71bac5131969ef738 | [
"MIT"
] | null | null | null | 29.617647 | 104 | 0.67428 | 10,456 | package com.javarush.task.pro.task09.task0914;
/**
* Обновление пути
* Реализуй метод changePath(String, String) так, чтобы он заменял версию jdk в пути,
* полученном первым параметром метода, на версию, полученную вторым параметром, и возвращал новый путь.
* Версия jdk расположена между третьим и четвертым "/".
*
* Пример:
* путь — "/usr/java/jdk1.8/bin"
* версия jdk — "jdk-13"
*
* Метод changePath(путь, версия jdk) должен вернуть путь — "/usr/java/jdk-13/bin".
* Метод main() не принимает участия в тестировании.
*
*
* Требования:
* 1. Нужно, чтобы метод changePath(String, String) был реализован согласно условию.
*/
public class Solution {
public static void main(String[] args) {
String path = "/usr/java/jdk1.8/bin";
String jdk13 = "jdk-13";
System.out.println(changePath(path, jdk13));
}
public static String changePath(String path, String jdk) {
String[] split = path.split("/");
return path.replace(split[3], jdk);
}
}
|
3e18975467fe309fc119cc718cfd165c09dd06db | 6,750 | java | Java | infinispan/core/src/test/java/org/infinispan/test/fwk/UnitTestTestNGListener.java | nmldiegues/stibt | 1ee662b7d4ed1f80e6092c22e235a3c994d1d393 | [
"Apache-2.0"
] | 4 | 2015-01-28T20:46:14.000Z | 2021-11-16T06:45:27.000Z | infinispan/core/src/test/java/org/infinispan/test/fwk/UnitTestTestNGListener.java | cloudtm/sti-bt | ef80d454627cc376d35d434a48088c311bdf3408 | [
"FTL"
] | 5 | 2022-01-21T23:13:01.000Z | 2022-02-09T23:01:28.000Z | infinispan/core/src/test/java/org/infinispan/test/fwk/UnitTestTestNGListener.java | cloudtm/sti-bt | ef80d454627cc376d35d434a48088c311bdf3408 | [
"FTL"
] | 2 | 2015-05-29T00:07:29.000Z | 2019-05-22T17:52:45.000Z | 40.22619 | 150 | 0.684818 | 10,457 | /*
* JBoss, Home of Professional Open Source
* Copyright 2010 Red Hat Inc. and/or its affiliates and other
* contributors as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a full listing of
* individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.infinispan.test.fwk;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.IClass;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author kenaa@example.com
* @author kenaa@example.com
*/
public class UnitTestTestNGListener implements ITestListener, IInvokedMethodListener {
/**
* Holds test classes actually running in all threads.
*/
private ThreadLocal<IClass> threadTestClass = new ThreadLocal<IClass>();
private static final Log log = LogFactory.getLog(UnitTestTestNGListener.class);
private AtomicInteger failed = new AtomicInteger(0);
private AtomicInteger succeeded = new AtomicInteger(0);
private AtomicInteger skipped = new AtomicInteger(0);
private AtomicBoolean oomHandled = new AtomicBoolean();
public void onTestStart(ITestResult res) {
log.info("Starting test " + getTestDesc(res));
addOomLoggingSupport();
threadTestClass.set(res.getTestClass());
}
private void addOomLoggingSupport() {
final Thread.UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(final Thread t, final Throwable e) {
try {
// we need to ensure we only handle first OOM occurrence (multiple threads could see one) to avoid duplicated thread dumps
if (e instanceof OutOfMemoryError && oomHandled.compareAndSet(false, true)) {
printAllTheThreadsInTheJvm();
}
} finally {
if (oldHandler != null) {
// invoke the old handler if any
oldHandler.uncaughtException(t, e);
}
}
}
});
}
synchronized public void onTestSuccess(ITestResult arg0) {
String message = "Test " + getTestDesc(arg0) + " succeeded.";
System.out.println(getThreadId() + ' ' + message);
log.info(message);
succeeded.incrementAndGet();
printStatus();
}
synchronized public void onTestFailure(ITestResult arg0) {
String message = "Test " + getTestDesc(arg0) + " failed.";
System.out.println(getThreadId() + ' ' + message);
log.error(message, arg0.getThrowable());
failed.incrementAndGet();
printStatus();
}
synchronized public void onTestSkipped(ITestResult arg0) {
String message = "Test " + getTestDesc(arg0) + " skipped.";
System.out.println(getThreadId() + ' ' + message);
log.error(message, arg0.getThrowable());
skipped.incrementAndGet();
printStatus();
}
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
}
public void onStart(ITestContext arg0) {
String fullName = arg0.getName();
String simpleName = fullName.substring(fullName.lastIndexOf('.') + 1);
Class testClass = arg0.getCurrentXmlTest().getXmlClasses().get(0).getSupportClass();
boolean isAbstract = Modifier.isAbstract(testClass.getModifiers());
if (!isAbstract && !simpleName.equals(testClass.getSimpleName())) {
log.warnf("Wrong test name %s for class %s", simpleName, testClass.getSimpleName());
}
TestCacheManagerFactory.testStarted(testClass.getSimpleName(), testClass.getName());
}
public void onFinish(ITestContext arg0) {
Class testClass = arg0.getCurrentXmlTest().getXmlClasses().get(0).getSupportClass();
TestCacheManagerFactory.testFinished(testClass.getSimpleName());
}
private String getThreadId() {
return "[" + Thread.currentThread().getName() + "]";
}
private String getTestDesc(ITestResult res) {
return res.getMethod().getMethodName() + "(" + res.getTestClass().getName() + ")";
}
private void printStatus() {
String message = "Test suite progress: tests succeeded: " + succeeded.get() + ", failed: " + failed.get() + ", skipped: " + skipped.get() + ".";
System.out.println(message);
log.info(message);
}
@Override
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
}
@Override
public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
if (testResult.getThrowable() != null && method.isConfigurationMethod()) {
String message = String.format("Configuration method %s threw an exception", getTestDesc(testResult));
System.out.println(message);
log.error(message, testResult.getThrowable());
}
}
//todo [anistor] this approach can result in more OOM. maybe it's wiser to remove the whole thing and rely on -XX:+HeapDumpOnOutOfMemoryError
private void printAllTheThreadsInTheJvm() {
if (log.isTraceEnabled()) {
Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces();
log.tracef("Dumping all %s threads in the system.", allStackTraces.size());
for (Map.Entry<Thread, StackTraceElement[]> s : allStackTraces.entrySet()) {
StringBuilder sb = new StringBuilder();
sb.append("Thread: ").append(s.getKey().getName()).append(". Stack trace:\n");
for (StackTraceElement ste: s.getValue()) {
sb.append(" ").append(ste.toString()).append("\n");
}
log.trace(sb.toString());
}
}
}
}
|
3e1897f383cd45eb4ac57df475e8cbe72bad8c0f | 2,340 | java | Java | shout/src/instrumentTest/java/org/whispercomm/shout/id/KeyStorageImplTest.java | jackhe-umich/Shout-revised | 603f98c1a0c4a30136e09976bc6f3df785b26424 | [
"Apache-2.0"
] | 2 | 2018-11-11T01:06:55.000Z | 2020-05-30T06:44:04.000Z | shout/src/instrumentTest/java/org/whispercomm/shout/id/KeyStorageImplTest.java | jackhe-umich/Shout-revised | 603f98c1a0c4a30136e09976bc6f3df785b26424 | [
"Apache-2.0"
] | null | null | null | shout/src/instrumentTest/java/org/whispercomm/shout/id/KeyStorageImplTest.java | jackhe-umich/Shout-revised | 603f98c1a0c4a30136e09976bc6f3df785b26424 | [
"Apache-2.0"
] | 2 | 2018-11-11T01:07:00.000Z | 2019-10-30T22:26:05.000Z | 24.375 | 68 | 0.741453 | 10,458 |
package org.whispercomm.shout.id;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.whispercomm.shout.crypto.ECKeyPair;
import org.whispercomm.shout.crypto.KeyGenerator;
import org.whispercomm.shout.test.ShoutTestRunner;
import android.app.Activity;
import android.content.Context;
@RunWith(ShoutTestRunner.class)
public class KeyStorageImplTest {
private static final String USER_INIT_FAIL = "User was initiated";
private KeyStorage keyStore;
private Context context;
private String username;
@Before
public void setUp() {
this.context = new Activity();
this.keyStore = new KeyStorageSharedPrefs(context);
this.username = "Day9";
}
@After
public void takeDown() {
this.keyStore = null;
this.username = null;
this.context = null;
}
@Test
public void testInitEmptyOnCreate() {
assertTrue(keyStore.isEmpty());
}
@Test
public void testCannotReadUnsetUser() {
try {
keyStore.readKeyPair();
} catch (UserNotInitiatedException e) {
try {
keyStore.readUsername();
} catch (UserNotInitiatedException e1) {
return;
}
fail("Did not throw exception on read unset username");
}
fail("Did not throw exception on read unset KeyPair");
}
@Test
public void testReadWriteKeyPair() {
try {
ECKeyPair keyPair = new KeyGenerator().generateKeyPair();
boolean status = keyStore.writeMe(username, keyPair);
assertTrue(status);
assertFalse(keyStore.isEmpty());
ECKeyPair fromStore;
fromStore = keyStore.readKeyPair();
assertEquals(keyPair.getPublicKey(), fromStore.getPublicKey());
assertEquals(keyPair.getPrivateKey(), fromStore.getPrivateKey());
} catch (UserNotInitiatedException e) {
e.printStackTrace();
fail(USER_INIT_FAIL);
}
}
@Test
public void testReadWriteUsername() {
ECKeyPair keyPair = new KeyGenerator().generateKeyPair();
boolean status = keyStore.writeMe(username, keyPair);
assertTrue(status);
assertFalse(keyStore.isEmpty());
try {
assertEquals(keyStore.readUsername(), username);
} catch (UserNotInitiatedException e) {
e.printStackTrace();
fail(USER_INIT_FAIL);
}
}
}
|
3e18989166d62b34fad8f3db3539859c1fca7b7d | 3,851 | java | Java | java/java.source.base/test/unit/src/org/netbeans/modules/java/source/transform/Transformer.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,056 | 2019-04-25T20:00:35.000Z | 2022-03-30T04:46:14.000Z | java/java.source.base/test/unit/src/org/netbeans/modules/java/source/transform/Transformer.java | Marc382/netbeans | 4bee741d24a3fdb05baf135de5e11a7cd95bd64e | [
"Apache-2.0"
] | 1,846 | 2019-04-25T20:50:05.000Z | 2022-03-31T23:40:41.000Z | java/java.source.base/test/unit/src/org/netbeans/modules/java/source/transform/Transformer.java | Marc382/netbeans | 4bee741d24a3fdb05baf135de5e11a7cd95bd64e | [
"Apache-2.0"
] | 550 | 2019-04-25T20:04:33.000Z | 2022-03-25T17:43:01.000Z | 34.079646 | 95 | 0.712802 | 10,459 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.java.source.transform;
import org.netbeans.modules.java.source.query.CommentHandler;
import org.openide.util.NbBundle;
import com.sun.source.tree.*;
import org.netbeans.api.java.source.support.ErrorAwareTreeScanner;
import com.sun.tools.javac.model.JavacTypes;
import com.sun.tools.javac.util.Context;
import java.util.List;
import java.util.logging.*;
import javax.lang.model.util.Types;
import org.netbeans.api.java.source.TreeMaker;
import org.netbeans.api.java.source.WorkingCopy;
import org.netbeans.modules.java.source.builder.ASTService;
import org.netbeans.modules.java.source.builder.CommentHandlerService;
import org.netbeans.modules.java.source.builder.TreeFactory;
/**
* A Transformer is an Query that modifies the model. Model transformation
* is done by a supplied ImmutableTreeTranslator implementation. A new context
* is set upon successful completion of this Transformer.
*/
public abstract class Transformer<R, P> extends ErrorAwareTreeScanner<R,P> {
CommentHandler commentHandler;
public TreeMaker make;
protected WorkingCopy copy;
protected String refactoringDescription;
protected Types types; // used by tests
private String failureMessage;
protected ASTService model;
static final Logger logger = Logger.getLogger("org.netbeans.modules.java.source");
public void init() {
}
/**
* Initialize and associate this Query instance with the
* specified QueryEnvironment.
*/
public void attach(Context context, WorkingCopy copy) {
make = copy.getTreeMaker();
types = JavacTypes.instance(context);
commentHandler = CommentHandlerService.instance(context);
model = ASTService.instance(context);
this.copy = copy;
}
/**
* Release any instance data created during attach() invocation. This
* is necessary because the Java reflection support may cache created
* instances, preventing the session data from being garbage-collected.
*/
public void release() {
//changes.release(); // enable when async results are supported
//result.release()
make = null;
types = null;
this.copy = null;
}
public void destroy() {}
public String getRefactoringDescription() {
return refactoringDescription != null ? refactoringDescription : "Unnamed Refactoring";
}
public void setRefactoringDescription(String description) {
refactoringDescription = description;
}
public void apply(Tree t) {
t.accept(this, null);
}
String getString(String key) {
return NbBundle.getBundle(Transformer.class).getString(key); //NOI18N
}
/**
* True if no translation failures occurred.
*/
protected boolean translationSuccessful() {
return failureMessage == null;
}
public final void copyCommentTo(Tree from, Tree to) {
if (from != null && to != null) {
commentHandler.copyComments(from, to);
}
}
}
|
3e1898f0bfc7eb3d2d4710e977ba9a92c1ae52a4 | 680 | java | Java | SpringBoot-Mybatis-Audit/src/main/java/cn/z201/audit/service/impl/AuditServiceImpl.java | z201/code-example | 391591a3ff48f7c66cebec516132ea74e8178337 | [
"Unlicense"
] | null | null | null | SpringBoot-Mybatis-Audit/src/main/java/cn/z201/audit/service/impl/AuditServiceImpl.java | z201/code-example | 391591a3ff48f7c66cebec516132ea74e8178337 | [
"Unlicense"
] | 8 | 2022-01-27T02:57:11.000Z | 2022-02-07T14:13:03.000Z | SpringBoot-Mybatis-Audit/src/main/java/cn/z201/audit/service/impl/AuditServiceImpl.java | z201/code-example | 391591a3ff48f7c66cebec516132ea74e8178337 | [
"Unlicense"
] | null | null | null | 24.428571 | 62 | 0.747076 | 10,460 | package cn.z201.audit.service.impl;
import cn.z201.audit.repository.AuditRepository;
import cn.z201.audit.service.AuditServiceI;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author efpyi@example.com
**/
@Service
@Slf4j
public class AuditServiceImpl implements AuditServiceI {
private AuditRepository auditRepository;
@Autowired
public AuditServiceImpl(AuditRepository auditRepository) {
this.auditRepository = auditRepository;
}
@Override
public void test(String key) {
auditRepository.add("查看","测试方法写入","#{[0]}",key);
}
}
|
3e189901e90da17784e7a24e726782ed2a80d64e | 324 | java | Java | 10_Printf/src/Program.java | martin919191/JavaIntermedio | a5b109e771da058b46bdcafd287255c1e5118a19 | [
"MIT"
] | null | null | null | 10_Printf/src/Program.java | martin919191/JavaIntermedio | a5b109e771da058b46bdcafd287255c1e5118a19 | [
"MIT"
] | null | null | null | 10_Printf/src/Program.java | martin919191/JavaIntermedio | a5b109e771da058b46bdcafd287255c1e5118a19 | [
"MIT"
] | null | null | null | 20.25 | 84 | 0.626543 | 10,461 |
public class Program {
public static void main(String[] args) {
float f1 = 0.38134F;
float f2 = 37.9999F;
System.out.printf("El primer numero es %.2f y el segundo numero es %.2f\n",f1,f2);
String s = "texto en minuscula";
System.out.printf("%s", s);
System.out.printf("El numero es \"%.2f\"",f1);
}
}
|
3e189a37b131f4094f25da68af08efce7b155711 | 1,068 | java | Java | src/main/java/com/ichess/jvoodoo/ParameterPredicat.java | i-chess/jvoodoo | c1a2a509c98281b6322d2fe9a1133c92f9beaa28 | [
"MIT"
] | null | null | null | src/main/java/com/ichess/jvoodoo/ParameterPredicat.java | i-chess/jvoodoo | c1a2a509c98281b6322d2fe9a1133c92f9beaa28 | [
"MIT"
] | null | null | null | src/main/java/com/ichess/jvoodoo/ParameterPredicat.java | i-chess/jvoodoo | c1a2a509c98281b6322d2fe9a1133c92f9beaa28 | [
"MIT"
] | null | null | null | 28.105263 | 80 | 0.574906 | 10,462 | //==============================================================================
// Copyright (c) 2009-2014 ichess.co.il
//
//This document contains confidential information which is protected by
//copyright and is proprietary to ichess.co.il. No part
//of this document may be used, copied, disclosed, or conveyed to another
//party without prior written consent of ichess.co.il.
//==============================================================================
package com.ichess.jvoodoo;
public class ParameterPredicat extends ParameterHandle {
public static abstract class Predicat
{
public abstract void validate(Object value);
}
private Object value;
private Predicat predicat;
public ParameterPredicat(Predicat predicat)
{
this.predicat = predicat;
}
@Override
public void consume( Object actualValue )
{
value = actualValue;
predicat.validate(value);
}
@Override
public String toString() {
return value == null ? "null" : value.toString();
}
}
|
3e189a6b524797b8d108344d8531e6aa7938ad00 | 3,415 | java | Java | osc-domain/src/main/java/org/osc/core/broker/model/entities/virtualization/openstack/VM.java | lakodali/osc-core | 5f006a1a543d79695dd86485cc15a016f2ea015e | [
"Apache-2.0"
] | 46 | 2017-06-28T16:21:25.000Z | 2022-02-26T03:27:52.000Z | osc-domain/src/main/java/org/osc/core/broker/model/entities/virtualization/openstack/VM.java | lakodali/osc-core | 5f006a1a543d79695dd86485cc15a016f2ea015e | [
"Apache-2.0"
] | 216 | 2017-06-28T16:47:06.000Z | 2018-07-21T04:04:19.000Z | osc-domain/src/main/java/org/osc/core/broker/model/entities/virtualization/openstack/VM.java | lakodali/osc-core | 5f006a1a543d79695dd86485cc15a016f2ea015e | [
"Apache-2.0"
] | 30 | 2017-06-29T03:13:02.000Z | 2021-08-16T03:01:54.000Z | 26.679688 | 100 | 0.641874 | 10,463 | /*******************************************************************************
* Copyright (c) Intel Corporation
* Copyright (c) 2017
*
* 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.osc.core.broker.model.entities.virtualization.openstack;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.osc.core.broker.model.entities.BaseEntity;
import org.osc.core.broker.model.entities.virtualization.SecurityGroupMember;
import org.osc.core.broker.model.entities.virtualization.SecurityGroupMemberType;
@SuppressWarnings("serial")
@Entity
@Table(name = "VM")
public class VM extends BaseEntity implements OsProtectionEntity {
@Column(name = "region", nullable = false)
private String region;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "vm_id", nullable = false, unique = true)
private String openstackId;
@Column(name = "host")
private String host;
@OneToMany(mappedBy = "vm", fetch = FetchType.LAZY)
private Set<VMPort> ports = new HashSet<VMPort>();
@OneToMany(mappedBy = "vm", fetch = FetchType.LAZY)
private Set<SecurityGroupMember> securityGroupMembers = new HashSet<>();
public VM(String region, String vmId, String name) {
super();
this.region = region;
this.openstackId = vmId;
this.name = name;
}
VM() {
}
@Override
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getOpenstackId() {
return this.openstackId;
}
public String getHost() {
return this.host;
}
public void setHost(String host) {
this.host = host;
}
public Set<VMPort> getPorts() {
return this.ports;
}
void setPorts(Set<VMPort> ports) {
this.ports = ports;
}
public void addPort(VMPort vmPort) {
this.ports.add(vmPort);
}
public void removePort(VMPort vmPort) {
this.ports.remove(vmPort);
}
@Override
public String getRegion() {
return this.region;
}
@Override
public Set<SecurityGroupMember> getSecurityGroupMembers() {
return this.securityGroupMembers;
}
public void addSecurityGroupMember(SecurityGroupMember member) {
this.securityGroupMembers.add(member);
}
@Override
public String toString() {
return "VM [name=" + this.name + ", vmId=" + this.openstackId + ", host=" + this.host + "]";
}
@Override
public SecurityGroupMemberType getType() {
return SecurityGroupMemberType.VM;
}
}
|
3e189acdfb3aa595c5626c96c051304a3266d1df | 20,561 | java | Java | src/main/java/com/paraam/cpeagent/core/CpeActions.java | LuKePicci/tr069-simulator | 72612814329257477411a6039b83718db96d118a | [
"MIT"
] | 4 | 2019-08-07T08:19:37.000Z | 2021-08-17T06:45:59.000Z | src/main/java/com/paraam/cpeagent/core/CpeActions.java | LuKePicci/tr069-simulator | 72612814329257477411a6039b83718db96d118a | [
"MIT"
] | 2 | 2017-11-28T09:09:59.000Z | 2019-04-03T14:35:09.000Z | src/main/java/com/paraam/cpeagent/core/CpeActions.java | LuKePicci/tr069-simulator | 72612814329257477411a6039b83718db96d118a | [
"MIT"
] | 10 | 2017-06-30T22:57:31.000Z | 2021-01-26T13:38:55.000Z | 41.287149 | 129 | 0.692622 | 10,464 | package com.paraam.cpeagent.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import org.dslforum.cwmp_1_0.AccessList;
import org.dslforum.cwmp_1_0.AddObject;
import org.dslforum.cwmp_1_0.AddObjectResponse;
import org.dslforum.cwmp_1_0.Body;
import org.dslforum.cwmp_1_0.DeleteObject;
import org.dslforum.cwmp_1_0.DeleteObjectResponse;
import org.dslforum.cwmp_1_0.DeviceIdStruct;
import org.dslforum.cwmp_1_0.Download;
import org.dslforum.cwmp_1_0.DownloadResponse;
import org.dslforum.cwmp_1_0.Envelope;
import org.dslforum.cwmp_1_0.EventList;
import org.dslforum.cwmp_1_0.EventStruct;
import org.dslforum.cwmp_1_0.FactoryReset;
import org.dslforum.cwmp_1_0.FactoryResetResponse;
import org.dslforum.cwmp_1_0.GetParameterAttributes;
import org.dslforum.cwmp_1_0.GetParameterAttributesResponse;
import org.dslforum.cwmp_1_0.GetParameterNames;
import org.dslforum.cwmp_1_0.GetParameterNamesResponse;
import org.dslforum.cwmp_1_0.GetParameterValues;
import org.dslforum.cwmp_1_0.GetParameterValuesResponse;
import org.dslforum.cwmp_1_0.GetRPCMethodsResponse;
import org.dslforum.cwmp_1_0.Header;
import org.dslforum.cwmp_1_0.ID;
import org.dslforum.cwmp_1_0.Inform;
import org.dslforum.cwmp_1_0.MethodList;
import org.dslforum.cwmp_1_0.ParameterAttributeList;
import org.dslforum.cwmp_1_0.ParameterAttributeStruct;
import org.dslforum.cwmp_1_0.ParameterAttributeStruct.Notification;
import org.dslforum.cwmp_1_0.ParameterInfoList;
import org.dslforum.cwmp_1_0.ParameterInfoStruct;
import org.dslforum.cwmp_1_0.ParameterValueList;
import org.dslforum.cwmp_1_0.ParameterValueStruct;
import org.dslforum.cwmp_1_0.Reboot;
import org.dslforum.cwmp_1_0.RebootResponse;
import org.dslforum.cwmp_1_0.SetParameterAttributes;
import org.dslforum.cwmp_1_0.SetParameterAttributesStruct;
import org.dslforum.cwmp_1_0.SetParameterValues;
import org.dslforum.cwmp_1_0.SetParameterValuesResponse;
import org.dslforum.cwmp_1_0.Upload;
import org.dslforum.cwmp_1_0.UploadResponse;
public class CpeActions {
CpeDBReader confdb;
public static void main(String[] args){
System.out.println( "Starting CpeConfDB");
//def c = CpeConfDB.readFromGetMessages('testfiles/parameters_zyxel2602/')
CpeDBReader c = CpeDBReader.readFromGetMessages("D://Paraam//ACS//groovy_src//groovycpe//testfiles//parameters_zyxel2602//");
System.out.println( " Hashtable >>>>>> " + c.confs.toString());
System.out.println( " SerialNumber ----> " + ((ConfParameter)c.confs.get("Device.DeviceInfo.SerialNumber")).value);
//c.serialize("test.txt");
//System.out.println( " " + CpeDBReader.deserialize("test.txt"));
ArrayList<EventStruct> eventKeyList = new ArrayList<EventStruct>();
EventStruct eventStruct = new EventStruct();
eventStruct.setEventCode("1 BOOT");
eventKeyList.add(eventStruct);
CpeActions cpeactions = new CpeActions(c);
Envelope evn = cpeactions.doInform(eventKeyList);
String str = JibxHelper.marshalObject(evn, "cwmp_1_0");
System.out.println("" + str);
}
public CpeActions (CpeDBReader confdb) {
this.confdb = confdb;
}
public Envelope doInform(ArrayList eventKeyList) {
Inform inform = new Inform();
DeviceIdStruct deviceId = new DeviceIdStruct();
inform.setDeviceId(deviceId);
inform.setMaxEnvelopes(1);
inform.setCurrentTime(new Date());
inform.setRetryCount(0);
deviceId.setManufacturer(((ConfParameter)confdb.confs.get(confdb.props.getProperty("Manufacturer"))).value);
deviceId.setOUI(((ConfParameter) confdb.confs.get(confdb.props.getProperty("ManufacturerOUI"))).value);
deviceId.setSerialNumber(((ConfParameter)confdb.confs.get(confdb.props.getProperty("SerialNumber"))).value);
deviceId.setProductClass(((ConfParameter)confdb.confs.get(confdb.props.getProperty("ProductClass"))).value);
ParameterValueList pvlist = new ParameterValueList();
// use a mixed list of fixed and custom keys
ArrayList<String> pList = new ArrayList<String>();
pList.add(confdb.props.getProperty("HardwareVersion"));
pList.add(confdb.props.getProperty("ProvisioningCode"));
pList.add(confdb.props.getProperty("SoftwareVersion"));
pList.add(confdb.props.getProperty("SpecVersion"));
pList.add(confdb.props.getProperty("DeviceSummary"));
pList.add(confdb.props.getProperty("ConnectionRequestURL"));
pList.add(confdb.props.getProperty("ParameterKey"));
pList.add(confdb.props.getProperty("ExternalIPAddress"));
try {
pList.addAll(Arrays.asList(confdb.props.getProperty("AdditionalInformParameters").split(",")));
} catch (NullPointerException ex) {
System.out.println(" INFO: No additional parameters will be included in Inform messages");
}
ArrayList arr = new ArrayList();
for (String p: pList) {
ParameterValueStruct pvstruct = new ParameterValueStruct();
pvstruct.setName(p);
pvstruct.setValue(((ConfParameter)confdb.confs.get(p)).value);
arr.add(pvstruct);
}
pvlist.setParameterValueStruct(arr);
inform.setParameterList(pvlist);
//ArrayList<String> tlist = new ArrayList();
//tlist.add("1 BOOT");
EventList eventList = new EventList();
eventList.setEventStruct(eventKeyList);
inform.setEvent(eventList);
return inEnvelope(inform);
}
public Envelope doGetRPCMethods() {
GetRPCMethodsResponse resp = new GetRPCMethodsResponse();
MethodList methodList = new MethodList();
String[] methods = { "GetRPCMethods", "SetParameterValues", "GetParameterValues", "GetParameterNames",
"SetParameterAttributes", "GetParameterAttributes", "AddObject", "DeleteObject",
"Reboot", "Download", "ScheduleInform", "Upload", "FactoryReset" };
methodList.setStrings(methods);
resp.setMethodList(methodList);
return inEnvelope(resp);
}
public Envelope doGetParameterValues( GetParameterValues getParameterValues ) {
return this.doGetParameterValues(getParameterValues, true, this.confdb.confs);
}
public Envelope doGetParameterValues( GetParameterValues getParameterValues, boolean learn, HashMap valobj) {
ParameterValueList pvl = new ParameterValueList();
String[] nameList = getParameterValues.getParameterNames().getStrings();
GetParameterValuesResponse valresp = new GetParameterValuesResponse();
if ((nameList.length == 1) && nameList[0].trim().isEmpty()) {
for(ConfObject conf : this.confdb.confs.values()) {
if (conf instanceof ConfParameter) {
final ParameterValueStruct pvs = new ParameterValueStruct();
pvs.setName(conf.name);
pvs.setValue(((ConfParameter)conf).value);
pvl.getParameterValueStruct().add(pvs);
}
}
} else {
for (int i = 0; i < nameList.length; i++) {
String paramname = nameList[i];
if (paramname.endsWith(".")) {
//System.out.println(" paramname ----> " + paramname);
Iterator it = valobj.entrySet().iterator();
int initialSize = pvl.getParameterValueStruct().size();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
String keyname = (String) pairs.getKey();
if (keyname.startsWith(paramname)) {
Object obj = pairs.getValue();
if (obj instanceof ConfParameter) {
ConfParameter cp = (ConfParameter) obj;
if (cp.value == null) {
continue;
}
ParameterValueStruct pvs = new ParameterValueStruct();
pvs.setName(cp.name);
pvs.setValue(cp.value);
pvl.getParameterValueStruct().add(pvs);
//System.out.println("Adding Nested --->>> " + cp.name + " = " + cp.value);
}
}
}
if (learn && pvl.getParameterValueStruct().size() == initialSize) {
ConfParameter cp = new ConfParameter(paramname, "0", "", null, null);
this.confdb.learns.put(paramname, cp);
System.out.println("Learning Unknown DataModel Path --->>> " + paramname);
}
} else if (this.confdb.confs.keySet().contains(paramname)) {
Object obj = this.confdb.confs.get(nameList[i]);
if (obj instanceof ConfParameter) {
ConfParameter cp = (ConfParameter) obj;
if (cp.value == null) {
//if(learn)
// System.out.println("Getting Known Null Value --->>> " + cp.name);
continue;
}
ParameterValueStruct pvs = new ParameterValueStruct();
pvs.setName(cp.name);
pvs.setValue(cp.value);
pvl.getParameterValueStruct().add(pvs);
//System.out.println("Getting Known Value --->>> " + cp.name + " = " + cp.value);
}
} else if (learn) {
ConfParameter cp = new ConfParameter(paramname, "0", "", null, null);
this.confdb.learns.put(paramname, cp);
System.out.println("Learning Unknown Parameter Name --->>> " + cp.name);
}
}
}
valresp.setParameterList(pvl);
return inEnvelope(valresp);
}
public Envelope doGetParameterNames( GetParameterNames getParameterName ) {
return this.doGetParameterNames(getParameterName, true);
}
public Envelope doGetParameterNames( GetParameterNames getParameterName, boolean learn ) {
GetParameterNamesResponse nameresp = new GetParameterNamesResponse();
ParameterInfoList pil = new ParameterInfoList();
String paramname = getParameterName.getParameterPath();
if (paramname.equals(""))
paramname = confdb.props.getProperty("RootNode");
if (paramname.endsWith(".")) {
// System.out.println("Adding Children Parameter Names ----> " + paramname);
HashMap valobj = this.confdb.confs;
Iterator it = valobj.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
String keyname = (String)pairs.getKey() ;
if (isMatching(paramname, keyname, getParameterName.isNextLevel())){
Object obj = pairs.getValue();
ConfObject co = (ConfObject)obj;
ParameterInfoStruct pvs = new ParameterInfoStruct();
pvs.setName(co.name);
pvs.setWritable(new Integer(co.writable));
pil.getParameterInfoStruct().add(pvs);
}
}
if(learn) {
valobj = this.confdb.learns;
it = valobj.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
String keyname = (String)pairs.getKey() ;
if (keyname.startsWith(paramname) && !keyname.equals(paramname)) {
Object obj = pairs.getValue();
ConfObject co = (ConfObject)obj;
ParameterInfoStruct pvs = new ParameterInfoStruct();
pvs.setName(co.name);
pvs.setWritable(new Integer(co.writable));
pil.getParameterInfoStruct().add(pvs);
//System.out.println("Adding Learned Parameter Name ----> " + co.name);
}
}
}
} else if ( this.confdb.confs.keySet().contains( paramname) ) {
Object obj = this.confdb.confs.get(paramname);
ConfObject co = (ConfObject)obj;
ParameterInfoStruct pvs = new ParameterInfoStruct();
pvs.setName(co.name);
pvs.setWritable(new Integer(co.writable));
pil.getParameterInfoStruct().add(pvs);
//System.out.println("Adding Single Parameter Name --->>> " + cp.name + " = " + cp.value);
}
nameresp.setParameterList(pil);
return inEnvelope(nameresp);
}
public Envelope doSetParameterValues( SetParameterValues setParameterValues ) {
return this.doSetParameterValues(setParameterValues, true);
}
public Envelope doSetParameterValues( SetParameterValues setParameterValues, boolean learn ) {
ParameterValueList pvl = new ParameterValueList();
ArrayList<ParameterValueStruct> nameList = setParameterValues.getParameterList().getParameterValueStruct();
SetParameterValuesResponse valresp = new SetParameterValuesResponse();
for (int i =0; i < nameList.size(); i++) {
ParameterValueStruct pvs = nameList.get(i);
if ( this.confdb.confs.keySet().contains( pvs.getName()) ) {
Object obj = this.confdb.confs.get(pvs.getName());
if (obj instanceof ConfParameter) {
ConfParameter cp = (ConfParameter)obj;
cp.value = pvs.getValue();
//System.out.println("Setting Value --->>> " + cp.name + " = " + cp.value);
}
} else if (learn) {
ConfParameter cp = new ConfParameter(pvs.getName(), "1", pvs.getValue(), null, null);
this.confdb.learns.put(pvs.getName(), cp);
System.out.println("Learning Unknown Parameter Name and Value --->>> " + cp.name + " = " + cp.value);
}
}
valresp.setStatus(org.dslforum.cwmp_1_0.SetParameterValuesResponse.Status._0);
((ConfParameter)confdb.confs.get(confdb.props.getProperty("ParameterKey"))).value = setParameterValues.getParameterKey();
return inEnvelope(valresp);
}
public Envelope doGetParameterAttributes( GetParameterAttributes getParameterAttributes ) {
String[] nameList = getParameterAttributes.getParameterNames().getStrings();
GetParameterAttributesResponse valresp = new GetParameterAttributesResponse();
ParameterAttributeList pal = new ParameterAttributeList();
for (int i =0; i < nameList.length; i++) {
String paramname = nameList[i];
if (paramname.endsWith(".")) {
// System.out.println(" paramname ----> " + paramname);
HashMap valobj = this.confdb.confs;
Iterator it = valobj.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
String keyname = (String)pairs.getKey() ;
if (keyname.startsWith(paramname)) {
Object obj = pairs.getValue();
if (obj instanceof ConfParameter) {
ConfParameter cp = (ConfParameter)obj;
ParameterAttributeStruct pas = new ParameterAttributeStruct();
pas.setName(cp.name);
pas.setNotification(Notification.convert(cp.notification));
AccessList accessList = new AccessList();
accessList.setStrings(cp.accessList.split(","));
pas.setAccessList(accessList);
pal.getParameterAttributeStruct().add(pas);
//System.out.println("Adding Nested --->>> " + cp.name + " = " + cp.value);
}
}
}
} else if ( this.confdb.confs.keySet().contains( paramname) ) {
Object obj = this.confdb.confs.get(nameList[i]);
if (obj instanceof ConfParameter) {
ConfParameter cp = (ConfParameter)obj;
ParameterAttributeStruct pas = new ParameterAttributeStruct();
pas.setName(cp.name);
pas.setNotification(Notification.convert(cp.notification));
AccessList accessList = new AccessList();
accessList.setStrings(cp.accessList.split(","));
pas.setAccessList(accessList);
pal.getParameterAttributeStruct().add(pas);
//System.out.println("Adding Direct --->>> " + cp.name + " = " + cp.value);
}
}
}
valresp.setParameterList(pal);
return inEnvelope(valresp);
}
public Envelope doSetParameterAttributes( SetParameterAttributes setParameterAttributes ) {
ParameterValueList pvl = new ParameterValueList();
ArrayList<SetParameterAttributesStruct> nameList = setParameterAttributes.getParameterList().getSetParameterAttributesStruct();
SetParameterValuesResponse valresp = new SetParameterValuesResponse();
for (int i =0; i < nameList.size(); i++) {
SetParameterAttributesStruct spvs = nameList.get(i);
if ( this.confdb.confs.keySet().contains( spvs.getName()) ) {
Object obj = this.confdb.confs.get(spvs.getName());
if (obj instanceof ConfParameter) {
ConfParameter cp = (ConfParameter)obj;
String[] aclist = spvs.getAccessList().getStrings();
if (spvs.isNotificationChange()) {
cp.notification = spvs.getNotification().toString();
}
if (spvs.isAccessListChange()) {
cp.accessList = Arrays.toString(aclist);
}
// System.out.println("Setting Value --->>> " + cp.notification + " = " + cp.accessList);
}
}
}
valresp.setStatus(org.dslforum.cwmp_1_0.SetParameterValuesResponse.Status._0);
return inEnvelope(valresp);
}
public Envelope doAddObject(AddObject addObject) {
AddObjectResponse respobj = new AddObjectResponse();
Random rn = new Random();
respobj.setInstanceNumber(rn.nextInt(424242424) + 1);
respobj.setStatus(org.dslforum.cwmp_1_0.AddObjectResponse.Status._0);
return inEnvelope(respobj);
}
public Envelope doDeleteObject(DeleteObject deleteObject) {
DeleteObjectResponse respobj = new DeleteObjectResponse();
respobj.setStatus(org.dslforum.cwmp_1_0.DeleteObjectResponse.Status._0);
return inEnvelope(respobj);
}
public Envelope doReboot(Reboot reboot) {
RebootResponse respobj = new RebootResponse();
return inEnvelope(respobj);
}
public Envelope doDownload(Download download) {
DownloadResponse respobj = new DownloadResponse();
respobj.setStartTime(new Date());
CPEDownloadServer cds = new CPEDownloadServer(download.getURL());
Thread cdsthread = new Thread(cds, "DownloadThread");
cdsthread.start();
respobj.setStatus(org.dslforum.cwmp_1_0.DownloadResponse.Status._0);
respobj.setCompleteTime(new Date());
return inEnvelope(respobj);
}
public Envelope doUpload(Upload upload) {
UploadResponse respobj = new UploadResponse();
respobj.setStartTime(new Date());
respobj.setStatus(org.dslforum.cwmp_1_0.UploadResponse.Status._0);
respobj.setCompleteTime(new Date());
return inEnvelope(respobj);
}
public Envelope doFactoryReset(FactoryReset reboot) {
FactoryResetResponse respobj = new FactoryResetResponse();
return inEnvelope(respobj);
}
/*
def doGetParameterAttributes( GetParameterAttributes getParameterAttributes ){
def nameList = getParameterAttributes.parameterNames.any
def attrs = confdb.confs.keySet().findAll{ confkey ->
nameList.any{confkey.startsWith(it)} &&
confdb.confs[confkey] instanceof ConfParameter &&
confdb.confs[confkey].notification != null
}.collect{
new ParameterAttributeStruct(
name: it,
notification: Integer.parseInt(confdb.confs[it].notification),
accessList: new AccessList(any: confdb.confs[it].accessList.split(",")) )
}
return inEnvelope(new GetParameterAttributesResponse(parameterList: new ParameterAttributeList(any: attrs)))
}
def doSetParameterAttributes(SetParameterAttributes setParameterAttributes){
// add error handling
setParameterAttributes.parameterList.getAny().each{
def conf = confdb.confs[it.name]
conf.accessList = it.accessList.getAny().join(",")
conf.notification = it.notification.toString()
}
return inEnvelope(new SetParameterValuesResponse(status: 0))
}
*/
/*public static Envelope inEnvelope(Object cwmpObject) {
Envelope envlope = new Envelope();
Body body = new Body();
ArrayList bodyobj = new ArrayList();
bodyobj.add(cwmpObject);
body.setObjects(bodyobj);
envlope.setBody(body);
return envlope;
}
*/
public static Envelope inEnvelope(Object cwmpObject) {
Envelope envlope = new Envelope();
Body body = new Body();
Header header = new Header();
// ID id = new ID();
// id.setMustUnderstand(true);
// id.setString(headerID);
// NoMoreRequests noMore = new NoMoreRequests();
// noMore.setString("0");
ArrayList headobj = new ArrayList();
//headobj.add(id);
// headobj.add(noMore);
header.setObjects(headobj);
ArrayList bodyobj = new ArrayList();
bodyobj.add(cwmpObject);
body.setObjects(bodyobj);
envlope.setHeader(header);
envlope.setBody(body);
return envlope;
}
/*def inEnvelope( cwmpObject, headerID ){
ID id = new ID(value: headerID, mustUnderstand: Boolean.TRUE )
Header header = new Header(any: [ id ])
Envelope envelope = new Envelope(body: new Body(any: [cwmpObject]), header: header);
return envelope
}*/
private boolean isMatching(String paramname, String keyname) {
return this.isMatching(paramname, keyname, false);
}
private boolean isMatching(String paramname, String keyname, boolean isNextLevel) {
return keyname.startsWith(paramname)
&& (!isNextLevel || depthOf(paramname) == depthOf(keyname) + 1);
}
private int depthOf(String param) {
return param.split(".").length;
}
} |
3e189b29b3274140830d584bf6fa7a9296a9bfe7 | 510 | java | Java | jmx/src/main/java/org/suggs/sandbox/jmx/jmxbook/components/propertymanager/PropertyManagerMBean.java | suggitpe/java-sandbox | 0abfb9282e12d40eef0d1c4e7dc925b1b39f728d | [
"Apache-2.0"
] | null | null | null | jmx/src/main/java/org/suggs/sandbox/jmx/jmxbook/components/propertymanager/PropertyManagerMBean.java | suggitpe/java-sandbox | 0abfb9282e12d40eef0d1c4e7dc925b1b39f728d | [
"Apache-2.0"
] | null | null | null | jmx/src/main/java/org/suggs/sandbox/jmx/jmxbook/components/propertymanager/PropertyManagerMBean.java | suggitpe/java-sandbox | 0abfb9282e12d40eef0d1c4e7dc925b1b39f728d | [
"Apache-2.0"
] | null | null | null | 22.173913 | 99 | 0.713725 | 10,465 | /*
* PropertyManagerMBean.java created on 20 Feb 2008 19:18:14 by suggitpe for project SandBox - JMX
*
*/
package org.suggs.sandbox.jmx.jmxbook.components.propertymanager;
import java.util.Enumeration;
/**
* MBean interface for setting properties
*/
public interface PropertyManagerMBean {
public String getProperty(String aName);
public void setProperty(String aName, String aValue);
public Enumeration<String> keys();
public void setSource(String aPath);
}
|
3e189b4a6ccef17d7f2071d8a6283938ee5a49cc | 2,122 | java | Java | cfsdk/src/main/java/io/harness/cfsdk/cloud/core/model/AuthenticationResponse.java | milos85vasic/ff-android-client-sdk | 1f6f4696ff56227be7563d583ea22440c794efcd | [
"Apache-2.0"
] | 2 | 2021-04-29T17:42:30.000Z | 2021-05-07T16:25:53.000Z | cfsdk/src/main/java/io/harness/cfsdk/cloud/core/model/AuthenticationResponse.java | milos85vasic/ff-android-client-sdk | 1f6f4696ff56227be7563d583ea22440c794efcd | [
"Apache-2.0"
] | 3 | 2021-05-13T13:47:44.000Z | 2021-06-12T08:47:29.000Z | cfsdk/src/main/java/io/harness/cfsdk/cloud/core/model/AuthenticationResponse.java | milos85vasic/ff-android-client-sdk | 1f6f4696ff56227be7563d583ea22440c794efcd | [
"Apache-2.0"
] | 2 | 2021-03-02T02:42:54.000Z | 2021-03-02T09:52:51.000Z | 22.774194 | 109 | 0.684608 | 10,466 | /*
* Harness feature flag service client apis
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 1.0.0
* Contact: anpch@example.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package io.harness.cfsdk.cloud.core.model;
import com.google.gson.annotations.SerializedName;
import java.util.Objects;
import io.swagger.annotations.ApiModelProperty;
/**
* AuthenticationResponse
*/
public class AuthenticationResponse {
public static final String SERIALIZED_NAME_AUTH_TOKEN = "authToken";
@SerializedName(SERIALIZED_NAME_AUTH_TOKEN)
private String authToken;
public AuthenticationResponse authToken(String authToken) {
this.authToken = authToken;
return this;
}
/**
* Get authToken
* @return authToken
**/
@ApiModelProperty(required = true, value = "")
public String getAuthToken() {
return authToken;
}
public void setAuthToken(String authToken) {
this.authToken = authToken;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AuthenticationResponse authenticationResponse = (AuthenticationResponse) o;
return Objects.equals(this.authToken, authenticationResponse.authToken);
}
@Override
public int hashCode() {
return Objects.hash(authToken);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class AuthenticationResponse {\n");
sb.append(" authToken: ").append(toIndentedString(authToken)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
3e189be3ee90913f97c0a6f8051565bed2b86384 | 806 | java | Java | src/java/runtime/intrinsic/_f2i.java | bhosmer/mesh | e8f7bca498a91d9fd447fa3ffe00f8d96fa01b1b | [
"MIT"
] | 6 | 2017-02-24T05:38:25.000Z | 2021-06-14T12:06:15.000Z | src/java/runtime/intrinsic/_f2i.java | bhosmer/mesh | e8f7bca498a91d9fd447fa3ffe00f8d96fa01b1b | [
"MIT"
] | null | null | null | src/java/runtime/intrinsic/_f2i.java | bhosmer/mesh | e8f7bca498a91d9fd447fa3ffe00f8d96fa01b1b | [
"MIT"
] | 2 | 2016-09-19T03:12:33.000Z | 2017-02-24T05:38:29.000Z | 22.388889 | 61 | 0.666253 | 10,467 | /**
* ADOBE SYSTEMS INCORPORATED
* Copyright 2009-2013 Adobe Systems Incorporated
* All Rights Reserved.
*
* NOTICE: Adobe permits you to use, modify, and distribute
* this file in accordance with the terms of the MIT license,
* a copy of which can be found in the LICENSE.txt file or at
* http://opensource.org/licenses/MIT.
*/
package runtime.intrinsic;
/**
* take floor of double, return int
*/
public final class _f2i extends IntrinsicLambda
{
public static final _f2i INSTANCE = new _f2i();
public static final String NAME = "f2i";
public String getName()
{
return NAME;
}
public Object apply(final Object arg)
{
return invoke((Double)arg);
}
public static int invoke(final double d)
{
return (int)Math.floor(d);
}
}
|
3e189c339e25e3e04a44855bec6dec61cdd76128 | 2,680 | java | Java | src/main/java/seedu/address/storage/StorageManager.java | lirc572/tp | b533d4f1aa3cc51b9d42540bbafe2763c5ea8f8a | [
"MIT"
] | 3 | 2021-02-09T08:52:39.000Z | 2021-02-24T10:28:02.000Z | src/main/java/seedu/address/storage/StorageManager.java | lirc572/tp | b533d4f1aa3cc51b9d42540bbafe2763c5ea8f8a | [
"MIT"
] | 370 | 2021-02-21T07:02:45.000Z | 2021-04-15T18:08:53.000Z | src/main/java/seedu/address/storage/StorageManager.java | lirc572/tp | b533d4f1aa3cc51b9d42540bbafe2763c5ea8f8a | [
"MIT"
] | 5 | 2021-02-13T12:59:17.000Z | 2021-04-12T13:36:39.000Z | 33.924051 | 117 | 0.724627 | 10,468 | package seedu.address.storage;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Optional;
import java.util.logging.Logger;
import seedu.address.commons.core.LogsCenter;
import seedu.address.commons.exceptions.DataConversionException;
import seedu.address.model.ReadOnlyColabFolder;
import seedu.address.model.ReadOnlyUserPrefs;
import seedu.address.model.UserPrefs;
/**
* Manages storage of ColabFolder data in local storage.
*/
public class StorageManager implements Storage {
private static final Logger logger = LogsCenter.getLogger(StorageManager.class);
private ColabFolderStorage colabFolderStorage;
private UserPrefsStorage userPrefsStorage;
/**
* Creates a {@code StorageManager} with the given {@code ColabFolderStorage} and {@code UserPrefStorage}.
*/
public StorageManager(ColabFolderStorage colabFolderStorage, UserPrefsStorage userPrefsStorage) {
super();
this.colabFolderStorage = colabFolderStorage;
this.userPrefsStorage = userPrefsStorage;
}
// ================ UserPrefs methods ==============================
@Override
public Path getUserPrefsFilePath() {
return userPrefsStorage.getUserPrefsFilePath();
}
@Override
public Optional<UserPrefs> readUserPrefs() throws DataConversionException, IOException {
return userPrefsStorage.readUserPrefs();
}
@Override
public void saveUserPrefs(ReadOnlyUserPrefs userPrefs) throws IOException {
userPrefsStorage.saveUserPrefs(userPrefs);
}
// ================ ColabFolder methods ==============================
@Override
public Path getColabFolderFilePath() {
return colabFolderStorage.getColabFolderFilePath();
}
@Override
public Optional<ReadOnlyColabFolder> readColabFolder() throws DataConversionException, IOException {
return readColabFolder(colabFolderStorage.getColabFolderFilePath());
}
@Override
public Optional<ReadOnlyColabFolder> readColabFolder(Path filePath) throws DataConversionException, IOException {
logger.fine("Attempting to read data from file: " + filePath);
return colabFolderStorage.readColabFolder(filePath);
}
@Override
public void saveColabFolder(ReadOnlyColabFolder colabFolder) throws IOException {
saveColabFolder(colabFolder, colabFolderStorage.getColabFolderFilePath());
}
@Override
public void saveColabFolder(ReadOnlyColabFolder colabFolder, Path filePath) throws IOException {
logger.fine("Attempting to write to data file: " + filePath);
colabFolderStorage.saveColabFolder(colabFolder, filePath);
}
}
|
3e189cda9c66e353f121b94afc4f2de0820aaace | 58,112 | java | Java | MetaVisualizer/src/main/java/com/entoptic/metaVisualizer/misc/WMV_Utilities.java | spatialized/MetaVisualizer | 9818de99e3599a7890443a72d917b3119eab4cb7 | [
"Apache-2.0"
] | null | null | null | MetaVisualizer/src/main/java/com/entoptic/metaVisualizer/misc/WMV_Utilities.java | spatialized/MetaVisualizer | 9818de99e3599a7890443a72d917b3119eab4cb7 | [
"Apache-2.0"
] | null | null | null | MetaVisualizer/src/main/java/com/entoptic/metaVisualizer/misc/WMV_Utilities.java | spatialized/MetaVisualizer | 9818de99e3599a7890443a72d917b3119eab4cb7 | [
"Apache-2.0"
] | null | null | null | 28.969093 | 268 | 0.659124 | 10,469 | package main.java.com.entoptic.metaVisualizer.misc;
import processing.core.PApplet;
import processing.core.PConstants;
import processing.core.PImage;
import processing.core.PVector;
import processing.data.IntList;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.time.Duration;
import java.time.LocalDateTime;
//import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
//import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;
import com.luckycatlabs.sunrisesunset.SunriseSunsetCalculator;
import com.luckycatlabs.sunrisesunset.dto.Location;
import main.java.com.entoptic.metaVisualizer.MetaVisualizer;
import main.java.com.entoptic.metaVisualizer.media.WMV_Sound;
import main.java.com.entoptic.metaVisualizer.model.WMV_Date;
import main.java.com.entoptic.metaVisualizer.model.WMV_Model;
import main.java.com.entoptic.metaVisualizer.model.WMV_Time;
import main.java.com.entoptic.metaVisualizer.model.WMV_TimeSegment;
import main.java.com.entoptic.metaVisualizer.model.WMV_Waypoint;
import main.java.com.entoptic.metaVisualizer.system.MV_Command;
import main.java.com.entoptic.metaVisualizer.world.WMV_Field;
/******************
* Utility methods
* @author davidgordon
*/
public class WMV_Utilities
{
/**
* Constructor for utilities class
*/
public WMV_Utilities(){}
/**
* Get path of specified program
* @param programName
*/
public String getProgramPath(String programName)
{
MV_Command commandExecutor;
ArrayList<String> command = new ArrayList<String>();
command = new ArrayList<String>(); /* Create small_images directory */
command.add("which");
command.add(programName);
commandExecutor = new MV_Command("", command);
try {
int result = commandExecutor.execute();
StringBuilder stderr = commandExecutor.getStandardError();
StringBuilder stdout = commandExecutor.getStandardOutput();
if (stderr.length() > 0 || result != 0)
System.out.println("Utilities.getProgramPath()... getting program name "+ programName+ "... result:"+result+" stderr:"+stderr.toString());
System.out.println("Utilities.getProgramPath()... stdout: "+stdout.toString());
if(result == 0)
{
return stdout.toString();
}
}
catch(Throwable t)
{
System.out.println("Throwable t while creating small_images directory:"+t);
return null;
}
return null;
}
/**
* Perform linear interpolation between two 3D points
* @param point1 First point
* @param point2 Second point
* @param step Step size {Between 0.f and 1.f}
* @return Interpolated point
*/
public PVector lerp3D(PVector point1, PVector point2, float step)
{
// System.out.println("Utilities.lerp3D()... point1.x:"+point1.x+" point2.x:"+point2.x+" step:"+step);
// System.out.println(" result will be:"+( lerp(point1.x, point2.x, step) ));
PVector result = new PVector(0,0,0);
result.x = lerp(point1.x, point2.x, step);
result.y = lerp(point1.y, point2.y, step);
result.z = lerp(point1.z, point2.z, step);
return result;
}
/**
* Purge all files and sub-folders in a directory
* @param directory Directory to purge
*/
public void purgeDirectory(File directory) {
for (File file: directory.listFiles()) {
if (file.isDirectory()) purgeDirectory(file);
file.delete();
}
}
/**
* Rename folder
* @param oldFolderPath Folder to rename
* @param newFolderPath New folder name
* @param ignoreDirectoryStatus Whether to ignore whether paths are directories or not
* @return Whether successful
*/
public boolean renameFolder(String oldFolderPath, String newFolderPath, boolean ignoreDirectoryStatus)
{
if(oldFolderPath.equals(newFolderPath)) // No need to rename
return true;
File oldFolderFile = new File(oldFolderPath);
File newNameFile = new File(newFolderPath);
boolean success = false;
if(!newNameFile.exists())
{
if(ignoreDirectoryStatus)
{
success = oldFolderFile.renameTo(newNameFile);
}
else
{
if(oldFolderFile.isDirectory())
{
success = oldFolderFile.renameTo(newNameFile);
}
else
{
System.out.println("Utilities.renameFolder()... ERROR: File "+oldFolderFile.getName()+" is not a directory!");
success = false;
}
}
}
if(!success)
{
System.out.println("Failed at renaming to :"+newNameFile+"... will try appending numbers...");
boolean found = false;
int count = 2;
while(!found) // Append count to file name until non-duplicate name found
{
String path = newFolderPath + "_" + String.valueOf(count);
newNameFile = new File(path);
if(!newNameFile.exists()) found = true;
count++;
}
success = oldFolderFile.renameTo(newNameFile);
}
return success;
}
/**
* Perform linear interpolation between two values
* @param val1 First value
* @param val2 Second value
* @param step Interpolation step size {Between 0.f and 1.f}
* @return Interpolated value
*/
public float lerp(float val1, float val2, float step)
{
return val1 + step * (val2 - val1);
}
/**
* Create a directory at destination
* @param folderName Folder name
* @param destination Destination for folder
*/
public void makeDirectory(String folderName, String destination)
{
MV_Command commandExecutor;
ArrayList<String> command = new ArrayList<String>();
// ArrayList<String> files = new ArrayList<String>();
command = new ArrayList<String>(); /* Create small_images directory */
command.add("mkdir");
command.add(folderName);
commandExecutor = new MV_Command(destination, command);
try {
int result = commandExecutor.execute();
StringBuilder stderr = commandExecutor.getStandardError();
if (stderr.length() > 0 || result != 0)
System.out.println("Error creating small_images directory:" + stderr + " result:"+result);
}
catch(Throwable t)
{
System.out.println("Throwable t while creating small_images directory:"+t);
}
}
public ArrayList<PVector> findBorderPoints(ArrayList<PVector> points)
{
ArrayList<PVector> borderPts = new ArrayList<PVector>();
// PVector centerOfHull = new PVector(100000,100000);
// There must be at least 3 points
if (points.size() < 3) return null;
JarvisPoints pts = new JarvisPoints(points);
JarvisMarch jm = new JarvisMarch(pts);
// double start = System.currentTimeMillis();
int n = jm.calculateHull();
// double end = System.currentTimeMillis();
// System.out.printf("%d points found %d vertices %f seconds\n", points.size(), n, (end-start)/1000.);
int length = jm.getHullPoints().pts.length;
borderPts = new ArrayList<PVector>();
for(int i=0; i<length; i++)
borderPts.add( jm.getHullPoints().pts[i] );
// Print Result
// for (int i = 0; i < hull.size(); i++)
// System.out.println( "(" + hull.get(i).x + ", "
// + hull.get(i).y + ")\n");
// if(debugSettings.field)
// System.out.println("Found media points border of size:"+border.size());
// borderPts.sort(new PointComp(centerOfHull));
IntList removeList = new IntList();
ArrayList<PVector> removePoints = new ArrayList<PVector>();
int count = 0;
for(PVector pv : borderPts)
{
int ct = 0;
for(PVector comp : borderPts)
{
if(ct != count) // Don't compare same indices
{
if(pv.equals(comp))
{
if(!removePoints.contains(pv))
{
removeList.append(count);
removePoints.add(pv);
}
break;
}
}
ct++;
}
count++;
}
// if(debugSettings.field) System.out.println("Will remove "+removeList.size()+" points from field #"+getID()+" border of size "+borderPts.size()+"...");
ArrayList<PVector> newPoints = new ArrayList<PVector>();
count = 0;
for(PVector pv : borderPts)
{
if(!removeList.hasValue(count))
newPoints.add(pv);
count++;
}
borderPts = newPoints;
// for(int i=removeList.size()-1; i>=0; i--)
// {
// borderPts.remove(i);
// i--;
// }
// System.out.println("Points remaining: "+borderPts.size()+"...");
// System.out.println("Will sort remaining "+borderPts.size()+" points in border...");
// borderPts.sort(c);
return borderPts;
}
/**
* Round value to nearest <n> decimal places
* @param val Value to round
* @param n Decimal places to round to
* @return Rounded value
*/
public float round(float val, int n)
{
val *= Math.pow(10.f, n);
val = Math.round(val);
val /= Math.pow(10.f, n);
return val;
}
/**
* Map a value from given range to new range
* @param val Value to map
* @param min Initial range minimum
* @param max Initial range maximum
* @param min2 New range minimum
* @param max2 New range maximum
* @return
*/
public float mapValue(float val, float min, float max, float min2, float max2)
{
float res;
res = (((max2-min2)*(val-min))/(max-min)) + min2;
return res;
}
/**
* Constrain float value between <min> and <max> by wrapping values around
* @param value Value to constrain by wrapping
* @param min Minimum value
* @param max Maximum value
*/
public float constrainWrap(float value, float min, float max)
{
if(value < min)
value += max;
else if(value > max)
value -= max;
return value;
}
public boolean hasDuplicateInteger(List<Integer> intList)
{
boolean duplicate = false;
for(int i:intList)
{
for(int m:intList)
{
boolean found = false;
if(i == m)
{
if(found) duplicate = true;
else found = true;
}
}
}
return duplicate;
}
/**
* Get value in seconds of time PVector
* @param time PVector of the format (hour, minute, second)
* @return Number of seconds
*/
public float getTimePVectorSeconds(PVector time)
{
float result = time.z;
result += time.y * 60.f;
result += time.x * 60.f * 60.f;
return result;
}
public int roundSecondsToHour(float value)
{
return Math.round(value / 3600.f) * 3600;
}
/**
* Round given value in seconds to nearest value given by interval parameter
* @param value Value to round
* @param interval Number of seconds to round to
* @return Rounded value
*/
public int roundSecondsToInterval(float value, float interval)
{
return Math.round(Math.round(value / interval) * interval);
}
/**
* Get date as formatted string
* @param date Given date
* @return String in format: "April 12, 1982"
*/
public String getDateAsString(WMV_Date date)
{
int year = date.getYear();
int month = date.getMonth();
int day = date.getDay();
String monthStr = "";
switch(month)
{
case 1:
monthStr = "January";
break;
case 2:
monthStr = "February";
break;
case 3:
monthStr = "March";
break;
case 4:
monthStr = "April";
break;
case 5:
monthStr = "May";
break;
case 6:
monthStr = "June";
break;
case 7:
monthStr = "July";
break;
case 8:
monthStr = "August";
break;
case 9:
monthStr = "September";
break;
case 10:
monthStr = "October";
break;
case 11:
monthStr = "November";
break;
case 12:
monthStr = "December";
break;
}
String result = monthStr+" "+String.valueOf(day)+", "+String.valueOf(year);
return result;
}
public String secondsToTimeAsString( float seconds, boolean showSeconds, boolean military )
{
int hour = Math.round(seconds) / 3600;
int minute = (Math.round(seconds) % 3600) / 60;
int second = (Math.round(seconds) % 3600) % 60;
return getTimeAsString(hour, minute, second, showSeconds, military);
}
public String getTimeAsString( int hour, int minute, int second, boolean showSeconds, boolean military )
{
boolean pm = false;
if(!military)
{
if(hour == 0 && minute == 0)
{
hour = 12;
pm = false;
}
else
{
if(hour == 0) hour = 12;
if(hour > 12)
{
hour -= 12;
if(hour < 12) pm = true;
}
else if(hour == 12) pm = true;
}
}
String strHour = String.valueOf(hour);
String strMinute = String.valueOf(minute);
if(minute < 10) strMinute = "0"+strMinute;
if(showSeconds)
{
String strSecond = String.valueOf(second);
if(second < 10) strSecond = "0"+strSecond;
if(military)
return strHour + ":" + strMinute + ":" + strSecond;
else
return strHour + ":" + strMinute + ":" + strSecond + (pm ? " pm" : " am");
}
else
{
if(military)
return strHour + ":" + strMinute;
else
return strHour + ":" + strMinute + (pm ? " pm" : " am");
}
}
public String getMonthAsString(int month)
{
String monthStr = "";
switch(month)
{
case 1:
monthStr = "January";
break;
case 2:
monthStr = "February";
break;
case 3:
monthStr = "March";
break;
case 4:
monthStr = "April";
break;
case 5:
monthStr = "May";
break;
case 6:
monthStr = "June";
break;
case 7:
monthStr = "July";
break;
case 8:
monthStr = "August";
break;
case 9:
monthStr = "September";
break;
case 10:
monthStr = "October";
break;
case 11:
monthStr = "November";
break;
case 12:
monthStr = "December";
break;
}
return monthStr;
}
/**
* Get current date in days since Jan 1, 1980
* @return Days since Jan 1, 1980
*/
public int getCurrentDateInDaysSince1980(String timeZoneID)
{
ZonedDateTime now = ZonedDateTime.now(ZoneId.of(timeZoneID));
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
return getDaysSince1980(timeZoneID, day, month, year);
}
/**
* Get specified date as number of days from Jan 1, 1980
* @param day Day
* @param month Month
* @param year Year
* @return Number of days
*/
public int getDaysSince1980(String timeZoneID, int day, int month, int year)
{
ZonedDateTime date1980 = ZonedDateTime.parse("1980-01-01T00:00:00+00:00[America/Los_Angeles]");
ZonedDateTime date = ZonedDateTime.of(year, month, day, 0, 0, 0, 0, ZoneId.of(timeZoneID));
Duration duration = Duration.between(date1980, date);
return (int)duration.toDays();
}
/**
* Get distance in radians between two angles
* @param theta1 First angle
* @param theta2 Second angle
* @return Angular distance in radians
*/
public float getAngularDistance(float theta1, float theta2)
{
if (theta1 < 0)
theta1 += Math.PI * 2.f;
if (theta2 < 0)
theta2 += Math.PI * 2.f;
if (theta1 > Math.PI * 2.f)
theta1 -= Math.PI * 2.f;
if (theta2 > Math.PI * 2.f)
theta2 -= Math.PI * 2.f;
float dist1 = Math.abs(theta1-theta2);
float dist2;
if (theta1 > theta2)
dist2 = Math.abs(theta1 - (float)Math.PI*2.f-theta2);
else
dist2 = Math.abs(theta2 - (float)Math.PI*2.f-theta1);
if (dist1 > dist2)
return dist2;
else
return dist1;
}
/**
* Get sound locations from GPS track
*/
public void setSoundGPSLocationsFromGPSTrack(ArrayList<WMV_Sound> soundList, ArrayList<WMV_Waypoint> gpsTrack, float soundGPSTimeThreshold)
{
for(WMV_Sound s : soundList)
{
s.calculateLocationFromGPSTrack(gpsTrack, soundGPSTimeThreshold);
}
}
/**
* Get GPS track as formatted string
* @param loc {longitude, latitude}
*/
public String formatGPSLocation(PVector loc, boolean labels)
{
if(labels)
return "Lat:"+round(loc.y, 4)+", Lon:"+round(loc.x, 4);
else
return ""+round(loc.y, 4)+", "+round(loc.x, 4);
}
/**
* Shrink images to optimized size (640 pixels max width) for 3D environment
* @param largeImages Images to shrink
* @param destination Destination folder
* @return Whether successful
*/
public boolean shrinkImageFolder(String largeImages, String destination)
{
System.out.println("shrinkImageFolder()... Shrinking images:"+largeImages+" dest: "+destination+"...");
ArrayList<String> files = new ArrayList<String>();
/* Get files in directory */
files = getFilesInDirectory(largeImages);
copyFiles(largeImages, destination);
files = getFilesInDirectory(destination);
/* Shrink files in new directory */
shrinkImageFileList(files, destination);
return true;
}
/**
* Shrink list of image files
* @param files Image file list
* @param directory Directory containing image files
*/
public void shrinkImageFileList(ArrayList<String> files, String directory)
{
for (String fileName : files) // -- Do in one command??
{
boolean isJpeg = false;
if(fileName != null && !fileName.equals(""))
{
String[] parts = fileName.split("\\.");
if(parts.length > 0)
{
if(parts[parts.length-1].equals("jpg") || parts[parts.length-1].equals("JPG"))
isJpeg = true;
}
if(isJpeg)
shrinkImageInPlace(fileName, directory);
}
}
}
/**
* Get files in directory as list of Strings
* @param sourceFolder Directory to list files from
* @return File list
*/
private ArrayList<String> getFilesInDirectory(String sourceFolder)
{
ArrayList<String> files = new ArrayList<String>();
MV_Command commandExecutor;
ArrayList<String> command = new ArrayList<String>();
command.add("ls");
commandExecutor = new MV_Command(sourceFolder, command);
try {
int result = commandExecutor.execute();
// Get the output from the command
StringBuilder stdout = commandExecutor.getStandardOutput();
// StringBuilder stderr = commandExecutor.getStandardError();
String out = stdout.toString();
String[] parts = out.split("\n");
for (int i=0; i<parts.length; i++)
{
files.add(parts[i]);
//println("parts["+i+"]:"+parts[i]);
}
}
catch(Throwable t)
{
System.out.println("createNewLibrary()... Throwable t while getting folderString file list:"+t);
// return false;
}
return files;
}
/**
* Copy file to destination
* @param filePath File to copy
* @param destination Destination path
* @return Whether successful
*/
private boolean copyFile(String filePath, String destination)
{
MV_Command commandExecutor;
ArrayList<String> command = new ArrayList<String>();
command.add("cp");
command.add("-a"); // Improved recursive option that preserves all file attributes, and also preserve symlinks.
command.add(filePath);
command.add(destination);
// System.out.println("Utilities.copyFile()... Copying command:"+command.toString());
commandExecutor = new MV_Command("", command);
try {
int result = commandExecutor.execute();
// System.out.println("Utilities.copyFile()... Copying result ..."+result);
return true;
}
catch(Throwable t)
{
// System.out.println("Utilities.copyFile()... Throwable t while copying video files:"+t);
return false;
}
}
/**
* Copy files from source folder to destination
* @param sourceFolder Source folder
* @param destination Destination path
* @return Whether successful
*/
public boolean copyFiles(String sourceFolder, String destination)
{
MV_Command commandExecutor;
ArrayList<String> command = new ArrayList<String>();
/* Copy files to new directory */
command = new ArrayList<String>();
command.add("cp");
command.add("-a");
command.add(sourceFolder + ".");
command.add(destination);
commandExecutor = new MV_Command("", command);
try {
int result = commandExecutor.execute();
// StringBuilder stdout = commandExecutor.getStandardOutputFromCommand();
// StringBuilder stderr = commandExecutor.getStandardErrorFromCommand();
// System.out.println("... copying result ..."+result);
return true;
}
catch(Throwable t)
{
System.out.println("Utilities.copyFiles()... Throwable t while copying files:"+t);
return false;
}
}
/**
* Shrink image in place at specified directory
* @param fileName File path of image to shrink
* @param directory Image file directory
* @return Whether successful
*/
public boolean shrinkImageInPlace(String fileName, String directory)
{
MV_Command commandExecutor;
ArrayList<String> command = new ArrayList<String>();
//Command: sips -Z 640 *.jpg
command = new ArrayList<String>();
command.add("sips");
command.add("-Z");
command.add("640");
command.add(fileName);
// System.out.println("Utilities.shrinkImageInPlace()... directory:"+directory +" command:"+command);
commandExecutor = new MV_Command(directory, command);
try {
int result = commandExecutor.execute();
// StringBuilder stdout = commandExecutor.getStandardOutput(); // get the output from the command
// StringBuilder stderr = commandExecutor.getStandardError();
return true;
}
catch(Throwable t)
{
System.out.println("Throwable t:"+t);
return false;
}
}
public String getFileNameFromPath(String filePath)
{
String[] parts = filePath.split("/");
String filename = "";
if(parts.length>0)
filename= parts[parts.length-1];
return filename;
}
/**
* Shrink image in place at specified directory
* @param fileName File path of image to shrink
* @param inputDirectory Image file directory
* @param inputDirectory Image output directory
* @return Whether successful
*/
public boolean shrinkImage(String filePath, String outputDirectory)
{
String fileName = getFileNameFromPath(filePath);
MV_Command commandExecutor;
ArrayList<String> command = new ArrayList<String>();
command = new ArrayList<String>(); // Ex. Command: sips -Z 640 *.jpg
command.add("sips");
command.add("-Z");
command.add("640");
command.add(filePath);
command.add("--out");
command.add(outputDirectory + "/" + fileName);
// System.out.println("Utilities.shrinkImage()... no directory... command:"+command);
commandExecutor = new MV_Command("", command);
try {
int result = commandExecutor.execute();
// StringBuilder stdout = commandExecutor.getStandardOutput(); // get the output from the command
// StringBuilder stderr = commandExecutor.getStandardError();
return true;
}
catch(Throwable t)
{
System.out.println("Throwable t:"+t);
return false;
}
}
// /**
// * Convert list of videos to 480p (using QuickTime Player) and export to output folder
// * @param inputPath Input folder path
// * @param outputPath Output folder path
// * @return Whether successful
// */
// private Process shrinkVideos(MultimediaLocator ml, String inputPath, String outputPath)
// {
// Process process;
// String scriptPath = ml.getScriptResource("Convert_File_to_480p.txt");
// ml.delay(200);
//
// if(ml.debug.video)
// {
// System.out.println("Utilities.convertVideos()... scriptPath:"+scriptPath);
// System.out.println(" ... inputPath:"+inputPath);
// System.out.println(" ... outputPath:"+outputPath);
// }
//
// Runtime runtime = Runtime.getRuntime();
//
// String[] args = { "osascript", scriptPath, inputPath, outputPath };
//
// try
// {
// process = runtime.exec(args);
//
// InputStream input = process.getInputStream();
// for (int i = 0; i < input.available(); i++) {
// System.out.println("" + input.read());
// }
//
// InputStream error = process.getErrorStream();
// for (int i = 0; i < error.available(); i++) {
// System.out.println("" + error.read());
// }
// }
// catch (IOException e)
// {
// e.printStackTrace();
// return null;
// }
//
// return process;
// }
/**
* Convert list of videos to 480p (using QuickTime Player) and export to output folder
* @param inputPath Input folder path
* @param outputPath Output folder path
* @return Whether successful
*/
public void shrinkVideos(MetaVisualizer ml, String folderPath, String outputPath)
{
File folderFile = new File(folderPath);
File[] files = folderFile.listFiles();
for(int i=0; i<files.length; i++)
{
File videoFile = files[i];
String videoPath = videoFile.getAbsolutePath();
Process conversionProcess;
if(i == files.length - 1)
conversionProcess = shrinkVideo(ml, videoPath, outputPath, true); // -- Pass argument for delay time too?
else
conversionProcess = shrinkVideo(ml, videoPath, outputPath, false); // -- Pass argument for delay time too?
try{ // Copy original videos to small_videos directory and resize -- Move to ML class
conversionProcess.waitFor();
}
catch(Throwable t)
{
ml.systemMessage("Metadata.shrinkVideos()... ERROR in process.waitFor()... t:"+t);
t.printStackTrace();
}
}
}
/**
* Convert list of videos to 480p (using QuickTime Player) and export to output folder
* @param inputPath Input folder path
* @param outputPath Output folder path
* @param exitAfter Whether to quit QuickTime Player after finished
* @return Whether successful
*/
public Process shrinkVideo(MetaVisualizer ml, String filePath, String outputPath, boolean exitAfter) // -- Pass argument for delay time?
{
String fileName = getFileNameFromPath(filePath);
Process process;
String scriptPath = ml.getScriptResource("Convert_File_to_480p.txt");
ml.delay(200);
if(ml.debug.video)
{
System.out.println("Utilities.convertVideo()... scriptPath:"+scriptPath);
System.out.println(" ... filePath:"+filePath);
System.out.println(" ... fileName:"+fileName);
System.out.println(" ... outputPath:"+outputPath);
}
Runtime runtime = Runtime.getRuntime();
// String[] args = { "osascript", scriptPath, filePath, fileName, outputPath };
String[] args;
if(exitAfter)
{
String[] arguments = { "osascript", scriptPath, filePath, fileName, outputPath, "true" };
args = arguments;
}
else
{
String[] arguments = { "osascript", scriptPath, filePath, fileName, outputPath, "false" };
args = arguments;
}
try
{
process = runtime.exec(args);
InputStream input = process.getInputStream();
for (int i = 0; i < input.available(); i++) {
System.out.println("" + input.read());
}
InputStream error = process.getErrorStream();
for (int i = 0; i < error.available(); i++) {
System.out.println("" + error.read());
}
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
return process;
}
// /**
// * Convert videos in input folder to 480p (using QuickTime Player) and export to output folder
// * @param inputPath Input folder path
// * @param outputPath Output folder path
// * @return Whether successful
// */
// public Process convertVideos(MultimediaLocator ml, String inputPath, String outputPath)
// {
// Process process;
// String scriptPath = ml.getScriptResource("Convert_to_480p.txt");
// ml.delay(200);
//
// if(ml.debugSettings.video )
// {
// System.out.println("Utilities.convertVideos()... scriptPath:"+scriptPath);
// System.out.println(" ... inputPath:"+inputPath);
// System.out.println(" ... outputPath:"+outputPath);
// }
//
// Runtime runtime = Runtime.getRuntime();
//
// String[] args = { "osascript", scriptPath, inputPath, outputPath };
//
// try
// {
// process = runtime.exec(args);
//
// InputStream input = process.getInputStream();
// for (int i = 0; i < input.available(); i++) {
// System.out.println("" + input.read());
// }
//
// InputStream error = process.getErrorStream();
// for (int i = 0; i < error.available(); i++) {
// System.out.println("" + error.read());
// }
// }
// catch (IOException e)
// {
// e.printStackTrace();
// return null;
// }
//
// return process;
// }
public PImage bufferedImageToPImage(BufferedImage bimg)
{
try {
PImage img=new PImage(bimg.getWidth(), bimg.getHeight(), PConstants.ARGB);
bimg.getRGB(0, 0, img.width, img.height, img.pixels, 0, img.width);
img.updatePixels();
return img;
}
catch(Exception e) {
System.err.println("Can't create image from buffer");
e.printStackTrace();
}
return null;
}
/**
* @param x Float to check
* @return Whether the variable is NaN
*/
public boolean isNaN(float x) {
return x != x;
}
public boolean isNaN(double x) {
return x != x;
}
/**
* @param s String to check
* @param radix Maximum number of digits
* @return If the string is an integer
*/
public boolean isInteger(String s, int radix) {
Scanner sc = new Scanner(s.trim());
if(!sc.hasNextInt(radix))
{
sc.close();
return false;
}
sc.nextInt(radix);
boolean result = !sc.hasNext();
sc.close();
return result;
}
/**
* @param month Month
* @param year Year
* @return Number of days in given month of given year
*/
public int getDaysInMonth(int month, int year) {
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
int days = 0;
switch (month) {
case 1:
days = 31;
break;
case 2:
if (isLeapYear)
days = 29;
else
days = 28;
break;
case 3:
days = 31;
break;
case 4:
days = 30;
break;
case 5:
days = 31;
break;
case 6:
days = 30;
break;
case 7:
days = 31;
break;
case 8:
days = 31;
break;
case 9:
days = 30;
break;
case 10:
days = 31;
break;
case 11:
days = 30;
break;
case 12:
days = 31;
break;
default:
days = 0;
}
return days;
}
public void checkTimeSegment(WMV_TimeSegment ts)
{
float upper = ts.getUpper().getAbsoluteTime();
float lower = ts.getLower().getAbsoluteTime();
// System.out.println("checkTimeSegment()...");
for(WMV_Time t : ts.timeline)
{
// System.out.println(" checkTimeSegment()... t.getTime():"+t.getTime());
if(t.getAbsoluteTime() < lower)
{
System.out.println(" t.getTime() < lower... t.getTime():"+t.getAbsoluteTime()+" lower:"+lower);
}
if(t.getAbsoluteTime() > upper)
{
System.out.println(" t.getTime() < lower... t.getTime():"+t.getAbsoluteTime()+" upper:"+upper);
}
}
}
public float getTimelineLength(ArrayList<WMV_TimeSegment> timeline)
{
float start = timeline.get(0).getLower().getAbsoluteTime();
float end = timeline.get(timeline.size()-1).getUpper().getAbsoluteTime();
float length = (end - start) * getTimePVectorSeconds(new PVector(24,0,0));
return length;
}
/**
* @param radians (Yaw) angle in radians
* @return Corresponding cmpass orientation
*/
String angleToCompass(float radians)
{
float angle = (float)Math.toDegrees(radians);
float sweep = 360.f/8.f;
angle += sweep*0.5f;
if(angle < 0.f) // Adjust angle to between 0 and 360
angle = 360.f + angle % 360.f;
if(angle > 360.f)
angle %= 360.f;
for(int i=0; i<8; i++)
{
if(angle > 0 && angle < sweep)
{
switch(i)
{
case 0: return "N";
case 7: return "NE";
case 6: return "E";
case 5: return "SE";
case 4: return "S";
case 3: return "SW";
case 2: return "W";
case 1: return "NW";
}
}
angle -= sweep;
}
return null;
}
public String getCurrentTimeZoneID(float latitude, float longitude)
{
JSONObject json;
String start = "https://maps.googleapis.com/maps/api/timezone/json?location=";
String end = "×tamp=1331161200&key=AIzaSyBXrzfHmo4t8hhrTX1lVgXwfbuThSokjNY";
String url = start+String.valueOf(latitude)+","+String.valueOf(longitude)+end;
// String url = "https://maps.googleapis.com/maps/api/timezone/json?location=37.77492950,-122.41941550×tamp=1331161200&key=AIzaSyBXrzfHmo4t8hhrTX1lVgXwfbuThSokjNY";
try
{
json = readJsonFromUrl(url);
}
catch(Throwable t)
{
System.out.println("Error reading JSON from Google Time Zone API: "+t);
return null;
}
if (json!=null)
{
String timeZoneID= ((String)json.get("timeZoneId"));
return timeZoneID;
}
else
return null;
}
/**
* Calculate virtual capture location based on GPS location in format {longitude, latitude} and GPS altitude
* @param gpsLocation GPS location in format {longitude, altitude, latitude}
* @param altitude Altitude
* @param longitudeRef Longitude reference
* @param latitudeRef Latitude reference
* @param model Field model
* @return Capture location associated with GPS location
*/
public PVector getCaptureLocationFromGPSAndAltitude( PVector gpsLocation, float altitude, String longitudeRef, String latitudeRef, WMV_Model model )
{
PVector gpsWithAltitude = new PVector(gpsLocation.x, altitude, gpsLocation.y); // {longitude, altitude, latitude}
return getCaptureLocationFromGPSLocation(gpsWithAltitude, longitudeRef, latitudeRef, model);
}
/**
* Calculate virtual capture location based on GPS location in format {longitude, altitude, latitude}
* @param gpsLocation GPS location in format {longitude, altitude, latitude}
* @param longitudeRef Longitude reference
* @param latitudeRef Latitude reference
* @param model Field model
* @return Capture location associated with GPS location
*/
public PVector getCaptureLocationFromGPSLocation( PVector gpsLocation, String longitudeRef, String latitudeRef, WMV_Model model )
{
PVector newCaptureLocation = new PVector(0,0,0);
float highLongitude = model.getState().lowLongitude;
float lowLongitude = model.getState().highLongitude;
float highLatitude = model.getState().highLatitude;
float lowLatitude = model.getState().lowLatitude;
float lowAltitude = model.getState().lowAltitude;
float highAltitude = model.getState().highAltitude;
if(lowAltitude == 1000000.f && highAltitude != -1000000.f) // Adjust for fields with no altitude variation
lowAltitude = highAltitude;
else if(highAltitude == -1000000.f && lowAltitude != 1000000.f)
highAltitude = lowAltitude;
if(lowAltitude == 1000000.f || highAltitude == -1000000.f) // Adjust for fields with no altitude variation
System.out.println("Utilities.getCaptureLocationFromGPSAndAltitude()... ERROR: highAltitude:"+model.getState().highAltitude+" lowAltitude:"+model.getState().lowAltitude);
// if(model.getState().highLongitude != -1000000 && model.getState().lowLongitude != 1000000 && model.getState().highLatitude != -1000000 &&
// model.getState().lowLatitude != 1000000 && model.getState().highAltitude != -1000000 && model.getState().lowAltitude != 1000000)
if( highLongitude != -1000000.f && lowLongitude != 1000000.f && highLatitude != -1000000.f &&
lowLatitude != 1000000.f && highAltitude != -1000000.f && lowAltitude != 1000000.f )
{
if(model.getState().highLongitude != model.getState().lowLongitude && model.getState().highLatitude != model.getState().lowLatitude)
{
newCaptureLocation.x = mapValue( gpsLocation.x, model.getState().lowLongitude, // GPS longitude decreases from left to right
model.getState().highLongitude, -0.5f * model.getState().fieldWidth, 0.5f
* model.getState().fieldWidth);
newCaptureLocation.y = -mapValue( gpsLocation.y, model.getState().lowAltitude, // Convert altitude feet to meters, negative to match P3D coordinate space
model.getState().highAltitude, 0.f, model.getState().fieldHeight);
newCaptureLocation.z = mapValue( gpsLocation.z, model.getState().lowLatitude, // GPS latitude increases from bottom to top, reversed to match P3D coordinate space
model.getState().highLatitude, 0.5f * model.getState().fieldLength,
-0.5f * model.getState().fieldLength);
if(model.worldSettings.altitudeScaling)
newCaptureLocation.y *= model.worldSettings.altitudeScalingFactor;
else
newCaptureLocation.y *= model.worldSettings.defaultAltitudeScalingFactor;
if(model.debug.gps && model.debug.detailed)
{
System.out.println("Utilities.getCaptureLocationFromGPSLocation()... gpsLocation x:"+gpsLocation.x+" y:"+gpsLocation.y+" z:"+gpsLocation.z);
System.out.println(" High longitude:"+model.getState().highLongitude+" Low longitude:"+model.getState().lowLongitude);
System.out.println(" High latitude:"+model.getState().highLatitude+" Low latitude:"+model.getState().lowLatitude);
System.out.println(" newX:"+newCaptureLocation.x+" newY"+newCaptureLocation.y+" newZ"+newCaptureLocation.z);
}
}
else
{
System.out.println("Utilities.getCaptureLocationFromGPSAndAltitude()... ERROR 1: high longitude:"+model.getState().highLongitude+" lowLongitude:"+model.getState().lowLongitude);
System.out.println(" High latitude:"+model.getState().highLatitude+" Low latitude:"+model.getState().lowLatitude);
System.out.println(" High altitude:"+model.getState().highAltitude+" Low altitude:"+model.getState().lowAltitude);
}
}
else
{
System.out.println("Utilities.getCaptureLocationFromGPSAndAltitude()... ERROR 2: high longitude:"+model.getState().highLongitude+" lowLongitude:"+model.getState().lowLongitude);
System.out.println(" High latitude:"+model.getState().highLatitude+" Low latitude:"+model.getState().lowLatitude);
System.out.println(" High altitude:"+model.getState().highAltitude+" Low altitude:"+model.getState().lowAltitude);
}
return newCaptureLocation;
}
/**
* Get GPS location for a given point in a field -- Need to account for Longitude Ref?
* @param f Given field
* @param loc Given point
* @return GPS location for given point in format {longitude, latitude}
*/
public PVector getGPSLocationFromCaptureLocation(WMV_Field f, PVector loc)
{
if(loc != null)
{
WMV_Model m = f.getModel();
// newX = PApplet.map(mState.gpsLocation.x, model.getState().lowLongitude, model.getState().highLongitude, -0.5f * model.getState().fieldWidth, 0.5f*model.getState().fieldWidth); // GPS longitude decreases from left to right
// newZ = PApplet.map(mState.gpsLocation.z, model.getState().lowLatitude, model.getState().highLatitude, 0.5f*model.getState().fieldLength, -0.5f * model.getState().fieldLength); // GPS latitude increases from bottom to top, reversed to match P3D coordinate space
float gpsX = mapValue( loc.x, -0.5f * m.getState().fieldWidth, 0.5f*m.getState().fieldWidth, m.getState().lowLongitude, m.getState().highLongitude ); // GPS longitude decreases from left to right
float gpsY = mapValue( loc.z, -0.5f * m.getState().fieldLength, 0.5f*m.getState().fieldLength, m.getState().highLatitude, m.getState().lowLatitude ); // GPS latitude increases from bottom to top
PVector gpsLoc = new PVector(gpsX, gpsY);
return gpsLoc;
}
else
{
return null;
}
}
/**
* Get longitude reference from decimal longitude value
* @param decimal Decimal longitude input
* @return Longitude ref
*/
public String getLongitudeRefFromDecimal( float decimal )
{
String gpsLongitudeRef = "E";
if( (int)Math.signum(decimal) == -1 )
gpsLongitudeRef = "W";
return gpsLongitudeRef;
}
/**
* Get latitude reference from decimal latitude value
* @param decimal Decimal latitude input
* @return Latitude ref
*/
public String getLatitudeRefFromDecimal( float decimal )
{
String gpsLatitudeRef = "N";
if( (int)Math.signum(decimal) == -1 )
gpsLatitudeRef = "S";
return gpsLatitudeRef;
}
/**
* Parse date time string in UTC format (Ex. 2016-05-01T23:55:33Z)
* @param dateTimeStr Given date/time string
* @param zoneIDStr Time zone ID string
* @return ZonedDateTime object from date/time string
*/
public ZonedDateTime parseUTCDateTimeString(String dateTimeStr, String zoneIDStr)
{
String[] parts = dateTimeStr.split("T");
String dateStr = parts[0];
String timeStr = parts[1];
parts = dateStr.split("-");
String yearStr, monthStr, dayStr;
yearStr = parts[0];
monthStr = parts[1];
dayStr = parts[2];
int year = Integer.parseInt(yearStr);
int month = Integer.parseInt(monthStr);
int day = Integer.parseInt(dayStr);
parts = timeStr.split("Z"); /* Parse Time */
timeStr = parts[0];
parts = timeStr.split(":");
String hourStr, minuteStr, secondStr;
hourStr = parts[0];
minuteStr = parts[1];
secondStr = parts[2];
int hour = Integer.parseInt(hourStr);
int minute = Integer.parseInt(minuteStr);
int second = Integer.parseInt(secondStr);
LocalDateTime ldt = LocalDateTime.of(year, month, day, hour, minute, second);
ZonedDateTime utc = ldt.atZone(ZoneId.of("UTC"));
ZonedDateTime zoned = utc.withZoneSameInstant(ZoneId.of(zoneIDStr));
return zoned;
}
/**
* Get approximate distance between two GPS points in meters
* @param startLatitude Latitude of first point
* @param startLongitude Longitude of first point
* @param endLatitude Latitude of second point
* @param endLongitude Longitude of second point
* @return Distance in meters
*/
public float getGPSDistanceInMeters(double startLatitude, double startLongitude, double endLatitude, double endLongitude)
{
double R = 6371000; // Radius of Earth (m.)
double φ1 = Math.toRadians(startLatitude);
double φ2 = Math.toRadians(endLatitude);
double Δφ = Math.toRadians(endLatitude-startLatitude);
double Δλ = Math.toRadians(endLongitude-startLongitude);
double a = Math.sin(Δφ/2) * Math.sin(Δφ/2) + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ/2) * Math.sin(Δλ/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double d = R * c;
return (float)d;
}
/**
* Convert ZonedDateTime object to EXIF metadata-style string
* @param dateTime ZonedDateTime object
* @return Date/time string
*/
public String getDateTimeAsString(ZonedDateTime dateTime)
{
String result = ""; // Format: 2016:05:28 17:13:39
String yearStr = String.valueOf(dateTime.getYear());
String monthStr = String.valueOf(dateTime.getMonthValue());
String dayStr = String.valueOf(dateTime.getDayOfMonth());
String hourStr = String.valueOf(dateTime.getHour());
String minuteStr = String.valueOf(dateTime.getMinute());
String secondStr = String.valueOf(dateTime.getSecond());
result = yearStr + ":" + monthStr + ":" + dayStr + " " + hourStr + ":" + minuteStr + ":" + secondStr;
// System.out.println("getTimeStringFromDateTime()... result:"+result);
return result;
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException
{
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
}
finally {
is.close();
}
}
/**
* Read all lines in input buffer
* @param rd Reader object
* @return Single string output
* @throws IOException
*/
private static String readAll(Reader rd) throws IOException
{
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
/**
* Get altitude from a GPS location in format {longitude, altitude, latitude}
* @param loc GPS location
* @return Altitude
*/
public float getAltitude(PVector loc)
{
return loc.y;
}
/**
* Class for finding convex hull using Jarvis March Algorithm
* Based on JarvisMarch class by UncleBob
* @author davidgordon
*/
public class JarvisMarch
{
JarvisPoints pts;
private JarvisPoints hullPoints = null;
private List<Float> hy;
private List<Float> hx;
private int startingPoint;
private double currentAngle;
private static final double MAX_ANGLE = 4;
/**
* Constructor for JarvisMarch class
* @param pts JarvisPoints for which to find border
*/
JarvisMarch(JarvisPoints pts) {
this.pts = pts;
}
/**
* The Jarvis March, i.e. Gift Wrap Algorithm. The next point is the point with the next largest angle.
* Imagine wrapping a string around a set of nails in a board. Tie the string to the leftmost nail
* and hold the string vertical. Now move the string clockwise until you hit the next, then the next, then
* the next. When the string is vertical again, you will have found the hull.
*/
public int calculateHull()
{
initializeHull();
startingPoint = getStartingPoint();
currentAngle = 0;
addToHull(startingPoint);
for (int p = getNextPoint(startingPoint); p != startingPoint; p = getNextPoint(p))
addToHull(p);
buildHullPoints();
return hullPoints.pts.length;
}
public int getStartingPoint() {
return pts.startingPoint();
}
private int getNextPoint(int p) {
double minAngle = MAX_ANGLE;
int minP = startingPoint;
for (int i = 0; i < pts.pts.length; i++) {
if (i != p) {
double thisAngle = relativeAngle(i, p);
if (thisAngle >= currentAngle && thisAngle <= minAngle) {
minP = i;
minAngle = thisAngle;
}
}
}
currentAngle = minAngle;
return minP;
}
/**
* Find relative angle between two poins
* @param i First point
* @param p Second point
* @return Relative angle
*/
private double relativeAngle(int i, int p) {
return pseudoAngle(pts.pts[i].x - pts.pts[p].x, pts.pts[i].y - pts.pts[p].y);
}
/**
* Initialize points in hx and hy
*/
private void initializeHull() {
hx = new LinkedList<Float>();
hy = new LinkedList<Float>();
}
/**
* Build points in convex hull
*/
private void buildHullPoints() {
float[] ax = new float[hx.size()];
float[] ay = new float[hy.size()];
int n = 0;
for (Iterator<Float> ix = hx.iterator(); ix.hasNext(); )
ax[n++] = ix.next();
n = 0;
for (Iterator<Float> iy = hy.iterator(); iy.hasNext(); )
ay[n++] = iy.next();
ArrayList<PVector> newPts = new ArrayList<PVector>();
for(int i=0; i<ax.length; i++)
{
newPts.add(new PVector(ax[i], ay[i]));
}
hullPoints = new JarvisPoints(newPts);
}
/**
* Add point to hull
* @param p Index of point to add
*/
private void addToHull(int p) {
hx.add(pts.pts[p].x);
hy.add(pts.pts[p].y);
}
/**
* The PseudoAngle increases as the angle from vertical increases. Current implementation has the maximum pseudo angle < 4.
* The pseudo angle for each quadrant is 1. The algorithm finds where the angle intersects a square and measures the
* perimeter of the square at that point
*/
double pseudoAngle(double dx, double dy) {
if (dx >= 0 && dy >= 0)
return quadrantOnePseudoAngle(dx, dy);
if (dx >= 0 && dy < 0)
return 1 + quadrantOnePseudoAngle(Math.abs(dy), dx);
if (dx < 0 && dy < 0)
return 2 + quadrantOnePseudoAngle(Math.abs(dx), Math.abs(dy));
if (dx < 0 && dy >= 0)
return 3 + quadrantOnePseudoAngle(dy, Math.abs(dx));
throw new Error("pseudoAngle()... Impossible");
}
double quadrantOnePseudoAngle(double dx, double dy) {
return dx / (dy + dx);
}
public JarvisPoints getHullPoints() {
return hullPoints;
}
}
/**
* Array of points for Jarvis March algorithm
* Based on JarvisPoints class by UncleBob
* @author davidgordon
*/
class JarvisPoints
{
public PVector[] pts;
public JarvisPoints(ArrayList<PVector> newPts)
{
pts = new PVector[newPts.size()];
for(int i=0; i<newPts.size(); i++)
pts[i] = newPts.get(i);
}
// Find starting point, i.e. point with the lowest X with ties going to the lowest Y. This guarantees next point over is clockwise.
int startingPoint()
{
double minX = pts[0].x;
double minY = pts[0].y;
int iMin = 0;
for (int i = 1; i < pts.length; i++)
{
if (pts[i].x < minX)
{
minX = pts[i].x;
iMin = i;
}
else if (minX == pts[i].x && pts[i].y < minY)
{
minY = pts[i].y;
iMin = i;
}
}
return iMin;
}
}
/**
* Check Unix path -- Debugging
*/
public void checkPath()
{
MV_Command commandExecutor;
ArrayList<String> command = new ArrayList<String>();
command = new ArrayList<String>(); /* Create small_images directory */
command.add("env");
// command.add(programName);
commandExecutor = new MV_Command("", command);
try {
int result = commandExecutor.execute();
StringBuilder stderr = commandExecutor.getStandardError();
StringBuilder stdout = commandExecutor.getStandardOutput();
if (stderr.length() > 0 || result != 0)
System.out.println("Utilities.checkUnixPath() ... result:"+result+" stderr:"+stderr.toString());
System.out.println("Utilities.checkUnixPath()... stdout: "+stdout.toString());
}
catch(Throwable t)
{
System.out.println("Throwable t while checking Unix PATH:"+t);
}
}
/**
* @param c Calendar date
* @return Sunset time between 0. and 1.
* Get sunset time for given calendar date
*/
public float getSunsetTime(Calendar c, Location location)
{
// Location location = new Location("39.9522222", "-75.1641667"); // ??????
SunriseSunsetCalculator calculator = new SunriseSunsetCalculator(location, "America/Los_Angeles");
Calendar sr = calculator.getOfficialSunriseCalendarForDate(c); // Get sunrise time
Calendar ss = calculator.getOfficialSunsetCalendarForDate(c); // Get sunset time
/* Adjust for sunset time */
int cHour, cMin, cSec, srHour, srMin, srSec, ssHour, ssMin, ssSec;
int cDay, cMonth, cYear;
cYear = c.get(Calendar.YEAR);
cMonth = c.get(Calendar.MONTH);
cDay = c.get(Calendar.DAY_OF_MONTH);
cHour = c.get(Calendar.HOUR_OF_DAY); // Adjust for New York time
cMin = c.get(Calendar.MINUTE);
cSec = c.get(Calendar.SECOND);
srHour = sr.get(Calendar.HOUR_OF_DAY);
srMin = sr.get(Calendar.MINUTE);
srSec = sr.get(Calendar.SECOND);
ssHour = ss.get(Calendar.HOUR_OF_DAY);
ssMin = ss.get(Calendar.MINUTE);
ssSec = ss.get(Calendar.SECOND);
System.out.println("---> ssHour:"+ssHour);
if (cHour > ssHour)
{
float ssDiff = (cHour * 60 + cMin + cSec/60.f) - (ssHour * 60 + ssMin + ssSec/60.f);
System.out.println("ssDiff:"+ssDiff);
// if (ssDiff > p.minutesPastSunset) {
// if (p.p.debug.debugExif)
// PApplet.print("Adjusted Sunset Length from:" + p.minutesPastSunset);
//
// p.minutesPastSunset = ssDiff;
//
// if (p.p.debug.debugExif)
// System.out.println(" to:" + p.minutesPastSunset);
// }
}
if (cHour < srHour)
{
float srDiff = (srHour * 60 + srMin + srSec/60.f) - (cHour * 60 + cMin + cSec/60.f);
System.out.println("srDiff:"+srDiff);
// if (srDiff > p.minutesBeforeSunrise)
// {
// PApplet.print("Adjusted Sunrise Length from:" + p.sunriseLength);
// p.minutesBeforeSunrise = srDiff;
// System.out.println(" to:" + p.sunriseLength);
// }
}
if (cHour > ssHour)
{
System.out.println("Difference in Sunset Time (min.): " + ((cHour * 60 + cMin + cSec/60.f) - (ssHour * 60 + ssMin + ssSec/60.f)));
System.out.print("Hour:" + cHour);
System.out.println(" Min:" + cMin);
System.out.print("Sunset Hour:" + ssHour);
System.out.println(" Sunset Min:" + ssMin);
}
//
// if (cHour < srHour && p.p.debug.debugExif && p.p.debug.debugDetail) {
// System.out.println("Difference in Sunrise Time (min.): " + ((srHour * 60 + srMin + srSec/60.f) - (cHour * 60 + cMin + cSec/60.f)));
// PApplet.print("Hour:" + cHour);
// System.out.println(" Min:" + cMin);
// PApplet.print("Sunrise Hour:" + srHour);
// System.out.println(" Sunrise Min:" + srMin);
// }
float sunriseTime = srHour * 60 + srMin + srSec/60.f;
float sunsetTime = ssHour * 60 + ssMin + ssSec/60.f;
float dayLength = sunsetTime - sunriseTime;
float cTime = cHour * 60 + cMin + cSec/60.f;
// float time = PApplet.constrain(mapValue(cTime, sunriseTime, sunsetTime, 0.f, 1.f), 0.f, 1.f); // Time of day when photo was taken
float time = mapValue(cTime, sunriseTime, sunsetTime, 0.f, 1.f); // Time of day when photo was taken
// if (sunsetTime > p.lastSunset) {
// p.lastSunset = sunsetTime;
// }
int daysInMonth = 0, daysCount = 0;
for (int i = 1; i < cMonth; i++) // Find number of days in prior months
{
daysInMonth = getDaysInMonth(i, cYear); // Get days in month
daysCount += daysInMonth;
}
// int startYear = 2013;
// int date = (year - startYear) * 365 + daysCount + day;
float date = daysCount + cDay; // Days since Jan. 1st // NOTE: need to account for leap years!
// int endDate = 5000;
date = PApplet.constrain(mapValue(date, 0.f, 365, 0.f, 1.f), 0.f, 1.f); // NOTE: need to account for leap years!
time = mapValue(sunsetTime, 0.f, 1439.f, 0.f, 1.f); // Time of day when photo was taken
return time; // Date between 0.f and 1.f, time between 0. and 1., dayLength in minutes
}
/**
* @param c Calendar date
* @return Sunrise time between 0. and 1.
* Get sunrise time for given calendar date
*/
public float getSunriseTime(Calendar c, Location location)
{
// Location location = new Location("39.9522222", "-75.1641667"); // ??????
SunriseSunsetCalculator calculator = new SunriseSunsetCalculator(location, "America/Los_Angeles");
Calendar sr = calculator.getOfficialSunriseCalendarForDate(c); // Get sunrise time
Calendar ss = calculator.getOfficialSunsetCalendarForDate(c); // Get sunset time
/* Adjust for sunset time */
int cHour, cMin, cSec, srHour, srMin, srSec, ssHour, ssMin, ssSec;
int cDay, cMonth, cYear;
cYear = c.get(Calendar.YEAR);
cMonth = c.get(Calendar.MONTH);
cDay = c.get(Calendar.DAY_OF_MONTH);
cHour = c.get(Calendar.HOUR_OF_DAY); // Adjust for New York time
cMin = c.get(Calendar.MINUTE);
cSec = c.get(Calendar.SECOND);
srHour = sr.get(Calendar.HOUR_OF_DAY);
srMin = sr.get(Calendar.MINUTE);
srSec = sr.get(Calendar.SECOND);
ssHour = ss.get(Calendar.HOUR_OF_DAY);
ssMin = ss.get(Calendar.MINUTE);
ssSec = ss.get(Calendar.SECOND);
System.out.println("---> ssHour:"+ssHour);
// if (cHour > ssHour)
// {
// float ssDiff = (cHour * 60 + cMin + cSec/60.f) - (ssHour * 60 + ssMin + ssSec/60.f);
// System.out.println("ssDiff:"+ssDiff);
// if (ssDiff > p.minutesPastSunset) {
// if (p.p.debug.debugExif)
// PApplet.print("Adjusted Sunset Length from:" + p.minutesPastSunset);
//
// p.minutesPastSunset = ssDiff;
//
// if (p.p.debug.debugExif)
// System.out.println(" to:" + p.minutesPastSunset);
// }
// }
if (cHour < srHour)
{
float srDiff = (srHour * 60 + srMin + srSec/60.f) - (cHour * 60 + cMin + cSec/60.f);
System.out.println("srDiff:"+srDiff);
// if (srDiff > p.minutesBeforeSunrise)
// {
// PApplet.print("Adjusted Sunrise Length from:" + p.sunriseLength);
// p.minutesBeforeSunrise = srDiff;
// System.out.println(" to:" + p.sunriseLength);
// }
}
if (cHour < srHour) {
System.out.println("Difference in Sunrise Time (min.): " + ((srHour * 60 + srMin + srSec/60.f) - (cHour * 60 + cMin + cSec/60.f)));
System.out.print("Hour:" + cHour);
System.out.println(" Min:" + cMin);
System.out.print("Sunrise Hour:" + srHour);
System.out.println(" Sunrise Min:" + srMin);
}
float sunriseTime = srHour * 60 + srMin + srSec/60.f;
float sunsetTime = ssHour * 60 + ssMin + ssSec/60.f;
// float dayLength = sunsetTime - sunriseTime;
float cTime = cHour * 60 + cMin + cSec/60.f;
// float time = PApplet.constrain(mapValue(cTime, sunriseTime, sunsetTime, 0.f, 1.f), 0.f, 1.f); // Time of day when photo was taken
float time = mapValue(cTime, sunriseTime, sunsetTime, 0.f, 1.f); // Time of day when photo was taken
// if (sunsetTime > p.lastSunset) {
// p.lastSunset = sunsetTime;
// }
int daysInMonth = 0, daysCount = 0;
for (int i = 1; i < cMonth; i++) // Find number of days in prior months
{
daysInMonth = getDaysInMonth(i, cYear); // Get days in month
daysCount += daysInMonth;
}
// int startYear = 2013;
// int date = (year - startYear) * 365 + daysCount + day;
float date = daysCount + cDay; // Days since Jan. 1st // NOTE: need to account for leap years!
// int endDate = 5000;
date = PApplet.constrain(mapValue(date, 0.f, 365, 0.f, 1.f), 0.f, 1.f); // NOTE: need to account for leap years!
time = mapValue(sunriseTime, 0.f, 1439.f, 0.f, 1.f); // Time of day when photo was taken
return time; // Date between 0.f and 1.f, time between 0. and 1., dayLength in minutes
}
// private PImage getDesaturated(PImage in, float amt)
// {
// PImage out = in.get();
// for (int i = 0; i < out.pixels.length; i++) {
// int c = out.pixels[i];
// float h = p.p.p.hue(c);
// float s = p.p.p.saturation(c) * amt;
// float b = p.p.p.brightness(c);
// out.pixels[i] = p.p.p.color(h, s, b);
// }
// return out;
// }
//
// private PImage getFaintImage(PImage image, float amt)
// {
// PImage out = image.get();
// for (int i = 0; i < out.pixels.length; i++) {
// int c = out.pixels[i];
// float h = p.p.p.hue(c);
// float s = p.p.p.saturation(c) * amt;
// float b = p.p.p.brightness(c) * amt;
// out.pixels[i] = p.p.p.color(h, s, b);
// }
// return out;
// }
// public float calculateAverageDistance(float[] distances)
// {
// float sum = 0;
// float result;
//
// for (int i=0; i<distances.length; i++)
// {
// float dist = distances[i];
// sum += dist;
// }
//
// if (distances.length > 0)
// result = sum / distances.length;
// else
// result = 0.f;
//
// return result;
// }
/**
* @param hour UTC hour
* @return Corresponding hour in Pacific Time
*/
// public WMV_Time utcToPacificTime(WMV_Time time)
// {
// int year = time.getYear();
// int day = time.getDay();
// int month = time.getMonth();
// int hour = time.getHour();
//
// ZonedDateTime utcDateTime = ZonedDateTime.of(year, month, day, hour, time.getMinute(), time.getSecond(), time.getMillisecond(), ZoneId.of("UTC"));
// ZonedDateTime localDateTime = utcDateTime.withZoneSameInstant(ZoneId.of("America/Los_Angeles"));
//
// WMV_Time result = new WMV_Time( localDateTime, time.getID(), time.getClusterID(), time.getMediaType(), "America/Los_Angeles" );
// return result;
// }
}
|
3e189d7f39c9e3f7e61f77473b884adf68c79e3d | 718 | java | Java | common-core-open/src/main/java/com/bbn/bue/common/files/KeyValueSink.java | rgabbard-bbn/bue-common-open | d618652674d647867306e2e4b987a21b7c29c015 | [
"MIT"
] | null | null | null | common-core-open/src/main/java/com/bbn/bue/common/files/KeyValueSink.java | rgabbard-bbn/bue-common-open | d618652674d647867306e2e4b987a21b7c29c015 | [
"MIT"
] | 10 | 2019-03-17T15:48:45.000Z | 2019-03-17T15:49:01.000Z | common-core-open/src/main/java/com/bbn/bue/common/files/KeyValueSink.java | rgabbard-bbn/bue-common-open | d618652674d647867306e2e4b987a21b7c29c015 | [
"MIT"
] | null | null | null | 27.615385 | 88 | 0.724234 | 10,470 | package com.bbn.bue.common.files;
import java.io.IOException;
/**
* Something which accepts key value pairs. Typically this will write to some data store
* which can later be opened as a {@link KeyValueSource}, but this is not required.
*
* Some standard implementations are provided in {@link KeyValueSinks}.
*
* @param <K> type of the key
* @param <V> type of the value
* @author Constantine Lignos, Ryan Gabbard
*/
public interface KeyValueSink<K, V> extends AutoCloseable {
/**
* Put the specified key and value.
*/
void put(K key, V value) throws IOException;
// This override is necessary to change the exception signature from Exception
@Override
void close() throws IOException;
}
|
3e189e5827dca079e7e0f83080c1bc5eb4447d9c | 170 | java | Java | core-lib/es5/src/main/java/def/dom/OES_element_index_uint.java | chfeiler/jsweet | 2421eea53d6f83b8e0cd1574de50492a41ccd385 | [
"Apache-2.0"
] | 1,374 | 2015-11-18T19:09:59.000Z | 2022-03-27T16:33:01.000Z | core-lib/es5/src/main/java/def/dom/OES_element_index_uint.java | chfeiler/jsweet | 2421eea53d6f83b8e0cd1574de50492a41ccd385 | [
"Apache-2.0"
] | 661 | 2015-11-22T08:00:56.000Z | 2022-03-07T07:11:15.000Z | core-lib/es5/src/main/java/def/dom/OES_element_index_uint.java | chfeiler/jsweet | 2421eea53d6f83b8e0cd1574de50492a41ccd385 | [
"Apache-2.0"
] | 193 | 2015-12-04T16:00:18.000Z | 2022-03-22T06:06:07.000Z | 24.285714 | 59 | 0.794118 | 10,471 | package def.dom;
public class OES_element_index_uint extends def.js.Object {
public static OES_element_index_uint prototype;
public OES_element_index_uint(){}
}
|
3e189e5c13b0812bb118f75ec060300ed22c968f | 17,259 | java | Java | app/src/main/java/com/romickid/simpbook/fragments/FragmentExpense.java | romic7x/Simpbook | ee71b8dd8714bbc3dd2932fdcd34358fbaf1fce3 | [
"BSD-3-Clause"
] | 1 | 2019-01-03T22:15:50.000Z | 2019-01-03T22:15:50.000Z | app/src/main/java/com/romickid/simpbook/fragments/FragmentExpense.java | romic7x/Simpbook | ee71b8dd8714bbc3dd2932fdcd34358fbaf1fce3 | [
"BSD-3-Clause"
] | null | null | null | app/src/main/java/com/romickid/simpbook/fragments/FragmentExpense.java | romic7x/Simpbook | ee71b8dd8714bbc3dd2932fdcd34358fbaf1fce3 | [
"BSD-3-Clause"
] | null | null | null | 30.709964 | 113 | 0.61481 | 10,472 | package com.romickid.simpbook.fragments;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import com.romickid.simpbook.R;
import com.romickid.simpbook.database.AccountDb;
import com.romickid.simpbook.database.CategoryDb;
import com.romickid.simpbook.database.CustomSQLiteOpenHelper;
import com.romickid.simpbook.database.RecordDb;
import com.romickid.simpbook.database.SubcategoryDb;
import com.romickid.simpbook.database.TemplateDb;
import com.romickid.simpbook.main.ActivityMain;
import com.romickid.simpbook.util.Account;
import com.romickid.simpbook.util.Collection;
import com.romickid.simpbook.util.Record;
import com.romickid.simpbook.util.SpinnerAdapterAccount;
import com.romickid.simpbook.util.Class1;
import com.romickid.simpbook.util.Class2;
import com.romickid.simpbook.util.SpinnerAdapterClass2;
import com.romickid.simpbook.util.Date;
import com.romickid.simpbook.util.SpinnerAdapterClass1;
import static com.romickid.simpbook.util.Class1.sortListClass1s;
import static com.romickid.simpbook.util.Date.*;
import static com.romickid.simpbook.util.Money.*;
import static com.romickid.simpbook.util.Other.displayToast;
import static com.romickid.simpbook.util.Remark.createDialogRemark;
public class FragmentExpense extends Fragment {
private View view;
private Spinner spinnerClass1;
private Spinner spinnerClass2;
private Spinner spinnerAccount;
private EditText editTextMoney;
private TextView textViewDate;
private TextView textViewRemark;
private FloatingActionButton buttonAdd;
private SpinnerAdapterClass1 adapterClass1;
private SpinnerAdapterClass2 adapterClass2;
private SpinnerAdapterAccount adapterAccount;
private SQLiteDatabase sqLiteDatabase;
private CategoryDb class1Db;
private SubcategoryDb class2Db;
private AccountDb accountDb;
private RecordDb recordDb;
private TemplateDb collectionDb;
private ArrayList<Class1> listClass1s;
private ArrayList<Class2> listClass2s;
private ArrayList<Account> listAccounts;
private int class1Id;
private String recordScheme;
private int updateRecordId;
private int insertCollectionId;
private OnFragmentInteractionListener fragmentInteractionListener;
// Fragment相关
public FragmentExpense() {
}
public static FragmentExpense newInstance() {
FragmentExpense fragment = new FragmentExpense();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_expense, container, false);
initFindById();
initRecordScheme();
initMoney();
initDate();
initRemark();
initDatabase();
initData();
checkDataValidityEnd();
initClass();
initAccount();
initButton();
updateDataForUpdateScheme();
updateDataForInsertCollectionScheme();
return view;
}
@Override
public void onResume() {
super.onResume();
initData();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
fragmentInteractionListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
fragmentInteractionListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
// 初始化相关
/**
* 初始化Id
*/
private void initFindById() {
editTextMoney = view.findViewById(R.id.fexpense_editview_money);
spinnerClass1 = view.findViewById(R.id.fexpense_spinner_class1);
spinnerClass2 = view.findViewById(R.id.fexpense_spinner_class2);
spinnerAccount = view.findViewById(R.id.fexpense_spinner_account);
textViewDate = view.findViewById(R.id.fexpense_textview_date);
textViewRemark = view.findViewById(R.id.fexpense_textview_remark);
buttonAdd = view.findViewById(R.id.fexpense_button_add);
}
/**
* 初始化记录形式: Insert / Update
*/
private void initRecordScheme() {
recordScheme = getActivity().getIntent().getStringExtra("RecordScheme");
if (recordScheme.equals("Update")) {
updateRecordId = Integer.valueOf(getActivity().getIntent().getStringExtra("RecordUpdateId"));
}
if (recordScheme.equals("InsertFromCollection")) {
insertCollectionId = Integer.valueOf(getActivity().getIntent().getStringExtra("RecordCollectionId"));
}
}
/**
* 初始化金额
*/
private void initMoney() {
setEditTextDecimalScheme(editTextMoney);
}
/**
* 初始化分类
*/
private void initClass() {
adapterClass1 = new SpinnerAdapterClass1(getActivity(), listClass1s);
spinnerClass1.setAdapter(adapterClass1);
adapterClass2 = new SpinnerAdapterClass2(getActivity(), listClass2s);
spinnerClass2.setAdapter(adapterClass2);
setListenerSpinnerClass1();
}
/**
* 初始化账户
*/
private void initAccount() {
adapterAccount = new SpinnerAdapterAccount(getActivity(), listAccounts);
spinnerAccount.setAdapter(adapterAccount);
}
/**
* 初始化日期
*/
private void initDate() {
setDefaultDate();
setListenerDate();
}
/**
* 初始化备注
*/
private void initRemark() {
setDefaultRemark();
setListenerRemark();
}
/**
* 初始化按钮
*/
private void initButton() {
buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
switch (recordScheme) {
case "Insert":
case "InsertFromCollection":
Record recordInsert = getRecordInsert();
String messageInsert = insertRecord(recordInsert);
if (messageInsert.equals("成功")) {
displayToast(messageInsert, getContext(), 0);
Intent intent = new Intent(getContext(), ActivityMain.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
getActivity().finish();
} else {
displayToast(messageInsert, getContext(), 1);
}
break;
case "Update":
Record recordUpdate = getRecordUpdate(updateRecordId);
String messageUpdate = updateRecord(recordUpdate);
if (messageUpdate.equals("成功")) {
displayToast(messageUpdate, getContext(), 0);
getActivity().finish();
} else {
displayToast(messageUpdate, getContext(), 1);
}
break;
case "Collection":
Collection collection = getCollectionInsert();
String messageCollectionInsert = insertCollection(collection);
if (messageCollectionInsert.equals("成功")) {
displayToast(messageCollectionInsert, getContext(), 0);
getActivity().finish();
} else {
displayToast(messageCollectionInsert, getContext(), 1);
}
break;
default:
displayToast("内部错误: RecordScheme值错误", getContext(), 1);
break;
}
getActivity().finish();
}
});
}
/**
* 初始化数据库
*/
private void initDatabase() {
CustomSQLiteOpenHelper customSQLiteOpenHelper = new CustomSQLiteOpenHelper(getContext());
sqLiteDatabase = customSQLiteOpenHelper.getWritableDatabase();
class1Db = new CategoryDb(sqLiteDatabase);
class2Db = new SubcategoryDb(sqLiteDatabase);
accountDb = new AccountDb(sqLiteDatabase);
recordDb = new RecordDb(sqLiteDatabase);
collectionDb = new TemplateDb(sqLiteDatabase);
}
/**
* 初始化数据
*/
private void initData() {
updateListClass1s();
updateListClass2s();
updateListAccounts();
}
// 分类相关
/**
* 为SpinnerClass1设置与class1Id实例相同的位置
*
* @param class1Id 需要显示的class1实例id
*/
private void setSpinnerPositionClass1ById(int class1Id) {
for (int i = 0; i < listClass1s.size(); i++) {
if (class1Id == listClass1s.get(i).getId()) {
spinnerClass1.setSelection(i);
}
}
}
/**
* 为SpinnerClass2设置与class2Id实例相同的位置
*
* @param class2Id 需要显示的class2实例id
*/
private void setSpinnerPositionClass2ById(int class2Id) {
for (int i = 0; i < listClass2s.size(); i++) {
if (class2Id == listClass2s.get(i).getId()) {
spinnerClass2.setSelection(i);
}
}
}
/**
* 为SpinnerClass1设置与Class2联动的Listener
*/
private void setListenerSpinnerClass1() {
spinnerClass1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
class1Id = ((Class1) spinnerClass1.getSelectedItem()).getId();
updateListClass2s();
adapterClass2 = new SpinnerAdapterClass2(getActivity(), listClass2s);
spinnerClass2.setAdapter(adapterClass2);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
}
// 账户相关
/**
* 为SpinnerAccount设置与accountId实例相同的位置
*
* @param accountId 需要显示的account实例id
*/
private void setSpinnerPositionAccountById(int accountId) {
for (int i = 0; i < listAccounts.size(); i++) {
if (accountId == listAccounts.get(i).getId()) {
spinnerAccount.setSelection(i);
}
}
}
// 日期相关
/**
* 设置日期的默认形式(使用者使用的当天日期)
*/
private void setDefaultDate() {
setTextViewDate(textViewDate, new Date());
}
/**
* 设置日期的Listener
*/
private void setListenerDate() {
textViewDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
createDialogDate(textViewDate, getContext()).show();
}
});
}
// 备注相关
/**
* 设置备注的默认形式
*/
private void setDefaultRemark() {
textViewRemark.setText("None");
}
/**
* 设置备注的Listener
*/
private void setListenerRemark() {
textViewRemark.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
createDialogRemark(textViewRemark, getContext(), getActivity()).show();
}
});
}
// 更新数据相关
/**
* 更新所有一级支出分类信息
*/
private void updateListClass1s() {
listClass1s = class1Db.getCategoryListByType(1); // 1->支出分类
sortListClass1s(listClass1s);
class1Id = listClass1s.get(0).getId();
}
/**
* 更新所有二级支出分类信息
*/
private void updateListClass2s() {
listClass2s = class2Db.subcategoryList(class1Id);
}
/**
* 更新所有账户信息
*/
private void updateListAccounts() {
listAccounts = accountDb.accountList();
}
/**
* 检查数据合法性
*/
private void checkDataValidityEnd() {
for (Class1 class1 : listClass1s) {
ArrayList<Class2> listClass2 = class2Db.subcategoryList(class1.getId());
if (listClass2.isEmpty()) {
getActivity().finish();
displayToast("存在某个一级分类,其不含有二级分类\n请在设置中更新二级分类数据", getContext(), 1);
}
}
}
/**
* 若Scheme为更新状态, 则使用数据更新控件
*/
private void updateDataForUpdateScheme() {
if (recordScheme.equals("Update")) {
Record record = recordDb.getRecordListById(updateRecordId).get(0);
float money = record.getMoney();
int class1Id = record.getClass1Id();
int class2Id = record.getClass2Id();
int accountId = record.getAccountId();
Date date = record.getDate();
String remark = record.getRemark();
setEditTextDecimalMoney(editTextMoney, money);
setSpinnerPositionClass1ById(class1Id);
setSpinnerPositionClass2ById(class2Id);
setSpinnerPositionAccountById(accountId);
setTextViewDate(textViewDate, date);
textViewRemark.setText(remark);
}
}
/**
* 若Scheme为模板添加状态, 则使用数据更新控件
*/
private void updateDataForInsertCollectionScheme() {
if (recordScheme.equals("InsertFromCollection")) {
Collection collection = collectionDb.getTemplateListById(insertCollectionId).get(0);
float money = collection.getMoney();
int class1Id = collection.getClass1Id();
int class2Id = collection.getClass2Id();
int accountId = collection.getAccountId();
String remark = collection.getRemark();
setEditTextDecimalMoney(editTextMoney, money);
setSpinnerPositionClass1ById(class1Id);
setSpinnerPositionClass2ById(class2Id);
setSpinnerPositionAccountById(accountId);
textViewRemark.setText(remark);
}
}
// 修改数据相关
/**
* 向数据库中添加数据
*/
private String insertRecord(Record recordInsert) {
return recordDb.insertRecord(recordInsert);
}
/**
* 向数据库中更新数据
*/
private String updateRecord(Record recordUpdate) {
return recordDb.updateRecord(recordUpdate);
}
/**
* 向数据库中添加模板数据
*/
private String insertCollection(Collection collectionInsert) {
return collectionDb.insertTemplate(collectionInsert);
}
/**
* 获取用于添加的Record数据
*
* @return record数据
*/
private Record getRecordInsert() {
int tAccountId = ((Account) spinnerAccount.getSelectedItem()).getId();
float tMoney = getEditTextMoney(editTextMoney);
int tType = 1; // 1->支出
Date tDate = getDate(textViewDate);
String tRemark = textViewRemark.getText().toString();
int tClass1Id = ((Class1) spinnerClass1.getSelectedItem()).getId();
int tClass2Id = ((Class2) spinnerClass2.getSelectedItem()).getId();
return new Record(tAccountId, tMoney, tType, tDate, tRemark, tClass1Id, tClass2Id);
}
/**
* 获取用于更新的Record数据
*
* @return record数据
*/
private Record getRecordUpdate(int tId) {
int tAccountId = ((Account) spinnerAccount.getSelectedItem()).getId();
float tMoney = getEditTextMoney(editTextMoney);
int tType = 1; // 1->支出
Date tDate = getDate(textViewDate);
String tRemark = textViewRemark.getText().toString();
int tClass1Id = ((Class1) spinnerClass1.getSelectedItem()).getId();
int tClass2Id = ((Class2) spinnerClass2.getSelectedItem()).getId();
return new Record(tId, tAccountId, tMoney, tType, tDate, tRemark, tClass1Id, tClass2Id);
}
/**
* 获取用于添加的Collection数据
*
* @return collection数据
*/
private Collection getCollectionInsert() {
int tAccountId = ((Account) spinnerAccount.getSelectedItem()).getId();
float tMoney = getEditTextMoney(editTextMoney);
int tType = 1; // 1->支出
Date tDate = getDate(textViewDate);
String tRemark = textViewRemark.getText().toString();
int tClass1Id = ((Class1) spinnerClass1.getSelectedItem()).getId();
int tClass2Id = ((Class2) spinnerClass2.getSelectedItem()).getId();
return new Collection(tAccountId, tMoney, tType, tDate, tRemark, tClass1Id, tClass2Id);
}
}
|
3e189e7e2ec6cfee69dbc9c58081672552348c0a | 1,904 | java | Java | driver-pulsar/src/main/java/io/nosqlbench/driver/pulsar/ops/PulsarBatchProducerStartOp.java | MC-JY/nosqlbench | 5902239cba6063d2394ca495f1f5100eb49ca7c1 | [
"Apache-2.0"
] | null | null | null | driver-pulsar/src/main/java/io/nosqlbench/driver/pulsar/ops/PulsarBatchProducerStartOp.java | MC-JY/nosqlbench | 5902239cba6063d2394ca495f1f5100eb49ca7c1 | [
"Apache-2.0"
] | null | null | null | driver-pulsar/src/main/java/io/nosqlbench/driver/pulsar/ops/PulsarBatchProducerStartOp.java | MC-JY/nosqlbench | 5902239cba6063d2394ca495f1f5100eb49ca7c1 | [
"Apache-2.0"
] | null | null | null | 38.08 | 133 | 0.718487 | 10,473 | /*
* Copyright (c) 2022 nosqlbench
*
* 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 io.nosqlbench.driver.pulsar.ops;
import io.nosqlbench.nb.api.errors.BasicError;
import org.apache.commons.compress.utils.Lists;
import org.apache.pulsar.client.api.*;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class PulsarBatchProducerStartOp extends SyncPulsarOp {
// TODO: ensure sane container lifecycle management
public final transient static ThreadLocal<List<CompletableFuture<MessageId>>> threadLocalBatchMsgContainer = new ThreadLocal<>();
public final transient static ThreadLocal<Producer<?>> threadLocalProducer = new ThreadLocal<>();
public PulsarBatchProducerStartOp(Producer<?> batchProducer) {
threadLocalProducer.set(batchProducer);
}
@Override
public void run() {
List<CompletableFuture<MessageId>> container = threadLocalBatchMsgContainer.get();
if (container == null) {
container = Lists.newArrayList();
threadLocalBatchMsgContainer.set(container);
} else {
throw new BasicError("You tried to create a batch message container where one was already" +
" defined. This means you did not flush and unset the last container, or there is an error in your" +
" pulsar op sequencing and ratios.");
}
}
}
|
3e189ea6a716f13f0c653c2ab5b630d9a3a1646d | 5,306 | java | Java | sharding-spring/sharding-jdbc-spring/sharding-jdbc-spring-namespace/src/main/java/org/apache/shardingsphere/shardingjdbc/spring/namespace/parser/EncryptDataSourceBeanDefinitionParser.java | rayoo/incubator-shardingsphere | 04682faf3d31eef68fa066c256ba8574920bb7b5 | [
"Apache-2.0"
] | null | null | null | sharding-spring/sharding-jdbc-spring/sharding-jdbc-spring-namespace/src/main/java/org/apache/shardingsphere/shardingjdbc/spring/namespace/parser/EncryptDataSourceBeanDefinitionParser.java | rayoo/incubator-shardingsphere | 04682faf3d31eef68fa066c256ba8574920bb7b5 | [
"Apache-2.0"
] | 2 | 2022-01-21T23:50:46.000Z | 2022-02-16T01:21:32.000Z | sharding-spring/sharding-jdbc-spring/sharding-jdbc-spring-namespace/src/main/java/org/apache/shardingsphere/shardingjdbc/spring/namespace/parser/EncryptDataSourceBeanDefinitionParser.java | rayoo/incubator-shardingsphere | 04682faf3d31eef68fa066c256ba8574920bb7b5 | [
"Apache-2.0"
] | null | null | null | 54.142857 | 153 | 0.797588 | 10,474 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.shardingjdbc.spring.namespace.parser;
import com.google.common.base.Strings;
import org.apache.shardingsphere.api.config.encryptor.EncryptRuleConfiguration;
import org.apache.shardingsphere.api.config.encryptor.EncryptTableRuleConfiguration;
import org.apache.shardingsphere.shardingjdbc.spring.datasource.SpringEncryptDataSource;
import org.apache.shardingsphere.shardingjdbc.spring.namespace.constants.EncryptDataSourceBeanDefinitionParserTag;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
import java.util.List;
/**
* Encrypt data source parser for spring namespace.
*
* @author panjuan
*/
public final class EncryptDataSourceBeanDefinitionParser extends AbstractBeanDefinitionParser {
@Override
protected AbstractBeanDefinition parseInternal(final Element element, final ParserContext parserContext) {
BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(SpringEncryptDataSource.class);
factory.addConstructorArgValue(parseDataSource(element));
factory.addConstructorArgValue(parseEncryptRuleConfiguration(element));
factory.setDestroyMethodName("close");
return factory.getBeanDefinition();
}
private RuntimeBeanReference parseDataSource(final Element element) {
Element encryptRuleElement = DomUtils.getChildElementByTagName(element, EncryptDataSourceBeanDefinitionParserTag.ENCRYPT_RULE_CONFIG_TAG);
String dataSource = encryptRuleElement.getAttribute(EncryptDataSourceBeanDefinitionParserTag.DATA_SOURCE_NAME_TAG);
return new RuntimeBeanReference(dataSource);
}
private BeanDefinition parseEncryptRuleConfiguration(final Element element) {
Element encryptRuleElement = DomUtils.getChildElementByTagName(element, EncryptDataSourceBeanDefinitionParserTag.ENCRYPT_RULE_CONFIG_TAG);
BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(EncryptRuleConfiguration.class);
factory.addConstructorArgValue(parseTableRulesConfiguration(encryptRuleElement));
parseDefaultEncryptor(factory, encryptRuleElement);
return factory.getBeanDefinition();
}
private List<BeanDefinition> parseTableRulesConfiguration(final Element element) {
Element tableRulesElement = DomUtils.getChildElementByTagName(element, EncryptDataSourceBeanDefinitionParserTag.TABLE_RULES_TAG);
List<Element> tableRuleElements = DomUtils.getChildElementsByTagName(tableRulesElement, EncryptDataSourceBeanDefinitionParserTag.TABLE_RULE_TAG);
List<BeanDefinition> result = new ManagedList<>(tableRuleElements.size());
for (Element each : tableRuleElements) {
result.add(parseTableRuleConfiguration(each));
}
return result;
}
private void parseDefaultEncryptor(final BeanDefinitionBuilder factory, final Element element) {
String defaultEncryptorConfig = element.getAttribute(EncryptDataSourceBeanDefinitionParserTag.DEFAULT_ENCRYPTOR_REF_ATTRIBUTE);
if (!Strings.isNullOrEmpty(defaultEncryptorConfig)) {
factory.addConstructorArgReference(defaultEncryptorConfig);
} else {
factory.addConstructorArgValue(null);
}
}
private BeanDefinition parseTableRuleConfiguration(final Element tableElement) {
BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(EncryptTableRuleConfiguration.class);
factory.addConstructorArgValue(tableElement.getAttribute(EncryptDataSourceBeanDefinitionParserTag.ENCRYPT_TABLE_ATTRIBUTE));
parseEncryptorConfiguration(tableElement, factory);
return factory.getBeanDefinition();
}
private void parseEncryptorConfiguration(final Element tableElement, final BeanDefinitionBuilder factory) {
String encryptor = tableElement.getAttribute(EncryptDataSourceBeanDefinitionParserTag.ENCRYPTOR_REF_ATTRIBUTE);
factory.addConstructorArgReference(encryptor);
}
}
|
3e189ef28c4037b4779734ffdcbf601de6720883 | 1,209 | java | Java | eLMaze-Desktop/core/src/com/mygdx/elmaze/view/menus/ButtonFactory.java | FilipaDurao/LPOO-eLMaze | b4ed7e2ebe98a6e496f2154dd73f79014b2fa992 | [
"MIT"
] | null | null | null | eLMaze-Desktop/core/src/com/mygdx/elmaze/view/menus/ButtonFactory.java | FilipaDurao/LPOO-eLMaze | b4ed7e2ebe98a6e496f2154dd73f79014b2fa992 | [
"MIT"
] | null | null | null | eLMaze-Desktop/core/src/com/mygdx/elmaze/view/menus/ButtonFactory.java | FilipaDurao/LPOO-eLMaze | b4ed7e2ebe98a6e496f2154dd73f79014b2fa992 | [
"MIT"
] | null | null | null | 31 | 124 | 0.716294 | 10,475 | package com.mygdx.elmaze.view.menus;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.Align;
/**
* Implements functions related to the creation of Buttons
*/
public class ButtonFactory {
/**
* Creates a Button object
*
* @param upTexture The texture when the Button is up
* @param downTexture The texture when the Button is down (pressed)
* @param xPos The x position of the Button
* @param yPos The y position of the Button
* @param width The Button's width
* @param height The Button's height
*
* @return Returns a Button object
*/
public static Button makeButton(Texture upTexture, Texture downTexture, float xPos, float yPos, int width, int height) {
Button button = new Button(
new TextureRegionDrawable(new TextureRegion(upTexture)),
new TextureRegionDrawable(new TextureRegion(downTexture))
);
button.setBounds(xPos, yPos, width, height);
button.setPosition(xPos, yPos, Align.center);
return button;
}
}
|
3e18a0799bcd48b72d149c55a942d84629e12e82 | 37,960 | java | Java | TerrainViewer/src/ch/ethz/karto/map3d/Map3DViewer.java | OSUCartography/TerrainViewer | 588f51a23c66ae7fd06cc0df11bb021f820f4bb7 | [
"MIT"
] | 2 | 2015-01-16T19:27:33.000Z | 2017-11-01T15:56:13.000Z | TerrainViewer/src/ch/ethz/karto/map3d/Map3DViewer.java | OSUCartography/TerrainViewer | 588f51a23c66ae7fd06cc0df11bb021f820f4bb7 | [
"MIT"
] | null | null | null | TerrainViewer/src/ch/ethz/karto/map3d/Map3DViewer.java | OSUCartography/TerrainViewer | 588f51a23c66ae7fd06cc0df11bb021f820f4bb7 | [
"MIT"
] | null | null | null | 31.294312 | 101 | 0.595601 | 10,476 | package ch.ethz.karto.map3d;
import ch.ethz.karto.map3d.gui.Map3DOptionsPanel;
import javax.media.opengl.DebugGL2;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLProfile;
import javax.media.opengl.awt.GLCanvas;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.glu.GLU;
import ika.gui.GUIUtil;
import ika.utils.ErrorDialog;
import ika.utils.TextWindow;
import java.awt.Color;
import java.awt.Component;
import java.awt.Frame;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.media.opengl.awt.GLJPanel;
import com.jogamp.opengl.util.awt.Screenshot;
/**
* This class implements a Map3D viewer.
*/
public class Map3DViewer extends GLCanvas implements GLEventListener {
private static final float MAX_CYLINDER_FOV = 165f;
private boolean highResCylindricalRendering = false;
public void setHighResCylindricalRendering(boolean useHighRes) {
if (useHighRes != highResCylindricalRendering) {
highResCylindricalRendering = useHighRes;
if (this.camera == Camera.cylindrical) {
this.updateView();
}
}
}
private boolean bindLightDirectionToViewDirection = false;
public void setBindLightDirectionToViewDirection(boolean bind) {
if (this.bindLightDirectionToViewDirection != bind) {
this.bindLightDirectionToViewDirection = bind;
if (this.camera == Camera.cylindrical) {
this.updateView();
}
}
}
public enum Camera {
perspective, parallelOblique, planOblique, orthogonal, cylindrical
}
public static String camera(Camera camera) {
switch (camera) {
case perspective:
return "Perspective View";
case parallelOblique:
return "Parallel Oblique";
case planOblique:
return "Plan Oblique";
case orthogonal:
return "2D Orthogonal";
case cylindrical:
return "Cylindrical";
default:
return "";
}
}
public static Camera camera(String name) {
if ("Perspective View".equals(name)) {
return Camera.perspective;
}
if ("Parallel Oblique".equals(name)) {
return Camera.parallelOblique;
}
if ("Plan Oblique".equals(name)) {
return Camera.planOblique;
}
if ("2D Orthogonal".equals(name)) {
return Camera.orthogonal;
}
if ("Cylindrical".equals(name)) {
return Camera.cylindrical;
}
return Camera.perspective;
}
/**
* only use glu in callbacks
*/
private GLU glu_callback_only;
private Component component;
private GLAutoDrawable drawable;
private Map3DModel model;
private Map3DTexture texture;
private Map3DAnimation animation;
private boolean antialiasing = true;
private Map3DMouseHandler mouseHandler;
/**
* Default rotation around x-axis. Positive values between 0 and 90 degrees.
* 0 degree corresponds to vertical view, 90 degrees to a horizontal view.
*/
private float defaultXAngle = 55.0f;
/**
* Default rotation around z-axis. Positive values corresponds to a
* clockwise rotation. Units in degrees.
*/
private float defaultZAngle = 0.0f;
/**
* Default view angle. A value of 25 degrees corresponds roughly to an
* object of 25 cm size held at an eye distance of 50 cm.
*/
private float defaultViewAngle = 25.0f;
private float defaultShiftX = 0f;
private float defaultShiftY = 0f;
/**
* Minimum and maximum angle around x-axis.
*/
protected static final float MIN_X_ANGLE = 1.0f, MAX_X_ANGLE = 90.0f;
/**
* Minimum, maximum, and default distance from model.
*/
//private static final float MIN_DISTANCE = 1.2f, MAX_DISTANCE = 3.6f, DEFAULT_DISTANCE = 2.4f;
public static final float MIN_DISTANCE = 0.2f, MAX_DISTANCE = 3f;
private float defaultDistance = 2.4f;
private float defaultCylindricalHeight = 0.2f;
/**
* Rotation around the x axis in degrees.
*/
protected float xAngle = defaultXAngle;
/**
* Rotation around the z axis in degrees.
*/
protected float zAngle = defaultZAngle;
/**
* Distance of camera from origin
*/
protected float viewDistance = defaultDistance;
/**
* Height of cylindrical camera
*/
private float cylindricalHeight = defaultCylindricalHeight;
/**
* Field of view of camera
*/
protected float fov = defaultViewAngle;
protected float shearX = 0;
protected float shearY = 0;
protected float shiftX = defaultShiftX;
protected float shiftY = defaultShiftY;
private float bgRed = 1.0f;
private float bgGreen = 1.0f;
private float bgBlue = 1.0f;
protected boolean shadingEnabled = true;
private Camera camera = Camera.planOblique;//Camera.perspective;
protected static final float MIN_SHEAR_ANGLE = 0.0f, MAX_SHEAR_ANGLE = 180.0f;
private static final float DEFAULT_LIGHT_AMBIENT = 0.4f;
private static final float DEFAULT_LIGHT_DIFFUSE = 0.6f;
private static final float DEFAULT_LIGHT_AZIMUTH = 315; //225;
private static final float DEFAULT_LIGHT_ZENITH = 45;
private float ambientLight = DEFAULT_LIGHT_AMBIENT;
private float diffuseLight = DEFAULT_LIGHT_DIFFUSE;
private float lightAzimuth = DEFAULT_LIGHT_AZIMUTH;
private float lightZenith = DEFAULT_LIGHT_ZENITH;
private static final float Z_NEAR = 0.001f;
private static final float Z_FAR = 100.0f;
private float aspectRatio_callback_only = -1;
private static final int DEF_CYLINDER_IMAGES_COUNT = 8;
private boolean fogEnabled = false;
private float fogStart = 0f;
private float fogEnd = 1f;
private Color fogColor = Color.WHITE;
/**
* @return the antialiasing
*/
public boolean isAntialiasing() {
return antialiasing;
}
/**
* @param antialiasing the antialiasing to set
*/
public void setAntialiasing(boolean antialiasing) {
this.antialiasing = antialiasing;
}
private int getCylindricalImagesCount() {
if (this.highResCylindricalRendering) {
return this.drawable.getContext().getGLDrawable().getWidth();
} else {
return DEF_CYLINDER_IMAGES_COUNT;
}
}
public static enum GLComponentType {
GL_AWT, GL_Swing
};
/**
* Map3D viewer constructor
*
* @param glComponentType With GL_AWT a heavyweight AWT component GLCanvas
* is created. With GL_Swing a lightweight GLJPanel is created. GLCanvas
* offers faster rendering, but may cause problems when combined with other
* Swing components with certain layout managers.
*/
public Map3DViewer(GLComponentType glComponentType, GLProfile glProfile) {
this(glComponentType, glProfile, null);
}
/**
* Map3D viewer constructor
*
* @param glComponentType With GL_AWT a heavyweight AWT component GLCanvas
* is created. With GL_Swing a lightweight GLJPanel is created. GLCanvas
* offers faster rendering, but may cause problems when combined with other
* Swing components with certain layout managers.
*/
public Map3DViewer(GLComponentType glComponentType, GLProfile glProfile, Map3DModel model) {
this.init(glComponentType, glProfile, model);
}
private void init(GLComponentType glComponentType, GLProfile profile, Map3DModel model) {
GLCapabilities caps = new GLCapabilities(profile);
// use sample buffers for antialiasing
caps.setSampleBuffers(true);
// set the number of supersampling for antialising
caps.setNumSamples(Map3DOptionsPanel.getAntialiasingLevel());
if (glComponentType == GLComponentType.GL_Swing) {
this.component = new GLJPanel(caps);
} else {
this.component = new GLCanvas(caps);
}
this.drawable = (GLAutoDrawable)this.component;
this.component.setSize(1024, 768);
//((Component) this.component).setIgnoreRepaint(true);
this.drawable.addGLEventListener(this);
if (model == null) {
model = new Map3DModelVBOShader();
if (!model.canRun()) {
model = new Map3DModelVBO();
}
if (!model.canRun()) {
model = new Map3DModelVertexArrays();
}
}
//model = new Map3DModelVertexArrays();
this.model = model;
this.texture = new Map3DTexture();
this.setAnimation(new Map3DRotationAnimation(this.drawable));
mouseHandler = new Map3DMouseHandler(this);
this.component.addMouseMotionListener(mouseHandler);
this.component.addMouseListener(mouseHandler);
this.component.addMouseWheelListener(mouseHandler);
}
public BufferedImage getImage() {
// Needs the "current context"!
this.drawable.getContext().makeCurrent();
int width = component.getWidth();
int height = component.getHeight();
return Screenshot.readToBufferedImage(width, height);
}
public Map3DModel getModel(){
return this.model;
}
public void setModel(float grid[][], float cellSize) {
Map3DTexture1DMapper mapper = new Map3DNonLinearTexture1DMapper(grid);
this.setModel(grid, cellSize, mapper);
}
public void setModel(float[][] grid, float cellSize, Map3DTexture1DMapper mapper) {
this.model.setModel(grid, cellSize, mapper);
this.updateView();
}
public void setTextureImage(BufferedImage textureImage) {
this.texture.setTexture(textureImage);
this.updateView();
}
public void clearTextureImage() {
this.texture.clearTexture();
this.updateView();
}
public boolean hasTexture() {
return this.texture.hasTexture();
}
public boolean isTexture1D() {
return this.texture.is1D();
}
/**
* Enables or disables light.
*
* @param enable turns light on or off
*/
public void setShading(boolean enable) {
this.shadingEnabled = enable;
this.updateView();
}
public boolean isShading() {
return shadingEnabled;
}
public void enableFog(GL gl1) {
GL2 gl = (GL2)gl1;
if (this.fogEnabled) {
gl.glEnable(GL2.GL_FOG);
float r = fogColor.getRed() / 255f;
float g = fogColor.getGreen() / 255f;
float b = fogColor.getBlue() / 255f;
gl.glFogfv(GL2.GL_FOG_COLOR, new float[]{r, g, b}, 0);
float start = fogStart;
if (camera != Camera.cylindrical) {
start += viewDistance - 0.5f;
}
gl.glFogf(GL2.GL_FOG_START, start);
float end = fogEnd;
if (camera != Camera.cylindrical) {
end += viewDistance - 0.5f;
}
gl.glFogf(GL2.GL_FOG_END, end);
gl.glFogi(GL2.GL_FOG_MODE, GL2.GL_LINEAR);
} else {
gl.glDisable(GL2.GL_FOG);
}
}
/**
* Get the OpenGL component.
*
* @return The OpenGL component
*/
public Component getComponent() {
return (Component) this.component;
}
private void setupLight(GL gl1, double lightAzimuthDeg, double lightZenithDeg) {
GL2 gl = (GL2)gl1;
if (this.shadingEnabled) {
gl.glEnable(GL2.GL_LIGHTING);
gl.glEnable(GL2.GL_LIGHT0);
final double a = -Math.PI / 2 - Math.toRadians(lightAzimuthDeg);
final double z = Math.toRadians(lightZenithDeg);
final double sinz = Math.sin(z);
final float lx = (float) (Math.cos(a) * sinz);
final float ly = (float) (Math.sin(a) * sinz);
final float lz = (float) Math.cos(z);
float light_ambient[] = {ambientLight, ambientLight, ambientLight, 1.0f};
float light_diffuse[] = {diffuseLight, diffuseLight, diffuseLight, 1.0f};
gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_AMBIENT, light_ambient, 0);
gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_DIFFUSE, light_diffuse, 0);
gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_POSITION, new float[]{-lx, ly, lz, 0}, 0);
} else {
// FIXME
gl.glDisable(GL2.GL_LIGHTING);
gl.glDisable(GL2.GL_LIGHT0);
float lmodel_ambient[] = {0f, 0f, 0f, 1.0f};
gl.glLightModelfv(GL2.GL_LIGHT_MODEL_AMBIENT, lmodel_ambient, 0);
}
}
public void setLight(float ambient, float diffuse) {
this.ambientLight = ambient;
this.diffuseLight = diffuse;
this.getComponent().firePropertyChange("view", 0, 1);
}
public float getAmbientLight() {
return ambientLight;
}
public float getDiffuseLight() {
return diffuseLight;
}
public void setLightDirection(float azimuth, float zenith) {
this.lightAzimuth = azimuth;
this.lightZenith = zenith;
this.getComponent().firePropertyChange("view", 0, 1);
}
public float getLightAzimuth() {
return this.lightAzimuth;
}
public float getLightZenith() {
return this.lightZenith;
}
public void defaultShading() {
this.ambientLight = DEFAULT_LIGHT_AMBIENT;
this.diffuseLight = DEFAULT_LIGHT_DIFFUSE;
this.lightAzimuth = DEFAULT_LIGHT_AZIMUTH;
this.lightZenith = DEFAULT_LIGHT_ZENITH;
}
private boolean installDebugGL(GLAutoDrawable drawable) {
GL gl = drawable.getGL();
if (gl == null) {
return false;
}
drawable.setGL(new DebugGL2((GL2)gl));
System.out.println("OpenGL debug mode: glError() called automatically "
+ "after each API call.");
return true;
}
/**
* GLEventListener Initialize material property and light source.
*/
@Override
public void init(GLAutoDrawable drawable) {
// for debugging only
assert installDebugGL(drawable);
GL gl1 = drawable.getGL();
GL2 gl = (GL2)gl1;
glu_callback_only = new GLU();
gl.glShadeModel(GL2.GL_SMOOTH);
gl.glClearColor(this.bgRed, this.bgGreen, this.bgBlue, 1.0f);
gl.glEnable(GL2.GL_DEPTH_TEST); // depth test must be enabled
gl.glHint(GL2.GL_PERSPECTIVE_CORRECTION_HINT, GL2.GL_NICEST);
setupLight(gl, this.lightAzimuth, this.lightZenith);
if (this.shadingEnabled) {
gl.glEnable(GL2.GL_COLOR_MATERIAL);
gl.glColorMaterial(GL2.GL_FRONT, GL2.GL_AMBIENT);
gl.glColor3f(0.5f, 0.5f, 0.5f);
gl.glColorMaterial(GL2.GL_FRONT, GL2.GL_DIFFUSE);
gl.glColor3f(1.0f, 1.0f, 1.0f);
} else {
gl.glDisable(GL2.GL_COLOR_MATERIAL);
}
}
/**
* Computes the height of an image section for the cylindrical projection.
* The cylindrical projection is approximated by CYLINDER_IMAGES_COUNT image
* sections.
*
* @param sectionWidth The width of a section
* @return The height of a tile
*/
private int cylinderSectionHeight(int sectionWidth) {
// the horizontal section of the full circle that this tile displays
double a = Math.toRadians(360f / getCylindricalImagesCount());
// the vertical viewing angle
// avoid tangens of Pi/2
double viewAngleCorr = Math.min(fov, MAX_CYLINDER_FOV);
double b = Math.toRadians(viewAngleCorr);
// the height of the tile
double h = sectionWidth * Math.tan(b / 2) / Math.tan(a / 2);
return (int) h;
}
/**
* GLEventListener Called by the drawable to initiate OpenGL rendering by
* the client.
*
* @param drawable
*/
@Override
public void display(GLAutoDrawable drawable) {
try {
GL gl = drawable.getGL();
gl.glClearColor(this.bgRed, this.bgGreen, this.bgBlue, 1.0f);
gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT | GL2.GL_ACCUM_BUFFER_BIT);
if (camera == Camera.cylindrical) {
displayCylindricalProjection(drawable);
} else {
display_(drawable, this.zAngle);
}
testOpenGLError(gl);
} catch (Throwable e) {
assert displayExtendedErrorDialog(e);
// FIXME try catch block
model.releaseModel(drawable.getGL());
if (model instanceof Map3DModelVBOShader) {
Map3DModel model2 = new Map3DModelVBO();
model2.setModel(model.grid, model.cellSize, model.texture1DMapper);
model = model2;
}
String errorTitle = "Rendering Error";
Frame parent = GUIUtil.getOwnerFrame(getComponent());
ErrorDialog.showErrorDialog(e.getMessage(), errorTitle, e, parent);
}
}
private boolean displayExtendedErrorDialog(Throwable e) {
String errorTitle = "Rendering Error";
StringWriter sw = new StringWriter();
sw.write(errorTitle);
sw.write(System.getProperty("line.separator"));
sw.write("Model: ");
sw.write(model.getClass().getSimpleName());
sw.write(System.getProperty("line.separator"));
if (e.getMessage() != null) {
sw.write(e.getMessage());
sw.write(System.getProperty("line.separator"));
}
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
Frame parent = GUIUtil.getOwnerFrame(getComponent());
new TextWindow(parent, true, true, sw.toString(), errorTitle);
return true;
}
/**
* Throws an exception if an OpenGL error occured since the last call to
* <code>glGetError</code>.
*
* @param gl
*/
private void testOpenGLError(GL gl) {
int errCode = gl.glGetError();
if (errCode != GL2.GL_NO_ERROR) {
StringBuilder sb = new StringBuilder("An OpenGL error occured: Code ");
sb.append(errCode);
sb.append(" - ");
sb.append(glu_callback_only.gluErrorString(errCode));
throw new RuntimeException(sb.toString());
}
}
/**
* Renders multiple perspective images to simulate a cylindrical projection.
*
* @param drawable
*/
private void displayCylindricalProjection(GLAutoDrawable drawable) {
GL gl = drawable.getGL();
// store the initial viewport
int[] vp = new int[4];
gl.glGetIntegerv(GL2.GL_VIEWPORT, vp, 0);
try {
int compH = this.drawable.getContext().getGLDrawable().getHeight();
int compW = this.drawable.getContext().getGLDrawable().getWidth();
float zoom = (viewDistance - MIN_DISTANCE) / (MAX_DISTANCE - MIN_DISTANCE);
// width and height of a single image
int w = (int) (compW / getCylindricalImagesCount() / zoom);
int h = (int) (cylinderSectionHeight(w) / zoom);
// vertical position of the image stripe
int y = (int) ((compH - h) / 2);
// angle covered by each image
float rotAngle = 360f / getCylindricalImagesCount();
// render getCylindricalImagesCount() views, each rotated by rotAngle
for (int i = 0; i < getCylindricalImagesCount(); i++) {
// adjust the viewport: draw to a section of the available space
gl.glViewport(i * w, y, w, h);
// increas the rotation around the z axis
float zAngle_ = this.zAngle - i * rotAngle;
zAngle_ = Map3DViewer.normalizeZAngle(zAngle_);
// render image
display_(drawable, zAngle_);
if (this.highResCylindricalRendering) {
System.out.println("Column: " + i);
}
}
} finally {
// restore the initial viewport
gl.glViewport(vp[0], vp[1], vp[2], vp[3]);
}
}
private void display_(GLAutoDrawable drawable, float zAngle) {
if (this.model == null) {
return;
}
GL gl1 = drawable.getGL();
GL2 gl = (GL2)gl1;
// use antialiasing when mouse is not being dragged.
if (!this.mouseHandler.isDragging() && antialiasing) {
gl.glEnable(GL2.GL_MULTISAMPLE);
} else {
gl.glDisable(GL2.GL_MULTISAMPLE);
}
this.setupProjection(gl);
this.enableFog(gl);
// with standart orientation: up vector 0/1/0
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glLoadIdentity();
if (camera == Camera.cylindrical) {
glu_callback_only.gluLookAt(0, 0, 0, 0, 1, 0, 0, 0, -1);
} else {
// position the camera at 0/0/viewDistance,
// looking at 0/0/0
glu_callback_only.gluLookAt(0, 0, viewDistance, 0, 0, 0, 0, 1, 0);
}
// load the texture if necessary
boolean textureChanged = texture.constructTexture(gl);
if (textureChanged) {
model.textureChanged();
}
// hack for shearing with vertex shader
if (model instanceof Map3DModelVBOShader) {
if (camera != Camera.planOblique) {
((Map3DModelVBOShader) model).setShearing(0, 0);
} else {
((Map3DModelVBOShader) model).setShearing(shearX, shearY);
}
}
// construct the geometry model if necessary
model.loadModel(gl, this.texture);
float modelWidth = this.model.getNormalizedModelWidth();
float modelHeight = this.model.getNormalizedModelHeight();
final float dz;
switch (camera) {
case perspective:
case parallelOblique:
case cylindrical:
dz = -model.getCenterElevation();
break;
default:
dz = 0;
}
// transform light without shearing
{
gl.glPushMatrix();
// rotate
switch (camera) {
case perspective:
case parallelOblique:
gl.glRotatef(xAngle, 1.0f, 0.0f, 0.0f);
}
gl.glRotatef(zAngle, 0.0f, 0.0f, 1.0f);
gl.glTranslatef(-modelWidth / 2, -modelHeight / 2, dz);
float azimuth = this.lightAzimuth;
if (bindLightDirectionToViewDirection) {
azimuth -= zAngle;
}
setupLight(gl, azimuth, this.lightZenith);
gl.glPopMatrix();
}
gl.glPushMatrix();
// vertical and horizontal shift to place model in viewport
// FIXME
// hack for compensating missing vertical shift in Map3DModelVBOShader.gridTexture()
// gl.glTranslatef(0, 0, this.model.getNormalizedMinimumValue());
if (camera != Camera.cylindrical) {
gl.glTranslatef(shiftX, shiftY, 0);
}
/*
// shear for plan oblique rendering
if (camera == Camera.planOblique && (shearX != 0 || shearY != 0)) {
gl.glEnable(GL2.GL_NORMALIZE);
shearMatrix(gl, shearX, -shearY);
gl.glTranslatef(0, 0, -Map3DModel.ZOFFSET);
}
*/
// rotate
switch (camera) {
case perspective:
case parallelOblique:
gl.glRotatef(xAngle, 1, 0, 0);
break;
}
gl.glRotatef(zAngle, 0.0f, 0.0f, 1.0f);
// center position of cylindrical camera on origin
if (camera == Camera.cylindrical) {
gl.glTranslatef(-shiftX / 2f, -shiftY / 2f, -cylindricalHeight);
}
// center model on origin by shifting by half width and size of model
gl.glTranslatef(-modelWidth / 2, -modelHeight / 2, dz);
if (camera == Camera.planOblique) {
gl.glEnable(GL2.GL_NORMALIZE);
// translate for XY shearing, which is proportional to Z
gl.glTranslatef(0, 0, -Map3DModel.ZOFFSET);
}
model.draw(gl, shadingEnabled, fogEnabled);
gl.glPopMatrix();
gl.glFlush();
animation.update(this);
}
private void setupProjection(GL gl1) {
GL2 gl = (GL2)gl1;
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
switch (camera) {
case perspective:
double top = Math.tan(Math.toRadians(fov * 0.5)) * Z_NEAR;
double bottom = -top;
double left = aspectRatio_callback_only * bottom;
double right = aspectRatio_callback_only * top;
gl.glFrustum(left, right, bottom, top, Z_NEAR, Z_FAR);
//glu_callback_only.gluPerspective(fov, aspectRatio_callback_only, Z_NEAR, Z_FAR);
break;
case cylindrical: {
int compW = this.drawable.getContext().getGLDrawable().getWidth();
int w = compW / getCylindricalImagesCount();
int h = cylinderSectionHeight(w);
float aspect = (float) w / h;
double va = Math.min(fov, MAX_CYLINDER_FOV);
glu_callback_only.gluPerspective(va, aspect, Z_NEAR, Z_FAR);
break;
}
default:
float w = aspectRatio_callback_only * viewDistance;
float h = viewDistance;
gl.glOrtho(-w / 2, w / 2, -h / 2, h / 2, 0/*Z_NEAR*/, Z_FAR);
}
gl.glScalef(1.0f, -1.0f, 1.0f); // this inverts the y coordinates of the grid. A MESS! FIXME
}
/**
* GLEventListener Called by the drawable during the first repaint after the
* component has been resized.
*
* @param drawable
* @param x
* @param y
* @param w
* @param h
*/
@Override
public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) {
// avoid division by zero
if (h == 0) {
h = 1;
}
GL gl1 = drawable.getGL();
GL2 gl = (GL2)gl1;
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glViewport(x, y, w, h);
this.aspectRatio_callback_only = (float) w / (float) h;
this.setupProjection(gl); // is this needed ? FIXME
}
void shearMatrix(GL gl1, float shearX, float shearY) {
GL2 gl = (GL2)gl1;
float m[] = {
1, 0, 0, 0, // col 1
0, 1, 0, 0, // col 2
shearX, shearY, 1, 0, // col 3
0, 0, 0, 1 // col 4
};
gl.glMultMatrixf(m, 0);
}
/**
* Renders the map.
*/
public void display() {
if (this.model.isInitialized()) {
this.updateView();
}
}
/**
* Set the background color. The color components are expected to be between
* 0 and 255.
*
* @param red the red color component
* @param green the green color component
* @param blue the blue color component
*/
public void setBackgroundColor(int red, int green, int blue) {
this.bgRed = red / 255.0f;
this.bgGreen = green / 255.0f;
this.bgBlue = blue / 255.0f;
this.component.repaint();
}
public void setBackgroundColor(Color bc) {
this.bgRed = bc.getRed() / 255.0f;
this.bgGreen = bc.getGreen() / 255.0f;
this.bgBlue = bc.getBlue() / 255.0f;
this.component.repaint();
}
public Color getBackgroundColor() {
return new Color((int) (bgRed * 255), (int) (bgGreen * 255), (int) (bgBlue * 255));
}
public void resetToDefaultCamera() {
this.setXAngle(defaultXAngle);
this.setZAngle(defaultZAngle);
this.setViewDistance(defaultDistance);
this.setViewAngle(defaultViewAngle);
this.setShearX(0);
this.setShearY(0);
this.setShiftX(defaultShiftX);
this.setShiftY(defaultShiftY);
this.setCylindricalHeight(defaultCylindricalHeight);
this.component.repaint();
}
public void setDefaultCamera(float defaultXAngle,
float defaultZAngle,
float defaultDistance,
float defaultViewAngle,
float defaultShiftX,
float defaultShiftY) {
this.defaultXAngle = defaultXAngle;
this.defaultZAngle = defaultZAngle;
this.defaultDistance = defaultDistance;
this.defaultViewAngle = defaultViewAngle;
this.defaultShiftX = defaultShiftX;
this.defaultShiftY = defaultShiftY;
}
public void setDefaultCylindricalCameraHeight(float defaultCylindricalHeight) {
this.defaultCylindricalHeight = defaultCylindricalHeight;
}
public Map3DAnimation getAnimation() {
return animation;
}
public void setAnimation(Map3DAnimation animation) {
if (animation == this.animation) {
return;
}
if (this.animation != null) {
this.animation.stopAnimation();
}
this.animation = animation;
this.component.addKeyListener(animation);
}
/**
* Rotation angle around x axis.
*
* @return Angle in degrees
*/
public float getXAngle() {
return xAngle;
}
/**
*
* @param xAngle in degrees
*/
public void setXAngle(float xAngle) {
xAngle = Math.max(Math.min(xAngle, MAX_X_ANGLE), MIN_X_ANGLE);
if (xAngle != this.xAngle) {
this.xAngle = xAngle;
this.updateView();
this.getComponent().firePropertyChange("view", 0, 1);
}
}
/**
* Returns the rotation angle around the z axis.
*
* @return Angle in degrees.
*/
public float getZAngle() {
return zAngle;
}
/**
*
* @param zAngle Angle in degrees.
* @return
*/
public static float normalizeZAngle(float zAngle) {
while (zAngle > 180) {
zAngle -= 360;
}
while (zAngle < -180) {
zAngle += 360;
}
return zAngle;
}
/**
* Rotation around vertical z axis.
*
* @param zAngle Angle in degrees.
*/
public void setZAngle(float zAngle) {
zAngle = normalizeZAngle(zAngle);
if (zAngle != this.zAngle) {
this.zAngle = zAngle;
this.updateView();
this.getComponent().firePropertyChange("view", 0, 1);
}
}
public float getViewDistance() {
return viewDistance;
}
public void setViewDistance(float viewDistance) {
viewDistance = Math.min(Math.max(viewDistance, MIN_DISTANCE), MAX_DISTANCE);
if (viewDistance != this.viewDistance) {
this.viewDistance = viewDistance;
this.updateView();
this.getComponent().firePropertyChange("view", 0, 1);
}
}
public float getViewAngle() {
return fov;
}
public void setViewAngle(float viewAngle) {
if (viewAngle != this.fov) {
this.fov = viewAngle;
this.updateView();
this.getComponent().firePropertyChange("view", 0, 1);
}
}
public float getShearXAngle() {
float angle = (float) (Math.toDegrees(Math.atan2(1, shearX)));
return Math.abs(angle) < 0.000001 ? 0f : angle;
}
public void setShearXAngle(float shearXAngle) {
shearXAngle = Math.min(Math.max(shearXAngle, MIN_SHEAR_ANGLE), MAX_SHEAR_ANGLE);
this.setShearX((float) (1. / Math.tan(shearXAngle)));
}
public float getShearX() {
return shearX;
}
public void setShearX(float shearX) {
if (this.shearX != shearX) {
this.shearX = shearX;
this.updateView();
this.getComponent().firePropertyChange("view", 0, 1);
}
}
public float getShearYAngle() {
float angle = (float) (Math.toDegrees(Math.atan2(1, shearY)));
return Math.abs(angle) < 0.000001 ? 0f : angle;
}
public void setShearYAngle(float shearYAngle) {
shearYAngle = Math.min(Math.max(shearYAngle, MIN_SHEAR_ANGLE), MAX_SHEAR_ANGLE);
this.setShearY((float) (1. / Math.tan(Math.toRadians(shearYAngle))));
}
public float getShearY() {
return shearY;
}
public void setShearY(float shearY) {
if (this.shearY != shearY) {
this.shearY = shearY;
this.updateView();
this.getComponent().firePropertyChange("view", 0, 1);
}
}
public float getShearDirection() {
return (float) Math.toDegrees(Math.atan2(shearY, shearX));
}
public float getShearRadius() {
return (float) Math.hypot(shearY, shearX);
}
public void setCamera(Camera camera) {
if (this.camera != camera) {
this.camera = camera;
this.updateView();
getComponent().firePropertyChange("camera changed", 0, 1);
}
}
public Camera getCamera() {
return camera;
}
public boolean is2D() {
return camera == Camera.orthogonal;
}
public float getShiftX() {
return shiftX;
}
public void setShiftX(float shiftX) {
if (this.shiftX != shiftX) {
this.shiftX = shiftX;
this.updateView();
this.getComponent().firePropertyChange("shiftX", 0, 1);
}
}
public float getShiftY() {
return shiftY;
}
public void setShiftY(float shiftY) {
if (this.shiftY != shiftY) {
this.shiftY = shiftY;
this.updateView();
this.getComponent().firePropertyChange("shiftY", 0, 1);
}
}
public void setShift(float shiftX, float shiftY) {
if (this.shiftX != shiftX || this.shiftY != shiftY) {
this.shiftX = shiftX;
this.shiftY = shiftY;
this.updateView();
this.getComponent().firePropertyChange("view", 0, 1);
}
}
/**
* @return the cylindricalHeight
*/
public float getCylindricalHeight() {
return cylindricalHeight;
}
/**
* @param cylindricalHeight the cylindricalHeight to set
*/
public void setCylindricalHeight(float h) {
if (this.cylindricalHeight != h) {
this.cylindricalHeight = h;
this.updateView();
this.getComponent().firePropertyChange("height", 0, 1);
}
}
private void updateView() {
this.component.repaint();
}
/**
* @return the fogEnabled
*/
public boolean isFogEnabled() {
return fogEnabled;
}
/**
* @param fogEnabled the fogEnabled to set
*/
public void setFogEnabled(boolean fogEnabled) {
this.fogEnabled = fogEnabled;
this.updateView();
this.getComponent().firePropertyChange("fog", 0, 1);
}
/**
* @return the fogStart
*/
public float getFogStart() {
return fogStart;
}
/**
* @param fogStart the fogStart to set
*/
public void setFogStart(float fogStart) {
this.fogStart = fogStart;
this.updateView();
this.getComponent().firePropertyChange("fogStart", 0, 1);
}
/**
* @return the fogEnd
*/
public float getFogEnd() {
return fogEnd;
}
/**
* @param fogEnd the fogEnd to set
*/
public void setFogEnd(float fogEnd) {
this.fogEnd = fogEnd;
this.updateView();
this.getComponent().firePropertyChange("fogEnd", 0, 1);
}
/**
* @return the fogColor
*/
public Color getFogColor() {
return fogColor;
}
/**
* @param fogColor the fogColor to set
*/
public void setFogColor(Color fogColor) {
this.fogColor = fogColor;
this.updateView();
this.getComponent().firePropertyChange("fogColor", 0, 1);
}
@Override
public void dispose(GLAutoDrawable arg0) {
// TODO Auto-generated method stub
}
/**
* FIXME: Hackish method for taking a mouse position and mapping
* it to a normalized location on the model.
* (a Point2D.Float with x & y values between [0.0-1.0])
* TODO: handle screen-to-map transformation when rotated
*/
protected Point2D.Float mouseXYtoModelXY(float x, float y){
int componentWidth = getComponent().getWidth();
int componentHeight = getComponent().getHeight();
float normalizedX = x / componentWidth;
float normalizedY = y / componentHeight;
float whRatio = (float)componentWidth / componentHeight;
float mapX = (normalizedX - 0.5f) * getViewDistance()*whRatio + 0.5f - getShiftX();
float mapY = (normalizedY - 0.5f) * getViewDistance() + 0.5f - getShiftY();
return new Point2D.Float(mapX, mapY);
}
/**
* Find the model coordinates corresponding to current viewport.
* FIXME: Depends on mouseXYtoModelXY, which only works with no rotations.
*/
public Rectangle2D.Float getViewBounds(){
int componentWidth = getComponent().getWidth();
int componentHeight = getComponent().getHeight();
Point2D.Float upperLeft = mouseXYtoModelXY(0,0);
Point2D.Float lowerRight = mouseXYtoModelXY(componentWidth, componentHeight);
return new Rectangle2D.Float(upperLeft.x, upperLeft.y,
lowerRight.x - upperLeft.x, lowerRight.y - upperLeft.y);
}
}
|
3e18a13a55e43f3b0925ae12c955eb44ed488646 | 1,885 | java | Java | src/main/java/com/swemel/sevenzip/CRC.java | srebrinb/OraSevenZip | 258f06063e2519bf0dde8efa01210071ab8e71fd | [
"Apache-2.0"
] | null | null | null | src/main/java/com/swemel/sevenzip/CRC.java | srebrinb/OraSevenZip | 258f06063e2519bf0dde8efa01210071ab8e71fd | [
"Apache-2.0"
] | null | null | null | src/main/java/com/swemel/sevenzip/CRC.java | srebrinb/OraSevenZip | 258f06063e2519bf0dde8efa01210071ab8e71fd | [
"Apache-2.0"
] | null | null | null | 21.420455 | 76 | 0.523077 | 10,477 | // SevenZip/CRC.java
package com.swemel.sevenzip;
public class CRC
{
static public int[] Table = new int[256];
static
{
for (int i = 0; i < 256; i++)
{
int r = i;
for (int j = 0; j < 8; j++)
if ((r & 1) != 0)
r = (r >>> 1) ^ 0xEDB88320;
else
r >>>= 1;
Table[i] = r;
}
}
int _value = -1;
public void Init()
{
_value = -1;
}
public void UpdateUInt32(int v) {
for (int i = 0; i < 4; i++)
UpdateByte((byte) ((v >> (8 * i)) & 0xFF));
}
public void UpdateUInt64(long v) {
for (int i = 0; i < 8; i++)
UpdateByte((byte) ((byte)((v >> (8 * i))) & 0xFF));
}
public void Update(byte[] data, int offset, int size)
{
for (int i = 0; i < size; i++)
_value = Table[(_value ^ data[offset + i]) & 0xFF] ^ (_value >>> 8);
}
public void Update(byte[] data)
{
int size = data.length;
for (int i = 0; i < size; i++)
_value = Table[(_value ^ data[i]) & 0xFF] ^ (_value >>> 8);
}
public void UpdateByte(byte b)
{
_value = Table[(_value ^ b) & 0xFF] ^ (_value >>> 8);
}
public void UpdateByte(int b)
{
_value = Table[(_value ^ b) & 0xFF] ^ (_value >>> 8);
}
public void Update(byte[] data, int size) {
for (int i = 0; i < size; i++)
_value = Table[(_value ^ data[i]) & 0xFF] ^ (_value >>> 8);
}
public int GetDigest()
{
return _value ^ (-1);
}
public static int CalculateDigest(byte [] data, int size) {
CRC crc = new CRC();
crc.Update(data, size);
return crc.GetDigest();
}
public static int CalculateDigest(byte [] data, int offset, int size) {
CRC crc = new CRC();
crc.Update(data, offset, size);
return crc.GetDigest();
}
static public boolean VerifyDigest(int digest, byte [] data, int size) {
return (CalculateDigest(data, size) == digest);
}
}
|
3e18a2710790447889ed90e5641f468f305788fa | 1,559 | java | Java | server-java/freetank-plugin/src/main/java/org/youngmonkeys/freetank/plugin/PluginEntry.java | blackdragon09796/freetank | cca6d5c355fb7094b8a20d4c486e6c390a09ec20 | [
"Apache-1.1"
] | 1 | 2021-08-01T12:24:11.000Z | 2021-08-01T12:24:11.000Z | server-java/freetank-plugin/src/main/java/org/youngmonkeys/freetank/plugin/PluginEntry.java | blackdragon09796/freetank | cca6d5c355fb7094b8a20d4c486e6c390a09ec20 | [
"Apache-1.1"
] | null | null | null | server-java/freetank-plugin/src/main/java/org/youngmonkeys/freetank/plugin/PluginEntry.java | blackdragon09796/freetank | cca6d5c355fb7094b8a20d4c486e6c390a09ec20 | [
"Apache-1.1"
] | 1 | 2021-07-27T14:06:33.000Z | 2021-07-27T14:06:33.000Z | 29.415094 | 91 | 0.74984 | 10,478 | /**
*
*/
package org.youngmonkeys.freetank.plugin;
import java.util.Properties;
import com.tvd12.ezyfox.bean.EzyBeanContextBuilder;
import com.tvd12.ezyfoxserver.context.EzyPluginContext;
import com.tvd12.ezyfoxserver.context.EzyZoneContext;
import com.tvd12.ezyfoxserver.setting.EzyPluginSetting;
import com.tvd12.ezyfoxserver.support.entry.EzyDefaultPluginEntry;
import org.youngmonkeys.freetank.common.constant.CommonConstants;
/**
* @author tavandung12
*
*/
public class PluginEntry extends EzyDefaultPluginEntry {
@Override
protected void preConfig(EzyPluginContext ctx) {
logger.info("\n=================== freetank PLUGIN START CONFIG ================\n");
}
@Override
protected void postConfig(EzyPluginContext ctx) {
logger.info("\n=================== freetank PLUGIN END CONFIG ================\n");
}
@Override
protected void setupBeanContext(EzyPluginContext context, EzyBeanContextBuilder builder) {
EzyPluginSetting setting = context.getPlugin().getSetting();
builder.addProperties("freetank-common-config.properties");
builder.addProperties(getConfigFile(setting));
Properties properties = builder.getProperties();
EzyZoneContext zoneContext = context.getParent();
zoneContext.setProperty(CommonConstants.PLUGIN_PROPERTIES, properties);
}
protected String getConfigFile(EzyPluginSetting setting) {
return setting.getConfigFile();
}
@Override
protected String[] getScanablePackages() {
return new String[] {
"org.youngmonkeys.freetank.common",
"org.youngmonkeys.freetank.plugin"
};
}
} |
3e18a2e40070da3a811a081460a25750308453e0 | 705 | java | Java | kxmall-data/src/main/java/com/kxmall/market/data/dto/CouponSkuDTO.java | zhengkaixing/kxmall | 572d4b9361a429c7770eac0fc50ec1fe4dff3736 | [
"Apache-2.0"
] | 99 | 2020-11-05T08:50:08.000Z | 2022-03-31T01:43:40.000Z | kxmall-data/src/main/java/com/kxmall/market/data/dto/CouponSkuDTO.java | canicula718/kxmall | 51e59ca3564cc0eacc04d830b307bcc7d12c977c | [
"Apache-2.0"
] | 2 | 2022-01-04T09:12:20.000Z | 2022-01-13T07:54:15.000Z | kxmall-data/src/main/java/com/kxmall/market/data/dto/CouponSkuDTO.java | canicula718/kxmall | 51e59ca3564cc0eacc04d830b307bcc7d12c977c | [
"Apache-2.0"
] | 16 | 2020-11-17T00:36:54.000Z | 2022-03-17T08:54:53.000Z | 17.195122 | 56 | 0.602837 | 10,479 | package com.kxmall.market.data.dto;
import com.kxmall.market.data.annotation.DtoDescription;
import lombok.Data;
/**
* 活动管理商品DTO
*
* @author kaixin
*/
@Data
public class CouponSkuDTO extends SuperDTO {
/**
* 活动主表id
*/
@DtoDescription(description = "优惠券id")
private Long couponId;
/**
* 规格id
*/
@DtoDescription(description = "规格id")
private Long skuId;
/**
* 商品id
*/
@DtoDescription(description = "商品id")
private Long spuId;
/**
* 优惠价格
*/
@DtoDescription(description = "优惠价格")
private Integer discountPrice;
/**
* 每日限量
*/
@DtoDescription(description = "每日限量")
private Integer limitNum;
}
|
3e18a55cc86c8877a78b486bafbceeff27f54303 | 1,186 | java | Java | src/main/java/com/majruszs_difficulty/features/monster_spawn/ChargeCreeperOnSpawn.java | Majrusz/MajruszsProgressiveDifficulty | decf28085fdbc7872d661de9f934f39cb5802894 | [
"MIT"
] | 5 | 2020-12-24T20:09:36.000Z | 2022-01-05T05:09:13.000Z | src/main/java/com/majruszs_difficulty/features/monster_spawn/ChargeCreeperOnSpawn.java | Majrusz/MajruszsProgressiveDifficulty | decf28085fdbc7872d661de9f934f39cb5802894 | [
"MIT"
] | 78 | 2020-12-31T00:29:22.000Z | 2022-03-24T19:59:46.000Z | src/main/java/com/majruszs_difficulty/features/monster_spawn/ChargeCreeperOnSpawn.java | Majrusz/MajruszsProgressiveDifficulty | decf28085fdbc7872d661de9f934f39cb5802894 | [
"MIT"
] | 10 | 2021-04-26T01:50:19.000Z | 2022-03-27T18:43:06.000Z | 33.885714 | 81 | 0.790894 | 10,480 | package com.majruszs_difficulty.features.monster_spawn;
import com.majruszs_difficulty.GameState;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LightningBolt;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.monster.Creeper;
/** Charges creeper on spawn. (emulates attacking creeper with lightning bolt) */
public class ChargeCreeperOnSpawn extends OnEnemyToBeSpawnedBase {
private static final String CONFIG_NAME = "CreeperCharged";
private static final String CONFIG_COMMENT = "Creepers spawning charged.";
public ChargeCreeperOnSpawn() {
super( CONFIG_NAME, CONFIG_COMMENT, 0.125, GameState.State.NORMAL, true );
}
@Override
public void onExecute( LivingEntity entity, ServerLevel world ) {
Creeper creeper = ( Creeper )entity;
LightningBolt lightningBolt = EntityType.LIGHTNING_BOLT.create( world );
if( lightningBolt != null )
creeper.thunderHit( world, lightningBolt );
creeper.clearFire();
}
@Override
public boolean shouldBeExecuted( LivingEntity entity ) {
return entity instanceof Creeper && super.shouldBeExecuted( entity );
}
}
|
3e18a56524c8ea7ff587c8dba0a8d9b3a5aae758 | 886 | java | Java | src/main/java/com/cutajarjames/codility/countingelements/FrogRiverOne.java | cutajarj/CodilityInJava | 20ba4a1348ce05270aa852a9c69d6402be38a3d1 | [
"MIT"
] | 23 | 2019-06-11T02:29:55.000Z | 2022-03-20T15:52:17.000Z | src/main/java/com/cutajarjames/codility/countingelements/FrogRiverOne.java | cutajarj/CodilityInJava | 20ba4a1348ce05270aa852a9c69d6402be38a3d1 | [
"MIT"
] | 1 | 2021-03-23T20:24:58.000Z | 2021-03-23T20:24:58.000Z | src/main/java/com/cutajarjames/codility/countingelements/FrogRiverOne.java | cutajarj/CodilityInJava | 20ba4a1348ce05270aa852a9c69d6402be38a3d1 | [
"MIT"
] | 26 | 2019-05-24T06:59:16.000Z | 2022-03-03T18:30:55.000Z | 31.642857 | 94 | 0.553047 | 10,481 | package com.cutajarjames.codility.countingelements;
/**
* This is the solution for CountingElements > FrogRiverOne
* <p>
* This is marked as PAINLESS difficulty
*/
public class FrogRiverOne {
public int solution(int X, int[] A) {
boolean[] riverPositions = new boolean[X + 1];
for (int time = 0; time < A.length; time++) {
int pos = A[time];
if (!riverPositions[pos]) {
riverPositions[pos] = true;
X -= 1;
if (X == 0) return time;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(new FrogRiverOne().solution(5, new int[]{1, 3, 1, 4, 2, 3, 5, 4}));
System.out.println(new FrogRiverOne().solution(1, new int[]{1, 1, 1}));
System.out.println(new FrogRiverOne().solution(3, new int[]{1, 2, 1}));
}
}
|
3e18a62b6e7066b716f1f83cdd24aa1b6825eed5 | 2,860 | java | Java | iwxxmCore/src/test/resources/iwxxm/2.1/output/net/opengis/sampling/_2/SFSamplingFeatureCollectionType.java | cb-steven-matison/iwxxmConverter | b2c0ac96f23680c667db11183d0689bc28cddf80 | [
"Apache-2.0"
] | 8 | 2019-12-18T06:46:04.000Z | 2020-10-14T10:13:56.000Z | iwxxmCore/src/test/resources/iwxxm/2.1/output/net/opengis/sampling/_2/SFSamplingFeatureCollectionType.java | cb-steven-matison/iwxxmConverter | b2c0ac96f23680c667db11183d0689bc28cddf80 | [
"Apache-2.0"
] | 8 | 2019-07-15T12:51:38.000Z | 2022-01-10T11:06:54.000Z | iwxxmCore/src/test/resources/iwxxm/2.1/output/net/opengis/sampling/_2/SFSamplingFeatureCollectionType.java | cb-steven-matison/iwxxmConverter | b2c0ac96f23680c667db11183d0689bc28cddf80 | [
"Apache-2.0"
] | 7 | 2019-06-11T10:25:12.000Z | 2020-10-14T10:13:58.000Z | 31.086957 | 135 | 0.678671 | 10,482 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2018.02.27 at 12:41:52 PM MSK
//
package net.opengis.sampling._2;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import net.opengis.gml.v_3_2_1.AbstractFeatureType;
/**
* The class SF_SamplingFeatureCollection (Figure 9) is an instance of the
* «metaclass» GF_FeatureType (ISO 19109:2005), which therefore represents a feature
* type. SF_SamplingFeatureCollection shall support one association.
*
* <p>Java class for SF_SamplingFeatureCollectionType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SF_SamplingFeatureCollectionType">
* <complexContent>
* <extension base="{http://www.opengis.net/gml/3.2}AbstractFeatureType">
* <sequence>
* <element name="member" type="{http://www.opengis.net/sampling/2.0}SF_SamplingFeaturePropertyType" maxOccurs="unbounded"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SF_SamplingFeatureCollectionType", propOrder = {
"member"
})
public class SFSamplingFeatureCollectionType
extends AbstractFeatureType
{
@XmlElement(required = true)
protected List<SFSamplingFeaturePropertyType> member;
/**
* Gets the value of the member property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the member property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMember().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SFSamplingFeaturePropertyType }
*
*
*/
public List<SFSamplingFeaturePropertyType> getMember() {
if (member == null) {
member = new ArrayList<SFSamplingFeaturePropertyType>();
}
return this.member;
}
public boolean isSetMember() {
return ((this.member!= null)&&(!this.member.isEmpty()));
}
public void unsetMember() {
this.member = null;
}
}
|
3e18a66827592535108f0139c0f4a918644dfbc1 | 1,526 | java | Java | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactEditionTests.java | Apakulya/java_pft | 23dc0c8dce2e6705445b9c11fa0125b1427f90f6 | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactEditionTests.java | Apakulya/java_pft | 23dc0c8dce2e6705445b9c11fa0125b1427f90f6 | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactEditionTests.java | Apakulya/java_pft | 23dc0c8dce2e6705445b9c11fa0125b1427f90f6 | [
"Apache-2.0"
] | null | null | null | 38.15 | 151 | 0.716252 | 10,483 | package ru.stqa.pft.addressbook.tests;
import org.hamcrest.CoreMatchers;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.ContactData;
import ru.stqa.pft.addressbook.model.Contacts;
import ru.stqa.pft.addressbook.model.GroupData;
import java.io.File;
import static org.hamcrest.MatcherAssert.assertThat;
public class ContactEditionTests extends TestBase{
@BeforeMethod
public void ensurePreconditions() {
if (app.db().groups().size()==0) {
app.goTo().groupPage();
app.group().create(new GroupData().withName("test"));
}
if (app.db().contacts().size() == 0) {
app.goTo().homepage();
File photo = new File("src/test/resources/photo.jpg");
app.contact().create(new ContactData().withFirstName("test").withLastName("test").withPhoto(photo).inGroup(app.db().groups().iterator().next()));
}
}
@Test public void testContactEditionTests() throws Exception {
Contacts before = app.db().contacts();
ContactData editedcontact = before.iterator().next();
File photo = new File("src/test/resources/photo.jpg");
ContactData contact = new ContactData().withId(editedcontact.getId()).withFirstName("test").withLastName("test").withPhoto(photo);
app.contact().edit(contact);
assertThat(app.contact().count(), CoreMatchers.equalTo(before.size()));
Contacts after = app.db().contacts();
assertThat(after,CoreMatchers.equalTo(before.without(editedcontact).withAdded(contact)));
}
}
|
3e18a66e6f23af04ff11ce4b671887d007f1d50f | 3,064 | java | Java | jOOQ/src/main/java/org/jooq/impl/Radians.java | Celebrate-future/jOOQ | 9ac7eb99bd5126198341ee56cb9549cf531dce85 | [
"Apache-2.0"
] | null | null | null | jOOQ/src/main/java/org/jooq/impl/Radians.java | Celebrate-future/jOOQ | 9ac7eb99bd5126198341ee56cb9549cf531dce85 | [
"Apache-2.0"
] | null | null | null | jOOQ/src/main/java/org/jooq/impl/Radians.java | Celebrate-future/jOOQ | 9ac7eb99bd5126198341ee56cb9549cf531dce85 | [
"Apache-2.0"
] | null | null | null | 24.125984 | 94 | 0.558094 | 10,484 | /*
* 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.
*
* Other licenses:
* -----------------------------------------------------------------------------
* Commercial licenses for this work are available. These replace the above
* ASL 2.0 and offer limited warranties, support, maintenance, and commercial
* database integrations.
*
* For more information, please visit: http://www.jooq.org/licenses
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package org.jooq.impl;
import static org.jooq.impl.DSL.*;
import static org.jooq.impl.Internal.*;
import static org.jooq.impl.Keywords.*;
import static org.jooq.impl.Names.*;
import static org.jooq.impl.SQLDataType.*;
import static org.jooq.impl.Tools.*;
import static org.jooq.impl.Tools.BooleanDataKey.*;
import static org.jooq.impl.Tools.DataExtendedKey.*;
import static org.jooq.impl.Tools.DataKey.*;
import static org.jooq.SQLDialect.*;
import org.jooq.*;
import org.jooq.conf.*;
import org.jooq.impl.*;
import org.jooq.tools.*;
import java.util.*;
import java.math.BigDecimal;
/**
* The <code>RAD</code> statement.
*/
@SuppressWarnings({ "rawtypes", "unused" })
final class Radians
extends
AbstractField<BigDecimal>
{
private static final long serialVersionUID = 1L;
private final Field<? extends Number> degrees;
Radians(
Field<? extends Number> degrees
) {
super(
N_RADIANS,
allNotNull(NUMERIC, degrees)
);
this.degrees = nullSafeNotNull(degrees, INTEGER);
}
// -------------------------------------------------------------------------
// XXX: QueryPart API
// -------------------------------------------------------------------------
@Override
public final void accept(Context<?> ctx) {
switch (ctx.family()) {
case FIREBIRD:
case SQLITE:
ctx.visit(castIfNeeded(degrees, BigDecimal.class).mul(pi()).div(inline(180)));
return;
default:
ctx.visit(function(N_RADIANS, NUMERIC, degrees));
return;
}
}
// -------------------------------------------------------------------------
// The Object API
// -------------------------------------------------------------------------
@Override
public boolean equals(Object that) {
if (that instanceof Radians) {
return
StringUtils.equals(degrees, ((Radians) that).degrees)
;
}
else
return super.equals(that);
}
}
|
3e18a6d9858ed0395878e978e1c9f99914136e5a | 1,015 | java | Java | api/src/main/java/ca/bc/gov/educ/grad/report/model/common/party/address/PostalAddress.java | bcgov/EDUC-GRAD-REPORT-API | 25dd01fe780af5d9cfd85a38dac1bba28cc9e07e | [
"Apache-2.0"
] | null | null | null | api/src/main/java/ca/bc/gov/educ/grad/report/model/common/party/address/PostalAddress.java | bcgov/EDUC-GRAD-REPORT-API | 25dd01fe780af5d9cfd85a38dac1bba28cc9e07e | [
"Apache-2.0"
] | 20 | 2021-07-06T00:04:38.000Z | 2022-03-29T16:34:59.000Z | api/src/main/java/ca/bc/gov/educ/grad/report/model/common/party/address/PostalAddress.java | bcgov/EDUC-GRAD-REPORT-API | 25dd01fe780af5d9cfd85a38dac1bba28cc9e07e | [
"Apache-2.0"
] | null | null | null | 40.6 | 80 | 0.53202 | 10,485 | /* *********************************************************************
* Copyright (c) 2016, Ministry of Education, BC.
*
* All rights reserved.
* This information contained herein may not be used in whole
* or in part without the express written consent of the
* Government of British Columbia, Canada.
*
* Revision Control Information
* File: $Id:: PostalAddress.java 5618 2016-12-12 20:47:02Z DA#$
* Date of Last Commit: $Date:: 2016-12-12 12:47:02 -0800 (Mon, 12 Dec 2016) $
* Revision Number: $Rev:: 5618 $
* Last Commit by: $Author:: DAJARVIS $
*
* ********************************************************************** */
package ca.bc.gov.educ.grad.report.model.common.party.address;
/**
* Represents a mailing address for postal deliveries.
*
* @author CGI Information Management Consultants Inc.
*/
public interface PostalAddress extends MailingAddress, Address {
}
|
3e18a6e037ee2732384619fa62c7ee8d477e7115 | 39,993 | java | Java | google/cloud/notebooks/v1/google-cloud-notebooks-v1-java/proto-google-cloud-notebooks-v1-java/src/main/java/com/google/cloud/notebooks/v1/GetInstanceHealthResponse.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 7 | 2021-02-21T10:39:41.000Z | 2021-12-07T07:31:28.000Z | google/cloud/notebooks/v1/google-cloud-notebooks-v1-java/proto-google-cloud-notebooks-v1-java/src/main/java/com/google/cloud/notebooks/v1/GetInstanceHealthResponse.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 6 | 2021-02-02T23:46:11.000Z | 2021-11-15T01:46:02.000Z | google/cloud/notebooks/v1/google-cloud-notebooks-v1-java/proto-google-cloud-notebooks-v1-java/src/main/java/com/google/cloud/notebooks/v1/GetInstanceHealthResponse.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 4 | 2021-01-28T23:25:45.000Z | 2021-08-30T01:55:16.000Z | 34.447028 | 173 | 0.667967 | 10,486 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/notebooks/v1/service.proto
package com.google.cloud.notebooks.v1;
/**
* <pre>
* Response for checking if a notebook instance is healthy.
* </pre>
*
* Protobuf type {@code google.cloud.notebooks.v1.GetInstanceHealthResponse}
*/
public final class GetInstanceHealthResponse extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.cloud.notebooks.v1.GetInstanceHealthResponse)
GetInstanceHealthResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use GetInstanceHealthResponse.newBuilder() to construct.
private GetInstanceHealthResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GetInstanceHealthResponse() {
healthState_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new GetInstanceHealthResponse();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private GetInstanceHealthResponse(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 8: {
int rawValue = input.readEnum();
healthState_ = rawValue;
break;
}
case 18: {
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
healthInfo_ = com.google.protobuf.MapField.newMapField(
HealthInfoDefaultEntryHolder.defaultEntry);
mutable_bitField0_ |= 0x00000001;
}
com.google.protobuf.MapEntry<java.lang.String, java.lang.String>
healthInfo__ = input.readMessage(
HealthInfoDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry);
healthInfo_.getMutableMap().put(
healthInfo__.getKey(), healthInfo__.getValue());
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.notebooks.v1.NotebooksProto.internal_static_google_cloud_notebooks_v1_GetInstanceHealthResponse_descriptor;
}
@SuppressWarnings({"rawtypes"})
@java.lang.Override
protected com.google.protobuf.MapField internalGetMapField(
int number) {
switch (number) {
case 2:
return internalGetHealthInfo();
default:
throw new RuntimeException(
"Invalid map field number: " + number);
}
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.notebooks.v1.NotebooksProto.internal_static_google_cloud_notebooks_v1_GetInstanceHealthResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.notebooks.v1.GetInstanceHealthResponse.class, com.google.cloud.notebooks.v1.GetInstanceHealthResponse.Builder.class);
}
/**
* <pre>
* If an instance is healthy or not.
* </pre>
*
* Protobuf enum {@code google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState}
*/
public enum HealthState
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <pre>
* The instance substate is unknown.
* </pre>
*
* <code>HEALTH_STATE_UNSPECIFIED = 0;</code>
*/
HEALTH_STATE_UNSPECIFIED(0),
/**
* <pre>
* The instance is known to be in an healthy state
* (for example, critical daemons are running)
* Applies to ACTIVE state.
* </pre>
*
* <code>HEALTHY = 1;</code>
*/
HEALTHY(1),
/**
* <pre>
* The instance is known to be in an unhealthy state
* (for example, critical daemons are not running)
* Applies to ACTIVE state.
* </pre>
*
* <code>UNHEALTHY = 2;</code>
*/
UNHEALTHY(2),
/**
* <pre>
* The instance has not installed health monitoring agent.
* Applies to ACTIVE state.
* </pre>
*
* <code>AGENT_NOT_INSTALLED = 3;</code>
*/
AGENT_NOT_INSTALLED(3),
/**
* <pre>
* The instance health monitoring agent is not running.
* Applies to ACTIVE state.
* </pre>
*
* <code>AGENT_NOT_RUNNING = 4;</code>
*/
AGENT_NOT_RUNNING(4),
UNRECOGNIZED(-1),
;
/**
* <pre>
* The instance substate is unknown.
* </pre>
*
* <code>HEALTH_STATE_UNSPECIFIED = 0;</code>
*/
public static final int HEALTH_STATE_UNSPECIFIED_VALUE = 0;
/**
* <pre>
* The instance is known to be in an healthy state
* (for example, critical daemons are running)
* Applies to ACTIVE state.
* </pre>
*
* <code>HEALTHY = 1;</code>
*/
public static final int HEALTHY_VALUE = 1;
/**
* <pre>
* The instance is known to be in an unhealthy state
* (for example, critical daemons are not running)
* Applies to ACTIVE state.
* </pre>
*
* <code>UNHEALTHY = 2;</code>
*/
public static final int UNHEALTHY_VALUE = 2;
/**
* <pre>
* The instance has not installed health monitoring agent.
* Applies to ACTIVE state.
* </pre>
*
* <code>AGENT_NOT_INSTALLED = 3;</code>
*/
public static final int AGENT_NOT_INSTALLED_VALUE = 3;
/**
* <pre>
* The instance health monitoring agent is not running.
* Applies to ACTIVE state.
* </pre>
*
* <code>AGENT_NOT_RUNNING = 4;</code>
*/
public static final int AGENT_NOT_RUNNING_VALUE = 4;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static HealthState valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static HealthState forNumber(int value) {
switch (value) {
case 0: return HEALTH_STATE_UNSPECIFIED;
case 1: return HEALTHY;
case 2: return UNHEALTHY;
case 3: return AGENT_NOT_INSTALLED;
case 4: return AGENT_NOT_RUNNING;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<HealthState>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
HealthState> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<HealthState>() {
public HealthState findValueByNumber(int number) {
return HealthState.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return com.google.cloud.notebooks.v1.GetInstanceHealthResponse.getDescriptor().getEnumTypes().get(0);
}
private static final HealthState[] VALUES = values();
public static HealthState valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException(
"EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private HealthState(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState)
}
public static final int HEALTH_STATE_FIELD_NUMBER = 1;
private int healthState_;
/**
* <pre>
* Output only. Runtime health_state.
* </pre>
*
* <code>.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState health_state = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The enum numeric value on the wire for healthState.
*/
@java.lang.Override public int getHealthStateValue() {
return healthState_;
}
/**
* <pre>
* Output only. Runtime health_state.
* </pre>
*
* <code>.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState health_state = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The healthState.
*/
@java.lang.Override public com.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState getHealthState() {
@SuppressWarnings("deprecation")
com.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState result = com.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState.valueOf(healthState_);
return result == null ? com.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState.UNRECOGNIZED : result;
}
public static final int HEALTH_INFO_FIELD_NUMBER = 2;
private static final class HealthInfoDefaultEntryHolder {
static final com.google.protobuf.MapEntry<
java.lang.String, java.lang.String> defaultEntry =
com.google.protobuf.MapEntry
.<java.lang.String, java.lang.String>newDefaultInstance(
com.google.cloud.notebooks.v1.NotebooksProto.internal_static_google_cloud_notebooks_v1_GetInstanceHealthResponse_HealthInfoEntry_descriptor,
com.google.protobuf.WireFormat.FieldType.STRING,
"",
com.google.protobuf.WireFormat.FieldType.STRING,
"");
}
private com.google.protobuf.MapField<
java.lang.String, java.lang.String> healthInfo_;
private com.google.protobuf.MapField<java.lang.String, java.lang.String>
internalGetHealthInfo() {
if (healthInfo_ == null) {
return com.google.protobuf.MapField.emptyMapField(
HealthInfoDefaultEntryHolder.defaultEntry);
}
return healthInfo_;
}
public int getHealthInfoCount() {
return internalGetHealthInfo().getMap().size();
}
/**
* <pre>
* Output only. Additional information about instance health.
* Example:
* healthInfo": {
* "docker_proxy_agent_status": "1",
* "docker_status": "1",
* "jupyterlab_api_status": "-1",
* "jupyterlab_status": "-1",
* "updated": "2020-10-18 09:40:03.573409"
* }
* </pre>
*
* <code>map<string, string> health_info = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public boolean containsHealthInfo(
java.lang.String key) {
if (key == null) { throw new java.lang.NullPointerException(); }
return internalGetHealthInfo().getMap().containsKey(key);
}
/**
* Use {@link #getHealthInfoMap()} instead.
*/
@java.lang.Override
@java.lang.Deprecated
public java.util.Map<java.lang.String, java.lang.String> getHealthInfo() {
return getHealthInfoMap();
}
/**
* <pre>
* Output only. Additional information about instance health.
* Example:
* healthInfo": {
* "docker_proxy_agent_status": "1",
* "docker_status": "1",
* "jupyterlab_api_status": "-1",
* "jupyterlab_status": "-1",
* "updated": "2020-10-18 09:40:03.573409"
* }
* </pre>
*
* <code>map<string, string> health_info = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public java.util.Map<java.lang.String, java.lang.String> getHealthInfoMap() {
return internalGetHealthInfo().getMap();
}
/**
* <pre>
* Output only. Additional information about instance health.
* Example:
* healthInfo": {
* "docker_proxy_agent_status": "1",
* "docker_status": "1",
* "jupyterlab_api_status": "-1",
* "jupyterlab_status": "-1",
* "updated": "2020-10-18 09:40:03.573409"
* }
* </pre>
*
* <code>map<string, string> health_info = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public java.lang.String getHealthInfoOrDefault(
java.lang.String key,
java.lang.String defaultValue) {
if (key == null) { throw new java.lang.NullPointerException(); }
java.util.Map<java.lang.String, java.lang.String> map =
internalGetHealthInfo().getMap();
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
* <pre>
* Output only. Additional information about instance health.
* Example:
* healthInfo": {
* "docker_proxy_agent_status": "1",
* "docker_status": "1",
* "jupyterlab_api_status": "-1",
* "jupyterlab_status": "-1",
* "updated": "2020-10-18 09:40:03.573409"
* }
* </pre>
*
* <code>map<string, string> health_info = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public java.lang.String getHealthInfoOrThrow(
java.lang.String key) {
if (key == null) { throw new java.lang.NullPointerException(); }
java.util.Map<java.lang.String, java.lang.String> map =
internalGetHealthInfo().getMap();
if (!map.containsKey(key)) {
throw new java.lang.IllegalArgumentException();
}
return map.get(key);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (healthState_ != com.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState.HEALTH_STATE_UNSPECIFIED.getNumber()) {
output.writeEnum(1, healthState_);
}
com.google.protobuf.GeneratedMessageV3
.serializeStringMapTo(
output,
internalGetHealthInfo(),
HealthInfoDefaultEntryHolder.defaultEntry,
2);
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (healthState_ != com.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState.HEALTH_STATE_UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(1, healthState_);
}
for (java.util.Map.Entry<java.lang.String, java.lang.String> entry
: internalGetHealthInfo().getMap().entrySet()) {
com.google.protobuf.MapEntry<java.lang.String, java.lang.String>
healthInfo__ = HealthInfoDefaultEntryHolder.defaultEntry.newBuilderForType()
.setKey(entry.getKey())
.setValue(entry.getValue())
.build();
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, healthInfo__);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.notebooks.v1.GetInstanceHealthResponse)) {
return super.equals(obj);
}
com.google.cloud.notebooks.v1.GetInstanceHealthResponse other = (com.google.cloud.notebooks.v1.GetInstanceHealthResponse) obj;
if (healthState_ != other.healthState_) return false;
if (!internalGetHealthInfo().equals(
other.internalGetHealthInfo())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + HEALTH_STATE_FIELD_NUMBER;
hash = (53 * hash) + healthState_;
if (!internalGetHealthInfo().getMap().isEmpty()) {
hash = (37 * hash) + HEALTH_INFO_FIELD_NUMBER;
hash = (53 * hash) + internalGetHealthInfo().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.notebooks.v1.GetInstanceHealthResponse parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v1.GetInstanceHealthResponse parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.notebooks.v1.GetInstanceHealthResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v1.GetInstanceHealthResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.notebooks.v1.GetInstanceHealthResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v1.GetInstanceHealthResponse parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.notebooks.v1.GetInstanceHealthResponse parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.notebooks.v1.GetInstanceHealthResponse parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.cloud.notebooks.v1.GetInstanceHealthResponse parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.notebooks.v1.GetInstanceHealthResponse parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.cloud.notebooks.v1.GetInstanceHealthResponse parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.notebooks.v1.GetInstanceHealthResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.notebooks.v1.GetInstanceHealthResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Response for checking if a notebook instance is healthy.
* </pre>
*
* Protobuf type {@code google.cloud.notebooks.v1.GetInstanceHealthResponse}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.cloud.notebooks.v1.GetInstanceHealthResponse)
com.google.cloud.notebooks.v1.GetInstanceHealthResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.notebooks.v1.NotebooksProto.internal_static_google_cloud_notebooks_v1_GetInstanceHealthResponse_descriptor;
}
@SuppressWarnings({"rawtypes"})
protected com.google.protobuf.MapField internalGetMapField(
int number) {
switch (number) {
case 2:
return internalGetHealthInfo();
default:
throw new RuntimeException(
"Invalid map field number: " + number);
}
}
@SuppressWarnings({"rawtypes"})
protected com.google.protobuf.MapField internalGetMutableMapField(
int number) {
switch (number) {
case 2:
return internalGetMutableHealthInfo();
default:
throw new RuntimeException(
"Invalid map field number: " + number);
}
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.notebooks.v1.NotebooksProto.internal_static_google_cloud_notebooks_v1_GetInstanceHealthResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.notebooks.v1.GetInstanceHealthResponse.class, com.google.cloud.notebooks.v1.GetInstanceHealthResponse.Builder.class);
}
// Construct using com.google.cloud.notebooks.v1.GetInstanceHealthResponse.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
healthState_ = 0;
internalGetMutableHealthInfo().clear();
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.cloud.notebooks.v1.NotebooksProto.internal_static_google_cloud_notebooks_v1_GetInstanceHealthResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.notebooks.v1.GetInstanceHealthResponse getDefaultInstanceForType() {
return com.google.cloud.notebooks.v1.GetInstanceHealthResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.notebooks.v1.GetInstanceHealthResponse build() {
com.google.cloud.notebooks.v1.GetInstanceHealthResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.notebooks.v1.GetInstanceHealthResponse buildPartial() {
com.google.cloud.notebooks.v1.GetInstanceHealthResponse result = new com.google.cloud.notebooks.v1.GetInstanceHealthResponse(this);
int from_bitField0_ = bitField0_;
result.healthState_ = healthState_;
result.healthInfo_ = internalGetHealthInfo();
result.healthInfo_.makeImmutable();
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.notebooks.v1.GetInstanceHealthResponse) {
return mergeFrom((com.google.cloud.notebooks.v1.GetInstanceHealthResponse)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.notebooks.v1.GetInstanceHealthResponse other) {
if (other == com.google.cloud.notebooks.v1.GetInstanceHealthResponse.getDefaultInstance()) return this;
if (other.healthState_ != 0) {
setHealthStateValue(other.getHealthStateValue());
}
internalGetMutableHealthInfo().mergeFrom(
other.internalGetHealthInfo());
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.notebooks.v1.GetInstanceHealthResponse parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.notebooks.v1.GetInstanceHealthResponse) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private int healthState_ = 0;
/**
* <pre>
* Output only. Runtime health_state.
* </pre>
*
* <code>.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState health_state = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The enum numeric value on the wire for healthState.
*/
@java.lang.Override public int getHealthStateValue() {
return healthState_;
}
/**
* <pre>
* Output only. Runtime health_state.
* </pre>
*
* <code>.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState health_state = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @param value The enum numeric value on the wire for healthState to set.
* @return This builder for chaining.
*/
public Builder setHealthStateValue(int value) {
healthState_ = value;
onChanged();
return this;
}
/**
* <pre>
* Output only. Runtime health_state.
* </pre>
*
* <code>.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState health_state = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The healthState.
*/
@java.lang.Override
public com.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState getHealthState() {
@SuppressWarnings("deprecation")
com.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState result = com.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState.valueOf(healthState_);
return result == null ? com.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState.UNRECOGNIZED : result;
}
/**
* <pre>
* Output only. Runtime health_state.
* </pre>
*
* <code>.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState health_state = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @param value The healthState to set.
* @return This builder for chaining.
*/
public Builder setHealthState(com.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState value) {
if (value == null) {
throw new NullPointerException();
}
healthState_ = value.getNumber();
onChanged();
return this;
}
/**
* <pre>
* Output only. Runtime health_state.
* </pre>
*
* <code>.google.cloud.notebooks.v1.GetInstanceHealthResponse.HealthState health_state = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return This builder for chaining.
*/
public Builder clearHealthState() {
healthState_ = 0;
onChanged();
return this;
}
private com.google.protobuf.MapField<
java.lang.String, java.lang.String> healthInfo_;
private com.google.protobuf.MapField<java.lang.String, java.lang.String>
internalGetHealthInfo() {
if (healthInfo_ == null) {
return com.google.protobuf.MapField.emptyMapField(
HealthInfoDefaultEntryHolder.defaultEntry);
}
return healthInfo_;
}
private com.google.protobuf.MapField<java.lang.String, java.lang.String>
internalGetMutableHealthInfo() {
onChanged();;
if (healthInfo_ == null) {
healthInfo_ = com.google.protobuf.MapField.newMapField(
HealthInfoDefaultEntryHolder.defaultEntry);
}
if (!healthInfo_.isMutable()) {
healthInfo_ = healthInfo_.copy();
}
return healthInfo_;
}
public int getHealthInfoCount() {
return internalGetHealthInfo().getMap().size();
}
/**
* <pre>
* Output only. Additional information about instance health.
* Example:
* healthInfo": {
* "docker_proxy_agent_status": "1",
* "docker_status": "1",
* "jupyterlab_api_status": "-1",
* "jupyterlab_status": "-1",
* "updated": "2020-10-18 09:40:03.573409"
* }
* </pre>
*
* <code>map<string, string> health_info = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public boolean containsHealthInfo(
java.lang.String key) {
if (key == null) { throw new java.lang.NullPointerException(); }
return internalGetHealthInfo().getMap().containsKey(key);
}
/**
* Use {@link #getHealthInfoMap()} instead.
*/
@java.lang.Override
@java.lang.Deprecated
public java.util.Map<java.lang.String, java.lang.String> getHealthInfo() {
return getHealthInfoMap();
}
/**
* <pre>
* Output only. Additional information about instance health.
* Example:
* healthInfo": {
* "docker_proxy_agent_status": "1",
* "docker_status": "1",
* "jupyterlab_api_status": "-1",
* "jupyterlab_status": "-1",
* "updated": "2020-10-18 09:40:03.573409"
* }
* </pre>
*
* <code>map<string, string> health_info = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public java.util.Map<java.lang.String, java.lang.String> getHealthInfoMap() {
return internalGetHealthInfo().getMap();
}
/**
* <pre>
* Output only. Additional information about instance health.
* Example:
* healthInfo": {
* "docker_proxy_agent_status": "1",
* "docker_status": "1",
* "jupyterlab_api_status": "-1",
* "jupyterlab_status": "-1",
* "updated": "2020-10-18 09:40:03.573409"
* }
* </pre>
*
* <code>map<string, string> health_info = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public java.lang.String getHealthInfoOrDefault(
java.lang.String key,
java.lang.String defaultValue) {
if (key == null) { throw new java.lang.NullPointerException(); }
java.util.Map<java.lang.String, java.lang.String> map =
internalGetHealthInfo().getMap();
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
* <pre>
* Output only. Additional information about instance health.
* Example:
* healthInfo": {
* "docker_proxy_agent_status": "1",
* "docker_status": "1",
* "jupyterlab_api_status": "-1",
* "jupyterlab_status": "-1",
* "updated": "2020-10-18 09:40:03.573409"
* }
* </pre>
*
* <code>map<string, string> health_info = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public java.lang.String getHealthInfoOrThrow(
java.lang.String key) {
if (key == null) { throw new java.lang.NullPointerException(); }
java.util.Map<java.lang.String, java.lang.String> map =
internalGetHealthInfo().getMap();
if (!map.containsKey(key)) {
throw new java.lang.IllegalArgumentException();
}
return map.get(key);
}
public Builder clearHealthInfo() {
internalGetMutableHealthInfo().getMutableMap()
.clear();
return this;
}
/**
* <pre>
* Output only. Additional information about instance health.
* Example:
* healthInfo": {
* "docker_proxy_agent_status": "1",
* "docker_status": "1",
* "jupyterlab_api_status": "-1",
* "jupyterlab_status": "-1",
* "updated": "2020-10-18 09:40:03.573409"
* }
* </pre>
*
* <code>map<string, string> health_info = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder removeHealthInfo(
java.lang.String key) {
if (key == null) { throw new java.lang.NullPointerException(); }
internalGetMutableHealthInfo().getMutableMap()
.remove(key);
return this;
}
/**
* Use alternate mutation accessors instead.
*/
@java.lang.Deprecated
public java.util.Map<java.lang.String, java.lang.String>
getMutableHealthInfo() {
return internalGetMutableHealthInfo().getMutableMap();
}
/**
* <pre>
* Output only. Additional information about instance health.
* Example:
* healthInfo": {
* "docker_proxy_agent_status": "1",
* "docker_status": "1",
* "jupyterlab_api_status": "-1",
* "jupyterlab_status": "-1",
* "updated": "2020-10-18 09:40:03.573409"
* }
* </pre>
*
* <code>map<string, string> health_info = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder putHealthInfo(
java.lang.String key,
java.lang.String value) {
if (key == null) { throw new java.lang.NullPointerException(); }
if (value == null) { throw new java.lang.NullPointerException(); }
internalGetMutableHealthInfo().getMutableMap()
.put(key, value);
return this;
}
/**
* <pre>
* Output only. Additional information about instance health.
* Example:
* healthInfo": {
* "docker_proxy_agent_status": "1",
* "docker_status": "1",
* "jupyterlab_api_status": "-1",
* "jupyterlab_status": "-1",
* "updated": "2020-10-18 09:40:03.573409"
* }
* </pre>
*
* <code>map<string, string> health_info = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
public Builder putAllHealthInfo(
java.util.Map<java.lang.String, java.lang.String> values) {
internalGetMutableHealthInfo().getMutableMap()
.putAll(values);
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.notebooks.v1.GetInstanceHealthResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.notebooks.v1.GetInstanceHealthResponse)
private static final com.google.cloud.notebooks.v1.GetInstanceHealthResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.notebooks.v1.GetInstanceHealthResponse();
}
public static com.google.cloud.notebooks.v1.GetInstanceHealthResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GetInstanceHealthResponse>
PARSER = new com.google.protobuf.AbstractParser<GetInstanceHealthResponse>() {
@java.lang.Override
public GetInstanceHealthResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new GetInstanceHealthResponse(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<GetInstanceHealthResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GetInstanceHealthResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.notebooks.v1.GetInstanceHealthResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
3e18a774d95ad53dd8376d3217781b871bd9d599 | 10,392 | java | Java | smithy-diff/src/main/java/software/amazon/smithy/diff/ModelDiff.java | rschmitt/smithy | e480e6f856c21e8837b139b3e4eae96fbcc0b605 | [
"Apache-2.0"
] | 903 | 2019-06-18T21:07:54.000Z | 2022-03-28T07:13:30.000Z | smithy-diff/src/main/java/software/amazon/smithy/diff/ModelDiff.java | rschmitt/smithy | e480e6f856c21e8837b139b3e4eae96fbcc0b605 | [
"Apache-2.0"
] | 277 | 2019-06-19T17:10:48.000Z | 2022-03-28T20:19:39.000Z | smithy-diff/src/main/java/software/amazon/smithy/diff/ModelDiff.java | rschmitt/smithy | e480e6f856c21e8837b139b3e4eae96fbcc0b605 | [
"Apache-2.0"
] | 90 | 2019-06-19T20:08:34.000Z | 2022-03-21T23:04:22.000Z | 35.71134 | 112 | 0.612683 | 10,487 | /*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.diff;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.validation.Severity;
import software.amazon.smithy.model.validation.ValidatedResult;
import software.amazon.smithy.model.validation.ValidationEvent;
import software.amazon.smithy.utils.SmithyBuilder;
/**
* Computes the difference between two models and any problems that might
* occur due to those differences.
*/
public final class ModelDiff {
private ModelDiff() {}
/**
* Creates a new ModelDiff.Builder that provides in-depth diff analysis.
*
* @return Returns the builder.
*/
public static Builder builder() {
return new Builder();
}
/**
* Evaluates the differences between two models.
*
* <p>Use {@link Builder} directly to get access to additional information.
*
* @param oldModel Previous version of the model.
* @param newModel New model to compare.
* @return Returns the computed validation events.
*/
public static List<ValidationEvent> compare(Model oldModel, Model newModel) {
return compare(ModelDiff.class.getClassLoader(), oldModel, newModel);
}
/**
* Evaluates the differences between two models.
*
* <p>Use {@link Builder} directly to get access to additional information.
*
* @param classLoader ClassLoader used to find {@link DiffEvaluator} service providers.
* @param oldModel Previous version of the model.
* @param newModel New model to compare.
* @return Returns the computed validation events.
*/
public static List<ValidationEvent> compare(ClassLoader classLoader, Model oldModel, Model newModel) {
return builder()
.oldModel(oldModel)
.newModel(newModel)
.classLoader(classLoader)
.compare()
.getDiffEvents();
}
/**
* The result of comparing two Smithy models.
*/
public static final class Result {
private final Differences differences;
private final List<ValidationEvent> diffEvents;
private final List<ValidationEvent> oldModelEvents;
private final List<ValidationEvent> newModelEvents;
public Result(
Differences differences,
List<ValidationEvent> diffEvents,
List<ValidationEvent> oldModelEvents,
List<ValidationEvent> newModelEvents
) {
this.differences = Objects.requireNonNull(differences);
this.diffEvents = Objects.requireNonNull(diffEvents);
this.oldModelEvents = Objects.requireNonNull(oldModelEvents);
this.newModelEvents = Objects.requireNonNull(newModelEvents);
}
/**
* Gets a queryable set of differences between two models.
*
* @return Returns the differences.
*/
public Differences getDifferences() {
return differences;
}
/**
* Gets the diff analysis as a list of {@link ValidationEvent}s.
*
* @return Returns the diff validation events.
*/
public List<ValidationEvent> getDiffEvents() {
return diffEvents;
}
/**
* Gets the validation events emitted when validating the old model.
*
* @return Returns the old model's validation events.
*/
public List<ValidationEvent> getOldModelEvents() {
return oldModelEvents;
}
/**
* Gets the validation events emitted when validating the new model.
*
* @return Returns the new model's validation events.
*/
public List<ValidationEvent> getNewModelEvents() {
return newModelEvents;
}
/**
* Gets the validation events that were present in the old model but
* are no longer an issue in the new model.
*
* @return Returns the resolved validation events.
*/
public Set<ValidationEvent> determineResolvedEvents() {
Set<ValidationEvent> events = new TreeSet<>(getOldModelEvents());
events.removeAll(getNewModelEvents());
return events;
}
/**
* Gets the validation events that were introduced by whatever changes
* were made to the new model.
*
* @return Returns the validation events introduced by the new model.
*/
public Set<ValidationEvent> determineIntroducedEvents() {
Set<ValidationEvent> events = new TreeSet<>(getNewModelEvents());
events.removeAll(getOldModelEvents());
return events;
}
/**
* Determines if the diff events contain any DANGER or ERROR events.
*
* @return Returns true if this diff has breaking changes.
*/
public boolean isDiffBreaking() {
for (ValidationEvent event : getDiffEvents()) {
if (event.getSeverity() == Severity.ERROR || event.getSeverity() == Severity.DANGER) {
return true;
}
}
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (!(o instanceof Result)) {
return false;
}
Result result = (Result) o;
return getDifferences().equals(result.getDifferences())
&& getDiffEvents().equals(result.getDiffEvents())
&& getOldModelEvents().equals(result.getOldModelEvents())
&& getNewModelEvents().equals(result.getNewModelEvents());
}
@Override
public int hashCode() {
return Objects.hash(getDifferences(), getDiffEvents(), getOldModelEvents(), getNewModelEvents());
}
}
/**
* Builder used to construct a diff of two Smithy models.
*/
public static final class Builder {
private Model oldModel;
private Model newModel;
private List<ValidationEvent> oldModelEvents = Collections.emptyList();
private List<ValidationEvent> newModelEvents = Collections.emptyList();
private ClassLoader classLoader = ModelDiff.class.getClassLoader();
private Builder() {}
/**
* Sets the ClassLoader used to find {@link DiffEvaluator} service
* providers.
*
* @param classLoader ClassLoader to use.
* @return Returns the builder.
*/
public Builder classLoader(ClassLoader classLoader) {
this.classLoader = Objects.requireNonNull(classLoader);
return this;
}
/**
* Sets the old model to compare against.
*
* @param oldModel Old version of a model.
* @return Returns the builder.
*/
public Builder oldModel(Model oldModel) {
this.oldModel = Objects.requireNonNull(oldModel);
return this;
}
/**
* Sets the new model to compare against.
*
* @param newModel New version of a model.
* @return Returns the builder.
*/
public Builder newModel(Model newModel) {
this.newModel = Objects.requireNonNull(newModel);
return this;
}
/**
* Sets the old model to compare against along with the validation
* events encountered while loading the model.
*
* @param oldModel Old version of a model with events.
* @return Returns the builder.
*/
public Builder oldModel(ValidatedResult<Model> oldModel) {
this.oldModel = oldModel.getResult()
.orElseThrow(() -> new IllegalArgumentException("No old model present in ValidatedResult"));
this.oldModelEvents = oldModel.getValidationEvents();
return this;
}
/**
* Sets the new model to compare against along with the validation
* events encountered while loading the model.
*
* @param newModel New version of a model with events.
* @return Returns the builder.
*/
public Builder newModel(ValidatedResult<Model> newModel) {
this.newModel = newModel.getResult()
.orElseThrow(() -> new IllegalArgumentException("No new model present in ValidatedResult"));
this.newModelEvents = newModel.getValidationEvents();
return this;
}
/**
* Performs the diff of the old and new models.
*
* @return Returns the diff {@link Result}.
* @throws IllegalStateException if {@code oldModel} and {@code newModel} are not set.
*/
public Result compare() {
SmithyBuilder.requiredState("oldModel", oldModel);
SmithyBuilder.requiredState("newModel", newModel);
List<DiffEvaluator> evaluators = new ArrayList<>();
ServiceLoader.load(DiffEvaluator.class, classLoader).forEach(evaluators::add);
Differences differences = Differences.detect(oldModel, newModel);
List<ValidationEvent> diffEvents = evaluators.parallelStream()
.flatMap(evaluator -> evaluator.evaluate(differences).stream())
.collect(Collectors.toList());
return new Result(differences, diffEvents, oldModelEvents, newModelEvents);
}
}
}
|
3e18a78a1c3a2e4b76e0f227f3aacfe92aed1578 | 4,496 | java | Java | fhir-rest/src/main/java/com/kodality/fhir/rest/filter/FormatInterceptor.java | kodality/blaze | a5984a7bc14241a4bfae13bf49d2b5ad0ec96e75 | [
"Apache-2.0"
] | 1 | 2019-02-05T17:39:02.000Z | 2019-02-05T17:39:02.000Z | fhir-rest/src/main/java/com/kodality/fhir/rest/filter/FormatInterceptor.java | kodality/blaze | a5984a7bc14241a4bfae13bf49d2b5ad0ec96e75 | [
"Apache-2.0"
] | 1 | 2020-09-10T13:19:22.000Z | 2020-09-10T13:19:22.000Z | fhir-rest/src/main/java/com/kodality/fhir/rest/filter/FormatInterceptor.java | kodality/blaze | a5984a7bc14241a4bfae13bf49d2b5ad0ec96e75 | [
"Apache-2.0"
] | 1 | 2020-09-02T05:51:04.000Z | 2020-09-02T05:51:04.000Z | 35.401575 | 105 | 0.706406 | 10,488 | /* 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.kodality.fhir.rest.filter;
import com.kodality.blaze.core.exception.FhirException;
import com.kodality.blaze.core.exception.FhirServerException;
import com.kodality.blaze.fhir.structure.api.FhirContentType;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.hl7.fhir.r4.model.OperationOutcome.IssueType;
import javax.ws.rs.core.MediaType;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
public class FormatInterceptor extends AbstractPhaseInterceptor<Message> {
private static final String FORMAT = "_format";
public FormatInterceptor() {
super(Phase.READ);
}
@Override
public void handleMessage(Message message) throws Fault {
readUrlFormat(message);
fixHeaderType(message, Message.CONTENT_TYPE);
fixHeaderType(message, Message.ACCEPT_CONTENT_TYPE);
}
private void fixHeaderType(Message message, String header) {
String headerValue = getHeader(message, header);
if (headerValue == null) {
return;
}
List<String> newTypes = Stream.of(StringUtils.split(headerValue, ",")).map(value -> {
if (value.equals("application/x-www-form-urlencoded")) {
return value;
}
MediaType mediaType = MediaType.valueOf(StringUtils.trim(value));
if (mediaType.isWildcardSubtype() && mediaType.isWildcardType()) {
return mediaType.toString();
}
String contentType = mediaType.getType() + "/" + mediaType.getSubtype();
String charset = mediaType.getParameters().get(MediaType.CHARSET_PARAMETER);
String newType = FhirContentType.getMimeType(contentType);
if (newType == null) {
return null;
}
if (charset != null) {
newType = newType + ";" + MediaType.CHARSET_PARAMETER + "=" + charset;
}
return newType;
}).distinct().filter(n -> n != null).collect(toList());
if (CollectionUtils.isEmpty(newTypes)) {
throw new FhirException(415, IssueType.NOTSUPPORTED, "format '" + headerValue + "' not supported");
}
setHeader(message, header, newTypes.get(0));
}
private void readUrlFormat(Message message) {
String query = (String) message.get(Message.QUERY_STRING);
if (StringUtils.isEmpty(query)) {
return;
}
for (String param : query.split("&")) {
if (StringUtils.startsWith(param, FORMAT)) {
query = StringUtils.remove(query, param);
message.put(Message.QUERY_STRING, query);
String type = decode(StringUtils.remove(param, FORMAT + "="));
setHeader(message, Message.ACCEPT_CONTENT_TYPE, type);
setHeader(message, Message.CONTENT_TYPE, type);
return;
}
}
}
@SuppressWarnings("unchecked")
private String getHeader(Message message, String header) {
Map<String, List<?>> headers = (Map<String, List<?>>) message.get(Message.PROTOCOL_HEADERS);
if (headers.containsKey(header)) {
return (String) headers.get(header).get(0);
}
return null;
}
@SuppressWarnings("unchecked")
private void setHeader(Message message, String header, Object value) {
message.put(header, value);
Map<String, List<?>> map = (Map<String, List<?>>) message.get(Message.PROTOCOL_HEADERS);
map.put(header, Collections.singletonList(value));
message.put(Message.PROTOCOL_HEADERS, map);
}
private static String decode(String s) {
try {
return URLDecoder.decode(s, "UTF8");
} catch (UnsupportedEncodingException e) {
throw new FhirServerException(500, "there are two ways to write error-free programs");
}
}
}
|
3e18a89745b9152ed09c0a0f4fa1e944a3fbcf83 | 8,118 | java | Java | app/src/main/java/net/gsantner/markor/activity/DocumentShareIntoFragment.java | cham3333/markor | 39fb3427c7ee4d3142758ed735af348936a0a3d1 | [
"MIT"
] | null | null | null | app/src/main/java/net/gsantner/markor/activity/DocumentShareIntoFragment.java | cham3333/markor | 39fb3427c7ee4d3142758ed735af348936a0a3d1 | [
"MIT"
] | null | null | null | app/src/main/java/net/gsantner/markor/activity/DocumentShareIntoFragment.java | cham3333/markor | 39fb3427c7ee4d3142758ed735af348936a0a3d1 | [
"MIT"
] | null | null | null | 40.79397 | 259 | 0.677014 | 10,489 | /*
* Copyright (c) 2017 Gregor Santner and Markor contributors
*
* Licensed under the MIT license. See LICENSE file in the project root for details.
*/
package net.gsantner.markor.activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.TextView;
import net.gsantner.markor.R;
import net.gsantner.markor.format.converter.MarkdownTextConverter;
import net.gsantner.markor.model.Document;
import net.gsantner.markor.ui.BaseFragment;
import net.gsantner.markor.ui.FilesystemDialogCreator;
import net.gsantner.markor.util.AppSettings;
import net.gsantner.markor.util.ContextUtils;
import net.gsantner.markor.util.DocumentIO;
import net.gsantner.markor.util.PermissionChecker;
import net.gsantner.opoc.ui.FilesystemDialogData;
import java.io.File;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class DocumentShareIntoFragment extends BaseFragment {
public static final String FRAGMENT_TAG = "DocumentShareIntoFragment";
public static final String EXTRA_SHARED_TEXT = "EXTRA_SHARED_TEXT";
public static DocumentShareIntoFragment newInstance(String sharedText) {
DocumentShareIntoFragment f = new DocumentShareIntoFragment();
Bundle args = new Bundle();
args.putString(EXTRA_SHARED_TEXT, sharedText);
f.setArguments(args);
return f;
}
@BindView(R.id.document__fragment__share_into__webview)
WebView _webView;
private View _view;
private Context _context;
private String _sharedText;
public DocumentShareIntoFragment() {
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.document__fragment__share_into, container, false);
ButterKnife.bind(this, view);
_view = view;
_context = view.getContext();
_sharedText = getArguments() != null ? getArguments().getString(EXTRA_SHARED_TEXT, "") : "";
return view;
}
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
AppSettings as = new AppSettings(_context);
ContextUtils cu = new ContextUtils(_context);
cu.setAppLanguage(as.getLanguage());
int fg = as.isDarkThemeEnabled() ? Color.WHITE : Color.BLACK;
_view.setBackgroundColor(fg == Color.WHITE ? Color.BLACK : Color.WHITE);
for (int resid : new int[]{R.id.document__fragment__share_into__append_to_document, R.id.document__fragment__share_into__create_document, R.id.document__fragment__share_into__append_to_quicknote, R.id.document__fragment__share_into__append_to_todo}) {
LinearLayout layout = _view.findViewById(resid);
((TextView) (layout.getChildAt(1))).setTextColor(fg);
}
((TextView) _view.findViewById(R.id.document__fragment__share_into__append_to_document__text))
.setText(getString(R.string.append_to__arg_document_name, getString(R.string.document_one)));
((TextView) _view.findViewById(R.id.document__fragment__share_into__append_to_quicknote__text))
.setText(getString(R.string.append_to__arg_document_name, getString(R.string.quicknote)));
((TextView) _view.findViewById(R.id.document__fragment__share_into__append_to_todo__text))
.setText(getString(R.string.append_to__arg_document_name, getString(R.string.todo)));
((TextView) _view.findViewById(R.id.document__fragment__share_into__create_document__text))
.setText(getString(R.string.create_new_document));
Document document = new Document();
document.setContent(_sharedText);
new MarkdownTextConverter().convertMarkupShowInWebView(document, _webView);
}
@OnClick({R.id.document__fragment__share_into__append_to_document, R.id.document__fragment__share_into__create_document, R.id.document__fragment__share_into__append_to_quicknote})
public void onClick(View view) {
switch (view.getId()) {
case R.id.document__fragment__share_into__create_document: {
if (PermissionChecker.doIfPermissionGranted(getActivity())) {
createNewDocument();
}
break;
}
case R.id.document__fragment__share_into__append_to_document: {
if (PermissionChecker.doIfPermissionGranted(getActivity())) {
showAppendDialog();
}
break;
}
case R.id.document__fragment__share_into__append_to_quicknote: {
if (PermissionChecker.doIfPermissionGranted(getActivity())) {
appendToExistingDocument(AppSettings.get().getQuickNoteFile(), false);
if (getActivity() != null) {
getActivity().finish();
}
}
break;
}
case R.id.document__fragment__share_into__append_to_todo: {
if (PermissionChecker.doIfPermissionGranted(getActivity())) {
appendToExistingDocument(AppSettings.get().getTodoTxtFile(), false);
if (getActivity() != null) {
getActivity().finish();
}
}
break;
}
}
}
private void showAppendDialog() {
FilesystemDialogCreator.showFileDialog(new FilesystemDialogData.SelectionListenerAdapter() {
@Override
public void onFsDialogConfig(FilesystemDialogData.Options opt) {
opt.rootFolder = AppSettings.get().getNotebookDirectory();
}
@Override
public void onFsSelected(String request, File file) {
appendToExistingDocument(file, true);
}
}, getFragmentManager(), getActivity());
}
private void appendToExistingDocument(File file, boolean showEditor) {
Bundle args = new Bundle();
args.putSerializable(DocumentIO.EXTRA_PATH, file);
args.putBoolean(DocumentIO.EXTRA_PATH_IS_FOLDER, false);
Document document = DocumentIO.loadDocument(_context, args, null);
String prepend = TextUtils.isEmpty(document.getContent()) ? "" : (document.getContent() + "\n");
DocumentIO.saveDocument(document, false, prepend + _sharedText);
if (showEditor) {
showInDocumentActivity(document);
}
}
private void createNewDocument() {
// Create a new document
Bundle args = new Bundle();
args.putSerializable(DocumentIO.EXTRA_PATH, AppSettings.get().getNotebookDirectory());
args.putBoolean(DocumentIO.EXTRA_PATH_IS_FOLDER, true);
Document document = DocumentIO.loadDocument(_context, args, null);
DocumentIO.saveDocument(document, false, _sharedText);
// Load document as file
args.putSerializable(DocumentIO.EXTRA_PATH, document.getFile());
args.putBoolean(DocumentIO.EXTRA_PATH_IS_FOLDER, false);
document = DocumentIO.loadDocument(_context, args, null);
document.setTitle("");
showInDocumentActivity(document);
}
private void showInDocumentActivity(Document document) {
if (getActivity() instanceof DocumentActivity) {
DocumentActivity a = (DocumentActivity) getActivity();
a.setDocument(document);
if (AppSettings.get().isPreviewFirst()) {
a.showPreview(document, null);
} else {
a.showTextEditor(document, null, false);
}
}
}
@Override
public String getFragmentTag() {
return FRAGMENT_TAG;
}
@Override
public boolean onBackPressed() {
return false;
}
}
|
3e18a8c93506a476eab78d13ebeda2f6ec90d235 | 10,458 | java | Java | testing/src/test/java/org/motechproject/wa/testing/it/utils/RegionHelper.java | washacademy/wa-motech-implementation | b6a4b4aa9cf63c4d975fc662ccecc28a1f30eab8 | [
"BSD-3-Clause"
] | null | null | null | testing/src/test/java/org/motechproject/wa/testing/it/utils/RegionHelper.java | washacademy/wa-motech-implementation | b6a4b4aa9cf63c4d975fc662ccecc28a1f30eab8 | [
"BSD-3-Clause"
] | null | null | null | testing/src/test/java/org/motechproject/wa/testing/it/utils/RegionHelper.java | washacademy/wa-motech-implementation | b6a4b4aa9cf63c4d975fc662ccecc28a1f30eab8 | [
"BSD-3-Clause"
] | 1 | 2020-10-08T06:30:30.000Z | 2020-10-08T06:30:30.000Z | 30.313043 | 133 | 0.617231 | 10,490 | package org.motechproject.wa.testing.it.utils;
import org.motechproject.wa.region.domain.*;
import org.motechproject.wa.region.repository.CircleDataService;
import org.motechproject.wa.region.repository.DistrictDataService;
import org.motechproject.wa.region.repository.LanguageDataService;
import org.motechproject.wa.region.repository.StateDataService;
import org.motechproject.wa.region.service.DistrictService;
import org.motechproject.wa.region.service.LanguageService;
public class RegionHelper {
private LanguageDataService languageDataService;
private LanguageService languageService;
private CircleDataService circleDataService;
private DistrictDataService districtDataService;
private DistrictService districtService;
private StateDataService stateDataService;
public RegionHelper(LanguageDataService languageDataService,
LanguageService languageService,
CircleDataService circleDataService,
StateDataService stateDataService,
DistrictDataService districtDataService,
DistrictService districtService) {
this.languageDataService = languageDataService;
this.languageService = languageService;
this.circleDataService = circleDataService;
this.stateDataService = stateDataService;
this.districtDataService = districtDataService;
this.districtService = districtService;
}
public Circle delhiCircle() {
Circle c = circleDataService.findByName("DE");
if (c == null) {
c = new Circle("DE");
c.setDefaultLanguage(hindiLanguage());
circleDataService.create(c);
// Create the dehli district which is linked to this circle. Also creates state
newDelhiDistrict();
}
return c;
}
public Circle karnatakaCircle() {
Circle c = circleDataService.findByName("KA");
if (c == null) {
c = new Circle("KA");
c.setDefaultLanguage(kannadaLanguage());
circleDataService.create(c);
// Create a district which also creates the link and the state
bangaloreDistrict();
}
return c;
}
public State delhiState() {
State s = stateDataService.findByCode(1l);
if (s == null) {
s = new State();
s.setName("National Capital Territory of Delhi");
s.setCode(1L);
stateDataService.create(s);
}
return s;
}
public State karnatakaState() {
State s = stateDataService.findByCode(2l);
if (s == null) {
s = new State();
s.setName("Karnataka");
s.setCode(2L);
stateDataService.create(s);
}
return s;
}
public District newDelhiDistrict() {
delhiState();
delhiCircle();
District d = districtService.findByStateAndCode(delhiState(), 1L);
if (d == null) {
d = new District();
d.setName("New Delhi");
d.setRegionalName("New Delhi");
d.setCode(1L);
d.setState(delhiState());
d.setLanguage(hindiLanguage());
d.setCircle(delhiCircle());
districtDataService.create(d);
stateDataService.evictAllCache();
}
return d;
}
public District southDelhiDistrict() {
District d = districtService.findByStateAndCode(delhiState(), 5L);
if (d == null) {
d = new District();
d.setName("South Delhi");
d.setRegionalName("South Delhi");
d.setCode(5L);
d.setState(delhiState());
d.setCircle(delhiCircle());
d.setLanguage(punjabiLanguage());
districtDataService.create(d);
stateDataService.evictAllCache();
}
return d;
}
public District bangaloreDistrict() {
karnatakaState();
karnatakaCircle();
District d = districtService.findByStateAndCode(karnatakaState(), 4L);
if (d == null) {
d = new District();
d.setName("Bengaluru");
d.setRegionalName("Bengaluru");
d.setCode(4L);
d.setState(karnatakaState());
d.setCircle(karnatakaCircle());
d.setLanguage(tamilLanguage());
districtDataService.create(d);
stateDataService.evictAllCache();
}
return d;
}
public District mysuruDistrict() {
District d = districtService.findByStateAndCode(karnatakaState(), 2L);
if (d == null) {
d = new District();
d.setName("Mysuru");
d.setRegionalName("Mysuru");
d.setCode(2L);
d.setState(karnatakaState());
d.setCircle(karnatakaCircle());
d.setLanguage(kannadaLanguage());
districtDataService.create(d);
stateDataService.evictAllCache();
}
return d;
}
public Language tamilLanguage() {
Language l = languageService.getForName("Tamil");
if (l == null) {
l = languageDataService.create(new Language("ta", "Tamil"));
}
return l;
}
public Language kannadaLanguage() {
Language l = languageService.getForName("Kannada");
if (l == null) {
l = languageDataService.create(new Language("kn", "Kannada"));
}
return l;
}
public Language punjabiLanguage() {
Language l = languageService.getForName("Punjabi");
if (l == null) {
l = languageDataService.create(new Language("pa", "Punjabi"));
}
return l;
}
public Language hindiLanguage() {
Language l = languageService.getForName("Hindi");
if (l == null) {
l = languageDataService.create(new Language("hi", "Hindi"));
}
return l;
}
public String airtelOperator()
{
return "A";
}
public static State createState(Long code, String name) {
State state = new State();
state.setCode(code);
state.setName(name);
return state;
}
public static District createDistrict(State state, Long code, String name) {
return createDistrict(state, code, name, null, null);
}
public static District createDistrict(State state, Long code, String name, Language language) {
return createDistrict(state, code, name, language, null);
}
public static District createDistrict(State state, Long code, String name, Circle circle) {
return createDistrict(state, code, name, null, circle);
}
public static District createDistrict(State state, Long code, String name, Language language, Circle circle) {
District district = new District();
district.setState(state);
district.setCode(code);
district.setName(name);
district.setRegionalName(regionalName(name));
district.setLanguage(language);
if (circle != null) {
district.setCircle(circle);
circle.getDistricts().add(district);
}
return district;
}
public static Language createLanguage(String code, String name) {
return new Language(code, name);
}
public static Block createTaluka(District district, Long code, String name, int identity) {
Block block = new Block();
block.setDistrict(district);
block.setCode(code);
block.setName(name);
block.setRegionalName(regionalName(name));
block.setIdentity(identity);
return block;
}
// public static HealthBlock createHealthBlock(Block block, Long code, String name, String hq) {
// HealthBlock healthBlock = new HealthBlock();
// healthBlock.setBlock(block);
// healthBlock.setCode(code);
// healthBlock.setName(name);
// healthBlock.setRegionalName(regionalName(name));
// healthBlock.setHq(hq);
// return healthBlock;
// }
public static Panchayat createVillage(Block block, long svid, long vcode, String name) {
Panchayat panchayat = new Panchayat();
panchayat.setBlock(block);
panchayat.setSvid(svid);
panchayat.setVcode(vcode);
panchayat.setName(name);
panchayat.setRegionalName(regionalName(name));
return panchayat;
}
// public static HealthFacility createHealthFacility(HealthBlock healthBlock, Long code, String name, HealthFacilityType type) {
// HealthFacility healthFacility = new HealthFacility();
// healthFacility.setHealthBlock(healthBlock);
// healthFacility.setCode(code);
// healthFacility.setName(name);
// healthFacility.setRegionalName(regionalName(name));
// healthFacility.setHealthFacilityType(type);
// return healthFacility;
// }
//
// public static HealthFacilityType createHealthFacilityType(String name, Long code) {
// HealthFacilityType healthFacilityType = new HealthFacilityType();
// healthFacilityType.setName(name);
// healthFacilityType.setCode(code);
// return healthFacilityType;
// }
//
// public static HealthSubFacility createHealthSubFacility(String name, Long code, HealthFacility healthFacility) {
// HealthSubFacility healthSubFacility = new HealthSubFacility();
// healthSubFacility.setName(name);
// healthSubFacility.setCode(code);
// healthSubFacility.setRegionalName(name + " regional name");
// healthSubFacility.setHealthFacility(healthFacility);
// return healthSubFacility;
// }
public static Language createLanguage(String code, String name, Circle circle, boolean defaultForCircle, District... districts) {
Language language = new Language();
language.setCode(code);
language.setName(name);
for (District district : districts) {
district.setLanguage(language);
}
if (defaultForCircle) {
circle.setDefaultLanguage(language);
}
return language;
}
public static Circle createCircle(String name) {
return new Circle(name);
}
public static String regionalName(String name) {
return String.format("regional name of %s", name);
}
}
|
3e18a949c33d2e697e02f2fa10541b5c94bbb807 | 3,259 | java | Java | estimote/Demos/src/main/java/com/estimote/examples/demos/activities/ListEddystoneActivity.java | thirdbridge/android_beacon | ab014c8b2eec2c267dc6a18492edebb543b761a3 | [
"MIT"
] | null | null | null | estimote/Demos/src/main/java/com/estimote/examples/demos/activities/ListEddystoneActivity.java | thirdbridge/android_beacon | ab014c8b2eec2c267dc6a18492edebb543b761a3 | [
"MIT"
] | null | null | null | estimote/Demos/src/main/java/com/estimote/examples/demos/activities/ListEddystoneActivity.java | thirdbridge/android_beacon | ab014c8b2eec2c267dc6a18492edebb543b761a3 | [
"MIT"
] | null | null | null | 32.039216 | 98 | 0.724908 | 10,491 | package com.estimote.examples.demos.activities;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.estimote.examples.demos.R;
import com.estimote.examples.demos.adapters.EddystonesListAdapter;
import com.estimote.sdk.BeaconManager;
import com.estimote.sdk.SystemRequirementsChecker;
import com.estimote.sdk.eddystone.Eddystone;
import java.util.Collections;
import java.util.List;
/**
* Displays list of found eddystones sorted by RSSI.
* Starts new activity with selected eddystone if activity was provided.
*
* @author lyhxr@example.com (Wiktor Gworek)
*/
public class ListEddystoneActivity extends BaseActivity {
private static final String TAG = ListEddystoneActivity.class.getSimpleName();
public static final String EXTRAS_TARGET_ACTIVITY = "extrasTargetActivity";
public static final String EXTRAS_EDDYSTONE = "extrasEddystone";
private BeaconManager beaconManager;
private EddystonesListAdapter adapter;
@Override protected int getLayoutResId() {
return R.layout.main;
}
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Configure device list.
adapter = new EddystonesListAdapter(this);
ListView list = (ListView) findViewById(R.id.device_list);
list.setAdapter(adapter);
list.setOnItemClickListener(createOnItemClickListener());
beaconManager = new BeaconManager(this);
}
@Override protected void onDestroy() {
beaconManager.disconnect();
super.onDestroy();
}
@Override protected void onResume() {
super.onResume();
if (SystemRequirementsChecker.checkWithDefaultDialogs(this)) {
startScanning();
}
}
@Override protected void onStop() {
beaconManager.disconnect();
super.onStop();
}
private void startScanning() {
toolbar.setSubtitle("Scanning...");
adapter.replaceWith(Collections.<Eddystone>emptyList());
beaconManager.setEddystoneListener(new BeaconManager.EddystoneListener() {
@Override public void onEddystonesFound(List<Eddystone> eddystones) {
toolbar.setSubtitle("Found beacons with Eddystone protocol: " + eddystones.size());
adapter.replaceWith(eddystones);
}
});
beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
@Override public void onServiceReady() {
beaconManager.startEddystoneScanning();
}
});
}
private AdapterView.OnItemClickListener createOnItemClickListener() {
return new AdapterView.OnItemClickListener() {
@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (getIntent().getStringExtra(EXTRAS_TARGET_ACTIVITY) != null) {
try {
Class<?> clazz = Class.forName(getIntent().getStringExtra(EXTRAS_TARGET_ACTIVITY));
Intent intent = new Intent(ListEddystoneActivity.this, clazz);
intent.putExtra(EXTRAS_EDDYSTONE, adapter.getItem(position));
startActivity(intent);
} catch (ClassNotFoundException e) {
Log.e(TAG, "Finding class by name failed", e);
}
}
}
};
}
}
|
3e18aa1c2b74728a5a9092af3fb687857c0b99b0 | 7,200 | java | Java | app/helper/WebgatherUtils.java | pellerito/to.science.api | d1a48f610f8b35b6cfad77c7af36c443867570db | [
"Apache-2.0"
] | 1 | 2020-12-04T01:15:28.000Z | 2020-12-04T01:15:28.000Z | app/helper/WebgatherUtils.java | pellerito/to.science.api | d1a48f610f8b35b6cfad77c7af36c443867570db | [
"Apache-2.0"
] | 99 | 2015-01-15T07:41:41.000Z | 2020-07-01T18:32:44.000Z | app/helper/WebgatherUtils.java | pellerito/to.science.api | d1a48f610f8b35b6cfad77c7af36c443867570db | [
"Apache-2.0"
] | 5 | 2016-03-02T13:24:20.000Z | 2020-11-12T12:57:06.000Z | 35.121951 | 139 | 0.6925 | 10,492 | /*
* Copyright 2017 hbz NRW (http://www.hbz-nrw.de/)
*
* 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 helper;
import java.io.File;
import java.net.IDN;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import actions.Create;
import helper.mail.Mail;
import models.Gatherconf;
import models.Globals;
import models.Message;
import models.Node;
import play.Logger;
/**
* Eine Klasse mit nützlichen Methoden im Umfeld des Webgatherings
*
* @author I. Kuss, hbz
*/
public class WebgatherUtils {
private static final Logger.ALogger WebgatherLogger =
Logger.of("webgatherer");
/** Datumsformat für String-Repräsentation von Datümern */
public static final DateFormat dateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz");
/**
* Eine Methode zum Validieren und Umwandeln einer URL. Die URL wird nach
* ASCII konvertiert, falls sie noch nicht in dieser Kodierung ist. Wahlweise
* wird vorher nach Punycode konvertiert. Das Schema kann wahlweise erhalten
* (falls vorhanden) oder entfernt werden. Bei ungültigen URL wird eine
* URISyntaxException geschmissen.
*
* von hier kopiert:
* https://nealvs.wordpress.com/2016/01/18/how-to-convert-unicode-url-to-ascii
* -in-java/
*
* @param url ein Uniform Resource Locator als Zeichenkette
* @return eine URL als Zeichenkette
*/
public static String convertUnicodeURLToAscii(String url) {
try {
URL u = new URL(url);
URI uri =
new URI(u.getProtocol(), u.getUserInfo(), IDN.toASCII(u.getHost()),
u.getPort(), u.getPath(), u.getQuery(), u.getRef());
String correctEncodedURL = uri.toASCIIString();
return correctEncodedURL;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Erzeugt eine Nachricht für den Fall, dass eine URL umgezogen ist.
*
* @param conf die Crawler-Settings (Gatherconf)
* @return die Nachricht
*/
public static Message createInvalidUrlMessage(Gatherconf conf) {
Message msg = null;
if (conf.getUrlNew() == null) {
msg = new Message("Die Website ist unbekannt verzogen.\n"
+ "Bitte geben Sie auf dem Tab \"Crawler settings\" eine neue, gültige URL ein. Solange wird die Website nicht erneut eingesammelt.");
} else {
msg = new Message("Die Website ist umgezogen nach " + conf.getUrlNew()
+ ".\n"
+ "Bitte bestätigen Sie den Umzug auf dem Tab \"Crawler settings\" (URL kann dort vorher editiert werden).");
}
return msg;
}
/**
* Schickt E-Mail mit einer Umzugsnotiz und Aufforderung, die neue URL zu
* bestätigen.
*
* @param node der Knoten der Website
* @param conf die Gatherconf der umgezogenen Website
*/
public static void sendInvalidUrlEmail(Node node, Gatherconf conf) {
WebgatherLogger.info("Schicke E-Mail mit Umzugsnotiz.");
try {
String siteName =
conf.getName() == null ? node.getAggregationUri() : conf.getName();
String mailMsg = "Die Website " + siteName + " ist ";
if (conf.getUrlNew() == null) {
mailMsg += "unbekannt verzogen.\n"
+ "Bitte geben Sie auf diesem Webformular eine neue, gültige URL ein. Solange wird die Website nicht erneut eingesammelt: ";
} else {
mailMsg += "umgezogen.\n"
+ "Bitte bestätigen Sie den Umzug auf diesem Webformular (URL kann dort vorher editiert werden): ";
}
mailMsg += Globals.urnbase + node.getAggregationUri() + "/crawler .";
try {
Mail.sendMail(mailMsg, "Die Website " + siteName + " ist umgezogen ! ");
} catch (Exception e) {
throw new RuntimeException("Email could not be sent successfully!");
}
} catch (Exception e) {
WebgatherLogger.warn(e.toString());
}
}
/**
* Diese Methode stößt einen neuen Webcrawl an.
*
* @param node must be of type webpage: Die Webpage
*/
public void startCrawl(Node node) {
Gatherconf conf = null;
File crawlDir = null;
String localpath = null;
try {
if (!"webpage".equals(node.getContentType())) {
throw new HttpArchiveException(400, node.getContentType()
+ " is not supported. Operation works only on regalType:\"webpage\"");
}
WebgatherLogger.debug("Starte Webcrawl für PID: " + node.getPid());
conf = Gatherconf.create(node.getConf());
WebgatherLogger.debug("Gatherer-Konfiguration: " + conf.toString());
conf.setName(node.getPid());
if (conf.getCrawlerSelection()
.equals(Gatherconf.CrawlerSelection.heritrix)) {
if (Globals.heritrix.isBusy()) {
WebgatherLogger
.error("Webgatherer is too busy! Please try again later.");
throw new HttpArchiveException(403,
"Webgatherer is too busy! Please try again later.");
}
if (!Globals.heritrix.jobExists(conf.getName())) {
Globals.heritrix.createJob(conf);
}
boolean success = Globals.heritrix.teardown(conf.getName());
WebgatherLogger.debug("Teardown " + conf.getName() + " " + success);
Globals.heritrix.launch(conf.getName());
WebgatherLogger.debug("Launched " + conf.getName());
Thread.currentThread().sleep(10000);
Globals.heritrix.unpause(conf.getName());
WebgatherLogger.debug("Unpaused " + conf.getName());
Thread.currentThread().sleep(10000);
crawlDir = Globals.heritrix.getCurrentCrawlDir(conf.getName());
String warcPath = Globals.heritrix.findLatestWarc(crawlDir);
String uriPath = Globals.heritrix.getUriPath(warcPath);
localpath = Globals.heritrixData + "/heritrix-data" + "/" + uriPath;
WebgatherLogger.debug("Path to WARC " + localpath);
new Create().createWebpageVersion(node, conf, crawlDir, localpath);
} else if (conf.getCrawlerSelection()
.equals(Gatherconf.CrawlerSelection.wpull)) {
WpullCrawl wpullCrawl = new WpullCrawl(node, conf);
wpullCrawl.createJob();
/**
* Startet Job in neuem Thread, einschließlich CDN-Precrawl
*/
wpullCrawl.startJob();
crawlDir = wpullCrawl.getCrawlDir();
// localpath = wpullCrawl.getLocalpath();
if (wpullCrawl.getExitState() != 0) {
throw new RuntimeException("Crawl job returns with exit state "
+ wpullCrawl.getExitState() + "!");
}
WebgatherLogger
.debug("Path to WARC (crawldir):" + crawlDir.getAbsolutePath());
} else {
throw new RuntimeException(
"Unknown crawler selection " + conf.getCrawlerSelection() + "!");
}
} catch (Exception e) {
// WebgatherExceptionMail.sendMail(n.getPid(), conf.getUrl());
WebgatherLogger.warn("Crawl of Webpage " + node.getPid() + ","
+ conf.getUrl() + " has failed !\n\tReason: " + e.getMessage());
WebgatherLogger.debug("", e);
throw new RuntimeException(e);
}
} // Ende startCrawl
}
|
3e18ab46dfa53f00da460ce1b66d07619ec9a41b | 3,755 | java | Java | core/src/test/java/google/registry/tmch/TmchCrlActionTest.java | hstonec/nomulus | 59abc1d154ac17650fa3f22aa9996f8213565b76 | [
"Apache-2.0"
] | 1,644 | 2016-10-18T15:05:43.000Z | 2022-03-19T21:45:23.000Z | core/src/test/java/google/registry/tmch/TmchCrlActionTest.java | hstonec/nomulus | 59abc1d154ac17650fa3f22aa9996f8213565b76 | [
"Apache-2.0"
] | 332 | 2016-10-18T15:33:58.000Z | 2022-03-30T12:48:37.000Z | core/src/test/java/google/registry/tmch/TmchCrlActionTest.java | hstonec/nomulus | 59abc1d154ac17650fa3f22aa9996f8213565b76 | [
"Apache-2.0"
] | 270 | 2016-10-18T14:56:43.000Z | 2022-03-27T17:54:07.000Z | 42.670455 | 98 | 0.757656 | 10,493 | // Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// 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 google.registry.tmch;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.TestDataHelper.loadBytes;
import static google.registry.util.ResourceUtils.readResourceBytes;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import google.registry.config.RegistryConfig.ConfigModule.TmchCaMode;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.SignatureException;
import java.security.cert.CRLException;
import java.security.cert.CertificateNotYetValidException;
import org.joda.time.DateTime;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link TmchCrlAction}. */
class TmchCrlActionTest extends TmchActionTestCase {
private TmchCrlAction newTmchCrlAction(TmchCaMode tmchCaMode) throws MalformedURLException {
TmchCrlAction action = new TmchCrlAction();
action.marksdb = marksdb;
action.tmchCertificateAuthority = new TmchCertificateAuthority(tmchCaMode, clock);
action.tmchCrlUrl = new URL("http://sloth.lol/tmch.crl");
return action;
}
@Test
void testSuccess() throws Exception {
clock.setTo(DateTime.parse("2013-07-24TZ"));
when(httpResponse.getContent()).thenReturn(
readResourceBytes(TmchCertificateAuthority.class, "icann-tmch.crl").read());
newTmchCrlAction(TmchCaMode.PRODUCTION).run();
verify(httpResponse).getContent();
verify(fetchService).fetch(httpRequest.capture());
assertThat(httpRequest.getValue().getURL().toString()).isEqualTo("http://sloth.lol/tmch.crl");
}
@Test
void testFailure_crlTooOld() throws Exception {
clock.setTo(DateTime.parse("2020-01-01TZ"));
when(httpResponse.getContent())
.thenReturn(loadBytes(TmchCrlActionTest.class, "icann-tmch-pilot-old.crl").read());
TmchCrlAction action = newTmchCrlAction(TmchCaMode.PILOT);
Exception e = assertThrows(Exception.class, action::run);
assertThat(e).hasCauseThat().isInstanceOf(CRLException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("New CRL is more out of date than our current CRL.");
}
@Test
void testFailure_crlNotSignedByRoot() throws Exception {
clock.setTo(DateTime.parse("2013-07-24TZ"));
when(httpResponse.getContent())
.thenReturn(readResourceBytes(TmchCertificateAuthority.class, "icann-tmch.crl").read());
Exception e = assertThrows(Exception.class, newTmchCrlAction(TmchCaMode.PILOT)::run);
assertThat(e).hasCauseThat().isInstanceOf(SignatureException.class);
assertThat(e).hasCauseThat().hasMessageThat().isEqualTo("Signature does not match.");
}
@Test
void testFailure_crlNotYetValid() throws Exception {
clock.setTo(DateTime.parse("1984-01-01TZ"));
when(httpResponse.getContent()).thenReturn(
readResourceBytes(TmchCertificateAuthority.class, "icann-tmch-pilot.crl").read());
Exception e = assertThrows(Exception.class, newTmchCrlAction(TmchCaMode.PILOT)::run);
assertThat(e).hasCauseThat().isInstanceOf(CertificateNotYetValidException.class);
}
}
|
3e18ab7aced782cb842920d059b7c52044a2fd4e | 2,367 | java | Java | src/main/java/org/spongepowered/common/mixin/core/block/tiles/MixinTileEntityBeacon.java | phroa/SpongeCommon | cc9dfd77b67852a1442af771021cc41993fe9a44 | [
"MIT"
] | null | null | null | src/main/java/org/spongepowered/common/mixin/core/block/tiles/MixinTileEntityBeacon.java | phroa/SpongeCommon | cc9dfd77b67852a1442af771021cc41993fe9a44 | [
"MIT"
] | null | null | null | src/main/java/org/spongepowered/common/mixin/core/block/tiles/MixinTileEntityBeacon.java | phroa/SpongeCommon | cc9dfd77b67852a1442af771021cc41993fe9a44 | [
"MIT"
] | null | null | null | 40.810345 | 95 | 0.757076 | 10,494 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.mixin.core.block.tiles;
import static org.spongepowered.api.data.DataQuery.of;
import net.minecraft.tileentity.TileEntityBeacon;
import org.spongepowered.api.block.tileentity.carrier.Beacon;
import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.data.DataView;
import org.spongepowered.api.util.annotation.NonnullByDefault;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@NonnullByDefault
@Mixin(TileEntityBeacon.class)
public abstract class MixinTileEntityBeacon extends MixinTileEntityLockable implements Beacon {
@Shadow private int primaryEffect;
@Shadow private int secondaryEffect;
@Override
public DataContainer toContainer() {
DataContainer container = super.toContainer();
container.set(of("effect1"), getField(1));
container.set(of("effect2"), getField(2));
return container;
}
@Override
public void sendDataToContainer(DataView dataView) {
dataView.set(of("effect1"), getField(1));
dataView.set(of("effect2"), getField(2));
}
}
|
3e18ac24a4842f5ebb4864d1c7619cfdd26426f0 | 5,803 | java | Java | mowl.metamodel.edit/src/mowl/provider/ObjectMaxCardinalityItemProvider.java | cabrerac/mowl | b7fcc67e49c47e5837ffb3981aa8648b87484939 | [
"MIT"
] | null | null | null | mowl.metamodel.edit/src/mowl/provider/ObjectMaxCardinalityItemProvider.java | cabrerac/mowl | b7fcc67e49c47e5837ffb3981aa8648b87484939 | [
"MIT"
] | null | null | null | mowl.metamodel.edit/src/mowl/provider/ObjectMaxCardinalityItemProvider.java | cabrerac/mowl | b7fcc67e49c47e5837ffb3981aa8648b87484939 | [
"MIT"
] | null | null | null | 30.867021 | 139 | 0.74496 | 10,495 | /**
*/
package mowl.provider;
import java.util.Collection;
import java.util.List;
import mowl.ObjectMaxCardinality;
import mowl.mowlPackage;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ViewerNotification;
/**
* This is the item provider adapter for a {@link mowl.ObjectMaxCardinality} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class ObjectMaxCardinalityItemProvider
extends ClassExpressionItemProvider
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ObjectMaxCardinalityItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addCardinalityPropertyDescriptor(object);
addClassesPropertyDescriptor(object);
addObjectPropertiesPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Cardinality feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addCardinalityPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_ObjectMaxCardinality_cardinality_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_ObjectMaxCardinality_cardinality_feature", "_UI_ObjectMaxCardinality_type"),
mowlPackage.Literals.OBJECT_MAX_CARDINALITY__CARDINALITY,
true,
false,
false,
ItemPropertyDescriptor.INTEGRAL_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Classes feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addClassesPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_ObjectMaxCardinality_classes_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_ObjectMaxCardinality_classes_feature", "_UI_ObjectMaxCardinality_type"),
mowlPackage.Literals.OBJECT_MAX_CARDINALITY__CLASSES,
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Object Properties feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addObjectPropertiesPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_ObjectMaxCardinality_objectProperties_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_ObjectMaxCardinality_objectProperties_feature", "_UI_ObjectMaxCardinality_type"),
mowlPackage.Literals.OBJECT_MAX_CARDINALITY__OBJECT_PROPERTIES,
true,
false,
true,
null,
null,
null));
}
/**
* This returns ObjectMaxCardinality.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/ObjectMaxCardinality"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
ObjectMaxCardinality objectMaxCardinality = (ObjectMaxCardinality)object;
return getString("_UI_ObjectMaxCardinality_type") + " " + objectMaxCardinality.getCardinality();
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(ObjectMaxCardinality.class)) {
case mowlPackage.OBJECT_MAX_CARDINALITY__CARDINALITY:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
|
3e18add3a357356e56807c9432848cea28279833 | 1,376 | java | Java | src/main/java/com/yjh/cqa/command/JenkinsCommand.java | yangjinhe/jcqrobot | 3b1e5444b810c13264572dfdf5e571a5281616ed | [
"MIT"
] | null | null | null | src/main/java/com/yjh/cqa/command/JenkinsCommand.java | yangjinhe/jcqrobot | 3b1e5444b810c13264572dfdf5e571a5281616ed | [
"MIT"
] | null | null | null | src/main/java/com/yjh/cqa/command/JenkinsCommand.java | yangjinhe/jcqrobot | 3b1e5444b810c13264572dfdf5e571a5281616ed | [
"MIT"
] | null | null | null | 34.4 | 115 | 0.505087 | 10,496 | package com.yjh.cqa.command;
import cn.hutool.core.util.StrUtil;
import com.yjh.cqa.util.NetworkMonitor;
/**
* Created by yangjh on 2019/7/20.
*/
public class JenkinsCommand extends BaseCommand {
@Override
public void exec(Long fromGroup, long fromQQ, String msg) {
try {
if (msg.equals("help")) {
sendMsg(fromGroup, fromQQ, "以下命令可用:\n" +
"build job_name #构建任务\n" +
"list-jobs [job_name] #展示所有的任务列表,job_name参数可选 \n" +
"enable-job job_name #启用任务\n" +
"disable-job job_name #禁用任务\n" +
"get-job job_name #展示任务的XML配置文件\n" +
"version #展示当前jenkins的版本\n" +
"更多命令请参考官方文档");
return;
}
if (!NetworkMonitor.isNetworkAvailable()) {
sendMsg(fromGroup, fromQQ, "svn连接失败,请检查网络!");
return;
}
String resultLog = executeJenkinsCmd(msg, fromGroup, fromQQ);
if (null != resultLog) {
sendMsg(fromGroup, fromQQ, msg + " 命令提交完成" + (StrUtil.isBlank(resultLog) ? "" : "\n" + resultLog));
}
} catch (Exception e) {
CQ.logDebug("debug", e.getMessage());
sendMsg(fromGroup, fromQQ, msg + " 命令执行异常");
}
}
}
|
3e18ae15776e55211b3af21a86ba22b98a846408 | 6,234 | java | Java | hudson-service/src/main/java/org/hudsonci/service/internal/ServicePreconditions.java | mcculls/hudson | 7e94773277c2067a38c9929ac818dcec53f3855b | [
"MIT"
] | 15 | 2015-03-04T20:19:23.000Z | 2021-08-05T07:13:40.000Z | hudson-service/src/main/java/org/hudsonci/service/internal/ServicePreconditions.java | mcculls/hudson | 7e94773277c2067a38c9929ac818dcec53f3855b | [
"MIT"
] | 2 | 2021-02-03T19:30:28.000Z | 2022-03-02T07:14:30.000Z | hudson-service/src/main/java/org/hudsonci/service/internal/ServicePreconditions.java | hudson/hudson-2.x | 82286f0890b72c47fc4a8ea848d86cbbc5bbd868 | [
"MIT"
] | 14 | 2015-02-11T04:29:14.000Z | 2021-05-02T07:06:29.000Z | 36.244186 | 105 | 0.684151 | 10,497 | /**
* The MIT License
*
* Copyright (c) 2010-2011 Sonatype, Inc. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.hudsonci.service.internal;
import static com.google.common.base.Preconditions.*;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
/**
* Preconditions to check common arguments to Service API calls
*
* @since 2.1.0
*/
public abstract class ServicePreconditions {
protected static final Logger log = LoggerFactory.getLogger(ServicePreconditions.class);
// should not normally instantiate
protected ServicePreconditions() {
}
/**
* Check a project buildNumber for being greater than zero.
*
* @param buildNumber buildNumber to test for validity
* @return the passed in argument if valid
* @throws IllegalArgumentException if buildNumber is less than one
*/
public static int checkBuildNumber(final int buildNumber) {
checkArgument(buildNumber > 0, "buildNumber (%s) must be greater than zero.", buildNumber);
return buildNumber;
}
/**
* Check a project build state index for shallow validity.
*
* @param index a value that should be non-negative
* @return the passed in argument if valid
* @throws IllegalArgumentException if index is negative
*/
public static int checkBuildStateIndex(final int index) {
checkArgument(index >= 0, "build state index (%s) must be greater than zero.", index);
return index;
}
/**
* Check a project builder index for shallow validity
*
* @param index a value that should be non-negative
* @return the passed in argument if valid
* @throws IllegalArgumentException if index is negative
*/
public static int checkBuilderIndex(final int index) {
checkArgument(index >= 0, "builder index (%s) must be greater than zero.", index);
return index;
}
/**
* Check the projectName of an {@link hudson.model.AbstractProject} for shallow validity
*
* @param projectName the project name to check
* @return the unmodified projectName if not null
* @throws NullPointerException if projectName is null
*/
public static String checkProjectName(final String projectName) {
return checkNotNull(projectName, "project name");
}
/**
* Check the nodeName of an {@link hudson.model.Node} for shallow validity
*
* @param nodeName the node name to check
* @return the unmodified nodeName if not null
* @throws NullPointerException if nodeName is null
*/
public static String checkNodeName(final String nodeName) {
// FIXME: Probably need to validate encode/decode the nodeName
return checkNotNull(nodeName, "node name");
}
/**
* Check a {@link org.hudsonci.rest.model.DocumentDTO} ID (UUID) for
* shallow validity
*
* @param id the Document id to check
* @return the unmodified document id
* @throws NullPointerException if document id is null
* @throws IllegalArgumentException if document id is not in the expected
* format of UUID
*/
public static String checkDocumentId(final String id) {
checkNotNull(id, "Document ID");
checkUUID(id);
return id;
}
/**
* Check a uuid string for validity.
*
* @param uuid the argument to check for validity
* @return the uuid argument unmodified
* @throws IllegalArgumentException if uuid cannot be converted to a UUID
* according to {@link java.util.UUID#fromString(String)}
*/
public static String checkUUID(final String uuid) {
UUID.fromString(uuid);
return uuid;
}
/**
* Check an argument for null. If it is null, then throw
* NullPointerException
*
* @param reference a reference to what we are checking for null
* @param msgKey a name describing what we are checking for null, to be
* added to the NullPointerException msg in case of error
*/
public static <T> T checkNotNull(T reference, String msgKey) {
return Preconditions.checkNotNull(reference, "%s must not be null.", msgKey);
}
/**
* IF the passed reference is null, throws a NullPointerException with
* appropriate message.
* <p>
* While not itself a precondition, this is a common operation if a
* precondition fails and can be used when custom validation was performed
* for a rest argument.
*
* @param <T> reference to a value to check for null
* @param reference reference to a value to check for null
* @param clazz the type of reference, may be null
* @return reference unchanged
* @throws NullPointerException with message derived from clazz value if
* reference is null
*/
public static <T> T checkNotNull(T reference, Class<T> clazz) {
if (reference == null) {
final String msg = clazz == null ? "Required value" : clazz.getName() + " must not be null.";
throw new NullPointerException(msg);
}
return reference;
}
}
|
3e18aea9f23e63eebc837c78d85eb7d2bc5564a2 | 867 | java | Java | Java_Advanced_2021/src/JavaAdvancedRetakeExam16December2020/P03Openning/bakery/Employee.java | lmarinov/Java_Basics_And_Advanced_Repo | e08e4f2ee3c1e6e1e47172cdee9ae3cbfa514f15 | [
"MIT"
] | null | null | null | Java_Advanced_2021/src/JavaAdvancedRetakeExam16December2020/P03Openning/bakery/Employee.java | lmarinov/Java_Basics_And_Advanced_Repo | e08e4f2ee3c1e6e1e47172cdee9ae3cbfa514f15 | [
"MIT"
] | null | null | null | Java_Advanced_2021/src/JavaAdvancedRetakeExam16December2020/P03Openning/bakery/Employee.java | lmarinov/Java_Basics_And_Advanced_Repo | e08e4f2ee3c1e6e1e47172cdee9ae3cbfa514f15 | [
"MIT"
] | null | null | null | 20.162791 | 104 | 0.592849 | 10,498 | package JavaAdvancedRetakeExam16December2020.P03Openning.bakery;
public class Employee {
private String name;
private int age;
private String country;
public Employee(String name, int age, String country) {
this.name = name;
this.age = age;
this.country = country;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString(){
return String.format("Employee: %s, %d (%s)", this.getName(), this.getAge(), this.getCountry());
}
}
|
3e18af6dbc14eb2697f8b4f72e7f464e063ef74b | 1,736 | java | Java | app/src/main/java/newsapp/xtapp/com/staggeredpic/view/personal/PersonalLowerFragment.java | dadaTang/xtan | e41bbe0532c76e5ce44d487f09ff8248c2a59e05 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/newsapp/xtapp/com/staggeredpic/view/personal/PersonalLowerFragment.java | dadaTang/xtan | e41bbe0532c76e5ce44d487f09ff8248c2a59e05 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/newsapp/xtapp/com/staggeredpic/view/personal/PersonalLowerFragment.java | dadaTang/xtan | e41bbe0532c76e5ce44d487f09ff8248c2a59e05 | [
"Apache-2.0"
] | null | null | null | 26.30303 | 74 | 0.677995 | 10,499 | package newsapp.xtapp.com.staggeredpic.view.personal;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import newsapp.xtapp.com.staggeredpic.R;
import newsapp.xtapp.com.staggeredpic.base.fragment.BaseFragment;
import newsapp.xtapp.com.staggeredpic.view.about.AboutActivity;
/**
* Created by Horrarndoo on 2017/9/26.
* <p>
*/
public class PersonalLowerFragment extends BaseFragment {
@BindView(R.id.tv_btn_settings)
TextView tvBtnSetting;
@BindView(R.id.tv_btn_about)
TextView tvBtnAbout;
public static PersonalLowerFragment newInstance() {
Bundle args = new Bundle();
PersonalLowerFragment fragment = new PersonalLowerFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public int getLayoutId() {
return R.layout.fragment_personal_lower;
}
@Override
public void initUI(View view, @Nullable Bundle savedInstanceState) {
}
@OnClick({R.id.tv_btn_settings, R.id.tv_btn_about})
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_btn_settings:
start(PersonalSettingFragment.newInstance());
break;
case R.id.tv_btn_about:
startActivity(new Intent(mActivity, AboutActivity.class));
break;
default:
break;
}
}
@Override
public boolean onBackPressedSupport() {
//不处理,直接丢给Activity onBackPressedSupport处理
//若此处要拦截回退逻辑到HomeFragment,直接使用RxBus处理
return false;
}
}
|
3e18b27ae72339d6a4bc7f82ebedfc9fdc788e66 | 14,328 | java | Java | core/viewer-restfulobjects-applib/src/main/java/org/apache/isis/viewer/restfulobjects/applib/util/Parser.java | kshithijiyer/isis | b99a6a9057fdcd4af25b0a2f36f7b32efa6f137c | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-03-17T03:19:33.000Z | 2019-03-17T03:19:33.000Z | core/viewer-restfulobjects-applib/src/main/java/org/apache/isis/viewer/restfulobjects/applib/util/Parser.java | DalavanCloud/isis | 2af2ef3e2edcb807d742f089839e0571d8132bd9 | [
"Apache-2.0"
] | null | null | null | core/viewer-restfulobjects-applib/src/main/java/org/apache/isis/viewer/restfulobjects/applib/util/Parser.java | DalavanCloud/isis | 2af2ef3e2edcb807d742f089839e0571d8132bd9 | [
"Apache-2.0"
] | null | null | null | 33.166667 | 136 | 0.50328 | 10,500 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.isis.viewer.restfulobjects.applib.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.MediaType;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.isis.viewer.restfulobjects.applib.JsonRepresentation;
public abstract class Parser<T> {
public T valueOf(final List<String> str) {
if (str == null) {
return null;
}
if (str.size() == 0) {
return null;
}
return valueOf(str.get(0));
}
public T valueOf(final String[] str) {
if (str == null) {
return null;
}
if (str.length == 0) {
return null;
}
return valueOf(str[0]);
}
public T valueOf(final JsonRepresentation jsonRepresentation) {
if (jsonRepresentation == null) {
return null;
}
return valueOf(jsonRepresentation.asString());
}
public JsonRepresentation asJsonRepresentation(final T t) {
return JsonRepresentation.newMap("dummy", asString(t)).getRepresentation("dummy");
}
public abstract T valueOf(String str);
public abstract String asString(T t);
public final static Parser<String> forString() {
return new Parser<String>() {
@Override
public String valueOf(final String str) {
return str;
}
@Override
public String asString(final String t) {
return t;
}
};
}
public static Parser<Date> forDate() {
return new Parser<Date>() {
private final SimpleDateFormat RFC1123_DATE_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyyy HH:mm:ss z");
@Override
public Date valueOf(final String str) {
if (str == null) {
return null;
}
try {
return RFC1123_DATE_FORMAT.parse(str);
} catch (final ParseException e) {
return null;
}
}
@Override
public String asString(final Date t) {
return RFC1123_DATE_FORMAT.format(t);
}
};
}
public static Parser<CacheControl> forCacheControl() {
return new Parser<CacheControl>() {
@Override
public CacheControl valueOf(final String str) {
if (str == null) {
return null;
}
final CacheControl cacheControl = CacheControl.valueOf(str);
// workaround for bug in CacheControl's equals() method
cacheControl.getCacheExtension();
cacheControl.getNoCacheFields();
return cacheControl;
}
@Override
public String asString(final CacheControl cacheControl) {
return cacheControl.toString();
}
};
}
public static Parser<MediaType> forJaxRsMediaType() {
return new Parser<MediaType>() {
@Override
public MediaType valueOf(final String str) {
if (str == null) {
return null;
}
return MediaType.valueOf(str);
}
@Override
public String asString(final MediaType t) {
return t.toString();
}
};
}
public static Parser<com.google.common.net.MediaType> forGuavaMediaType() {
return new Parser<com.google.common.net.MediaType>() {
@Override
public com.google.common.net.MediaType valueOf(final String str) {
if (str == null) {
return null;
}
return com.google.common.net.MediaType.parse(str);
}
@Override
public String asString(final com.google.common.net.MediaType t) {
return t.toString();
}
};
}
public static Parser<Boolean> forBoolean() {
return new Parser<Boolean>() {
@Override
public Boolean valueOf(final String str) {
if (str == null) {
return null;
}
return "yes".equalsIgnoreCase(str) || "true".equalsIgnoreCase(str)
? Boolean.TRUE
: Boolean.FALSE;
}
@Override
public String asString(final Boolean t) {
return t ? "yes" : "no";
}
};
}
public static Parser<Integer> forInteger() {
return new Parser<Integer>() {
@Override
public Integer valueOf(final String str) {
if (str == null) {
return null;
}
return Integer.valueOf(str);
}
@Override
public String asString(final Integer t) {
return t.toString();
}
};
}
public static Parser<List<String>> forListOfStrings() {
return new Parser<List<String>>() {
@Override
public List<String> valueOf(final List<String> strings) {
if (strings == null) {
return Collections.emptyList();
}
if (strings.size() == 1) {
// special case processing to handle comma-separated values
return valueOf(strings.get(0));
}
return strings;
}
@Override
public List<String> valueOf(final String[] strings) {
if (strings == null) {
return Collections.emptyList();
}
if (strings.length == 1) {
// special case processing to handle comma-separated values
return valueOf(strings[0]);
}
return Arrays.asList(strings);
}
@Override
public List<String> valueOf(final String str) {
if (str == null) {
return Collections.emptyList();
}
return Lists.newArrayList(Splitter.on(",").split(str));
}
@Override
public String asString(final List<String> strings) {
return Joiner.on(",").join(strings);
}
};
}
public static Parser<List<List<String>>> forListOfListOfStrings() {
return new Parser<List<List<String>>>() {
@Override
public List<List<String>> valueOf(final List<String> str) {
if (str == null) {
return null;
}
if (str.size() == 0) {
return null;
}
final List<List<String>> listOfLists = Lists.newArrayList();
for (final String s : str) {
listOfLists.add(PathNode.split(s));
}
return listOfLists;
}
@Override
public List<List<String>> valueOf(final String[] str) {
if (str == null) {
return null;
}
if (str.length == 0) {
return null;
}
return valueOf(Arrays.asList(str));
}
@Override
public List<List<String>> valueOf(final String str) {
if (str == null || str.isEmpty()) {
return Collections.emptyList();
}
final Iterable<String> listOfStrings = Splitter.on(',').split(str);
return Lists.transform(Lists.newArrayList(listOfStrings), new Function<String, List<String>>() {
@Override
public List<String> apply(final String input) {
return PathNode.split(input);
}
});
}
@Override
public String asString(final List<List<String>> listOfLists) {
final List<String> listOfStrings = Lists.transform(listOfLists, new Function<List<String>, String>() {
@Override
public String apply(final List<String> listOfStrings) {
return Joiner.on('.').join(listOfStrings);
}
});
return Joiner.on(',').join(listOfStrings);
}
};
}
public static Parser<String[]> forArrayOfStrings() {
return new Parser<String[]>() {
@Override
public String[] valueOf(final List<String> strings) {
if (strings == null) {
return new String[] {};
}
if (strings.size() == 1) {
// special case processing to handle comma-separated values
return valueOf(strings.get(0));
}
return strings.toArray(new String[] {});
}
@Override
public String[] valueOf(final String[] strings) {
if (strings == null) {
return new String[] {};
}
if (strings.length == 1) {
// special case processing to handle comma-separated values
return valueOf(strings[0]);
}
return strings;
}
@Override
public String[] valueOf(final String str) {
if (str == null) {
return new String[] {};
}
final Iterable<String> split = Splitter.on(",").split(str);
return Iterables.toArray(split, String.class);
}
@Override
public String asString(final String[] strings) {
return Joiner.on(",").join(strings);
}
};
}
public static Parser<List<MediaType>> forListOfJaxRsMediaTypes() {
return new Parser<List<MediaType>>() {
@Override
public List<MediaType> valueOf(final String str) {
if (str == null) {
return Collections.emptyList();
}
final List<String> strings = Lists.newArrayList(Splitter.on(",").split(str));
return Lists.transform(strings, new Function<String, MediaType>() {
@Override
public MediaType apply(final String input) {
return MediaType.valueOf(input);
}
});
}
@Override
public String asString(final List<MediaType> listOfMediaTypes) {
final List<String> strings = Lists.transform(listOfMediaTypes, new Function<MediaType, String>() {
@Override
public String apply(final MediaType input) {
return input.toString();
}
});
return Joiner.on(",").join(strings);
}
};
}
public static Parser<List<com.google.common.net.MediaType>> forListOfGuavaMediaTypes() {
return new Parser<List<com.google.common.net.MediaType>>() {
@Override
public List<com.google.common.net.MediaType> valueOf(final String str) {
if (str == null) {
return Collections.emptyList();
}
final List<String> strings = Lists.newArrayList(Splitter.on(",").split(str));
return Lists.transform(strings, new Function<String, com.google.common.net.MediaType>() {
@Override
public com.google.common.net.MediaType apply(final String input) {
return com.google.common.net.MediaType.parse(input);
}
});
}
@Override
public String asString(final List<com.google.common.net.MediaType> listOfMediaTypes) {
final List<String> strings = Lists.transform(listOfMediaTypes, new Function<com.google.common.net.MediaType, String>() {
@Override
public String apply(final com.google.common.net.MediaType input) {
return input.toString();
}
});
return Joiner.on(",").join(strings);
}
};
}
public static Parser<String> forETag() {
return new Parser<String>(){
private final static String WEAK_PREFIX="W/";
@Override
public String valueOf(String str) {
if(str == null) {
return null;
}
return null;
}
@Override
public String asString(String t) {
// TODO Auto-generated method stub
return null;
}};
}
}
|
3e18b4635c429ef3202d56699074a9e53d3696cd | 3,218 | java | Java | src/main/java/com/linetoart/core/solver/AbstractDepthSolver.java | arglin/linetoart-core | 42d292b806b965235b24f8dc304dfb2c0176b667 | [
"MIT"
] | 8 | 2022-02-05T14:54:43.000Z | 2022-03-15T12:01:48.000Z | src/main/java/com/linetoart/core/solver/AbstractDepthSolver.java | arglin/linetoart-core | 42d292b806b965235b24f8dc304dfb2c0176b667 | [
"MIT"
] | null | null | null | src/main/java/com/linetoart/core/solver/AbstractDepthSolver.java | arglin/linetoart-core | 42d292b806b965235b24f8dc304dfb2c0176b667 | [
"MIT"
] | null | null | null | 39.243902 | 121 | 0.699814 | 10,501 | /*
* MIT License
*
* Copyright (c) 2022.
*
* Author: arglin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.linetoart.core.solver;
import com.linetoart.core.L2ASolution;
import com.linetoart.core.L2ASolver;
import com.linetoart.core.basic.DepthMatchReport;
import com.linetoart.core.basic.L2ADefault;
import com.linetoart.core.basic.Bresenham;
import com.linetoart.core.basic.PixelActionListener;
import com.linetoart.core.model.ComputeData;
import com.linetoart.core.model.Nail;
import com.linetoart.core.model.NailsFormation;
import com.linetoart.core.tool.ImageConvertor;
import java.awt.*;
public abstract class AbstractDepthSolver implements L2ASolver {
public L2ASolution solve(Image image, int nailNum) {
ComputeData computeData = new ComputeData(image, NailsFormation.OVAL);
L2Art l2Art = new L2Art(computeData.getComputeNails(nailNum));
int[][] blackDepth = ImageConvertor.pixelsToGrayDepthArray(computeData.getComputePixels());
this.crossThreads(blackDepth, l2Art, (x, y) -> {
//every time deeper the depth of every pixel the line goes through
blackDepth[x][y] += L2ADefault.lineDepth;
if (blackDepth[x][y] > 255) {
blackDepth[x][y] = 255;
}
if (blackDepth[x][y] < 0) {
blackDepth[x][y] = 0;
}
});
return l2Art;
}
/**
* evaluate the accuracy of one line start from the startPin to the endPin
*/
protected DepthMatchReport analyse(int startPin, int endPin, int[][] depth, Nail[] nails) {
DepthMatchReport depthMatchReport = new DepthMatchReport();
try {
Bresenham.plotLine(nails[startPin].centerX, nails[startPin].centerY,
nails[endPin].centerX, nails[endPin].centerY, (x, y) -> depthMatchReport.compare(0x00, depth[x][y]));
} catch (Exception e) {
System.out.println(nails[startPin].centerX);
System.out.println(nails[startPin].centerY);
}
return depthMatchReport;
}
protected abstract void crossThreads(int[][] pixels, L2Art l2Art, PixelActionListener listener);
}
|
3e18b4dc2ae37dd3136e82f576915587767c29b9 | 369 | java | Java | projekt6/src/hr/fer/zemris/java/primjeri/DatumIVrijeme.java | DomagojGalic/java_tutorial | bfe6fa320bf29ad17eb9ba799617a0f085bd395c | [
"MIT"
] | null | null | null | projekt6/src/hr/fer/zemris/java/primjeri/DatumIVrijeme.java | DomagojGalic/java_tutorial | bfe6fa320bf29ad17eb9ba799617a0f085bd395c | [
"MIT"
] | null | null | null | projekt6/src/hr/fer/zemris/java/primjeri/DatumIVrijeme.java | DomagojGalic/java_tutorial | bfe6fa320bf29ad17eb9ba799617a0f085bd395c | [
"MIT"
] | null | null | null | 20.5 | 63 | 0.696477 | 10,502 | package hr.fer.zemris.java.primjeri;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DatumIVrijeme implements IIspisivo {
private String format;
public DatumIVrijeme(String format) {
this.format = format;
}
@Override
public String poruka() {
return new SimpleDateFormat(format).format(new Date());
}
} |
3e18b4ddb403fbcc3e22e0807cc9e5c486a877cc | 419 | java | Java | src/main/java/pt/it/av/tnav/ml/dataset/Dataset.java | mariolpantunes/ml | a07b8d9c642ebafb142fe5d83800c011c53c4e90 | [
"MIT"
] | 7 | 2015-11-26T16:37:50.000Z | 2021-09-01T07:00:34.000Z | src/main/java/pt/it/av/tnav/ml/dataset/Dataset.java | mariolpantunes/ml | a07b8d9c642ebafb142fe5d83800c011c53c4e90 | [
"MIT"
] | 2 | 2018-06-12T00:10:05.000Z | 2018-06-12T00:16:46.000Z | src/main/java/pt/it/av/tnav/ml/dataset/Dataset.java | mariolpantunes/ml | a07b8d9c642ebafb142fe5d83800c011c53c4e90 | [
"MIT"
] | 2 | 2018-06-05T10:19:02.000Z | 2018-06-19T22:31:09.000Z | 17.458333 | 77 | 0.615752 | 10,503 | package pt.it.av.tnav.ml.dataset;
import pt.it.av.tnav.utils.structures.Distance;
import java.util.List;
/**
*
* @param <T>
*/
public interface Dataset<T extends Distance<T>> {
/**
* Returns a {@link List} of {@link Vector} with the data from the dataset.
*
* @return a {@link List} of {@link Vector} with the data from the dataset.
*/
List<T> load();
/**
* @return
*/
int classes();
}
|
3e18b51d33f047aa40a501897bca05bd60a6897c | 4,165 | java | Java | aws/src/main/java/org/apache/iceberg/aws/AssumeRoleAwsClientFactory.java | kingeasternsun/iceberg | 1634ab6c9861e8934d9f8f7e823b6a87ce76fd63 | [
"Apache-2.0"
] | 2,161 | 2020-05-28T01:20:01.000Z | 2022-03-31T14:48:04.000Z | aws/src/main/java/org/apache/iceberg/aws/AssumeRoleAwsClientFactory.java | kingeasternsun/iceberg | 1634ab6c9861e8934d9f8f7e823b6a87ce76fd63 | [
"Apache-2.0"
] | 3,096 | 2020-05-27T20:57:13.000Z | 2022-03-31T22:55:42.000Z | aws/src/main/java/org/apache/iceberg/aws/AssumeRoleAwsClientFactory.java | kingeasternsun/iceberg | 1634ab6c9861e8934d9f8f7e823b6a87ce76fd63 | [
"Apache-2.0"
] | 879 | 2020-05-28T01:20:01.000Z | 2022-03-31T12:48:48.000Z | 37.522523 | 108 | 0.768547 | 10,504 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iceberg.aws;
import java.util.Map;
import java.util.UUID;
import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
import org.apache.iceberg.util.PropertyUtil;
import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder;
import software.amazon.awssdk.awscore.client.builder.AwsSyncClientBuilder;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.glue.GlueClient;
import software.amazon.awssdk.services.kms.KmsClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.auth.StsAssumeRoleCredentialsProvider;
import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
public class AssumeRoleAwsClientFactory implements AwsClientFactory {
private static final SdkHttpClient HTTP_CLIENT_DEFAULT = UrlConnectionHttpClient.create();
private String roleArn;
private String externalId;
private int timeout;
private String region;
private String s3Endpoint;
@Override
public S3Client s3() {
return S3Client.builder()
.applyMutation(this::configure)
.applyMutation(builder -> AwsClientFactories.configureEndpoint(builder, s3Endpoint))
.build();
}
@Override
public GlueClient glue() {
return GlueClient.builder().applyMutation(this::configure).build();
}
@Override
public KmsClient kms() {
return KmsClient.builder().applyMutation(this::configure).build();
}
@Override
public DynamoDbClient dynamo() {
return DynamoDbClient.builder().applyMutation(this::configure).build();
}
@Override
public void initialize(Map<String, String> properties) {
roleArn = properties.get(AwsProperties.CLIENT_ASSUME_ROLE_ARN);
Preconditions.checkNotNull(roleArn,
"Cannot initialize AssumeRoleClientConfigFactory with null role ARN");
timeout = PropertyUtil.propertyAsInt(properties,
AwsProperties.CLIENT_ASSUME_ROLE_TIMEOUT_SEC, AwsProperties.CLIENT_ASSUME_ROLE_TIMEOUT_SEC_DEFAULT);
externalId = properties.get(AwsProperties.CLIENT_ASSUME_ROLE_EXTERNAL_ID);
region = properties.get(AwsProperties.CLIENT_ASSUME_ROLE_REGION);
Preconditions.checkNotNull(region, "Cannot initialize AssumeRoleClientConfigFactory with null region");
this.s3Endpoint = properties.get(AwsProperties.S3FILEIO_ENDPOINT);
}
private <T extends AwsClientBuilder & AwsSyncClientBuilder> T configure(T clientBuilder) {
AssumeRoleRequest request = AssumeRoleRequest.builder()
.roleArn(roleArn)
.roleSessionName(genSessionName())
.durationSeconds(timeout)
.externalId(externalId)
.build();
clientBuilder.credentialsProvider(
StsAssumeRoleCredentialsProvider.builder()
.stsClient(StsClient.builder().httpClient(HTTP_CLIENT_DEFAULT).build())
.refreshRequest(request)
.build());
clientBuilder.region(Region.of(region));
clientBuilder.httpClient(HTTP_CLIENT_DEFAULT);
return clientBuilder;
}
private String genSessionName() {
return String.format("iceberg-aws-%s", UUID.randomUUID());
}
}
|
3e18b5741030172f945e7f7e09e4340ed34cc22c | 1,359 | java | Java | src/main/java/cn/edu/jxnu/leetcode/Leetcode_455.java | yangzaiqiong/cs-summary-reflection | 3356520e44a0f892c72b37f93e6836f8422cd3ae | [
"Apache-2.0"
] | 1 | 2019-08-27T16:42:22.000Z | 2019-08-27T16:42:22.000Z | src/main/java/cn/edu/jxnu/leetcode/Leetcode_455.java | yangzaiqiong/cs-summary-reflection | 3356520e44a0f892c72b37f93e6836f8422cd3ae | [
"Apache-2.0"
] | null | null | null | src/main/java/cn/edu/jxnu/leetcode/Leetcode_455.java | yangzaiqiong/cs-summary-reflection | 3356520e44a0f892c72b37f93e6836f8422cd3ae | [
"Apache-2.0"
] | null | null | null | 24.267857 | 80 | 0.534952 | 10,505 | package cn.edu.jxnu.leetcode;
import java.util.Arrays;
/**
* @author 梦境迷离
* @description 题目描述:每个孩子都有一个满足度,每个饼干都有一个大小,只有饼干的大小大于一个孩子的满足度,该孩子才会获得满足。
* 求解最多可以获得满足的孩子数量。
*
* 因为最小的孩子最容易得到满足,因此先满足最小孩子。给一个孩子的饼干应当尽量小又能满足该孩子,
* 这样大饼干就能拿来给满足度比较大的孩子。
*
* 证明:假设在某次选择中,贪心策略选择给第 i 个孩子分配第 m 个饼干,并且第 i 个孩子满足度最小,第 m 个饼干为可以满足第
* i 个孩子的最小饼干,利用贪心策略最终可以满足 k 个孩子。假设最优策略在这次选择中给 i 个孩子分配第 n
* 个饼干,并且这个饼干大于第 m 个饼干,那么最优策略最终需要满足大于 k 个孩子。我们发现使用第 m 个饼干去替代第 n
* 个饼干完全不影响后续的结果,因此贪心策略就是最优策略,因此贪心策略是最优的。
* @time 2018年3月30日
*/
public class Leetcode_455 {
/**
*
* @author 梦境迷离
* @description 注意:
*
* 你可以假设胃口值为正。 一个小朋友最多只能拥有一块饼干。
*
* 示例 1:
*
* 输入: [1,2,3], [1,1]
*
* 输出: 1
*
* 解释: 你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。
* 虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。 所以你应该输出1。 示例 2:
*
* 输入: [1,2], [1,2,3]
*
* 输出: 2
*
* 解释: 你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。 你拥有的饼干数量和尺寸都足以让所有孩子满足。
* 所以你应该输出2.
* @time 2018年3月30日
*/
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int i = 0, j = 0;
while (i < g.length && j < s.length) {
if (g[i] <= s[j])
i++;
j++;
}
return i;
}
}
|
3e18b72bcda8c9a16b0d96219a37458fff17814c | 352 | java | Java | src/main/java/com/infomaximum/cluster/graphql/utils/ExceptionUtils.java | Infomaximum/cluster-graphql | b3ea646e3319068a8d15b1c82f2317f5b4e76cfc | [
"Apache-2.0"
] | null | null | null | src/main/java/com/infomaximum/cluster/graphql/utils/ExceptionUtils.java | Infomaximum/cluster-graphql | b3ea646e3319068a8d15b1c82f2317f5b4e76cfc | [
"Apache-2.0"
] | null | null | null | src/main/java/com/infomaximum/cluster/graphql/utils/ExceptionUtils.java | Infomaximum/cluster-graphql | b3ea646e3319068a8d15b1c82f2317f5b4e76cfc | [
"Apache-2.0"
] | null | null | null | 25.142857 | 82 | 0.684659 | 10,506 | package com.infomaximum.cluster.graphql.utils;
public class ExceptionUtils {
public static RuntimeException coercionRuntimeException(Throwable throwable) {
if (throwable instanceof RuntimeException) {
return (RuntimeException) throwable;
} else {
return new RuntimeException(throwable);
}
}
}
|
3e18b838eaa5707d7432b4a30a6be8acdf63de8c | 5,058 | java | Java | core/src/test/java/edu/northwestern/bioinformatics/studycalendar/xml/writers/ScheduledActivityStateXmlSerializerTest.java | NUBIC/psc-mirror | d9930757ae31fe365f5df7ae49cb03e629ddb8b8 | [
"BSD-3-Clause"
] | 1 | 2017-03-02T11:39:40.000Z | 2017-03-02T11:39:40.000Z | core/src/test/java/edu/northwestern/bioinformatics/studycalendar/xml/writers/ScheduledActivityStateXmlSerializerTest.java | NUBIC/psc-mirror | d9930757ae31fe365f5df7ae49cb03e629ddb8b8 | [
"BSD-3-Clause"
] | null | null | null | core/src/test/java/edu/northwestern/bioinformatics/studycalendar/xml/writers/ScheduledActivityStateXmlSerializerTest.java | NUBIC/psc-mirror | d9930757ae31fe365f5df7ae49cb03e629ddb8b8 | [
"BSD-3-Clause"
] | null | null | null | 41.121951 | 128 | 0.739818 | 10,507 | package edu.northwestern.bioinformatics.studycalendar.xml.writers;
import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledActivityMode;
import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledActivityState;
import edu.northwestern.bioinformatics.studycalendar.core.StudyCalendarXmlTestCase;
import edu.nwu.bioinformatics.commons.DateUtils;
import org.dom4j.Element;
import org.dom4j.tree.BaseElement;
import static java.util.Calendar.JANUARY;
/**
* @author John Dzak
*/
public class ScheduledActivityStateXmlSerializerTest extends StudyCalendarXmlTestCase {
private CurrentScheduledActivityStateXmlSerializer serializer;
private ScheduledActivityState missed, scheduled, occurred, canceled, conditional, notApplicable;
protected void setUp() throws Exception {
super.setUp();
serializer = new CurrentScheduledActivityStateXmlSerializer();
missed = missed();
occurred = occurred();
canceled = canceled();
scheduled = scheduled();
conditional = conditional();
notApplicable = notApplicable();
}
public void testCreateElementWhenStateIsMissed() {
Element actual = serializer.createElement(missed);
assertStateAttributesEquals("missed", "some reason", null, actual);
}
public void testCreateElementWhenStateIsOccurred() {
Element actual = serializer.createElement(occurred);
assertStateAttributesEquals("occurred", "some reason", "2008-01-05", actual);
}
public void testCreateElementWhenStateIsScheduled() {
Element actual = serializer.createElement(scheduled);
assertStateAttributesEquals("scheduled", "some reason", "2008-01-05", actual);
}
public void testCreateElementWhenStateIsCancelled() {
Element actual = serializer.createElement(canceled);
assertStateAttributesEquals("canceled", "some reason", null, actual);
}
public void testCreateElementWhenStateIsConditional() {
Element actual = serializer.createElement(conditional);
assertStateAttributesEquals("conditional", "some reason", "2008-01-05", actual);
}
public void testCreateElementWhenStateIsNotApplicable() {
Element actual = serializer.createElement(notApplicable);
assertStateAttributesEquals("not-applicable", "some reason", null, actual);
}
public void testCreateElementForPreviousScheduledActivityState() {
PreviousScheduledActivityStateXmlSerializer prevStateSerializer = new PreviousScheduledActivityStateXmlSerializer();
Element actual = prevStateSerializer.createElement(scheduled);
assertEquals("Wrong element name", "previous-scheduled-activity-state", actual.getName());
}
public void testReadElement() {
try {
PreviousScheduledActivityStateXmlSerializer prevStateSerializer = new PreviousScheduledActivityStateXmlSerializer();
prevStateSerializer.readElement(new BaseElement("previous-scheduled-activity-state"));
fail("Exception should be thrown, method not implemented");
} catch (UnsupportedOperationException success) {
assertEquals("Functionality to read a scheduled activity state element does not exist", success.getMessage());
}
}
////// Helper Asserts
public void assertStateAttributesEquals(String expectedState, String expectedReason, String expectedDate, Element actual) {
assertEquals("Wrong element name", "current-scheduled-activity-state", actual.getName());
assertEquals("Wrong state", expectedState, actual.attributeValue("state"));
assertEquals("Wrong reason", expectedReason, actual.attributeValue("reason"));
assertEquals("Wrong date", expectedDate, actual.attributeValue("date"));
}
////// Helper Methods
private ScheduledActivityState missed() {
return setBaseAttributes(ScheduledActivityMode.MISSED.createStateInstance());
}
private ScheduledActivityState scheduled() {
return setDateAttributes(ScheduledActivityMode.SCHEDULED.createStateInstance());
}
private ScheduledActivityState occurred() {
return setDateAttributes(ScheduledActivityMode.OCCURRED.createStateInstance());
}
private ScheduledActivityState canceled() {
return setBaseAttributes(ScheduledActivityMode.CANCELED.createStateInstance());
}
private ScheduledActivityState conditional() {
return setDateAttributes(ScheduledActivityMode.CONDITIONAL.createStateInstance());
}
private ScheduledActivityState notApplicable() {
return setBaseAttributes(ScheduledActivityMode.NOT_APPLICABLE.createStateInstance());
}
private ScheduledActivityState setDateAttributes(ScheduledActivityState state) {
state.setDate(DateUtils.createDate(2008, JANUARY, 5));
return setBaseAttributes(state);
}
private ScheduledActivityState setBaseAttributes(ScheduledActivityState state) {
state.setReason("some reason");
return state;
}
}
|
3e18b8bb2ae0336f2a00a0711f5d1b2c8feec07a | 6,237 | java | Java | app/src/main/java/com/codemelinux/HUSAP/main/pickImageBase/PickImageActivity.java | codemelinux/HUSAP | 641a73aca35a5d36db186f51100fc15e7bb65d4c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/codemelinux/HUSAP/main/pickImageBase/PickImageActivity.java | codemelinux/HUSAP | 641a73aca35a5d36db186f51100fc15e7bb65d4c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/codemelinux/HUSAP/main/pickImageBase/PickImageActivity.java | codemelinux/HUSAP | 641a73aca35a5d36db186f51100fc15e7bb65d4c | [
"Apache-2.0"
] | null | null | null | 39.726115 | 151 | 0.684784 | 10,508 |
package com.codemelinux.HUSAP.main.pickImageBase;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.codemelinux.HUSAP.Constants;
import com.codemelinux.HUSAP.R;
import com.codemelinux.HUSAP.main.base.BaseActivity;
import com.codemelinux.HUSAP.utils.GlideApp;
import com.codemelinux.HUSAP.utils.ImageUtil;
import com.codemelinux.HUSAP.utils.LogUtil;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
public abstract class PickImageActivity<V extends PickImageView, P extends PickImagePresenter<V>> extends BaseActivity<V, P> implements PickImageView {
private static final String SAVED_STATE_IMAGE_URI = "RegistrationActivity.SAVED_STATE_IMAGE_URI";
protected Uri imageUri;
protected abstract ProgressBar getProgressView();
protected abstract ImageView getImageView();
protected abstract void onImagePikedAction();
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(SAVED_STATE_IMAGE_URI, imageUri);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(SAVED_STATE_IMAGE_URI)) {
imageUri = savedInstanceState.getParcelable(SAVED_STATE_IMAGE_URI);
loadImageToImageView(imageUri);
}
}
super.onRestoreInstanceState(savedInstanceState);
}
@SuppressLint("NewApi")
public void onSelectImageClick(View view) {
if (CropImage.isExplicitCameraPermissionRequired(this)) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, CropImage.CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE);
} else {
CropImage.startPickImageActivity(this);
}
}
@Override
public void loadImageToImageView(Uri imageUri) {
if (imageUri == null) {
return;
}
this.imageUri = imageUri;
ImageUtil.loadLocalImage(GlideApp.with(this), imageUri, getImageView(), new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
getProgressView().setVisibility(View.GONE);
LogUtil.logDebug(TAG, "Glide Success Loading image from uri : " + imageUri.getPath());
return false;
}
});
}
@Override
@SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// handle result of pick image chooser
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri imageUri = CropImage.getPickImageResultUri(this, data);
if (presenter.isImageFileValid(imageUri)) {
this.imageUri = imageUri;
}
// For API >= 23 we need to check specifically that we have permissions to read external storage.
if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE);
} else {
// no permissions required or already grunted
onImagePikedAction();
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == CropImage.CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
LogUtil.logDebug(TAG, "CAMERA_CAPTURE_PERMISSIONS granted");
CropImage.startPickImageActivity(this);
} else {
showSnackBar(R.string.permissions_not_granted);
LogUtil.logDebug(TAG, "CAMERA_CAPTURE_PERMISSIONS not granted");
}
}
if (requestCode == CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE) {
if (imageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
LogUtil.logDebug(TAG, "PICK_IMAGE_PERMISSIONS granted");
onImagePikedAction();
} else {
showSnackBar(R.string.permissions_not_granted);
LogUtil.logDebug(TAG, "PICK_IMAGE_PERMISSIONS not granted");
}
}
}
protected void handleCropImageResult(int requestCode, int resultCode, Intent data) {
presenter.handleCropImageResult(requestCode, resultCode, data);
}
protected void startCropImageActivity() {
if (imageUri == null) {
return;
}
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setFixAspectRatio(true)
.setMinCropResultSize(Constants.Profile.MIN_AVATAR_SIZE, Constants.Profile.MIN_AVATAR_SIZE)
.setRequestedSize(Constants.Profile.MAX_AVATAR_SIZE, Constants.Profile.MAX_AVATAR_SIZE)
.start(this);
}
@Override
public void hideLocalProgress() {
getProgressView().setVisibility(View.GONE);
}
}
|
3e18b8fd096976a0634d8bd2dadea383d4ec1cc5 | 369 | java | Java | TLS-Core/src/main/java/de/rub/nds/tlsattacker/core/workflow/filter/FilterType.java | woniuxia/TLS-Attacker | 09dd837deb49f79158c99177c2f1ec6b7dcbc106 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2021-02-11T01:13:15.000Z | 2021-02-11T01:13:15.000Z | TLS-Core/src/main/java/de/rub/nds/tlsattacker/core/workflow/filter/FilterType.java | woniuxia/TLS-Attacker | 09dd837deb49f79158c99177c2f1ec6b7dcbc106 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | TLS-Core/src/main/java/de/rub/nds/tlsattacker/core/workflow/filter/FilterType.java | woniuxia/TLS-Attacker | 09dd837deb49f79158c99177c2f1ec6b7dcbc106 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 23.0625 | 68 | 0.734417 | 10,509 | /**
* TLS-Attacker - A Modular Penetration Testing Framework for TLS
*
* Copyright 2014-2020 Ruhr University Bochum, Paderborn University,
* and Hackmanit GmbH
*
* Licensed under Apache License 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*/
package de.rub.nds.tlsattacker.core.workflow.filter;
public enum FilterType {
DEFAULT,
DISCARD_RECORDS,
}
|
3e18b9935d094fdc06194a545f84903dada98108 | 1,035 | java | Java | mycateye-agent/src/main/java/io/mycat/eye/agent/mapper/MycatSqlSumMapper.java | karakapi/Mycat-Web | 4901c32658fffbaa4f542e27d369b5cff5283fd3 | [
"Apache-2.0"
] | 2 | 2020-06-04T05:14:13.000Z | 2020-11-25T05:54:05.000Z | mycateye-agent/src/main/java/io/mycat/eye/agent/mapper/MycatSqlSumMapper.java | karakapi/Mycat-Web | 4901c32658fffbaa4f542e27d369b5cff5283fd3 | [
"Apache-2.0"
] | null | null | null | mycateye-agent/src/main/java/io/mycat/eye/agent/mapper/MycatSqlSumMapper.java | karakapi/Mycat-Web | 4901c32658fffbaa4f542e27d369b5cff5283fd3 | [
"Apache-2.0"
] | null | null | null | 31.363636 | 116 | 0.795169 | 10,511 | package io.mycat.eye.agent.mapper;
import io.mycat.eye.agent.bean.MycatSqlSum;
import io.mycat.eye.agent.bean.MycatSqlSumExample;
import io.mycat.eye.agent.bean.MycatSqlSumKey;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface MycatSqlSumMapper {
long countByExample(MycatSqlSumExample example);
int deleteByExample(MycatSqlSumExample example);
int deleteByPrimaryKey(MycatSqlSumKey key);
int insert(MycatSqlSum record);
int insertSelective(MycatSqlSum record);
List<MycatSqlSum> selectByExample(MycatSqlSumExample example);
MycatSqlSum selectByPrimaryKey(MycatSqlSumKey key);
int updateByExampleSelective(@Param("record") MycatSqlSum record, @Param("example") MycatSqlSumExample example);
int updateByExample(@Param("record") MycatSqlSum record, @Param("example") MycatSqlSumExample example);
int updateByPrimaryKeySelective(MycatSqlSum record);
int updateByPrimaryKey(MycatSqlSum record);
} |
3e18b9bedb9511fa6268059e43772e226cdf720c | 3,368 | java | Java | src/com/m00ware/ftpindex/indexer/IndexerScheduler.java | gilles-duboscq/m00FTPIndex | 9e74d39f159f9113c0ab1a034db2146471da6bfe | [
"MIT"
] | 1 | 2020-01-24T05:16:29.000Z | 2020-01-24T05:16:29.000Z | src/com/m00ware/ftpindex/indexer/IndexerScheduler.java | gilles-duboscq/m00FTPIndex | 9e74d39f159f9113c0ab1a034db2146471da6bfe | [
"MIT"
] | null | null | null | src/com/m00ware/ftpindex/indexer/IndexerScheduler.java | gilles-duboscq/m00FTPIndex | 9e74d39f159f9113c0ab1a034db2146471da6bfe | [
"MIT"
] | null | null | null | 35.829787 | 203 | 0.610154 | 10,512 | package com.m00ware.ftpindex.indexer;
import java.net.SocketTimeoutException;
import java.util.*;
import java.util.concurrent.*;
import com.m00ware.ftpindex.*;
/**
* @author Wooden
*
*/
public class IndexerScheduler {
private FilesDB db;
private long indexingDelay;
private ScheduledExecutorService executorIndex;
private List<IndexerEventListener> listeners;
public IndexerScheduler(FilesDB db) {
this.db = db;
this.indexingDelay = TimeUnit.MINUTES.toSeconds(30);
this.executorIndex = Executors.newScheduledThreadPool(4);
this.db.registerEventListener(new DBListener());
this.listeners = new LinkedList<IndexerEventListener>();
Random rnd = new Random();
for (FTP ftp : this.db.getFTPs()) {
long initialDelay = this.indexingDelay + rnd.nextInt(120) * 30;
System.out.println("Scheduled Indexation for " + ftp.getAddress().getHostName() + ":" + ftp.getPort() + " in " + initialDelay + "s and periodicaly with " + indexingDelay + "s delay");
executorIndex.scheduleWithFixedDelay(new Indexer(ftp), initialDelay, this.indexingDelay, TimeUnit.SECONDS);
}
}
public void setIndexingDelay(long indexingDelay, TimeUnit unit) {
this.indexingDelay = unit.toSeconds(indexingDelay);
}
public void scheduleEarlyIndexing() {
Random rnd = new Random();
for (FTP ftp : this.db.getFTPs()) {
int delay = 8 + rnd.nextInt(30);
System.out.println("Scheduled Indexation for " + ftp.getAddress().getHostName() + ":" + ftp.getPort() + " in " + delay + "s");
executorIndex.schedule(new Indexer(ftp), delay, TimeUnit.SECONDS);
}
}
public void registerIndexerEventListener(IndexerEventListener iel) {
this.listeners.add(iel);
}
public void removeIndexerEventListener(IndexerEventListener iel) {
this.listeners.remove(iel);
}
private class DBListener extends DBEventListener {
@Override
public void newFtp(FTP ftp) {
System.out.println("Scheduled Indexation for " + ftp.getAddress().getHostName() + ":" + ftp.getPort() + " in 5s and periodicaly with " + indexingDelay + "s delay");
executorIndex.scheduleWithFixedDelay(new Indexer(ftp), 5, indexingDelay, TimeUnit.SECONDS);
}
}
private static class Indexer implements Runnable {
private FTP ftp;
public Indexer(FTP ftp) {
this.ftp = ftp;
}
@Override
public void run() {
if (!ftp.isUp() || ftp.isIndexingInProgress()) {
System.out.println("Can not start indexer for " + ftp.getAddress().getHostName() + ":" + 21 + " Status: " + (ftp.isUp() ? "Up" : "Down") + " Last indexed: " + ftp.getLastIndexedString());
return;
}
System.out.println("Starting indexer for " + ftp.getAddress().getHostName() + ":" + 21);
try {
IndexerRunnable ir = new IndexerRunnable(ftp);
ir.init();
ir.run();
} catch (SocketTimeoutException ste) {
ftp.setUp(false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void shutdownt() {
this.executorIndex.shutdownNow();
}
}
|
3e18b9da522b36d97b2ccda9ad527ff2196f114e | 1,664 | java | Java | test/algorithms/AlgorithmTest.java | HanzehogeschoolSICT/ITV1D-Louis-Sorting | fb0a9bddcbc57c8facda2532199f08e981a2ce58 | [
"MIT"
] | null | null | null | test/algorithms/AlgorithmTest.java | HanzehogeschoolSICT/ITV1D-Louis-Sorting | fb0a9bddcbc57c8facda2532199f08e981a2ce58 | [
"MIT"
] | null | null | null | test/algorithms/AlgorithmTest.java | HanzehogeschoolSICT/ITV1D-Louis-Sorting | fb0a9bddcbc57c8facda2532199f08e981a2ce58 | [
"MIT"
] | 2 | 2017-03-08T10:50:51.000Z | 2017-05-06T12:21:52.000Z | 29.714286 | 103 | 0.667067 | 10,513 | package algorithms;
import models.DataSetModel;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.*;
class AlgorithmTest {
/**
* Test the Bubble Sort Algorithm.
*/
@Test
void bubbleSortAlgorithmTest() {
algorithmTest(BubbleSortAlgorithm::new, 16);
}
/**
* Test the Insertion Sort Algorithm.
*/
@Test
void insertionSortAlgorithmTest() {
algorithmTest(InsertionSortAlgorithm::new, 15);
}
/**
* Test the Quick Sort Algorithm.
*/
@Test
void quickSortAlgorithmTest() {
algorithmTest(QuickSortAlgorithm::new, 13);
}
/**
* Test an algorithm using the given algorithm factory and the given expected number of steps.
*
* @param algorithmFactory Factory for the algorithm to test.
* @param expectedSteps Expected number of steps for the algorithm.
*/
private void algorithmTest(Function<DataSetModel, Algorithm> algorithmFactory, int expectedSteps) {
LinkedList<Integer> data = new LinkedList<>(Arrays.asList(4, 5, 6, 3, 1, 2));
DataSetModel dataSet = new DataSetModel(data);
int stepCount = 0;
Algorithm algorithm = algorithmFactory.apply(dataSet);
while (algorithm.nextStep())
stepCount++;
LinkedList<Integer> resultData = new LinkedList<>(Arrays.asList(1, 2, 3, 4, 5, 6));
assertEquals(data, resultData, "Set has not been sorted correctly");
assertEquals(stepCount, expectedSteps, "Sorting took invalid number of steps");
}
} |
3e18ba1b25c67ba3efba5befc25bb4c31b914f8d | 3,360 | java | Java | java/sho/largest-rectangle-in-histogram.java | jaredkoontz/lintcode | 228f3326381f6356d7be2f249d6b74bf394f844e | [
"MIT"
] | null | null | null | java/sho/largest-rectangle-in-histogram.java | jaredkoontz/lintcode | 228f3326381f6356d7be2f249d6b74bf394f844e | [
"MIT"
] | null | null | null | java/sho/largest-rectangle-in-histogram.java | jaredkoontz/lintcode | 228f3326381f6356d7be2f249d6b74bf394f844e | [
"MIT"
] | null | null | null | 28.235294 | 384 | 0.511607 | 10,514 | public class Solution {
/**
* @param height: A list of integer
* @return: The area of largest rectangle in the histogram
*/
// 9/18 cases passed, wrong solution.
public int largestRectangleArea2(int[] height) {
// write your code here
int len = height.length;
if (len == 0) {
return 0;
}
int maxArea = 0;
for (int i = 0; i < len; i++) {
for (int j = i; j < len; j++) {
int minHeight = Math.min(height[i], height[j]);
// ensure all elements between i, j are at most minHeight
if (!isUnderMin(height, i, j, minHeight)) {
continue;
}
maxArea = Math.max(maxArea, minHeight * (j - i + 1));
}
}
return maxArea;
}
public boolean isUnderMin(int[] h, int start, int end, int min) {
for (int i = start; i <= end; i++) {
if (h[i] < min || h[i] == 0) {
return false;
}
}
return true;
}
// Correct O(n2) solution, 12/18 cases passed, TLE.
public int largestRectangleArea3(int[] height) {
int len = height.length;
if (len == 0) {
return 0;
}
int maxArea = 0;
// expand to two sides.
for (int i = 0; i < len; i++) {
int min = height[i];
int right = i;
while (right + 1 < len && height[right + 1] >= min) {
right++;
}
int left = i;
while (left - 1 >= 0 && height[left - 1] >= min) {
left--;
}
maxArea = Math.max(maxArea, min * (right - left + 1));
}
return maxArea;
}
// Correct version. O(n) time.
// Idea: Iterate over elements, if stack is empty(initial state),
// just push the element onto stack, otherwise compare current
// element with top element on stack, if its increasing, push current element onto stack and increse runner index i, so that all indexes in the stack are increasing even though there could be gaps between them. If current element if decreasing from stack top element, we start to compute the area.
// The correctness for doing this:
// At some point when decreasing pattern found, we have runner index i, current element index is poped from the stack and we name it as 'current', there are three interested indexes: i, current, st.peek(). 'current' index represent the element which we are computing as the height, we want to expand the index to right(i - current) and left (current - st.peek()) to get the width.
public int largestRectangleArea(int[] height) {
Stack<Integer> stack = new Stack<Integer>();
int len = height.length;
if (len == 0) {
return 0;
}
int i = 0;
int maxArea = 0;
while (i <= len) {
int cur = i == len ? 0 : height[i];
if (stack.isEmpty() || height[stack.peek()] <= cur) {
stack.push(i++);
} else {
int t = stack.pop();
maxArea = Math.max(maxArea, height[t] * (
stack.isEmpty() ? i : i - stack.peek() - 1));
}
}
return maxArea;
}
}
|
3e18baa7e84c0167f8974a7c8c3723f60af6793e | 4,281 | java | Java | LearningTicTacToe-java/src/main/java/TicTacToe.java | poojakokane/assignmentCodes | 9b789c2b0f5a6196ed4c48b3c5b0d48402ceecec | [
"MIT"
] | null | null | null | LearningTicTacToe-java/src/main/java/TicTacToe.java | poojakokane/assignmentCodes | 9b789c2b0f5a6196ed4c48b3c5b0d48402ceecec | [
"MIT"
] | null | null | null | LearningTicTacToe-java/src/main/java/TicTacToe.java | poojakokane/assignmentCodes | 9b789c2b0f5a6196ed4c48b3c5b0d48402ceecec | [
"MIT"
] | null | null | null | 34.524194 | 135 | 0.502219 | 10,515 | /**
* Board/State representation for the game of Shift Tac Toe.
*
*/
public class TicTacToe {
// Consider adding some more instance variables to help represent the board.
// Although you do need to be able to represent the board as a String,
// it is probably a lot easier to do board operations (drop, shift, etc)
// if you have a different representation internally (e.g., arrays?)
// and then generate Strings from those.
// provide a short (~1 line) description of the role each variable have.
/**
* Play a game of Tic Tac Toe!
*
* @param p1 - Player 1
* @param p2 - Player 2
*/
public int play(Player p1, Player p2, int maxbadmoves, boolean quietly) {
Board board = new Board();
Board nextBoard;
Player currentPlayer = p1;
int badmoves = 0;
int cell;
// inform the player's about the board size, and what player they are
p1.startGame(Board.GRID_DIMENSION, 1, quietly);
p2.startGame(Board.GRID_DIMENSION, 2, quietly);
while( board.getWinner() == -1 ) {
// if we're not in quiet mode, print out the board and the player's name
if (!quietly) {
System.out.println(board.toString());
System.out.println(currentPlayer.getName() + "'s turn...");
}
// ask the current player for a turn, until they give a legal move
badmoves = 0;
do {
cell = currentPlayer.requestMove(board);
nextBoard = board.move(currentPlayer.getMarker(), cell);
} while (nextBoard == null && ++badmoves <= maxbadmoves);
board = nextBoard;
if (currentPlayer == p1) {
currentPlayer = p2;
}
else {
currentPlayer = p1;
}
// if the last player made too many illegal moves, they loose.
if (badmoves > maxbadmoves) {
p1.endGame(board, currentPlayer.getMarker());
p2.endGame(board, currentPlayer.getMarker());
if (!quietly) System.out.println("* Bad moves exceeded! Winner: " + currentPlayer.getName());
return currentPlayer.getMarker();
}
}
if (!quietly) {
switch (board.getWinner()) {
case 0:
System.out.println("* Winner: no one! (it's a tie!)");
break;
case 1:
System.out.println("* Winner: " + p1.getName());
break;
case 2:
System.out.println("* Winner: " + p2.getName());
break;
}
}
p1.endGame(board, board.getWinner());
p2.endGame(board, board.getWinner());
return board.getWinner();
}
public static void main(String[] args) {
Player a = new AI();
// Player a = new Player();
Player b = new Player();
TicTacToe stt = new TicTacToe();
Player winningPlayer;
int rounds = 100000; // to gather useful data for learning, try 1000 or 10000
int i = 1;
int reportInterval = 100;
int aWins = 0;
int bWins = 0;
boolean quiet = true;
boolean beQuietNow;
while (i <= rounds) {
beQuietNow = (i % reportInterval != 0) && quiet;
if (!beQuietNow)
System.out.println(" ----------------- Game (rounds)" + i + "/" + rounds + "-----------------");
int winner = stt.play(a, b, 20, quiet);
if (winner == 1) aWins++;
else if (winner == 2) bWins++;
if (!beQuietNow)
System.out.println(" -------------------------------------------------");
winner = stt.play(b, a, 20, quiet);
if (winner == 1) bWins ++;
else if (winner == 2) aWins++;
if (!beQuietNow)
System.out.println(i*2 + " games played: wins for (" + a.getName() + "," + b.getName() + ") = " + aWins + "," + bWins);
i++;
}
System.out.println(i*2 + " games played: wins for (" + a.getName() + "," + b.getName() + ") = " + aWins + "," + bWins);
}
}
|
3e18baf4cd4a0d9762e8d9d1d42fed93dea19c4a | 2,260 | java | Java | src/main/java/net/warvale/prison/items/substances/AbstractSubstance.java | Warvale/Locked | 10da666cbf59a11e2ffbd29bf40916ec9ce5541e | [
"Apache-2.0"
] | 3 | 2017-08-09T14:28:17.000Z | 2017-08-12T13:09:50.000Z | src/main/java/net/warvale/prison/items/substances/AbstractSubstance.java | Warvale/Locked | 10da666cbf59a11e2ffbd29bf40916ec9ce5541e | [
"Apache-2.0"
] | null | null | null | src/main/java/net/warvale/prison/items/substances/AbstractSubstance.java | Warvale/Locked | 10da666cbf59a11e2ffbd29bf40916ec9ce5541e | [
"Apache-2.0"
] | null | null | null | 27.901235 | 111 | 0.649558 | 10,516 | package net.warvale.prison.items.substances;
import net.warvale.prison.items.substances.substances.Blast;
import net.warvale.prison.items.substances.substances.Coco;
import net.warvale.prison.items.substances.substances.EnergyDrink;
import net.warvale.prison.items.substances.substances.Sugar;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.Collections;
/**
* Created By AAces on 8/6/17
*/
public abstract class AbstractSubstance {
private static ArrayList<AbstractSubstance> substances;
private String name;
private ItemStack item;
private int id;
public AbstractSubstance(int id, String name, Material mat, ChatColor nameColor) {
this.name = name;
this.id = id;
ItemStack i = new ItemStack(mat, 1);
ItemMeta meta = i.getItemMeta();
meta.setDisplayName(ChatColor.DARK_RED + "[Substance] " + nameColor + name);
meta.setLore(Collections.singletonList(ChatColor.BOLD.toString() + ChatColor.DARK_RED + "CONTRABAND"));
i.setItemMeta(meta);
this.item = i;
}
public static void setup() {
substances = new ArrayList<>();
substances.add(new Sugar());
substances.add(new Coco());
substances.add(new EnergyDrink());
substances.add(new Blast());
}
public static ArrayList<AbstractSubstance> getSubstances() {
return substances;
}
public static AbstractSubstance getSubstance(String name) {
for (AbstractSubstance drug : getSubstances()) {
if (drug.getName().equals(name)) {
return drug;
}
}
return null;
}
public static AbstractSubstance getSubstance(int id) {
for (AbstractSubstance drug : getSubstances()) {
if (drug.getId() == id) {
return drug;
}
}
return null;
}
public abstract void effect(Player player);
public String getName() {
return name;
}
public int getId() {
return id;
}
public ItemStack getItemStack() {
return item;
}
}
|
3e18bb764159c5b61a8af36b09818836628b4a7a | 966 | java | Java | raw_dataset/64594234@unite@OK.java | zthang/code2vec_treelstm | 0c5f98d280b506317738ba603b719cac6036896f | [
"MIT"
] | 1 | 2020-04-24T03:35:40.000Z | 2020-04-24T03:35:40.000Z | raw_dataset/64594234@unite@OK.java | ruanyuan115/code2vec_treelstm | 0c5f98d280b506317738ba603b719cac6036896f | [
"MIT"
] | 2 | 2020-04-23T21:14:28.000Z | 2021-01-21T01:07:18.000Z | raw_dataset/64594234@unite@OK.java | zthang/code2vec_treelstm | 0c5f98d280b506317738ba603b719cac6036896f | [
"MIT"
] | null | null | null | 46 | 110 | 0.611801 | 10,517 | void unite(int a, int b, long edge) {
a = get(a);
b = get(b);
if (rank[a] > rank[b]) {
parent[b] = a;
cost_of_comp[a] += edge + cost_of_comp[b] - max(min_cost_for_station[a].x, min_cost_for_station[b].x);
if (min_cost_for_station[a].x > min_cost_for_station[b].x)
min_cost_for_station[a] = min_cost_for_station[b];
} else if (rank[b] > rank[a]) {
parent[a] = b;
cost_of_comp[b] += edge + cost_of_comp[a] - max(min_cost_for_station[a].x, min_cost_for_station[b].x);
if (min_cost_for_station[b].x > min_cost_for_station[a].x)
min_cost_for_station[b] = min_cost_for_station[a];
} else {
parent[a] = b;
cost_of_comp[b] += edge + cost_of_comp[a] - max(min_cost_for_station[a].x, min_cost_for_station[b].x);
if (min_cost_for_station[b].x > min_cost_for_station[a].x)
min_cost_for_station[b] = min_cost_for_station[a];
rank[b]++;
}
} |
3e18bbb3f2828d3d4668da8758dace490abdfcf5 | 3,274 | java | Java | RxJavaAndRetrofitSimple/library/src/main/java/com/android/qzy/library/flycodialog/BaseAnimatorSet.java | zongyangqu/RxJavaAndRetrofitSimple | 33583ac979dfd13b78ef1caba90ff6ffc41fea30 | [
"Apache-2.0"
] | 1 | 2020-03-03T14:16:40.000Z | 2020-03-03T14:16:40.000Z | RxJavaAndRetrofitSimple/library/src/main/java/com/android/qzy/library/flycodialog/BaseAnimatorSet.java | zongyangqu/RxJavaAndRetrofitSimple | 33583ac979dfd13b78ef1caba90ff6ffc41fea30 | [
"Apache-2.0"
] | null | null | null | RxJavaAndRetrofitSimple/library/src/main/java/com/android/qzy/library/flycodialog/BaseAnimatorSet.java | zongyangqu/RxJavaAndRetrofitSimple | 33583ac979dfd13b78ef1caba90ff6ffc41fea30 | [
"Apache-2.0"
] | null | null | null | 27.057851 | 71 | 0.608125 | 10,518 | package com.android.qzy.library.flycodialog;
import android.view.View;
import android.view.animation.Interpolator;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.view.ViewHelper;
/**
* 作者:quzongyang
*
* 创建时间:2017/4/11
*
* 类描述:Dialog动画基类
*/
public abstract class BaseAnimatorSet {
/** 动画时长,系统默认250 */
protected long duration = 500;
protected AnimatorSet animatorSet = new AnimatorSet();
private Interpolator interpolator;
private long delay;
private AnimatorListener listener;
public abstract void setAnimation(View view);
protected void start(final View view) {
/** 设置动画中心点:pivotX--->X轴方向动画中心点,pivotY--->Y轴方向动画中心点 */
// ViewHelper.setPivotX(view, view.getMeasuredWidth() / 2.0f);
// ViewHelper.setPivotY(view, view.getMeasuredHeight() / 2.0f);
reset(view);
setAnimation(view);
animatorSet.setDuration(duration);
if (interpolator != null) {
animatorSet.setInterpolator(interpolator);
}
if (delay > 0) {
animatorSet.setStartDelay(delay);
}
if (listener != null) {
animatorSet.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
listener.onAnimationStart(animator);
}
@Override
public void onAnimationRepeat(Animator animator) {
listener.onAnimationRepeat(animator);
}
@Override
public void onAnimationEnd(Animator animator) {
listener.onAnimationEnd(animator);
}
@Override
public void onAnimationCancel(Animator animator) {
listener.onAnimationCancel(animator);
}
});
}
animatorSet.start();
}
public static void reset(View view) {
ViewHelper.setAlpha(view, 1);
ViewHelper.setScaleX(view, 1);
ViewHelper.setScaleY(view, 1);
ViewHelper.setTranslationX(view, 0);
ViewHelper.setTranslationY(view, 0);
ViewHelper.setRotation(view, 0);
ViewHelper.setRotationY(view, 0);
ViewHelper.setRotationX(view, 0);
}
/** 设置动画时长 */
public BaseAnimatorSet duration(long duration) {
this.duration = duration;
return this;
}
/** 设置动画时长 */
public BaseAnimatorSet delay(long delay) {
this.delay = delay;
return this;
}
/** 设置动画插补器 */
public BaseAnimatorSet interpolator(Interpolator interpolator) {
this.interpolator = interpolator;
return this;
}
/** 动画监听 */
public BaseAnimatorSet listener(AnimatorListener listener) {
this.listener = listener;
return this;
}
/** 在View上执行动画 */
public void playOn(View view) {
start(view);
}
public interface AnimatorListener {
void onAnimationStart(Animator animator);
void onAnimationRepeat(Animator animator);
void onAnimationEnd(Animator animator);
void onAnimationCancel(Animator animator);
}
}
|
3e18bbe2e82ce00b7ea56abe88c2b972766d62b2 | 3,286 | java | Java | web/src/main/java/gr/helix/lab/web/config/HttpClientConfiguration.java | HELIX-GR/lab | 5d481941098fe4851538e3428b4c932bf1506921 | [
"Apache-2.0"
] | null | null | null | web/src/main/java/gr/helix/lab/web/config/HttpClientConfiguration.java | HELIX-GR/lab | 5d481941098fe4851538e3428b4c932bf1506921 | [
"Apache-2.0"
] | 10 | 2018-12-07T14:32:30.000Z | 2022-03-08T23:03:27.000Z | web/src/main/java/gr/helix/lab/web/config/HttpClientConfiguration.java | HELIX-GR/lab | 5d481941098fe4851538e3428b4c932bf1506921 | [
"Apache-2.0"
] | null | null | null | 37.770115 | 117 | 0.695679 | 10,519 | package gr.helix.lab.web.config;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.net.ssl.SSLContext;
import org.apache.http.client.HttpClient;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
public class HttpClientConfiguration {
private static final Logger logger = LoggerFactory.getLogger(HttpClientConfiguration.class);
private PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;
@Value("${http-client.maxTotal}")
private int maxTotal;
@Value("${http-client.maxPerRoute}")
private int maxPerRoute;
@Value("${http-client.ingore-ssl-validation}")
private boolean ignoreCertificateValidation;
@PostConstruct
public void init() throws Exception {
// https://stackoverflow.com/questions/2703161/how-to-ignore-ssl-certificate-errors-in-apache-httpclient-4-0
try {
if(this.ignoreCertificateValidation) {
logger.warn("Using non-validating SSL HttpClient");
final SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (x509CertChain, authType) -> true)
.build();
this.poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
.build()
);
} else {
this.poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
}
this.poolingHttpClientConnectionManager.setMaxTotal(this.maxTotal);
this.poolingHttpClientConnectionManager.setDefaultMaxPerRoute(this.maxPerRoute);
} catch(final Exception ex) {
logger.error("Failed to create HttpClientConnectionManager", ex);
throw ex;
}
}
@PreDestroy
public void destroy() {
this.poolingHttpClientConnectionManager.shutdown();
}
@Bean
@Primary
public HttpClient defaultHttpClient() {
final HttpClientBuilder builder = HttpClients.custom();
return builder
.setConnectionManager(this.poolingHttpClientConnectionManager)
.build();
}
} |
3e18bc801d5eab15e7b18b027ce60110338458a0 | 1,467 | java | Java | src/main/java/br/ufjf/dcc082/Client/ErrorCounter.java | SouzaJBR/adptive-rtp | 95b79a1ab9908ce9b590d850bd739dcaf3e91781 | [
"MIT"
] | 7 | 2018-05-08T22:49:39.000Z | 2020-10-30T16:55:13.000Z | src/main/java/br/ufjf/dcc082/Client/ErrorCounter.java | SouzaJBR/adptive-rtp | 95b79a1ab9908ce9b590d850bd739dcaf3e91781 | [
"MIT"
] | 2 | 2017-12-07T19:37:31.000Z | 2017-12-09T15:19:59.000Z | src/main/java/br/ufjf/dcc082/Client/ErrorCounter.java | SouzaJBR/adptive-rtp | 95b79a1ab9908ce9b590d850bd739dcaf3e91781 | [
"MIT"
] | null | null | null | 24.864407 | 91 | 0.536469 | 10,520 | package br.ufjf.dcc082.Client;
public class ErrorCounter {
private Object key = new Object();
private volatile int errorCount = 0;
private int goodThreshold;
private int badThreshold;
private int goodCount;
private int badCount;
private int minToGood;
private int minToBad;
public ErrorCounter(int goodThreshold, int badThreshold, int minToGood, int minToBad) {
this.goodThreshold = goodThreshold;
this.badThreshold = badThreshold;
this.minToGood = minToGood;
this.minToBad = minToBad;
this.goodCount = 0;
this.badCount = 0;
}
public int checkThreshold()
{
synchronized (key) {
int currentErrorCount = this.errorCount;
System.out.println("Nos últimos 30s, " + currentErrorCount + " erros");
this.errorCount = 0;
if(currentErrorCount >= badThreshold) {
this.badCount++;
if(this.badCount >= this.minToBad) {
this.badCount = 0;
return -1;
}
}
if(currentErrorCount <= goodThreshold)
goodCount++;
if(this.goodCount >= this.minToGood) {
this.goodCount = 0;
return 1;
}
return 0;
}
}
public void addError() {
synchronized (key) {
errorCount++;
}
}
}
|
3e18bc930bc52704118db9891b479fad2127c4f4 | 1,090 | java | Java | app/src/main/java/com/finitebits/boilerPlate/Repository/Model/SampleModelGroup.java | Olunuga/AndroidProjectBoilerPlate | 635887d62782d69829a08669e37d77020a6d55c8 | [
"MIT"
] | null | null | null | app/src/main/java/com/finitebits/boilerPlate/Repository/Model/SampleModelGroup.java | Olunuga/AndroidProjectBoilerPlate | 635887d62782d69829a08669e37d77020a6d55c8 | [
"MIT"
] | null | null | null | app/src/main/java/com/finitebits/boilerPlate/Repository/Model/SampleModelGroup.java | Olunuga/AndroidProjectBoilerPlate | 635887d62782d69829a08669e37d77020a6d55c8 | [
"MIT"
] | null | null | null | 20.961538 | 94 | 0.66789 | 10,521 | package com.finitebits.boilerPlate.Repository.Model;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by myorh on 06/09/2018.
*/
public class SampleModelGroup {
private String name;
private String seemMore;
@SerializedName("data")
private List<SampleModel> sampleModelList;
public SampleModelGroup() {
}
public SampleModelGroup(String name, String seemMore, List<SampleModel> sampleModelList) {
this.name = name;
this.seemMore = seemMore;
this.sampleModelList = sampleModelList;
}
public String getName() {
return name;
}
public String getSeemMore() {
return seemMore;
}
public List<SampleModel> getSampleModelList() {
return sampleModelList;
}
public void setName(String name) {
this.name = name;
}
public void setSeemMore(String seemMore) {
this.seemMore = seemMore;
}
public void setSampleModelList(List<SampleModel> sampleModelList) {
this.sampleModelList = sampleModelList;
}
}
|
3e18bd2ff5fca0876ecb38b3b086f479a04d2646 | 2,291 | java | Java | FacturaNet_Negocio/src/co/edu/uco/facturanet/negocio/ensamblador/implementacion/CiudadEnsamblador.java | DanielAristy/Transplus | 70773092d503e91360df216cf81d3a81871ade89 | [
"Apache-2.0"
] | null | null | null | FacturaNet_Negocio/src/co/edu/uco/facturanet/negocio/ensamblador/implementacion/CiudadEnsamblador.java | DanielAristy/Transplus | 70773092d503e91360df216cf81d3a81871ade89 | [
"Apache-2.0"
] | 8 | 2020-07-17T02:10:35.000Z | 2022-03-02T04:06:45.000Z | FacturaNet_Negocio/src/co/edu/uco/facturanet/negocio/ensamblador/implementacion/CiudadEnsamblador.java | DanielAristy/Transplus | 70773092d503e91360df216cf81d3a81871ade89 | [
"Apache-2.0"
] | null | null | null | 33.202899 | 126 | 0.78481 | 10,522 | package co.edu.uco.facturanet.negocio.ensamblador.implementacion;
import co.edu.uco.facturanet.dominio.CiudadDominio;
import static co.edu.uco.facturanet.negocio.ensamblador.implementacion.DepartamentoEnsamblador.obtenerDepartamentoEnsamblador;
import java.util.List;
import co.edu.uco.facturanet.dominio.DepartamentoDominio;
import co.edu.uco.facturanet.dominio.PaisDominio;
import co.edu.uco.facturanet.dto.CiudadDTO;
import co.edu.uco.facturanet.dto.DepartamentoDTO;
import co.edu.uco.facturanet.dto.PaisDTO;
import co.edu.uco.facturanet.negocio.ensamblador.IEnsamblador;
import co.edu.uco.facturanet.transversal.enumeracion.CapaEnum;
import co.edu.uco.facturanet.transversal.excepcion.FacturanetException;
public class CiudadEnsamblador implements IEnsamblador<CiudadDTO, CiudadDominio> {
private static final IEnsamblador<CiudadDTO, CiudadDominio>
INSTANCIA = new CiudadEnsamblador();
private CiudadEnsamblador() {
super();
}
public static IEnsamblador<CiudadDTO, CiudadDominio> obtenerCiudadEnsamblador() {
return INSTANCIA;
}
@Override
public CiudadDTO ensamblarDTO(CiudadDominio dominio) {
if (dominio == null) {
throw FacturanetException.CREAR("Para ensamblar un objeto de transferencia de datos de Ciuadad el objeto"
+ " de dominio de datos no puede ser nulo", CapaEnum.NEGOCIO);
}
DepartamentoDTO departamento = obtenerDepartamentoEnsamblador().ensamblarDTO(dominio.getDepartamento());
return new CiudadDTO(dominio.getCodigo(),
dominio.getNombre(),
departamento);
}
@Override
public CiudadDominio ensamblarDominio(CiudadDTO dto) {
if (dto == null) {
throw FacturanetException.CREAR("Para ensamblar un objeto de dominio de Ciudad el objeto"
+ " de transferencia de datos no puede ser nulo", CapaEnum.NEGOCIO);
}
DepartamentoDominio departamento = obtenerDepartamentoEnsamblador().ensamblarDominio(dto.getDepartamento());
return new CiudadDominio(dto.getCodigo(),
dto.getNombre(),
departamento);
}
@Override
public List<CiudadDominio> ensamblarListaDominios(List<CiudadDTO> listaDTOs) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<CiudadDTO> ensamblarListaDTOs(List<CiudadDominio> listaDominios) {
// TODO Auto-generated method stub
return null;
}
}
|
3e18bd53c3821092e02cbc96bbed0c8030b5e440 | 4,363 | java | Java | common/src/main/java/io/netty/util/ConstantPool.java | mh47838704/netty | 70b2e05c692fe7c1e5a4b70787658275e982a3de | [
"Apache-2.0"
] | 4 | 2018-03-03T03:09:01.000Z | 2020-03-26T10:58:31.000Z | common/src/main/java/io/netty/util/ConstantPool.java | mh47838704/netty | 70b2e05c692fe7c1e5a4b70787658275e982a3de | [
"Apache-2.0"
] | null | null | null | common/src/main/java/io/netty/util/ConstantPool.java | mh47838704/netty | 70b2e05c692fe7c1e5a4b70787658275e982a3de | [
"Apache-2.0"
] | 3 | 2018-05-31T03:42:00.000Z | 2020-06-01T15:04:03.000Z | 31.846715 | 114 | 0.643135 | 10,523 | /*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.util;
import io.netty.util.internal.ObjectUtil;
import io.netty.util.internal.PlatformDependent;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A pool of {@link Constant}s.
* 常量池:key是字符串,value泛型
*
* @param <T> the type of the constant
*/
public abstract class ConstantPool<T extends Constant<T>> {
/** Key:String表示常量的名字,value:泛型结果 */
private final ConcurrentMap<String, T> constants = PlatformDependent.newConcurrentHashMap();
/** 常量对象的唯一标识符 */
private final AtomicInteger nextId = new AtomicInteger(1);
/**
* Shortcut of {@link #valueOf(String) valueOf(firstNameComponent.getName() + "#" + secondNameComponent)}.
*/
public T valueOf(Class<?> firstNameComponent, String secondNameComponent) {
if (firstNameComponent == null) {
throw new NullPointerException("firstNameComponent");
}
if (secondNameComponent == null) {
throw new NullPointerException("secondNameComponent");
}
return valueOf(firstNameComponent.getName() + '#' + secondNameComponent);
}
/**
* Returns the {@link Constant} which is assigned to the specified {@code name}.
* If there's no such {@link Constant}, a new one will be created and returned.
* Once created, the subsequent calls with the same {@code name} will always return the previously created one
* (i.e. singleton.)
*
* @param name the name of the {@link Constant}
*/
public T valueOf(String name) {
checkNotNullAndNotEmpty(name);
return getOrCreate(name);
}
/**
* Get existing constant by name or creates new one if not exists. Threadsafe
* 生成或者返回常量名字对于得常量对象
*
* @param name the name of the {@link Constant}
*/
private T getOrCreate(String name) {
T constant = constants.get(name);
if (constant == null) {
final T tempConstant = newConstant(nextId(), name);
constant = constants.putIfAbsent(name, tempConstant);
if (constant == null) {
return tempConstant;
}
}
return constant;
}
/**
* Returns {@code true} if a {@link AttributeKey} exists for the given {@code name}.
*/
public boolean exists(String name) {
checkNotNullAndNotEmpty(name);
return constants.containsKey(name);
}
/**
* Creates a new {@link Constant} for the given {@code name} or fail with an
* {@link IllegalArgumentException} if a {@link Constant} for the given {@code name} exists.
*/
public T newInstance(String name) {
checkNotNullAndNotEmpty(name);
return createOrThrow(name);
}
/**
* Creates constant by name or throws exception. Threadsafe
*
* @param name the name of the {@link Constant}
*/
private T createOrThrow(String name) {
T constant = constants.get(name);
if (constant == null) {
final T tempConstant = newConstant(nextId(), name);
constant = constants.putIfAbsent(name, tempConstant);
if (constant == null) {
return tempConstant;
}
}
throw new IllegalArgumentException(String.format("'%s' is already in use", name));
}
private static String checkNotNullAndNotEmpty(String name) {
ObjectUtil.checkNotNull(name, "name");
if (name.isEmpty()) {
throw new IllegalArgumentException("empty name");
}
return name;
}
protected abstract T newConstant(int id, String name);
@Deprecated
public final int nextId() {
return nextId.getAndIncrement();
}
}
|
3e18bd61a950fce3d4efc672e2e48fa2d4e63dab | 483 | java | Java | src/main/java/com/mcjty/mytutorial/setup/ServerProxy.java | kmcnaught/YouTubeModding14 | d6771070983a530a4dc4e0c9ba3dd13c2c355e0c | [
"MIT"
] | null | null | null | src/main/java/com/mcjty/mytutorial/setup/ServerProxy.java | kmcnaught/YouTubeModding14 | d6771070983a530a4dc4e0c9ba3dd13c2c355e0c | [
"MIT"
] | null | null | null | src/main/java/com/mcjty/mytutorial/setup/ServerProxy.java | kmcnaught/YouTubeModding14 | d6771070983a530a4dc4e0c9ba3dd13c2c355e0c | [
"MIT"
] | null | null | null | 21 | 72 | 0.695652 | 10,524 | package com.mcjty.mytutorial.setup;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.world.World;
public class ServerProxy implements IProxy {
@Override
public void init() {
}
@Override
public World getClientWorld() {
throw new IllegalStateException("Only run this on the client!");
}
@Override
public PlayerEntity getClientPlayer() {
throw new IllegalStateException("Only run this on the client!");
}
}
|
3e18bde92c48d22131d367b5fb68f7a9da31bded | 350 | java | Java | android/upstream/javax/sip/header/ErrorInfoHeader.java | gordonjohnpatrick/XobotOS | 888ed3b8cc8d8e0a54b1858bfa5a3572545f4d2f | [
"Apache-2.0"
] | 263 | 2015-01-04T16:39:18.000Z | 2022-01-05T17:52:38.000Z | android/upstream/javax/sip/header/ErrorInfoHeader.java | mcanthony/XobotOS | f20db6295e878a2f298c5e3896528e240785805b | [
"Apache-2.0"
] | 3 | 2015-09-06T09:06:39.000Z | 2019-10-15T00:52:49.000Z | android/upstream/javax/sip/header/ErrorInfoHeader.java | mcanthony/XobotOS | f20db6295e878a2f298c5e3896528e240785805b | [
"Apache-2.0"
] | 105 | 2015-01-11T11:45:12.000Z | 2022-02-22T07:26:36.000Z | 23.333333 | 68 | 0.76 | 10,525 | package javax.sip.header;
import java.text.ParseException;
import javax.sip.address.URI;
public interface ErrorInfoHeader extends Header, Parameters {
String NAME = "Error-Info";
URI getErrorInfo();
void setErrorInfo(URI errorInfo);
String getErrorMessage();
void setErrorMessage(String errorMessage) throws ParseException;
}
|
3e18c04f3186808884df34071f1047d92b9e61d8 | 2,021 | java | Java | clean-architecture-example/application/io/src/main/java/com/mageddo/bank/moneytransference/io/cli/MoneyTransferenceCli.java | mageddo/java-examples | 666cd8a1b822e3102bb3edcc952b0862ec3b2cfd | [
"Apache-2.0"
] | 19 | 2019-02-14T21:22:49.000Z | 2022-02-23T20:25:36.000Z | clean-architecture-example/application/io/src/main/java/com/mageddo/bank/moneytransference/io/cli/MoneyTransferenceCli.java | mageddo/java-examples | 666cd8a1b822e3102bb3edcc952b0862ec3b2cfd | [
"Apache-2.0"
] | 4 | 2021-03-11T06:40:41.000Z | 2022-02-27T10:54:28.000Z | clean-architecture-example/application/io/src/main/java/com/mageddo/bank/moneytransference/io/cli/MoneyTransferenceCli.java | mageddo/java-examples | 666cd8a1b822e3102bb3edcc952b0862ec3b2cfd | [
"Apache-2.0"
] | 10 | 2019-09-05T04:44:15.000Z | 2022-02-02T04:51:03.000Z | 32.596774 | 98 | 0.787729 | 10,526 | package com.mageddo.bank.moneytransference.io.cli;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.mageddo.bank.moneytransference.entity.Account;
import com.mageddo.bank.moneytransference.entity.Transference;
import com.mageddo.bank.moneytransference.service.TransferenceMakerService;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import java.math.BigDecimal;
import java.util.Scanner;
@Configuration
@RequiredArgsConstructor
public class MoneyTransferenceCli implements CommandLineRunner {
private final TransferenceMakerService transferenceMakerService;
private final JdbcTemplate jdbcTemplate;
@Override
public void run(String... args) throws Exception {
final var scanner = new Scanner(System.in);
final var transferenceBuilder = Transference.builder();
System.out.println("what's the transference amount ?");
transferenceBuilder.amount(new BigDecimal(scanner.nextLine()));
System.out.println("who's the debtor?");
transferenceBuilder.debtor(
Account
.builder()
.code(scanner.nextLine())
.build()
);
System.out.println("who's the creditor?");
transferenceBuilder.creditor(
Account
.builder()
.code(scanner.nextLine())
.build()
);
System.out.println("who's the description?");
transferenceBuilder.description(scanner.nextLine());
transferenceMakerService.doTransfer(transferenceBuilder.build());
final var om = new ObjectMapper()
.enable(SerializationFeature.INDENT_OUTPUT)
.disable(SerializationFeature.CLOSE_CLOSEABLE)
;
// don't do that, don't access the database directly, I'm using just for debug
System.out.println(om.writeValueAsString(jdbcTemplate.queryForList("SELECT * FROM ACCOUNT")));
System.out.println(om.writeValueAsString(jdbcTemplate.queryForList("SELECT * FROM STATEMENT")));
}
}
|
3e18c12e45ed1ff5f6f21e385afac6bb48300259 | 302 | java | Java | objects/src/main/java/org/cthul/objects/instance/Instance.java | derari/cthul | 7d1208e633840a0a23b4ccc090f10e89736a5a14 | [
"MIT"
] | 7 | 2015-02-22T08:05:56.000Z | 2019-06-15T01:03:36.000Z | objects/src/main/java/org/cthul/objects/instance/Instance.java | derari/cthul | 7d1208e633840a0a23b4ccc090f10e89736a5a14 | [
"MIT"
] | null | null | null | objects/src/main/java/org/cthul/objects/instance/Instance.java | derari/cthul | 7d1208e633840a0a23b4ccc090f10e89736a5a14 | [
"MIT"
] | 1 | 2019-01-08T01:46:44.000Z | 2019-01-08T01:46:44.000Z | 20.133333 | 44 | 0.718543 | 10,527 | package org.cthul.objects.instance;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Instance {
String key() default "";
Class<?> impl() default void.class;
String factory() default "";
}
|
3e18c20a9ad848fa6e179f6d4a7de6e99c555631 | 543 | java | Java | config-manager/config-mapper/src/main/java/com/amos/dao/HardwareCategoryMapper.java | amos-chen/ConfigSystem | 58dd4b1538e4e65f676c9aae2cfb8ef07ddf25ee | [
"Apache-2.0"
] | 1 | 2019-10-13T06:27:32.000Z | 2019-10-13T06:27:32.000Z | config-manager/config-mapper/src/main/java/com/amos/dao/HardwareCategoryMapper.java | amos-chen/ConfigSystem | 58dd4b1538e4e65f676c9aae2cfb8ef07ddf25ee | [
"Apache-2.0"
] | 2 | 2021-01-20T21:58:33.000Z | 2021-12-09T19:47:46.000Z | config-manager/config-mapper/src/main/java/com/amos/dao/HardwareCategoryMapper.java | amos-chen/ConfigSystem | 58dd4b1538e4e65f676c9aae2cfb8ef07ddf25ee | [
"Apache-2.0"
] | null | null | null | 20.884615 | 62 | 0.764273 | 10,528 | package com.amos.dao;
import com.amos.pojo.HardwareCategory;
import java.util.List;
/**
* Created by ${chenlunwei} on 2018/4/11.
*/
public interface HardwareCategoryMapper {
int insertCategory(HardwareCategory hardwareCategory);
HardwareCategory selectByPrimaryKey(Integer id);
int updateByPrimaryKey(HardwareCategory hardwareCategory);
int deleteByPrimaryKey(Integer id);
List<HardwareCategory> selectList();
List<HardwareCategory> queryByParentId(Integer parentId);
String queryCatName(Integer id);
}
|
3e18c2a80d18ba53320e16562114d15963ad9551 | 12,325 | java | Java | xio-core/src/main/java/com/xjeffrose/xio/config/thrift/IpRule.java | manimaul/xio | cd3e24fa61f0d4bd2a3582077071ea9f0218a5fe | [
"Apache-2.0"
] | 40 | 2016-08-18T21:09:50.000Z | 2022-01-26T11:38:19.000Z | xio-core/src/main/java/com/xjeffrose/xio/config/thrift/IpRule.java | manimaul/xio | cd3e24fa61f0d4bd2a3582077071ea9f0218a5fe | [
"Apache-2.0"
] | 78 | 2015-01-27T05:45:46.000Z | 2021-03-31T18:47:13.000Z | xio-core/src/main/java/com/xjeffrose/xio/config/thrift/IpRule.java | manimaul/xio | cd3e24fa61f0d4bd2a3582077071ea9f0218a5fe | [
"Apache-2.0"
] | 29 | 2015-10-09T16:52:37.000Z | 2019-04-10T01:07:44.000Z | 29.842615 | 100 | 0.671481 | 10,529 | /**
* Autogenerated by Thrift Compiler (0.9.3)
*
* <p>DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
*
* @generated
*/
package com.xjeffrose.xio.config.thrift;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.server.AbstractNonblockingServer.*;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)", date = "2016-08-23")
public class IpRule
implements org.apache.thrift.TBase<IpRule, IpRule._Fields>,
java.io.Serializable,
Cloneable,
Comparable<IpRule> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC =
new org.apache.thrift.protocol.TStruct("IpRule");
private static final org.apache.thrift.protocol.TField IP_ADDRESS_FIELD_DESC =
new org.apache.thrift.protocol.TField(
"ipAddress", org.apache.thrift.protocol.TType.STRING, (short) 1);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes =
new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new IpRuleStandardSchemeFactory());
schemes.put(TupleScheme.class, new IpRuleTupleSchemeFactory());
}
public ByteBuffer ipAddress; // required
/**
* The set of fields this struct contains, along with convenience methods for finding and
* manipulating them.
*/
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
IP_ADDRESS((short) 1, "ipAddress");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/** Find the _Fields constant that matches fieldId, or null if its not found. */
public static _Fields findByThriftId(int fieldId) {
switch (fieldId) {
case 1: // IP_ADDRESS
return IP_ADDRESS;
default:
return null;
}
}
/** Find the _Fields constant that matches fieldId, throwing an exception if it is not found. */
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null)
throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/** Find the _Fields constant that matches name, or null if its not found. */
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap =
new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(
_Fields.IP_ADDRESS,
new org.apache.thrift.meta_data.FieldMetaData(
"ipAddress",
org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(
org.apache.thrift.protocol.TType.STRING, true)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(IpRule.class, metaDataMap);
}
public IpRule() {}
public IpRule(ByteBuffer ipAddress) {
this();
this.ipAddress = org.apache.thrift.TBaseHelper.copyBinary(ipAddress);
}
/** Performs a deep copy on <i>other</i>. */
public IpRule(IpRule other) {
if (other.isSetIpAddress()) {
this.ipAddress = org.apache.thrift.TBaseHelper.copyBinary(other.ipAddress);
}
}
public IpRule deepCopy() {
return new IpRule(this);
}
@Override
public void clear() {
this.ipAddress = null;
}
public byte[] getIpAddress() {
setIpAddress(org.apache.thrift.TBaseHelper.rightSize(ipAddress));
return ipAddress == null ? null : ipAddress.array();
}
public ByteBuffer bufferForIpAddress() {
return org.apache.thrift.TBaseHelper.copyBinary(ipAddress);
}
public IpRule setIpAddress(byte[] ipAddress) {
this.ipAddress =
ipAddress == null
? (ByteBuffer) null
: ByteBuffer.wrap(Arrays.copyOf(ipAddress, ipAddress.length));
return this;
}
public IpRule setIpAddress(ByteBuffer ipAddress) {
this.ipAddress = org.apache.thrift.TBaseHelper.copyBinary(ipAddress);
return this;
}
public void unsetIpAddress() {
this.ipAddress = null;
}
/** Returns true if field ipAddress is set (has been assigned a value) and false otherwise */
public boolean isSetIpAddress() {
return this.ipAddress != null;
}
public void setIpAddressIsSet(boolean value) {
if (!value) {
this.ipAddress = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case IP_ADDRESS:
if (value == null) {
unsetIpAddress();
} else {
setIpAddress((ByteBuffer) value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case IP_ADDRESS:
return getIpAddress();
}
throw new IllegalStateException();
}
/**
* Returns true if field corresponding to fieldID is set (has been assigned a value) and false
* otherwise
*/
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case IP_ADDRESS:
return isSetIpAddress();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null) return false;
if (that instanceof IpRule) return this.equals((IpRule) that);
return false;
}
public boolean equals(IpRule that) {
if (that == null) return false;
boolean this_present_ipAddress = true && this.isSetIpAddress();
boolean that_present_ipAddress = true && that.isSetIpAddress();
if (this_present_ipAddress || that_present_ipAddress) {
if (!(this_present_ipAddress && that_present_ipAddress)) return false;
if (!this.ipAddress.equals(that.ipAddress)) return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_ipAddress = true && (isSetIpAddress());
list.add(present_ipAddress);
if (present_ipAddress) list.add(ipAddress);
return list.hashCode();
}
@Override
public int compareTo(IpRule other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetIpAddress()).compareTo(other.isSetIpAddress());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetIpAddress()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ipAddress, other.ipAddress);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot)
throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("IpRule(");
boolean first = true;
sb.append("ipAddress:");
if (this.ipAddress == null) {
sb.append("null");
} else {
org.apache.thrift.TBaseHelper.toString(this.ipAddress, sb);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(
new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in)
throws java.io.IOException, ClassNotFoundException {
try {
read(
new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class IpRuleStandardSchemeFactory implements SchemeFactory {
public IpRuleStandardScheme getScheme() {
return new IpRuleStandardScheme();
}
}
private static class IpRuleStandardScheme extends StandardScheme<IpRule> {
public void read(org.apache.thrift.protocol.TProtocol iprot, IpRule struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true) {
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // IP_ADDRESS
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.ipAddress = iprot.readBinary();
struct.setIpAddressIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, IpRule struct)
throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.ipAddress != null) {
oprot.writeFieldBegin(IP_ADDRESS_FIELD_DESC);
oprot.writeBinary(struct.ipAddress);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class IpRuleTupleSchemeFactory implements SchemeFactory {
public IpRuleTupleScheme getScheme() {
return new IpRuleTupleScheme();
}
}
private static class IpRuleTupleScheme extends TupleScheme<IpRule> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, IpRule struct)
throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetIpAddress()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetIpAddress()) {
oprot.writeBinary(struct.ipAddress);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, IpRule struct)
throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
struct.ipAddress = iprot.readBinary();
struct.setIpAddressIsSet(true);
}
}
}
}
|
3e18c314224b4f9493fd5138993010f205013557 | 1,249 | java | Java | src/main/java/ru/job4j/accident/model/AccidentType.java | IvanPJF/job4j_car_accident | 0d4484a3f5d1d7b1bbe241a8851aa2050a34ba29 | [
"Apache-2.0"
] | null | null | null | src/main/java/ru/job4j/accident/model/AccidentType.java | IvanPJF/job4j_car_accident | 0d4484a3f5d1d7b1bbe241a8851aa2050a34ba29 | [
"Apache-2.0"
] | 1 | 2022-02-16T01:13:11.000Z | 2022-02-16T01:13:11.000Z | src/main/java/ru/job4j/accident/model/AccidentType.java | IvanPJF/job4j_car_accident | 0d4484a3f5d1d7b1bbe241a8851aa2050a34ba29 | [
"Apache-2.0"
] | null | null | null | 18.924242 | 56 | 0.549239 | 10,530 | package ru.job4j.accident.model;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "accident_type")
public class AccidentType {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
public AccidentType(int id, String name) {
this.id = id;
this.name = name;
}
public AccidentType() {
}
public static AccidentType of(int id, String name) {
AccidentType type = new AccidentType();
type.id = id;
type.name = name;
return type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AccidentType type = (AccidentType) o;
return id == type.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
|
3e18c4777311ec27cf947c964e1b56f091268cf6 | 1,711 | java | Java | worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BiomeRegistry.java | LaudateCorpus1/WorldEdit | de6fa17b01c08161aacd8ef3c7ee05fe0f7f77d5 | [
"BSD-3-Clause"
] | 1,428 | 2019-01-02T21:08:08.000Z | 2022-03-30T20:23:10.000Z | worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BiomeRegistry.java | LaudateCorpus1/WorldEdit | de6fa17b01c08161aacd8ef3c7ee05fe0f7f77d5 | [
"BSD-3-Clause"
] | 884 | 2019-01-21T22:45:13.000Z | 2022-03-28T16:21:00.000Z | worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BiomeRegistry.java | LaudateCorpus1/WorldEdit | de6fa17b01c08161aacd8ef3c7ee05fe0f7f77d5 | [
"BSD-3-Clause"
] | 453 | 2015-01-10T02:27:18.000Z | 2018-12-29T18:35:16.000Z | 31.685185 | 73 | 0.714787 | 10,531 | /*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.world.registry;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.world.biome.BiomeData;
import com.sk89q.worldedit.world.biome.BiomeType;
import javax.annotation.Nullable;
/**
* Provides information on biomes.
*/
public interface BiomeRegistry {
/**
* Get the name of the biome, usually as a translatable component.
*
* @param biomeType the biome type
* @return the name of the biome
*/
Component getRichName(BiomeType biomeType);
/**
* Get data about a biome.
*
* @param biome the biome
* @return a data object or null if information is not known
* @deprecated This method no longer returns any useful information.
* Use {@link #getRichName(BiomeType)} for the name of the biome.
*/
@Deprecated
@Nullable
BiomeData getData(BiomeType biome);
}
|
3e18c52517ae15a6be7ac8b3b5a2bbffa93844d8 | 3,236 | java | Java | enhanced/java/classlib/modules/awt/src/test/impl/boot/java/awt/geom/QuadCurve2DDoubleTest.java | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | 5 | 2017-03-08T20:32:39.000Z | 2021-07-10T10:12:38.000Z | enhanced/java/classlib/modules/awt/src/test/impl/boot/java/awt/geom/QuadCurve2DDoubleTest.java | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | 1 | 2021-10-17T13:03:49.000Z | 2021-10-17T13:03:49.000Z | enhanced/java/classlib/modules/awt/src/test/impl/boot/java/awt/geom/QuadCurve2DDoubleTest.java | qinFamily/freeVM | 9caa0256b4089d74186f84b8fb2afc95a0afc7bc | [
"Apache-2.0"
] | 4 | 2015-07-07T07:06:59.000Z | 2018-06-19T22:38:04.000Z | 28.892857 | 94 | 0.589926 | 10,532 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Denis M. Kishenko
*/
package java.awt.geom;
public class QuadCurve2DDoubleTest extends GeomTestCase {
QuadCurve2D.Double q;
public QuadCurve2DDoubleTest(String name) {
super(name);
}
@Override
protected void setUp() throws Exception {
super.setUp();
q = new QuadCurve2D.Double(1, 2, 3, 4, 5, 6);
}
@Override
protected void tearDown() throws Exception {
q = null;
super.tearDown();
}
public void testCreate() {
assertEquals(new QuadCurve2D.Double(), new QuadCurve2D.Double(0, 0, 0, 0, 0, 0), 0.0);
}
public void testGetX1() {
assertEquals(1.0, q.getX1(), 0.0);
}
public void testGetY1() {
assertEquals(2.0, q.getY1(), 0.0);
}
public void testGetCtrlX() {
assertEquals(3.0, q.getCtrlX(), 0.0);
}
public void testGetCtrlY() {
assertEquals(4.0, q.getCtrlY(), 0.0);
}
public void testGetX2() {
assertEquals(5.0, q.getX2(), 0.0);
}
public void testGetY2() {
assertEquals(6.0, q.getY2(), 0.0);
}
public void testGetP1() {
assertEquals(new Point2D.Double(1, 2), q.getP1());
}
public void testGetCtrlPt() {
assertEquals(new Point2D.Double(3, 4), q.getCtrlPt());
}
public void testGetP2() {
assertEquals(new Point2D.Double(5, 6), q.getP2());
}
public void testSetCurve1() {
q.setCurve(7.0, 8.0, 9.0, 10.0, 11.0, 12.0);
assertEquals(new QuadCurve2D.Double(7, 8, 9, 10, 11, 12), q, 0.0);
}
public void testSetCurve2() {
q.setCurve(7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f);
assertEquals(new QuadCurve2D.Double(7, 8, 9, 10, 11, 12), q, 0.0);
}
public void testGetBounds2D() {
for (double[][] element : QuadCurve2DTest.bounds) {
QuadCurve2D curve = new QuadCurve2D.Double();
curve.setCurve(element[0], 0);
assertEquals(
quadToStr(curve),
new Rectangle2D.Double(
(int)element[1][0],
(int)element[1][1],
(int)element[1][2],
(int)element[1][3]),
curve.getBounds2D());
}
}
public static void main(String[] args) {
junit.textui.TestRunner.run(QuadCurve2DDoubleTest.class);
}
}
|
3e18c544d79b4d198b51b1d35c503d6833c42afd | 11,118 | java | Java | mock-infrastructure/src/generated/com/sequenceiq/mock/swagger/model/ApiActivity.java | drorke/cloudbreak | 8a1d4749fe9d1d683f5bec3102e8b86f59928f67 | [
"Apache-2.0"
] | 174 | 2017-07-14T03:20:42.000Z | 2022-03-25T05:03:18.000Z | mock-infrastructure/src/generated/com/sequenceiq/mock/swagger/model/ApiActivity.java | drorke/cloudbreak | 8a1d4749fe9d1d683f5bec3102e8b86f59928f67 | [
"Apache-2.0"
] | 2,242 | 2017-07-12T05:52:01.000Z | 2022-03-31T15:50:08.000Z | mock-infrastructure/src/generated/com/sequenceiq/mock/swagger/model/ApiActivity.java | drorke/cloudbreak | 8a1d4749fe9d1d683f5bec3102e8b86f59928f67 | [
"Apache-2.0"
] | 172 | 2017-07-12T08:53:48.000Z | 2022-03-24T12:16:33.000Z | 23.909677 | 170 | 0.670714 | 10,533 | package com.sequenceiq.mock.swagger.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.sequenceiq.mock.swagger.model.ApiActivityStatus;
import com.sequenceiq.mock.swagger.model.ApiActivityType;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;
/**
* Represents a user activity, such as a MapReduce job, a Hive query, an Oozie workflow, etc.
*/
@ApiModel(description = "Represents a user activity, such as a MapReduce job, a Hive query, an Oozie workflow, etc.")
@Validated
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2020-10-26T08:01:08.932+01:00")
public class ApiActivity {
@JsonProperty("name")
private String name = null;
@JsonProperty("type")
private ApiActivityType type = null;
@JsonProperty("parent")
private String parent = null;
@JsonProperty("startTime")
private String startTime = null;
@JsonProperty("finishTime")
private String finishTime = null;
@JsonProperty("id")
private String id = null;
@JsonProperty("status")
private ApiActivityStatus status = null;
@JsonProperty("user")
private String user = null;
@JsonProperty("group")
private String group = null;
@JsonProperty("inputDir")
private String inputDir = null;
@JsonProperty("outputDir")
private String outputDir = null;
@JsonProperty("mapper")
private String mapper = null;
@JsonProperty("combiner")
private String combiner = null;
@JsonProperty("reducer")
private String reducer = null;
@JsonProperty("queueName")
private String queueName = null;
@JsonProperty("schedulerPriority")
private String schedulerPriority = null;
public ApiActivity name(String name) {
this.name = name;
return this;
}
/**
* Activity name.
* @return name
**/
@ApiModelProperty(value = "Activity name.")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ApiActivity type(ApiActivityType type) {
this.type = type;
return this;
}
/**
* Activity type. Whether it's an MR job, a Pig job, a Hive query, etc.
* @return type
**/
@ApiModelProperty(value = "Activity type. Whether it's an MR job, a Pig job, a Hive query, etc.")
@Valid
public ApiActivityType getType() {
return type;
}
public void setType(ApiActivityType type) {
this.type = type;
}
public ApiActivity parent(String parent) {
this.parent = parent;
return this;
}
/**
* The name of the parent activity.
* @return parent
**/
@ApiModelProperty(value = "The name of the parent activity.")
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public ApiActivity startTime(String startTime) {
this.startTime = startTime;
return this;
}
/**
* The start time of this activity.
* @return startTime
**/
@ApiModelProperty(value = "The start time of this activity.")
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public ApiActivity finishTime(String finishTime) {
this.finishTime = finishTime;
return this;
}
/**
* The finish time of this activity.
* @return finishTime
**/
@ApiModelProperty(value = "The finish time of this activity.")
public String getFinishTime() {
return finishTime;
}
public void setFinishTime(String finishTime) {
this.finishTime = finishTime;
}
public ApiActivity id(String id) {
this.id = id;
return this;
}
/**
* Activity id, which is unique within a MapReduce service.
* @return id
**/
@ApiModelProperty(value = "Activity id, which is unique within a MapReduce service.")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public ApiActivity status(ApiActivityStatus status) {
this.status = status;
return this;
}
/**
* Activity status.
* @return status
**/
@ApiModelProperty(value = "Activity status.")
@Valid
public ApiActivityStatus getStatus() {
return status;
}
public void setStatus(ApiActivityStatus status) {
this.status = status;
}
public ApiActivity user(String user) {
this.user = user;
return this;
}
/**
* The user who submitted this activity.
* @return user
**/
@ApiModelProperty(value = "The user who submitted this activity.")
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public ApiActivity group(String group) {
this.group = group;
return this;
}
/**
* The user-group of this activity.
* @return group
**/
@ApiModelProperty(value = "The user-group of this activity.")
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public ApiActivity inputDir(String inputDir) {
this.inputDir = inputDir;
return this;
}
/**
* The input data directory of the activity. An HDFS url.
* @return inputDir
**/
@ApiModelProperty(value = "The input data directory of the activity. An HDFS url.")
public String getInputDir() {
return inputDir;
}
public void setInputDir(String inputDir) {
this.inputDir = inputDir;
}
public ApiActivity outputDir(String outputDir) {
this.outputDir = outputDir;
return this;
}
/**
* The output result directory of the activity. An HDFS url.
* @return outputDir
**/
@ApiModelProperty(value = "The output result directory of the activity. An HDFS url.")
public String getOutputDir() {
return outputDir;
}
public void setOutputDir(String outputDir) {
this.outputDir = outputDir;
}
public ApiActivity mapper(String mapper) {
this.mapper = mapper;
return this;
}
/**
* The mapper class.
* @return mapper
**/
@ApiModelProperty(value = "The mapper class.")
public String getMapper() {
return mapper;
}
public void setMapper(String mapper) {
this.mapper = mapper;
}
public ApiActivity combiner(String combiner) {
this.combiner = combiner;
return this;
}
/**
* The combiner class.
* @return combiner
**/
@ApiModelProperty(value = "The combiner class.")
public String getCombiner() {
return combiner;
}
public void setCombiner(String combiner) {
this.combiner = combiner;
}
public ApiActivity reducer(String reducer) {
this.reducer = reducer;
return this;
}
/**
* The reducer class.
* @return reducer
**/
@ApiModelProperty(value = "The reducer class.")
public String getReducer() {
return reducer;
}
public void setReducer(String reducer) {
this.reducer = reducer;
}
public ApiActivity queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* The scheduler queue this activity is in.
* @return queueName
**/
@ApiModelProperty(value = "The scheduler queue this activity is in.")
public String getQueueName() {
return queueName;
}
public void setQueueName(String queueName) {
this.queueName = queueName;
}
public ApiActivity schedulerPriority(String schedulerPriority) {
this.schedulerPriority = schedulerPriority;
return this;
}
/**
* The scheduler priority of this activity.
* @return schedulerPriority
**/
@ApiModelProperty(value = "The scheduler priority of this activity.")
public String getSchedulerPriority() {
return schedulerPriority;
}
public void setSchedulerPriority(String schedulerPriority) {
this.schedulerPriority = schedulerPriority;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ApiActivity apiActivity = (ApiActivity) o;
return Objects.equals(this.name, apiActivity.name) &&
Objects.equals(this.type, apiActivity.type) &&
Objects.equals(this.parent, apiActivity.parent) &&
Objects.equals(this.startTime, apiActivity.startTime) &&
Objects.equals(this.finishTime, apiActivity.finishTime) &&
Objects.equals(this.id, apiActivity.id) &&
Objects.equals(this.status, apiActivity.status) &&
Objects.equals(this.user, apiActivity.user) &&
Objects.equals(this.group, apiActivity.group) &&
Objects.equals(this.inputDir, apiActivity.inputDir) &&
Objects.equals(this.outputDir, apiActivity.outputDir) &&
Objects.equals(this.mapper, apiActivity.mapper) &&
Objects.equals(this.combiner, apiActivity.combiner) &&
Objects.equals(this.reducer, apiActivity.reducer) &&
Objects.equals(this.queueName, apiActivity.queueName) &&
Objects.equals(this.schedulerPriority, apiActivity.schedulerPriority);
}
@Override
public int hashCode() {
return Objects.hash(name, type, parent, startTime, finishTime, id, status, user, group, inputDir, outputDir, mapper, combiner, reducer, queueName, schedulerPriority);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ApiActivity {\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" parent: ").append(toIndentedString(parent)).append("\n");
sb.append(" startTime: ").append(toIndentedString(startTime)).append("\n");
sb.append(" finishTime: ").append(toIndentedString(finishTime)).append("\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append(" user: ").append(toIndentedString(user)).append("\n");
sb.append(" group: ").append(toIndentedString(group)).append("\n");
sb.append(" inputDir: ").append(toIndentedString(inputDir)).append("\n");
sb.append(" outputDir: ").append(toIndentedString(outputDir)).append("\n");
sb.append(" mapper: ").append(toIndentedString(mapper)).append("\n");
sb.append(" combiner: ").append(toIndentedString(combiner)).append("\n");
sb.append(" reducer: ").append(toIndentedString(reducer)).append("\n");
sb.append(" queueName: ").append(toIndentedString(queueName)).append("\n");
sb.append(" schedulerPriority: ").append(toIndentedString(schedulerPriority)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
3e18c5c5dedbc752b591cc561077f2d3cf18779d | 224 | java | Java | BackEnd_Learn/Java/auth/src/main/java/io/github/leeseojune53/auth/error/ErrorResponse.java | leeseojune53/TIL | 6a27b56f8e3899c6ff0a427fc0eac34d3b7e504e | [
"MIT"
] | 12 | 2020-04-23T15:53:46.000Z | 2021-07-14T07:56:31.000Z | BackEnd_Learn/Java/auth/src/main/java/io/github/leeseojune53/auth/error/ErrorResponse.java | leeseojune53/BOJ | 3c477f4e977d7ffac6db6e79e6bf412525fd9c4a | [
"MIT"
] | 18 | 2021-05-27T23:48:37.000Z | 2022-02-27T23:20:07.000Z | BackEnd_Learn/Java/auth/src/main/java/io/github/leeseojune53/auth/error/ErrorResponse.java | leeseojune53/BOJ | 3c477f4e977d7ffac6db6e79e6bf412525fd9c4a | [
"MIT"
] | 3 | 2020-04-23T15:53:53.000Z | 2021-11-08T11:09:01.000Z | 18.666667 | 42 | 0.794643 | 10,534 | package io.github.leeseojune53.auth.error;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public class ErrorResponse {
private final int status;
private final String message;
}
|
3e18c65a33d51cfe9c5a37b76ce534a739c999ae | 6,737 | java | Java | src/test/java/com/enremmeta/rtb/proto/adx/AdXAdapterSpec_Constructor.java | opencmo/lot49 | 11d5a7bad792683f11ebd41f8185c0c303d9f1ea | [
"RSA-MD"
] | 1 | 2019-07-04T03:57:41.000Z | 2019-07-04T03:57:41.000Z | src/test/java/com/enremmeta/rtb/proto/adx/AdXAdapterSpec_Constructor.java | opencmo/lot49 | 11d5a7bad792683f11ebd41f8185c0c303d9f1ea | [
"RSA-MD"
] | null | null | null | src/test/java/com/enremmeta/rtb/proto/adx/AdXAdapterSpec_Constructor.java | opencmo/lot49 | 11d5a7bad792683f11ebd41f8185c0c303d9f1ea | [
"RSA-MD"
] | 2 | 2018-01-05T18:13:24.000Z | 2020-07-09T02:35:23.000Z | 37.220994 | 174 | 0.645836 | 10,535 | package com.enremmeta.rtb.proto.adx;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import com.enremmeta.rtb.Lot49Exception;
import com.enremmeta.rtb.SharedSetUp;
import com.enremmeta.rtb.config.ExchangesConfig;
import com.enremmeta.rtb.config.Lot49Config;
import com.enremmeta.util.ServiceRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ServiceRunner.class, CSVParser.class})
@PowerMockIgnore({"javax.crypto.*", "javax.management.*"})
public class AdXAdapterSpec_Constructor {
private static final String GEO_TABLE_FILE_NAME = "geo_table_file_name";
private final static int GEO_RECORD_ID = 1000010;
private ServiceRunner serviceRunnerSimpleMock;
private AdXConfig adxCfg;
Lot49Config configMock;
@Before
public void setUp() {
Whitebox.setInternalState(AdXAdapter.class, "geo", (Map<Integer, AdxGeo>) null);
serviceRunnerSimpleMock = Mockito.mock(ServiceRunner.class, Mockito.CALLS_REAL_METHODS);
configMock = Mockito.mock(Lot49Config.class);
adxCfg = new AdXConfig();
Mockito.when(configMock.getExchanges()).thenAnswer(new Answer<ExchangesConfig>() {
public ExchangesConfig answer(InvocationOnMock invocation) {
ExchangesConfig exchangesConfigMock = Mockito.mock(ExchangesConfig.class);
Mockito.when(exchangesConfigMock.getAdx()).thenReturn(adxCfg);
return exchangesConfigMock;
}
});
PowerMockito.mockStatic(ServiceRunner.class);
Mockito.when(ServiceRunner.getInstance()).thenReturn(serviceRunnerSimpleMock);
Mockito.when(serviceRunnerSimpleMock.getConfig()).thenReturn(configMock);
}
private void prepareAdxConfigSecurity(AdXConfig adxCfg) {
adxCfg.setEncryptionKey(SharedSetUp.ENCRIPTION_KEY);
adxCfg.setIntegrityKey(SharedSetUp.INTEGRITY_KEY);
}
@SuppressWarnings("serial")
@Test
public void positiveFlow_ShouldLoadGeoFile() throws Lot49Exception, IOException {
// set security config for bidder
prepareAdxConfigSecurity(adxCfg);
// set geotable config for bidder
adxCfg.setGeoTable(GEO_TABLE_FILE_NAME);
// mimic concurrent loading of geotable
ExecutorService testExecutor = Executors.newSingleThreadExecutor();
Mockito.when(serviceRunnerSimpleMock.getExecutor()).thenReturn(testExecutor);
PowerMockito.mockStatic(CSVParser.class);
PowerMockito.when(CSVParser.parse(Mockito.any(File.class), Mockito.any(Charset.class),
Mockito.any())).thenAnswer(new Answer<CSVParser>() {
public CSVParser answer(InvocationOnMock invocation)
throws IOException {
CSVParser testParser = new CSVParser(
new StringReader(
"1000010,\"Abu Dhabi\",\"Abu Dhabi,Abu Dhabi,United Arab Emirates\",\"9041082,2784\",\"\",\"AE\",\"City\"\n"),
CSVFormat.EXCEL);
return testParser;
}
});
// action under test
new AdXAdapter();
// verify assignment of task for bidder's executor
Mockito.verify(serviceRunnerSimpleMock, Mockito.times(1)).getExecutor();
// wait for finish of loading
long start = System.nanoTime();
while (((Map<?, ?>) Whitebox.getInternalState(AdXAdapter.class, "geo")).keySet()
.isEmpty()) {
long now = System.nanoTime();
if ((now - start) / 1.0e9 > 5) // keep 5 seconds timeout
fail("Concurrent task is not responding");
}
// verify result of geotable loading
assertEquals(new HashSet<Integer>() {
{
add(GEO_RECORD_ID);
}
}, ((Map<?, ?>) Whitebox.getInternalState(AdXAdapter.class, "geo")).keySet());
assertEquals("Abu Dhabi,Abu Dhabi,United Arab Emirates",
((AdxGeo) ((Map<?, ?>) Whitebox.getInternalState(AdXAdapter.class, "geo"))
.get(GEO_RECORD_ID)).getCanonicalName());
assertEquals("Abu Dhabi",
((AdxGeo) ((Map<?, ?>) Whitebox.getInternalState(AdXAdapter.class, "geo"))
.get(GEO_RECORD_ID)).getName());
assertEquals("ae",
((AdxGeo) ((Map<?, ?>) Whitebox.getInternalState(AdXAdapter.class, "geo"))
.get(GEO_RECORD_ID)).getCountryCode());
}
@Test
public void negativeFlow_SecurityKeysNotSpecified() throws Lot49Exception {
try {
new AdXAdapter();
fail("My method didn't throw when I expected it to");
} catch (Lot49Exception expectedException) {
assertTrue(expectedException.getMessage().contains(
"Either encryption or integrity key missing from OpenX configuration."));
}
}
@Test
public void negativeFlow_GeoTableNotSpecified() throws Lot49Exception {
prepareAdxConfigSecurity(adxCfg);
// mock getExecutor method
ExecutorService testExecutor = Executors.newSingleThreadExecutor();
Mockito.when(serviceRunnerSimpleMock.getExecutor()).thenReturn(testExecutor);
new AdXAdapter();
Mockito.verify(serviceRunnerSimpleMock, Mockito.never()).getExecutor();
}
// TODO
// Refactoring ideas for code under test:
// 1. extract runnable from constructor
// 2. make helper class for geotable loading to avoid testing concurrent code
// 3. remove parse method tests from constructor
}
|
3e18c7157954774fd4f0c6aaa41890f60b981c3b | 4,798 | java | Java | src/com/comparetraits/servlet/DemoServlet.java | Naraharibharathkumar/TeamMavericks-CompareTraits | 6f438328350e3a4a31e0c7045b36d93c3c9e2357 | [
"Apache-2.0"
] | null | null | null | src/com/comparetraits/servlet/DemoServlet.java | Naraharibharathkumar/TeamMavericks-CompareTraits | 6f438328350e3a4a31e0c7045b36d93c3c9e2357 | [
"Apache-2.0"
] | null | null | null | src/com/comparetraits/servlet/DemoServlet.java | Naraharibharathkumar/TeamMavericks-CompareTraits | 6f438328350e3a4a31e0c7045b36d93c3c9e2357 | [
"Apache-2.0"
] | null | null | null | 31.359477 | 88 | 0.721342 | 10,536 | package com.comparetraits.servlet;
import java.io.IOException;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.entity.ContentType;
import com.ibm.json.java.JSONArray;
import com.ibm.json.java.JSONObject;
@MultipartConfig
public class DemoServlet extends HttpServlet {
private static Logger logger = Logger.getLogger(DemoServlet.class.getName());
private static final long serialVersionUID = 1L;
private String serviceName = "personality_insights";
// If running locally complete the variables below
// with the information in VCAP_SERVICES
private String baseURL = "https://gateway.watsonplatform.net/personality-insights/api";
private String username = "d8dbdbd3-d29c-45b1-be25-6323efecef75";
private String password = "Px6sRFxjN0mH";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.getRequestDispatcher("/index.jsp").forward(req, resp);
}
/**
* Create and POST a request to the Personality Insights service
*
* @param req
* the Http Servlet request
* @param resp
* the Http Servlet pesponse
* @throws ServletException
* the servlet exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
throws ServletException, IOException {
logger.info("doPost");
req.setCharacterEncoding("UTF-8");
// create the request
String text = req.getParameter("text");
String language = req.getParameter("language");
String locale = req.getLocale().toString().replace("_", "-");
try {
URI profileURI = new URI(baseURL + "/v2/profile").normalize();
Request profileRequest = Request.Post(profileURI)
.addHeader("Accept", "application/json")
.addHeader("Content-Language", language)
.addHeader("Accept-Language", locale)
.bodyString(text, ContentType.TEXT_PLAIN);
Executor executor = Executor.newInstance().auth(username, password);
Response response = executor.execute(profileRequest);
HttpResponse httpResponse = response.returnResponse();
resp.setStatus(httpResponse.getStatusLine().getStatusCode());
ServletOutputStream servletOutputStream = resp.getOutputStream();
httpResponse.getEntity().writeTo(servletOutputStream);
servletOutputStream.flush();
servletOutputStream.close();
} catch (Exception e) {
logger.log(Level.SEVERE, "Service error: " + e.getMessage(), e);
resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
}
}
@Override
public void init() throws ServletException {
super.init();
processVCAPServices();
}
/**
* If exists, process the VCAP_SERVICES environment variable in order to get
* the username, password and baseURL
*/
private void processVCAPServices() {
logger.info("Processing VCAP_SERVICES");
JSONObject sysEnv = getVCAPServices();
if (sysEnv == null)
return;
logger.info("Looking for: " + serviceName);
for (Object key : sysEnv.keySet()) {
String keyString = (String) key;
logger.info("found key: " + key);
if (keyString.startsWith(serviceName)) {
JSONArray services = (JSONArray) sysEnv.get(key);
JSONObject service = (JSONObject) services.get(0);
JSONObject credentials = (JSONObject) service
.get("credentials");
baseURL = (String) credentials.get("url");
username = (String) credentials.get("username");
password = (String) credentials.get("password");
logger.info("baseURL = " + baseURL);
logger.info("username = " + username);
logger.info("password = " + password);
} else {
logger.info("Doesn't match /^" + serviceName + "/");
}
}
}
/**
* Gets the <b>VCAP_SERVICES</b> environment variable and return it as a
* JSONObject.
*
* @return the VCAP_SERVICES as Json
*/
private JSONObject getVCAPServices() {
String envServices = System.getenv("VCAP_SERVICES");
if (envServices == null)
return null;
JSONObject sysEnv = null;
try {
sysEnv = JSONObject.parse(envServices);
} catch (IOException e) {
// Do nothing, fall through to defaults
logger.log(Level.SEVERE,
"Error parsing VCAP_SERVICES: " + e.getMessage(), e);
}
return sysEnv;
}
}
|
3e18c720387464f559630fdc267b352bc295cb4e | 58 | java | Java | kukulkan-shell-plugin-generator/src/main/java/mx/infotec/dads/kukulkan/shell/commands/kukulkan/package-info.java | mosbaldo/kukulkan-shell | d4272c99cdb84c5a22501e38830f91cfa0166bf2 | [
"Apache-2.0"
] | null | null | null | kukulkan-shell-plugin-generator/src/main/java/mx/infotec/dads/kukulkan/shell/commands/kukulkan/package-info.java | mosbaldo/kukulkan-shell | d4272c99cdb84c5a22501e38830f91cfa0166bf2 | [
"Apache-2.0"
] | 20 | 2018-04-20T16:25:36.000Z | 2018-10-17T16:30:17.000Z | kukulkan-shell-plugin-generator/src/main/java/mx/infotec/dads/kukulkan/shell/commands/kukulkan/package-info.java | mosbaldo/kukulkan-shell | d4272c99cdb84c5a22501e38830f91cfa0166bf2 | [
"Apache-2.0"
] | 3 | 2018-01-31T22:30:11.000Z | 2021-08-21T03:59:55.000Z | 29 | 57 | 0.844828 | 10,537 | package mx.infotec.dads.kukulkan.shell.commands.kukulkan;
|
3e18c89ef56760b4201852da556cb04e8a33e60b | 6,123 | java | Java | console/src/main/java/com/alibaba/nacos/console/security/nacos/NacosAuthManager.java | yangzhiwei256/alibaba_nacos | 5543089822626582b67dc53bdc267eea0ab3605f | [
"Apache-2.0"
] | null | null | null | console/src/main/java/com/alibaba/nacos/console/security/nacos/NacosAuthManager.java | yangzhiwei256/alibaba_nacos | 5543089822626582b67dc53bdc267eea0ab3605f | [
"Apache-2.0"
] | 6 | 2021-01-21T01:27:56.000Z | 2022-02-27T08:47:48.000Z | console/src/main/java/com/alibaba/nacos/console/security/nacos/NacosAuthManager.java | yangzhiwei256/alibaba_nacos | 5543089822626582b67dc53bdc267eea0ab3605f | [
"Apache-2.0"
] | null | null | null | 38.26875 | 154 | 0.713866 | 10,538 | /*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* 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.alibaba.nacos.console.security.nacos;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.alibaba.nacos.common.constant.CommonConstants;
import com.alibaba.nacos.config.server.auth.UserRoleInfo;
import com.alibaba.nacos.console.security.nacos.roles.NacosRoleServiceImpl;
import com.alibaba.nacos.console.security.nacos.users.NacosUser;
import com.alibaba.nacos.core.auth.AccessException;
import com.alibaba.nacos.core.auth.AuthManager;
import com.alibaba.nacos.core.auth.Permission;
import com.alibaba.nacos.core.auth.User;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
/**
* Builtin access control entry of Nacos
*
* @author nkorange
* @since 1.2.0
*/
@Component
@Slf4j
public class NacosAuthManager implements AuthManager {
private static final String TOKEN_PREFIX = "Bearer ";
@Autowired
private JwtTokenManager tokenManager;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private NacosRoleServiceImpl roleService;
@Override
public User login(Object request) throws AccessException {
HttpServletRequest req = (HttpServletRequest) request;
String token = resolveToken(req);
if (StringUtils.isBlank(token)) {
throw new AccessException("user not found!");
}
try {
tokenManager.validateToken(token);
} catch (ExpiredJwtException e) {
throw new AccessException("token expired!");
} catch (Exception e) {
throw new AccessException("token invalid!");
}
Authentication authentication = tokenManager.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
String username = authentication.getName();
NacosUser user = new NacosUser();
user.setUserName(username);
user.setToken(token);
List<UserRoleInfo> userRoleInfoList = roleService.getRoles(username);
if(CollectionUtils.isEmpty(userRoleInfoList)){
throw new AccessException("user role invalid!");
}
String channel = req.getHeader(CommonConstants.LOGIN_CHANNEL);
boolean isAppChannel = userRoleInfoList.stream().map(UserRoleInfo::getRole).collect(Collectors.toList()).contains(CommonConstants.APP_LOGIN_ROLE);
//APP渠道不能登陆nacos管理后台
if(isAppChannel && StringUtils.isEmpty(channel)){
throw new AccessException("user login channel invalid!");
}
for (UserRoleInfo userRoleInfo : userRoleInfoList) {
if (userRoleInfo.getRole().equals(NacosRoleServiceImpl.GLOBAL_ADMIN_ROLE)) {
user.setGlobalAdmin(true);
break;
}
}
return user;
}
@Override
public void auth(Permission permission, User user) throws AccessException {
if (log.isDebugEnabled()) {
log.debug("auth permission: {}, user: {}", permission, user);
}
if (!roleService.hasPermission(user.getUserName(), permission)) {
throw new AccessException("authorization failed!");
}
}
/**
* Get token from header
*/
private String resolveToken(HttpServletRequest request) throws AccessException {
String bearerToken = request.getHeader(NacosAuthConfig.AUTHORIZATION_HEADER);
if(StringUtils.isNotBlank(bearerToken) && bearerToken.contains("null")){ //TODO 定位null设置出处
return StringUtils.EMPTY;
}
if (StringUtils.isNotBlank(bearerToken) && bearerToken.startsWith(TOKEN_PREFIX)) {
return bearerToken.substring(7);
}
//修复 accessToken存储在TokenMap bug
if (StringUtils.isNotBlank(bearerToken) && !bearerToken.startsWith(TOKEN_PREFIX)) {
JSONObject jsonObject = JSONObject.parseObject(bearerToken);
return jsonObject.getString(Constants.ACCESS_TOKEN);
}
bearerToken = request.getParameter(Constants.ACCESS_TOKEN);
if (StringUtils.isBlank(bearerToken)) {
String userName = request.getParameter("username");
String password = request.getParameter("password");
bearerToken = resolveTokenFromUser(userName, password);
}
return bearerToken;
}
private String resolveTokenFromUser(String userName, String rawPassword) throws AccessException {
try {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName, rawPassword);
authenticationManager.authenticate(authenticationToken);
} catch (AuthenticationException e) {
throw new AccessException("unknown user!");
}
return tokenManager.createToken(userName);
}
}
|
3e18c927fee1a4771b86ec2fbcec0b209253804b | 228 | java | Java | src/main/java/com/swampus/excercise/task/Task3Junior.java | swampus/EXCERSICE__OOP | b78a0cd20d3b6c490c104e56bedb0c8ca1ac4f93 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/swampus/excercise/task/Task3Junior.java | swampus/EXCERSICE__OOP | b78a0cd20d3b6c490c104e56bedb0c8ca1ac4f93 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/swampus/excercise/task/Task3Junior.java | swampus/EXCERSICE__OOP | b78a0cd20d3b6c490c104e56bedb0c8ca1ac4f93 | [
"Apache-2.0"
] | null | null | null | 19 | 65 | 0.798246 | 10,539 | package com.swampus.excercise.task;
import com.swampus.excercise.not.modify.clazz.ExtenderForJunior3;
/**
* Ovveride method doSomeUnsafeStaff is should do NOTHING
*/
public class Task3Junior extends ExtenderForJunior3 {
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.