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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e1948ef1f016e603202b6c8e7969fd3bd8d15b2 | 983 | java | Java | slideshowfx-markdown/src/integrationTest/java/com/twasyl/slideshowfx/markup/markdown/MarkdownMarkupIntegrationTest.java | twasyl/SlideshowFX | c24ea95aed8a050a79cddfd1809a5013c16c25cd | [
"Apache-2.0"
] | 47 | 2015-01-31T12:28:10.000Z | 2021-11-08T01:05:57.000Z | slideshowfx-markdown/src/integrationTest/java/com/twasyl/slideshowfx/markup/markdown/MarkdownMarkupIntegrationTest.java | twasyl/SlideshowFX | c24ea95aed8a050a79cddfd1809a5013c16c25cd | [
"Apache-2.0"
] | 33 | 2015-03-12T20:25:41.000Z | 2018-04-13T17:52:14.000Z | slideshowfx-markdown/src/integrationTest/java/com/twasyl/slideshowfx/markup/markdown/MarkdownMarkupIntegrationTest.java | twasyl/SlideshowFX | c24ea95aed8a050a79cddfd1809a5013c16c25cd | [
"Apache-2.0"
] | 8 | 2015-10-12T17:36:37.000Z | 2019-06-21T04:34:53.000Z | 31.709677 | 97 | 0.754832 | 10,740 | package com.twasyl.slideshowfx.markup.markdown;
import com.twasyl.slideshowfx.markup.IMarkup;
import com.twasyl.slideshowfx.plugin.manager.PluginManager;
import com.twasyl.slideshowfx.plugin.manager.BasePluginIntegrationTest;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
@DisplayName("The markdown plugin")
public class MarkdownMarkupIntegrationTest extends BasePluginIntegrationTest {
@Test
@DisplayName("can be installed in the plugin manager")
void pluginIsInstalled() {
assertPluginIsInstalled(IMarkup.class, "Markdown");
}
@Test
@DisplayName("can convert some text")
void convertText() {
List<IMarkup> installedServices = PluginManager.getInstance().getServices(IMarkup.class);
final String html = installedServices.get(0).convertAsHtml("# Hello");
assertEquals("<h1>Hello</h1>", html);
}
}
|
3e1949014d57c36c4e04d2bc0ff5371d503283c5 | 942 | java | Java | src/main/java/com/github/technus/tectech/nei/NEI_TT_Config.java | Sphyix/TecTech | 88474a18b40c51444ec5889e6d11f80549c1eef9 | [
"Unlicense"
] | 22 | 2017-03-18T12:12:20.000Z | 2022-03-15T04:30:45.000Z | src/main/java/com/github/technus/tectech/nei/NEI_TT_Config.java | Sphyix/TecTech | 88474a18b40c51444ec5889e6d11f80549c1eef9 | [
"Unlicense"
] | 41 | 2017-06-01T19:40:11.000Z | 2022-01-31T22:56:40.000Z | src/main/java/com/github/technus/tectech/nei/NEI_TT_Config.java | Sphyix/TecTech | 88474a18b40c51444ec5889e6d11f80549c1eef9 | [
"Unlicense"
] | 35 | 2017-10-13T00:51:33.000Z | 2021-12-02T22:51:52.000Z | 29.4375 | 99 | 0.703822 | 10,741 | package com.github.technus.tectech.nei;
import codechicken.nei.api.IConfigureNEI;
import com.github.technus.tectech.recipe.TT_recipe;
import cpw.mods.fml.common.FMLCommonHandler;
public class NEI_TT_Config implements IConfigureNEI {//must be NEI*Config
public static boolean sIsAdded = true;
public static TT_NEI_ResearchHandler TT_RH;
public static TT_NEI_ScannerHandler TT_SH;
@Override
public void loadConfig() {
sIsAdded = false;
if(FMLCommonHandler.instance().getEffectiveSide().isClient()) {
TT_RH = new TT_NEI_ResearchHandler(TT_recipe.GT_Recipe_MapTT.sResearchableFakeRecipes);
TT_SH = new TT_NEI_ScannerHandler(TT_recipe.GT_Recipe_MapTT.sScannableFakeRecipes);
}
sIsAdded = true;
}
@Override
public String getName() {
return "TecTech NEI Plugin";
}
@Override
public String getVersion() {
return "(1.0)";
}
}
|
3e19496df0a78cc8ac1fc14a82de48d7d71cdb68 | 6,586 | java | Java | Homework/HW1/src/State.java | fuadaghazada/X-WORD | 9d2f1f23e3bda31a27e038c90fc9ee30b73f5539 | [
"MIT"
] | 2 | 2019-06-12T08:32:12.000Z | 2020-04-03T13:09:54.000Z | Homework/HW1/src/State.java | fuadaghazada/X-WORD | 9d2f1f23e3bda31a27e038c90fc9ee30b73f5539 | [
"MIT"
] | null | null | null | Homework/HW1/src/State.java | fuadaghazada/X-WORD | 9d2f1f23e3bda31a27e038c90fc9ee30b73f5539 | [
"MIT"
] | 2 | 2019-05-31T08:56:03.000Z | 2019-12-17T01:58:20.000Z | 29.800905 | 129 | 0.596113 | 10,742 |
/**
*
* @author cagatay.sel-ug
*/
import java.util.ArrayList;
public class State{
//Problem constans
public static final int LEFT_JUG_CAP = 7;
public static final int RIGHT_JUG_CAP = 5;
public static final String CREATION_INITIAL = "Initial";
public static final String CREATION_FILL_LEFT = "Filled left jug";
public static final String CREATION_FILL_RIGHT = "Filled right jug";
public static final String CREATION_EMPTY_LEFT = "Emptied left jug";
public static final String CREATION_EMPTY_RIGHT = "Emptied right jug";
public static final String CREATION_POUR_LEFT_TO_RIGHT = "Poured left to right";
public static final String CREATION_POUR_RIGHT_TO_LEFT = "Poured right to left";
//Instance variables
private int leftJugWater;
private int rightJugWater;
private String creation;
private ArrayList<State> nextStates;
// To backtrack from goal state to initial state
private State parent;
public State(int leftJugWater,int rightJugWater,State parent,String creation){
this.leftJugWater = leftJugWater;
this.rightJugWater = rightJugWater;
this.parent = parent;
this.creation = creation;
this.nextStates = new ArrayList<State>();
}
public State fillLeftJug(){
int leftJugWater = LEFT_JUG_CAP;
int rightJugWater = this.rightJugWater;
State newState = new State(leftJugWater,rightJugWater,this,CREATION_FILL_LEFT);
return newState;
}
public State fillRightJug(){
int rightJugWater = RIGHT_JUG_CAP;
int leftJugWater = this.leftJugWater;
State newState = new State(leftJugWater,rightJugWater,this, CREATION_FILL_RIGHT);
return newState;
}
public State emptyLeftJug(){
int leftJugWater=0;
int rightJugWater = this.rightJugWater;
State newState = new State(leftJugWater,rightJugWater,this, CREATION_EMPTY_LEFT );
return newState;
}
public State emptyRightJug(){
int rightJugWater=0;
int leftJugWater = this.leftJugWater;
State newState = new State(leftJugWater,rightJugWater,this,CREATION_EMPTY_RIGHT);
return newState;
}
/**
* Pour water from big to small jug
*/
public State pourLeftToRight(){
int totalWater = this.leftJugWater + this.rightJugWater;
int leftJugWater = -1;
int rightJugWater = -1;
//Pour all water from left to right and it does not exceed
if(totalWater<=RIGHT_JUG_CAP){
leftJugWater = 0;
rightJugWater = totalWater;
}else if(totalWater>RIGHT_JUG_CAP){
rightJugWater = RIGHT_JUG_CAP;
leftJugWater = totalWater-rightJugWater;
}
State newState = new State(leftJugWater,rightJugWater,this,CREATION_POUR_LEFT_TO_RIGHT );
return newState;
}
/**
* Pour water from small to big jug
*/
public State pourRightToLeft(){
int totalWater = this.leftJugWater + this.rightJugWater;
int leftJugWater = -1;
int rightJugWater = -1;
//Pour all water from left to right and it does not exceed
if(totalWater<=LEFT_JUG_CAP){
leftJugWater = totalWater;
rightJugWater = 0;
}else if(totalWater>LEFT_JUG_CAP){
leftJugWater = LEFT_JUG_CAP;
rightJugWater = totalWater-leftJugWater;
}
State newState = new State(leftJugWater,rightJugWater,this,CREATION_POUR_RIGHT_TO_LEFT);
return newState;
}
/**
* This method back tracks states until initial state and reverses the order in order to print a path from root to leaf.
*/
public void printPath(){
State cur = this;
ArrayList<State> path = new ArrayList<State>();
while(cur!=null){
path.add(cur);
cur = cur.parent;
}
//Reverse printing the array
for(int i=path.size()-1;i>=0;i--){
cur = path.get(i);
System.out.println("Step "+(path.size()-i ) +" : " + cur.creation);
System.out.println(cur);
}
}
/**
*This method generates possible states by applying the 6 operations defines above
*/
public void generateNextStates(ArrayList<State> visitedStates){
State newState = fillLeftJug();
if(!visitedStates.contains(newState)){
this.nextStates.add(newState);
visitedStates.add(newState);
}
newState = fillRightJug();
if(!visitedStates.contains(newState)){
this.nextStates.add(newState);
visitedStates.add(newState);
}
newState = emptyLeftJug();
if(!visitedStates.contains(newState)){
this.nextStates.add(newState);
visitedStates.add(newState);
}
newState = emptyRightJug();
if(!visitedStates.contains(newState)){
this.nextStates.add(newState);
visitedStates.add(newState);
}
newState = pourLeftToRight();
if(!visitedStates.contains(newState)){
this.nextStates.add(newState);
visitedStates.add(newState);
}
newState = pourRightToLeft();
if(!visitedStates.contains(newState)){
this.nextStates.add(newState);
visitedStates.add(newState);
}
}
@Override
public String toString(){
String str = "Left jug water: "+ this.leftJugWater + " Right Jug Water: "+ this.rightJugWater+ "\n";
/*str +="------Next States-----"+"\n";
for(int i=0;i<nextStates.size();i++){
State cur = nextStates.get(i);
str += "Left jug water: "+cur.leftJugWater+
" Right jug water: " + cur.rightJugWater + "\n";
} */
return str;
}
public ArrayList<State> getNextStates(){
return nextStates;
}
public boolean isGoalState(int goal){
if(leftJugWater == goal || rightJugWater == goal){
return true;
}else{
return false;
}
}
@Override
public boolean equals(Object o){
State right = (State) o;
if(right.leftJugWater == this.leftJugWater && right.rightJugWater == this.rightJugWater){
return true;
}
return false;
}
}
|
3e1949787b91d79b8e2841f62265f4eb480d011f | 7,174 | java | Java | src/main/java/org/mskcc/shenkers/control/track/bam/BamView2.java | shenkers/ComparativeBrowser | e588799783f0e71b307e848590102e0d0ed70a3f | [
"Apache-2.0"
] | 10 | 2018-02-28T15:50:25.000Z | 2020-01-31T15:34:34.000Z | src/main/java/org/mskcc/shenkers/control/track/bam/BamView2.java | shenkers/CrossBrowse | e588799783f0e71b307e848590102e0d0ed70a3f | [
"Apache-2.0"
] | 4 | 2018-03-01T08:13:16.000Z | 2020-09-14T12:42:59.000Z | src/main/java/org/mskcc/shenkers/control/track/bam/BamView2.java | shenkers/CrossBrowse | e588799783f0e71b307e848590102e0d0ed70a3f | [
"Apache-2.0"
] | null | null | null | 35.166667 | 157 | 0.5276 | 10,743 | /*
* 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 org.mskcc.shenkers.control.track.bam;
import htsjdk.samtools.Cigar;
import htsjdk.samtools.CigarElement;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SAMRecordIterator;
import htsjdk.samtools.SamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.LockSupport;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.concurrent.Task;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.fxmisc.easybind.EasyBind;
import org.mskcc.shenkers.control.track.View;
import static org.mskcc.shenkers.control.track.bam.BamView1.coverage;
import org.mskcc.shenkers.model.datatypes.GenomeSpan;
import org.mskcc.shenkers.view.LineHistogramView;
import org.mskcc.shenkers.view.SparseLineHistogramView;
/**
*
* @author sol
*/
public class BamView2 implements View<BamContext> {
private final Logger logger = LogManager.getLogger();
@Override
public Task<Pane> getContent(BamContext context) {
return context.spanProperty().getValue().map(i -> {
String chr = i.getChr();
int start = i.getStart();
int end = i.getEnd();
Task<Pane> task = new PaneTask(context, chr, start, end);
logger.info("returning task");
return task;
}
).orElse(
new Task<Pane>() {
@Override
protected Pane call() throws Exception {
return new BorderPane(new Label("coordinates not set"));
}
}
// new BorderPane(new Label("bamview1: span not set"))
// new Pane()
);
}
public class PaneTask extends Task<Pane> {
BamContext context;
SamReader SAMReader;
String chr;
int start;
int end;
BooleanBinding flipBinding;
Semaphore semaphore;
public PaneTask(BamContext context, String chr, int start, int end) {
super();
this.context = context;
this.SAMReader = context.readerProperty().getValue();
this.chr = chr;
this.start = start;
this.end = end;
}
@Override
protected Pane call() throws Exception {
SAMRecordIterator sri = null;
try {
logger.info("calculating coverage for region {}:{}-{}", chr, start, end);
logger.info("allocating coverage map");
Map<Integer, Double> data = new HashMap<>();
logger.info("acquiring semaphore for sam reader");
while (!context.acquireReader()) {
logger.info("waiting...");
Thread.yield();
}
logger.info("parsing sam file");
sri = SAMReader.query(chr, start, end, false);
while (sri.hasNext()) {
if (isCancelled()) {
logger.info(Thread.currentThread().getName() + " recieved cancel and terminating");
break;
}
LockSupport.parkNanos(1);
SAMRecord sr = sri.next();
// logger.info("read: " + sr);
int alignmentPosition = sr.getAlignmentStart();
Cigar cigar = sr.getCigar();
for (int i = 0; i < cigar.numCigarElements(); i++) {
CigarElement cigarElement = cigar.getCigarElement(i);
if (cigarElement.getOperator().consumesReferenceBases()) {
boolean consumesReadBases = cigarElement.getOperator().consumesReadBases();
for (int j = 0; j < cigarElement.getLength(); j++) {
if (consumesReadBases && alignmentPosition >= start && alignmentPosition <= end) {
int k = alignmentPosition - start;
if (!data.containsKey(k)) {
data.put(k, 0.0);
}
data.put(k, data.get(k) + 1);
}
alignmentPosition++;
}
}
}
}
// double[] data = ArrayUtils.toPrimitive(IntStream.of(cov).mapToDouble(j -> j + 0.).boxed().collect(Collectors.toList()).toArray(new Double[0]));
logger.info("setting data");
SparseLineHistogramView lhv = new SparseLineHistogramView();
class FlipBinding extends BooleanBinding {
private final Property<Optional<GenomeSpan>> span;
private FlipBinding(Property<Optional<GenomeSpan>> spanProperty) {
this.span = spanProperty;
}
protected boolean computeValue() {
if (span.getValue().isPresent()) {
return span.getValue().get().isNegativeStrand();
} else {
return false;
}
}
}
flipBinding = new FlipBinding(context.spanProperty());
lhv.flipDomainProperty().bind(flipBinding);
lhv.setData(data, end - start + 1, this);
logger.info("calculating max");
data.values().stream().max((Double d1, Double d2)
-> Double.compare(d1, d2)
).ifPresent(m -> lhv.setMax(m));
// IntStream.of(cov).max().ifPresent(m -> lhv.setMax(m));
logger.info("returning graphic");
return lhv.getGraphic();
} catch (Throwable t) {
logger.info("task {} threw exception {}", this, t.getMessage());
logger.info("exception: ", t);
throw t;
} finally {
if (sri != null) {
sri.close();
}
logger.info("{} releasing semaphore for task {}", Thread.currentThread().getName(), this);
context.releaseReader();
logger.info("released sam reader semaphore");
}
}
@Override
protected void cancelled() {
super.cancelled();
logger.info("Cancelling task");
}
}
}
|
3e1949fbbd668e002500b1c294fe1671fe103e19 | 5,230 | java | Java | slice/slice-core/src/androidTest/java/androidx/slice/SliceTestProvider.java | LanderlYoung/androidx | d99c6ef82e67997b71b449840a8147f62f9537a8 | [
"Apache-2.0"
] | 3,799 | 2020-07-23T21:58:59.000Z | 2022-03-31T17:07:19.000Z | slice/slice-core/src/androidTest/java/androidx/slice/SliceTestProvider.java | LanderlYoung/androidx | d99c6ef82e67997b71b449840a8147f62f9537a8 | [
"Apache-2.0"
] | 152 | 2020-07-24T00:19:02.000Z | 2022-03-31T00:57:54.000Z | slice/slice-core/src/androidTest/java/androidx/slice/SliceTestProvider.java | LanderlYoung/androidx | d99c6ef82e67997b71b449840a8147f62f9537a8 | [
"Apache-2.0"
] | 582 | 2020-07-24T00:16:54.000Z | 2022-03-30T23:32:45.000Z | 43.583333 | 100 | 0.618929 | 10,744 | /*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.slice;
import static android.app.slice.Slice.HINT_LARGE;
import static android.app.slice.Slice.HINT_LIST;
import static android.app.slice.Slice.HINT_NO_TINT;
import static android.app.slice.Slice.HINT_TITLE;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.style.AbsoluteSizeSpan;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.graphics.drawable.IconCompat;
import androidx.slice.Slice.Builder;
import androidx.slice.core.test.R;
import androidx.test.filters.SdkSuppress;
@SdkSuppress(minSdkVersion = 19)
public class SliceTestProvider extends androidx.slice.SliceProvider {
@Override
public boolean onCreateSliceProvider() {
getContext().getPackageName();
return true;
}
@Override
public Slice onBindSlice(@NonNull Uri sliceUri) {
switch (sliceUri.getPath()) {
case "/set_flag":
SliceTest.sFlag = true;
break;
case "/subslice":
Builder b = new Builder(sliceUri);
return b.addSubSlice(new Slice.Builder(b).build(), "subslice").build();
case "/text":
return new Slice.Builder(sliceUri).addText("Expected text", "text").build();
case "/prohibited_span":
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
spannableStringBuilder.append("Expected text");
spannableStringBuilder.setSpan(
new AbsoluteSizeSpan(1000),
0, spannableStringBuilder.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return new Slice.Builder(sliceUri)
.addText(new SpannedString(spannableStringBuilder), "text")
.build();
case "/icon":
return new Slice.Builder(sliceUri).addIcon(
IconCompat.createWithResource(getContext(), R.drawable.size_48x48),
"icon").build();
case "/icon_null":
return new Slice.Builder(sliceUri).addIcon(null, "icon").build();
case "/icon_invalid":
return new Slice.Builder(sliceUri).addIcon(
IconCompat.createWithResource(getContext(), 0), "icon").build();
case "/icon_zero":
IconCompat icon = IconCompat.createWithResource(null, getContext().getPackageName(),
R.drawable.size_48x48);
Slice iconSlice = new Builder(sliceUri).addIcon(icon, "icon").build();
icon.mInt1 = 0;
return iconSlice;
case "/action":
Builder builder = new Builder(sliceUri);
Slice subSlice = new Slice.Builder(builder).build();
PendingIntent broadcast = PendingIntent.getBroadcast(getContext(), 0,
new Intent(getContext().getPackageName() + ".action"),
PendingIntent.FLAG_IMMUTABLE);
return builder.addAction(broadcast, subSlice, "action").build();
case "/int":
return new Slice.Builder(sliceUri).addInt(0xff121212, "int").build();
case "/timestamp":
return new Slice.Builder(sliceUri).addTimestamp(43, "timestamp").build();
case "/hints":
return new Slice.Builder(sliceUri)
.addHints(HINT_LIST)
.addText("Text", null, HINT_TITLE)
.addIcon(IconCompat.createWithResource(getContext(), R.drawable.size_48x48),
null, HINT_NO_TINT, HINT_LARGE)
.build();
case "/permission":
return createPermissionSlice(sliceUri, getContext().getPackageName());
}
return new Slice.Builder(sliceUri).build();
}
@Nullable
@Override
public PendingIntent onCreatePermissionRequest(@NonNull Uri sliceUri,
@NonNull String callingPackage) {
if (getContext().getPackageName().equals(callingPackage)) {
return PendingIntent.getBroadcast(getContext(), 0,
new Intent(getContext().getPackageName() + ".permission"),
PendingIntent.FLAG_IMMUTABLE);
}
return super.onCreatePermissionRequest(sliceUri, callingPackage);
}
}
|
3e194a4c5db584f248119e126d0a91d74b515cfa | 8,102 | java | Java | src/main/java/org/elasticsearch/index/fielddata/plain/DoubleArrayAtomicFieldData.java | corochoone/elasticsearch | 2708e453acb8e30b689ab7869eae58d5e1d54dd1 | [
"Apache-2.0"
] | 1 | 2019-01-10T00:10:11.000Z | 2019-01-10T00:10:11.000Z | src/main/java/org/elasticsearch/index/fielddata/plain/DoubleArrayAtomicFieldData.java | corochoone/elasticsearch | 2708e453acb8e30b689ab7869eae58d5e1d54dd1 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/elasticsearch/index/fielddata/plain/DoubleArrayAtomicFieldData.java | corochoone/elasticsearch | 2708e453acb8e30b689ab7869eae58d5e1d54dd1 | [
"Apache-2.0"
] | null | null | null | 28.131944 | 129 | 0.577265 | 10,745 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.fielddata.plain;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.RamUsageEstimator;
import org.elasticsearch.common.util.DoubleArray;
import org.elasticsearch.index.fielddata.*;
import org.elasticsearch.index.fielddata.ordinals.Ordinals;
/**
*/
public abstract class DoubleArrayAtomicFieldData extends AbstractAtomicNumericFieldData {
public static DoubleArrayAtomicFieldData empty() {
return new Empty();
}
protected long size = -1;
public DoubleArrayAtomicFieldData() {
super(true);
}
@Override
public void close() {
}
static class Empty extends DoubleArrayAtomicFieldData {
Empty() {
super();
}
@Override
public LongValues getLongValues() {
return LongValues.EMPTY;
}
@Override
public DoubleValues getDoubleValues() {
return DoubleValues.EMPTY;
}
@Override
public long getMemorySizeInBytes() {
return 0;
}
@Override
public BytesValues getBytesValues() {
return BytesValues.EMPTY;
}
@Override
public ScriptDocValues getScriptValues() {
return ScriptDocValues.EMPTY_DOUBLES;
}
}
public static class WithOrdinals extends DoubleArrayAtomicFieldData {
private final DoubleArray values;
private final Ordinals ordinals;
public WithOrdinals(DoubleArray values, Ordinals ordinals) {
super();
this.values = values;
this.ordinals = ordinals;
}
@Override
public long getMemorySizeInBytes() {
if (size == -1) {
size = RamUsageEstimator.NUM_BYTES_INT/*size*/ + values.sizeInBytes() + ordinals.getMemorySizeInBytes();
}
return size;
}
@Override
public LongValues getLongValues() {
return new LongValues(values, ordinals.ordinals());
}
@Override
public DoubleValues getDoubleValues() {
return new DoubleValues(values, ordinals.ordinals());
}
static class LongValues extends org.elasticsearch.index.fielddata.LongValues.WithOrdinals {
private final DoubleArray values;
LongValues(DoubleArray values, BytesValues.WithOrdinals ordinals) {
super(ordinals);
this.values = values;
}
@Override
public final long getValueByOrd(long ord) {
assert ord != BytesValues.WithOrdinals.MISSING_ORDINAL;
return (long) values.get(ord);
}
}
static class DoubleValues extends org.elasticsearch.index.fielddata.DoubleValues.WithOrdinals {
private final DoubleArray values;
DoubleValues(DoubleArray values, BytesValues.WithOrdinals ordinals) {
super(ordinals);
this.values = values;
}
@Override
public double getValueByOrd(long ord) {
assert ord != BytesValues.WithOrdinals.MISSING_ORDINAL;
return values.get(ord);
}
}
}
/**
* A single valued case, where not all values are "set", so we have a FixedBitSet that
* indicates which values have an actual value.
*/
public static class SingleFixedSet extends DoubleArrayAtomicFieldData {
private final DoubleArray values;
private final FixedBitSet set;
public SingleFixedSet(DoubleArray values, FixedBitSet set) {
super();
this.values = values;
this.set = set;
}
@Override
public long getMemorySizeInBytes() {
if (size == -1) {
size = RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + values.sizeInBytes() + RamUsageEstimator.sizeOf(set.getBits());
}
return size;
}
@Override
public LongValues getLongValues() {
return new LongValues(values, set);
}
@Override
public DoubleValues getDoubleValues() {
return new DoubleValues(values, set);
}
static class LongValues extends org.elasticsearch.index.fielddata.LongValues {
private final DoubleArray values;
private final FixedBitSet set;
LongValues(DoubleArray values, FixedBitSet set) {
super(false);
this.values = values;
this.set = set;
}
@Override
public int setDocument(int docId) {
this.docId = docId;
return set.get(docId) ? 1 : 0;
}
@Override
public long nextValue() {
return (long) values.get(docId);
}
}
static class DoubleValues extends org.elasticsearch.index.fielddata.DoubleValues {
private final DoubleArray values;
private final FixedBitSet set;
DoubleValues(DoubleArray values, FixedBitSet set) {
super(false);
this.values = values;
this.set = set;
}
@Override
public int setDocument(int docId) {
this.docId = docId;
return set.get(docId) ? 1 : 0;
}
@Override
public double nextValue() {
return values.get(docId);
}
}
}
/**
* Assumes all the values are "set", and docId is used as the index to the value array.
*/
public static class Single extends DoubleArrayAtomicFieldData {
private final DoubleArray values;
/**
* Note, here, we assume that there is no offset by 1 from docId, so position 0
* is the value for docId 0.
*/
public Single(DoubleArray values) {
super();
this.values = values;
}
@Override
public long getMemorySizeInBytes() {
if (size == -1) {
size = RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + values.sizeInBytes();
}
return size;
}
@Override
public LongValues getLongValues() {
return new LongValues(values);
}
@Override
public DoubleValues getDoubleValues() {
return new DoubleValues(values);
}
static final class LongValues extends DenseLongValues {
private final DoubleArray values;
LongValues(DoubleArray values) {
super(false);
this.values = values;
}
@Override
public long nextValue() {
return (long) values.get(docId);
}
}
static final class DoubleValues extends DenseDoubleValues {
private final DoubleArray values;
DoubleValues(DoubleArray values) {
super(false);
this.values = values;
}
@Override
public double nextValue() {
return values.get(docId);
}
}
}
}
|
3e194ae0b43d23ab7817aaf4b112d7c79b10d7c8 | 2,379 | java | Java | samples/src/main/java/com/kevinomyonga/pesapaldroid/samples/fragments/DemoPortalJavaFragment.java | ImperiusRex/PesapalDroid | 21c27badabc583be6b50493cf2465e980c4c9348 | [
"Apache-2.0"
] | 4 | 2016-08-13T16:14:21.000Z | 2017-09-12T16:28:30.000Z | samples/src/main/java/com/kevinomyonga/pesapaldroid/samples/fragments/DemoPortalJavaFragment.java | kevinomyonga/PesapalDroid | 21c27badabc583be6b50493cf2465e980c4c9348 | [
"Apache-2.0"
] | 2 | 2017-07-12T09:23:27.000Z | 2017-12-18T16:21:14.000Z | samples/src/main/java/com/kevinomyonga/pesapaldroid/samples/fragments/DemoPortalJavaFragment.java | ImperiusRex/PesapalDroid | 21c27badabc583be6b50493cf2465e980c4c9348 | [
"Apache-2.0"
] | 5 | 2016-11-25T14:02:39.000Z | 2018-03-14T17:50:45.000Z | 38.370968 | 103 | 0.697772 | 10,746 | package com.kevinomyonga.pesapaldroid.samples.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.kevinomyonga.pesapaldroid.PesapalDroidFragment;
import com.kevinomyonga.pesapaldroid.samples.R;
/**
* Created by Kevin Omyonga on 12/15/2015.
*/
public class DemoPortalJavaFragment extends Fragment {
public DemoPortalJavaFragment() {}
public static DemoPortalJavaFragment newInstance(String fname, String lname, String email,
String phone, String desc, String amount) {
DemoPortalJavaFragment f = new DemoPortalJavaFragment();
Bundle args = new Bundle();
args.putString("fname", fname);
args.putString("lname", lname);
args.putString("email", email);
args.putString("phone", phone);
args.putString("desc", desc);
args.putString("amount", amount);
f.setArguments(args);
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_java, container, false);
Bundle args = getArguments();
PesapalDroidFragment pesapalDroidFragment = new PesapalDroidFragment();
pesapalDroidFragment.setConsumerKey(getString(R.string.consumer_key));
pesapalDroidFragment.setConsumerSecret(getString(R.string.consumer_secret));
pesapalDroidFragment.setDemoEnabled(false);
pesapalDroidFragment.setMobileEnabled(true);
//Pass the buyer details
pesapalDroidFragment.setfName(args.getString("fname"));
pesapalDroidFragment.setlName(args.getString("lname"));
pesapalDroidFragment.setEmail(args.getString("email"));
pesapalDroidFragment.setPhone(args.getString("phone"));
pesapalDroidFragment.setDesc(args.getString("desc"));
pesapalDroidFragment.setAmount(args.getString("amount"));
// Insert the fragment by replacing any existing fragment
getChildFragmentManager().beginTransaction()
.replace(R.id.content_frame, pesapalDroidFragment)
.commit();
return view;
}
}
|
3e194b8a3ec5faf317ed55ef5be218ec424fbe8b | 319 | java | Java | src/main/java/org/blackist/web/springbootor/model/security/TokenDetailImpl.java | blackist/spring-boot-restful | 69788d00c2752f37462fc2ba04b3d452c8b6bf9b | [
"Apache-2.0"
] | 1 | 2020-12-13T14:09:38.000Z | 2020-12-13T14:09:38.000Z | src/main/java/org/blackist/web/springbootor/model/security/TokenDetailImpl.java | blackist/spring-boot-restful | 69788d00c2752f37462fc2ba04b3d452c8b6bf9b | [
"Apache-2.0"
] | null | null | null | src/main/java/org/blackist/web/springbootor/model/security/TokenDetailImpl.java | blackist/spring-boot-restful | 69788d00c2752f37462fc2ba04b3d452c8b6bf9b | [
"Apache-2.0"
] | null | null | null | 19.9375 | 53 | 0.69906 | 10,747 | package org.blackist.web.springbootor.model.security;
public class TokenDetailImpl implements TokenDetail {
private final String username;
public TokenDetailImpl(String username) {
this.username = username;
}
@Override
public String getUsername() {
return this.username;
}
}
|
3e194ca35bace5081f9daf540dbd711e65c7f483 | 4,695 | java | Java | src/main/java/com/github/netty/protocol/mqtt/security/ResourceAuthenticator.java | tuohai666/spring-boot-protocol | c05693fe4ba31e4cca39e0372d4373962fd5e1e4 | [
"Apache-2.0"
] | 73 | 2019-03-01T14:42:14.000Z | 2021-12-19T07:02:32.000Z | src/main/java/com/github/netty/protocol/mqtt/security/ResourceAuthenticator.java | wlj5240/spring-boot-protocol | 3ed595367870d2aeba26e513f742a5f78ba77b65 | [
"Apache-2.0"
] | 10 | 2019-11-12T02:57:03.000Z | 2022-02-25T07:21:31.000Z | src/main/java/com/github/netty/protocol/mqtt/security/ResourceAuthenticator.java | wlj5240/spring-boot-protocol | 3ed595367870d2aeba26e513f742a5f78ba77b65 | [
"Apache-2.0"
] | 39 | 2019-03-08T09:20:27.000Z | 2022-03-31T08:29:21.000Z | 36.115385 | 116 | 0.593184 | 10,748 | /*
* Copyright (c) 2012-2018 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package com.github.netty.protocol.mqtt.security;
import com.github.netty.core.util.LoggerFactoryX;
import com.github.netty.core.util.LoggerX;
import com.github.netty.protocol.mqtt.config.IResourceLoader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
/**
* Load user credentials from a text resource. Each line of the file is formatted as
* "[username]:[sha256(password)]". The username mustn't contains : char.
*
* To encode your password from command line on Linux systems, you could use:
*
* <pre>
* echo -n "yourpassword" | sha256sum
* </pre>
*
* NB -n is important because echo append a newline by default at the of string. -n avoid this
* behaviour.
*/
public class ResourceAuthenticator implements IAuthenticator {
protected static final LoggerX LOG = LoggerFactoryX.getLogger(ResourceAuthenticator.class);
private Map<String, String> m_identities = new HashMap<>();
public ResourceAuthenticator(IResourceLoader resourceLoader, String resourceName) {
try {
MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException nsaex) {
LOG.error("Can't find SHA-256 for password encoding", nsaex);
throw new RuntimeException(nsaex);
}
LOG.info(String.format("Loading password %s %s", resourceLoader.getName(), resourceName));
Reader reader = null;
try {
reader = resourceLoader.loadResource(resourceName);
if (reader == null) {
LOG.warn(String.format("Parsing not existing %s %s", resourceLoader.getName(), resourceName));
} else {
parse(reader);
}
} catch (IResourceLoader.ResourceIsDirectoryException e) {
LOG.warn(String.format("Trying to parse directory %s", resourceName));
} catch (ParseException pex) {
LOG.warn(
String.format("Format error in parsing password %s %s", resourceLoader.getName(), resourceName),
pex);
}
}
private void parse(Reader reader) throws ParseException {
if (reader == null) {
return;
}
BufferedReader br = new BufferedReader(reader);
String line;
try {
while ((line = br.readLine()) != null) {
int commentMarker = line.indexOf('#');
if (commentMarker != -1) {
if (commentMarker == 0) {
// skip its a comment
continue;
} else {
// it's a malformed comment
throw new ParseException(line, commentMarker);
}
} else {
if (line.isEmpty() || line.matches("^\\s*$")) {
// skip it's a black line
continue;
}
// split till the first space
int delimiterIdx = line.indexOf(':');
String username = line.substring(0, delimiterIdx).trim();
String password = line.substring(delimiterIdx + 1).trim();
m_identities.put(username, password);
}
}
} catch (IOException ex) {
throw new ParseException("Failed to read", 1);
}
}
@Override
public boolean checkValid(String clientId, String username, byte[] password) {
if (username == null || password == null) {
LOG.info("username or password was null");
return false;
}
String foundPwq = m_identities.get(username);
if (foundPwq == null) {
return false;
}
// String encodedPasswd = DigestUtils.sha256Hex(password);
String encodedPasswd = new String(password);
return foundPwq.equals(encodedPasswd);
}
}
|
3e194f46f2e183d4a9d1d704ffa195bbe3dcdfb8 | 297 | java | Java | src/test/java/com/github/charlemaznable/bunny/rabbittest/common/illegal/IllegalConfig.java | CharLemAznable/bunny-rabbit | c8a20bab8281f6b960f1b4d26408222da950a529 | [
"MIT"
] | null | null | null | src/test/java/com/github/charlemaznable/bunny/rabbittest/common/illegal/IllegalConfig.java | CharLemAznable/bunny-rabbit | c8a20bab8281f6b960f1b4d26408222da950a529 | [
"MIT"
] | null | null | null | src/test/java/com/github/charlemaznable/bunny/rabbittest/common/illegal/IllegalConfig.java | CharLemAznable/bunny-rabbit | c8a20bab8281f6b960f1b4d26408222da950a529 | [
"MIT"
] | null | null | null | 33 | 66 | 0.821549 | 10,749 | package com.github.charlemaznable.bunny.rabbittest.common.illegal;
import com.github.charlemaznable.bunny.rabbit.config.BunnyConfig;
import com.github.charlemaznable.core.miner.MinerConfig;
@MinerConfig(group = "Bunny", dataId = "illegal")
public interface IllegalConfig extends BunnyConfig {
}
|
3e1950160cca2df659b8fb7e5a4dd3d40f7479da | 748 | java | Java | li-utils/src/main/javaPegasus/com/linkedin/common/url/Url.java | iasoon/datahub | 34c27f076bb7c4c16a295292cee17a7d07fe6165 | [
"Apache-2.0"
] | 1,603 | 2016-03-03T17:21:03.000Z | 2020-01-22T22:12:02.000Z | li-utils/src/main/javaPegasus/com/linkedin/common/url/Url.java | zhch158/datahub | f2e2a4d5b7041400ab14dfd0109707518b9a02d3 | [
"Apache-2.0"
] | 1,157 | 2016-03-03T19:29:22.000Z | 2020-01-20T14:41:59.000Z | li-utils/src/main/javaPegasus/com/linkedin/common/url/Url.java | zhch158/datahub | f2e2a4d5b7041400ab14dfd0109707518b9a02d3 | [
"Apache-2.0"
] | 570 | 2016-03-03T17:21:05.000Z | 2020-01-21T06:54:10.000Z | 19.179487 | 67 | 0.558824 | 10,750 | package com.linkedin.common.url;
import java.net.URI;
import java.net.URISyntaxException;
public class Url {
private final String _url;
public Url(String url) {
if (url == null) {
throw new NullPointerException("URL must be non-null");
}
_url = url;
}
@Override
public String toString() {
return _url;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Url)) {
return false;
} else {
return _url.equals(((Url) obj)._url);
}
}
@Override
public int hashCode() {
return _url.hashCode();
}
public URI toURI() throws URISyntaxException {
return new URI(_url);
}
}
|
3e1950816097fd80b17949f2eeaf97b3fd12dc39 | 401 | java | Java | commonmark/src/main/java/me/mattstudios/msg/commonmark/node/Delimited.java | TriumphTeam/markdown-msg | 288c01aba2e861f3480e3b357f119ad51346b1a6 | [
"MIT"
] | 4 | 2021-02-07T14:53:47.000Z | 2021-12-20T17:00:24.000Z | commonmark/src/main/java/me/mattstudios/msg/commonmark/node/Delimited.java | ipsk/MF-MSG | 288c01aba2e861f3480e3b357f119ad51346b1a6 | [
"MIT"
] | 3 | 2020-08-25T19:39:05.000Z | 2021-01-13T16:11:47.000Z | commonmark/src/main/java/me/mattstudios/msg/commonmark/node/Delimited.java | TriumphTeam/markdown-msg | 288c01aba2e861f3480e3b357f119ad51346b1a6 | [
"MIT"
] | 2 | 2021-11-25T20:31:34.000Z | 2022-01-30T20:01:44.000Z | 22.277778 | 77 | 0.618454 | 10,751 | package me.mattstudios.msg.commonmark.node;
/**
* A node that uses delimiters in the source form (e.g. <code>*bold*</code>).
*/
public interface Delimited {
/**
* @return the opening (beginning) delimiter, e.g. <code>*</code>
*/
String getOpeningDelimiter();
/**
* @return the closing (ending) delimiter, e.g. <code>*</code>
*/
String getClosingDelimiter();
}
|
3e19512ba313f94ecc9c21b129dc88f506b46b31 | 2,056 | java | Java | sources/androidx/core/database/sqlite/SQLiteDatabaseKt.java | tonioshikanlu/tubman-hack | 8277e47c058174ca4411965ed67d05d2aba1c7fc | [
"MIT"
] | 2 | 2021-03-20T07:33:30.000Z | 2021-06-29T18:50:21.000Z | sources/androidx/core/database/sqlite/SQLiteDatabaseKt.java | tonioshikanlu/tubman-hack | 8277e47c058174ca4411965ed67d05d2aba1c7fc | [
"MIT"
] | null | null | null | sources/androidx/core/database/sqlite/SQLiteDatabaseKt.java | tonioshikanlu/tubman-hack | 8277e47c058174ca4411965ed67d05d2aba1c7fc | [
"MIT"
] | 2 | 2021-03-20T15:56:20.000Z | 2021-03-21T02:06:29.000Z | 43.744681 | 644 | 0.632782 | 10,752 | package androidx.core.database.sqlite;
import android.database.sqlite.SQLiteDatabase;
import e.x.b.l;
import e.x.c.i;
import kotlin.Metadata;
@Metadata(bv = {1, 0, 3}, d1 = {"\u0000\u0014\n\u0000\n\u0002\u0018\u0002\n\u0002\u0010\u000b\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0004\u001a8\u0010\u0006\u001a\u00028\u0000\"\u0004\b\u0000\u0010\u0000*\u00020\u00012\b\b\u0002\u0010\u0003\u001a\u00020\u00022\u0012\u0010\u0005\u001a\u000e\u0012\u0004\u0012\u00020\u0001\u0012\u0004\u0012\u00028\u00000\u0004H\b¢\u0006\u0004\b\u0006\u0010\u0007¨\u0006\b"}, d2 = {"T", "Landroid/database/sqlite/SQLiteDatabase;", "", "exclusive", "Lkotlin/Function1;", "body", "transaction", "(Landroid/database/sqlite/SQLiteDatabase;ZLe/x/b/l;)Ljava/lang/Object;", "core-ktx_release"}, k = 2, mv = {1, 1, 15})
public final class SQLiteDatabaseKt {
public static final <T> T transaction(SQLiteDatabase sQLiteDatabase, boolean z, l<? super SQLiteDatabase, ? extends T> lVar) {
i.f(sQLiteDatabase, "$this$transaction");
i.f(lVar, "body");
if (z) {
sQLiteDatabase.beginTransaction();
} else {
sQLiteDatabase.beginTransactionNonExclusive();
}
try {
T invoke = lVar.invoke(sQLiteDatabase);
sQLiteDatabase.setTransactionSuccessful();
return invoke;
} finally {
sQLiteDatabase.endTransaction();
}
}
public static Object transaction$default(SQLiteDatabase sQLiteDatabase, boolean z, l lVar, int i2, Object obj) {
if ((i2 & 1) != 0) {
z = true;
}
i.f(sQLiteDatabase, "$this$transaction");
i.f(lVar, "body");
if (z) {
sQLiteDatabase.beginTransaction();
} else {
sQLiteDatabase.beginTransactionNonExclusive();
}
try {
Object invoke = lVar.invoke(sQLiteDatabase);
sQLiteDatabase.setTransactionSuccessful();
return invoke;
} finally {
sQLiteDatabase.endTransaction();
}
}
}
|
3e19512e085433ff75479501005fe8a33bd18754 | 1,125 | java | Java | src/main/java/grondag/canvas/pipeline/config/SkyConfig.java | lmvdz/canvas | 21b875ed9fcd8a76bb9992ae814d27e419324f6f | [
"Apache-2.0"
] | 6 | 2021-02-02T13:02:53.000Z | 2021-06-08T16:28:51.000Z | src/main/java/grondag/canvas/pipeline/config/SkyConfig.java | spiralhalo/canvas | e72280adcb23062c7a7735748eb8566256a10f6f | [
"Apache-2.0"
] | null | null | null | src/main/java/grondag/canvas/pipeline/config/SkyConfig.java | spiralhalo/canvas | e72280adcb23062c7a7735748eb8566256a10f6f | [
"Apache-2.0"
] | null | null | null | 28.846154 | 81 | 0.752 | 10,753 | /*
* Copyright 2019, 2020 grondag
*
* 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 grondag.canvas.pipeline.config;
import blue.endless.jankson.JsonObject;
import grondag.canvas.pipeline.config.util.AbstractConfig;
import grondag.canvas.pipeline.config.util.ConfigContext;
public class SkyConfig extends AbstractConfig {
public final float defaultZenithAngle;
SkyConfig (ConfigContext ctx, JsonObject config) {
super(ctx);
defaultZenithAngle = config.getFloat("defaultZenithAngle", 0f);
}
@Override
public boolean validate() {
final boolean valid = true;
return valid;
}
}
|
3e19560734d1504aa8dc5b697caad0857ad9c3e2 | 3,904 | java | Java | cheddar/cheddar-persistence/src/test/java/com/clicktravel/cheddar/infrastructure/persistence/database/exception/NonUniqueResultExceptionTest.java | clicktravel-tajinder/Cheddar | 0c81bc7e426777f39f11500fb6761a8e8d4b3c32 | [
"Apache-2.0"
] | 59 | 2016-07-26T10:45:31.000Z | 2022-02-24T06:31:08.000Z | cheddar/cheddar-persistence/src/test/java/com/clicktravel/cheddar/infrastructure/persistence/database/exception/NonUniqueResultExceptionTest.java | clicktravel-tajinder/Cheddar | 0c81bc7e426777f39f11500fb6761a8e8d4b3c32 | [
"Apache-2.0"
] | 28 | 2016-07-18T15:49:41.000Z | 2021-03-03T13:04:31.000Z | cheddar/cheddar-persistence/src/test/java/com/clicktravel/cheddar/infrastructure/persistence/database/exception/NonUniqueResultExceptionTest.java | clicktravel-tajinder/Cheddar | 0c81bc7e426777f39f11500fb6761a8e8d4b3c32 | [
"Apache-2.0"
] | 33 | 2016-08-16T10:19:46.000Z | 2022-01-06T23:49:36.000Z | 33.084746 | 117 | 0.70082 | 10,754 | /*
* Copyright 2014 Click Travel 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.clicktravel.cheddar.infrastructure.persistence.database.exception;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import com.clicktravel.cheddar.infrastructure.persistence.database.Item;
import com.clicktravel.cheddar.infrastructure.persistence.database.StubItem;
public class NonUniqueResultExceptionTest {
@Test
public void shouldCreateException_withEmptyIdsAndClass() {
// Given
final Class<Item> itemClass = Item.class;
final Collection<Item> itemArray = new ArrayList<Item>();
// When
final NonUniqueResultException nonUniqueResultException = new NonUniqueResultException(itemClass, itemArray);
// Then
assertNotNull(nonUniqueResultException);
assertFalse(nonUniqueResultException.hasResults());
}
@Test
public void shouldNotCreateException_withNullIds() {
// Given
final Class<Item> itemClass = Item.class;
// When
IllegalArgumentException actualException = null;
try {
new NonUniqueResultException(itemClass, null);
} catch (final IllegalArgumentException e) {
actualException = e;
}
// Then
assertNotNull(actualException);
}
@Test
public void shouldCreateException_withIdsAndClass() {
// Given
final Class<Item> itemClass = Item.class;
final Item stubItem = new StubItem();
final Item stubItem2 = new StubItem();
final Collection<Item> itemArray = Arrays.asList(stubItem, stubItem2);
// When
final NonUniqueResultException nonUniqueResultException = new NonUniqueResultException(itemClass, itemArray);
// Then
assertNotNull(nonUniqueResultException);
assertTrue(nonUniqueResultException.hasResults());
}
@Test
public void shouldReturnMessage_withNoItemIds() {
// Given
final Class<Item> itemClass = Item.class;
final Collection<Item> itemArray = new ArrayList<Item>();
final NonUniqueResultException nonUniqueResultException = new NonUniqueResultException(itemClass, itemArray);
// When
final String validMessage = nonUniqueResultException.getMessage();
// Then
assertNotNull(validMessage);
assertTrue(validMessage.contains(itemClass.getName()));
}
@Test
public void shouldReturnMessage_withIds() {
// Given
final Class<Item> itemClass = Item.class;
final Item stubItem = new StubItem();
final Item stubItem2 = new StubItem();
final Collection<Item> itemArray = Arrays.asList(stubItem, stubItem2);
final NonUniqueResultException nonUniqueResultException = new NonUniqueResultException(itemClass, itemArray);
// When
final String validMessage = nonUniqueResultException.getMessage();
// Then
assertNotNull(validMessage);
assertTrue(validMessage.contains(stubItem.toString()));
assertTrue(validMessage.contains(stubItem2.toString()));
assertTrue(validMessage.contains(itemClass.getName()));
}
}
|
3e19572e945ddf767fea673ee83144a4afc1dbdf | 1,434 | java | Java | java/compiler/impl/src/com/intellij/task/impl/ArtifactBuildTaskImpl.java | protector1990/intellij-community | b30024b236e84c803ee0b2df7c39eb18dbcaf827 | [
"Apache-2.0"
] | 1 | 2018-10-03T12:35:12.000Z | 2018-10-03T12:35:12.000Z | java/compiler/impl/src/com/intellij/task/impl/ArtifactBuildTaskImpl.java | protector1990/intellij-community | b30024b236e84c803ee0b2df7c39eb18dbcaf827 | [
"Apache-2.0"
] | null | null | null | java/compiler/impl/src/com/intellij/task/impl/ArtifactBuildTaskImpl.java | protector1990/intellij-community | b30024b236e84c803ee0b2df7c39eb18dbcaf827 | [
"Apache-2.0"
] | 1 | 2018-10-03T12:35:06.000Z | 2018-10-03T12:35:06.000Z | 29.265306 | 91 | 0.751743 | 10,755 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* 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.intellij.task.impl;
import com.intellij.packaging.artifacts.Artifact;
import com.intellij.task.ArtifactBuildTask;
import com.intellij.task.ProjectModelBuildTask;
import org.jetbrains.annotations.NotNull;
/**
* @deprecated to be removed, use {@link ProjectModelBuildTask}
*
* @author Vladislav.Soroka
* @since 5/14/2016
*/
@Deprecated
public class ArtifactBuildTaskImpl extends AbstractBuildTask implements ArtifactBuildTask {
private final Artifact myArtifact;
public ArtifactBuildTaskImpl(Artifact artifact, boolean isIncrementalBuild) {
super(isIncrementalBuild);
myArtifact = artifact;
}
@Override
public Artifact getArtifact() {
return myArtifact;
}
@NotNull
@Override
public String getPresentableName() {
return "Artifact '" + myArtifact.getName() + "' build task";
}
}
|
3e19576fb281740781e13e860678e617dd5285f9 | 1,570 | java | Java | src/main/java/net/canarymod/api/entity/living/animal/CanarySheep.java | walterhiggins/CanaryMod | 7ec4670b23828f2f1978695db7f5c178b07c6894 | [
"Unlicense"
] | 1 | 2020-10-06T20:29:48.000Z | 2020-10-06T20:29:48.000Z | src/main/java/net/canarymod/api/entity/living/animal/CanarySheep.java | walterhiggins/CanaryMod | 7ec4670b23828f2f1978695db7f5c178b07c6894 | [
"Unlicense"
] | null | null | null | src/main/java/net/canarymod/api/entity/living/animal/CanarySheep.java | walterhiggins/CanaryMod | 7ec4670b23828f2f1978695db7f5c178b07c6894 | [
"Unlicense"
] | null | null | null | 18.045977 | 71 | 0.57707 | 10,756 | package net.canarymod.api.entity.living.animal;
import net.canarymod.api.DyeColor;
import net.canarymod.api.entity.EntityType;
import net.minecraft.entity.passive.EntitySheep;
import static net.canarymod.api.entity.EntityType.SHEEP;
/**
* Sheep wrapper implementation
*
* @author Jason (darkdiplomat)
*/
public class CanarySheep extends CanaryAgeableAnimal implements Sheep {
/**
* Constructs a new wrapper for EntitySheep
*
* @param entity the EntitySheep to wrap
*/
public CanarySheep(EntitySheep entity) {
super(entity);
}
/**
* {@inheritDoc}
*/
@Override
public EntityType getEntityType() {
return SHEEP;
}
@Override
public String getFqName() {
return "Sheep";
}
/**
* {@inheritDoc}
*/
@Override
public void eatGrass() {
getHandle().n();
}
/**
* {@inheritDoc}
*/
@Override
public DyeColor getColor() {
return DyeColor.values()[getHandle().bZ()];
}
/**
* {@inheritDoc}
*/
@Override
public void setColor(DyeColor color) {
getHandle().s(color.getDyeColorCode());
}
/**
* {@inheritDoc}
*/
@Override
public boolean isSheared() {
return getHandle().bY();
}
/**
* {@inheritDoc}
*/
@Override
public void setSheared(boolean sheared) {
getHandle().i(sheared);
}
/**
* {@inheritDoc}
*/
@Override
public EntitySheep getHandle() {
return (EntitySheep) entity;
}
}
|
3e195775e75de60fce2aadf468090050ab3775ba | 5,957 | java | Java | backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/irsbroker/GetImageInfoVDSCommand.java | SunOfShine/ovirt-engine | 7684597e2d38ff854e629e5cbcbb9f21888cb498 | [
"Apache-2.0"
] | 1 | 2021-02-02T05:38:35.000Z | 2021-02-02T05:38:35.000Z | backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/irsbroker/GetImageInfoVDSCommand.java | SunOfShine/ovirt-engine | 7684597e2d38ff854e629e5cbcbb9f21888cb498 | [
"Apache-2.0"
] | null | null | null | backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/irsbroker/GetImageInfoVDSCommand.java | SunOfShine/ovirt-engine | 7684597e2d38ff854e629e5cbcbb9f21888cb498 | [
"Apache-2.0"
] | null | null | null | 44.125926 | 171 | 0.639752 | 10,757 | package org.ovirt.engine.core.vdsbroker.irsbroker;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.ImageStatus;
import org.ovirt.engine.core.common.businessentities.VolumeFormat;
import org.ovirt.engine.core.common.businessentities.VolumeType;
import org.ovirt.engine.core.common.errors.VdcBllErrors;
import org.ovirt.engine.core.common.utils.EnumUtils;
import org.ovirt.engine.core.common.vdscommands.GetImageInfoVDSCommandParameters;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
import org.ovirt.engine.core.vdsbroker.vdsbroker.StatusForXmlRpc;
public class GetImageInfoVDSCommand<P extends GetImageInfoVDSCommandParameters> extends IrsBrokerCommand<P> {
protected OneImageInfoReturnForXmlRpc imageInfoReturn;
@Override
protected Object getReturnValueFromBroker() {
return imageInfoReturn;
}
public GetImageInfoVDSCommand(P parameters) {
super(parameters);
}
@Override
protected void ExecuteIrsBrokerCommand() {
imageInfoReturn = getIrsProxy().getVolumeInfo(getParameters().getStorageDomainId().toString(),
getParameters().getStoragePoolId().toString(), getParameters().getImageGroupId().toString(),
getParameters().getImageId().toString());
DiskImage di = null;
try {
ProceedProxyReturnValue();
di = buildImageEntity(imageInfoReturn.mInfo);
} catch (java.lang.Exception e) {
PrintReturnValue();
// nothing to do - logging inside upper functions
} finally {
// if couldn't parse image then succeeded should be false
getVDSReturnValue().setSucceeded((di != null));
setReturnValue(di);
}
}
@Override
protected StatusForXmlRpc getReturnStatus() {
return imageInfoReturn.mStatus;
}
@Override
protected void ProceedProxyReturnValue() {
VdcBllErrors returnStatus = GetReturnValueFromStatus(getReturnStatus());
if (returnStatus != VdcBllErrors.Done) {
log.errorFormat(
"IrsBroker::getImageInfo::Failed getting image info imageId = {0} does not exist on domainName = {1} , domainId = {2}, error code: {3}, message: {4}",
getParameters().getImageId().toString(),
DbFacade.getInstance().getStorageDomainStaticDao()
.get(getParameters().getStorageDomainId())
.getStorageName(),
getParameters()
.getStorageDomainId().toString(),
returnStatus
.toString(),
imageInfoReturn.mStatus.mMessage);
throw new IRSErrorException(returnStatus.toString());
}
}
/**
* <exception>VdcDAL.IrsBrokerIRSErrorException.
*/
public DiskImage buildImageEntity(Map<String, Object> xmlRpcStruct) {
DiskImage newImage = new DiskImage();
try {
newImage.setImageId(new Guid((String) xmlRpcStruct.get(IrsProperties.uuid)));
newImage.setParentId(new Guid((String) xmlRpcStruct.get(IrsProperties.parent)));
newImage.setDescription((String) xmlRpcStruct.get(IrsProperties.description));
newImage.setImageStatus(EnumUtils.valueOf(ImageStatus.class,
(String) xmlRpcStruct.get(IrsProperties.ImageStatus), true));
if (xmlRpcStruct.containsKey(IrsProperties.size)) {
newImage.setSize(Long.parseLong(xmlRpcStruct.get(IrsProperties.size).toString()) * 512);
}
if (xmlRpcStruct.containsKey("capacity")) {
newImage.setSize(Long.parseLong(xmlRpcStruct.get("capacity").toString()));
}
if (xmlRpcStruct.containsKey("truesize")) {
newImage.setActualSizeInBytes(Long.parseLong(xmlRpcStruct.get("truesize").toString()));
}
if (xmlRpcStruct.containsKey("ctime")) {
long secsSinceEpoch = Long.parseLong(xmlRpcStruct.get("ctime").toString());
newImage.setCreationDate(MakeDTFromCTime(secsSinceEpoch));
}
if (xmlRpcStruct.containsKey("mtime")) {
long secsSinceEpoch = Long.parseLong(xmlRpcStruct.get("mtime").toString());
newImage.setLastModifiedDate(MakeDTFromCTime(secsSinceEpoch));
}
if (xmlRpcStruct.containsKey("domain")) {
newImage.setStorageIds(new ArrayList<Guid>(Arrays.asList(new Guid(xmlRpcStruct.get("domain").toString()))));
}
if (xmlRpcStruct.containsKey("image")) {
newImage.setimage_group_id(new Guid(xmlRpcStruct.get("image").toString()));
}
if (xmlRpcStruct.containsKey("type")) {
newImage.setVolumeType(EnumUtils.valueOf(VolumeType.class, xmlRpcStruct.get("type").toString(),
true));
}
if (xmlRpcStruct.containsKey("format")) {
newImage.setvolumeFormat(EnumUtils.valueOf(VolumeFormat.class, xmlRpcStruct.get("format")
.toString(), true));
}
} catch (RuntimeException ex) {
log.errorFormat("irsBroker::buildImageEntity::Failed building DIskImage");
PrintReturnValue();
log.error(ex.getMessage(), ex);
newImage = null;
}
return newImage;
}
private static java.util.Date MakeDTFromCTime(long ctime) {
return new Date(ctime * 1000L);
}
private static Log log = LogFactory.getLog(GetImageInfoVDSCommand.class);
}
|
3e1957ac236dc9cadb94eed297efc3cc66d405d9 | 681 | java | Java | src/com/tetris/game/things/tetrominoes/TetrominoEnum.java | smk291/tetris | e5533aba0129d82a05205a6955bab3db89887c7f | [
"MIT"
] | 2 | 2021-04-18T19:37:02.000Z | 2021-11-06T12:50:02.000Z | src/com/tetris/game/things/tetrominoes/TetrominoEnum.java | smk291/tetris | e5533aba0129d82a05205a6955bab3db89887c7f | [
"MIT"
] | null | null | null | src/com/tetris/game/things/tetrominoes/TetrominoEnum.java | smk291/tetris | e5533aba0129d82a05205a6955bab3db89887c7f | [
"MIT"
] | null | null | null | 20.029412 | 61 | 0.687225 | 10,758 | package com.tetris.game.things.tetrominoes;
import com.tetris.game.things.Tetromino;
import java.util.Random;
public enum TetrominoEnum {
I(new IBlock()),
O(new OBlock()),
L(new LBlock()),
J(new JBlock()),
T(new TBlock()),
S(new SBlock()),
Z(new ZBlock());
public static final TetrominoEnum[] blocksArray = values();
public static final int enumSize = blocksArray.length;
public static final Random r = new Random();
Tetromino block;
TetrominoEnum(Tetromino block) {
this.block = block;
}
public static Tetromino getTetromino() {
return blocksArray[r.nextInt(enumSize)].block;
}
public Tetromino get() {
return this.block;
}
}
|
3e19585c4df97730ba3043b5c40f4875d9633cc2 | 2,701 | java | Java | tutorials-convert/src/main/java/org/netbeans/tools/tutorials/ExternalLinksMap.java | borisheithecker/incubator-netbeans-tools | ab4c20f291c04b91f96c234b6e3e6a92c0e46ddd | [
"Apache-2.0"
] | 10 | 2019-05-20T18:49:33.000Z | 2022-03-24T23:27:58.000Z | tutorials-convert/src/main/java/org/netbeans/tools/tutorials/ExternalLinksMap.java | borisheithecker/incubator-netbeans-tools | ab4c20f291c04b91f96c234b6e3e6a92c0e46ddd | [
"Apache-2.0"
] | 22 | 2019-10-15T13:34:29.000Z | 2022-01-28T10:16:17.000Z | tutorials-convert/src/main/java/org/netbeans/tools/tutorials/ExternalLinksMap.java | borisheithecker/incubator-netbeans-tools | ab4c20f291c04b91f96c234b6e3e6a92c0e46ddd | [
"Apache-2.0"
] | 16 | 2019-05-20T18:49:22.000Z | 2021-11-13T02:09:33.000Z | 32.939024 | 91 | 0.639023 | 10,759 | /*
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.tools.tutorials;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Maps external links (String, href) to File's referencing it.
*/
public class ExternalLinksMap {
/** Maps "href" to tutorials. */
private TreeMap<String, TreeSet<String>> hrefToFile;
/** Maps domain names ("bits.netbeans.org", for instance) to hrefs */
private TreeMap<String, TreeSet<String>> domainToHref;
public ExternalLinksMap() {
hrefToFile = new TreeMap<>();
domainToHref = new TreeMap<>();
}
public void addExternalLink(String href, String tutorial) {
try {
URL url = new URL(href);
TreeSet<String> hrefs = domainToHref.get(url.getHost());
if (hrefs == null) {
hrefs = new TreeSet<>();
domainToHref.put(url.getHost(), hrefs);
}
hrefs.add(href);
TreeSet<String> tutorials = hrefToFile.get(href);
if (tutorials == null) {
tutorials = new TreeSet<>();
hrefToFile.put(href, tutorials);
}
tutorials.add(tutorial);
} catch (MalformedURLException ex) {
Logger.getLogger(ExternalLinksMap.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Set<String> getDomains() {
return domainToHref.keySet();
}
public Set<String> getHrefs(String domain) {
return domainToHref.get(domain);
}
public Set<String> getTutorials(String href) {
return hrefToFile.get(href);
}
@Override
public String toString() {
return domainToHref.toString() + " " + hrefToFile.toString();
}
}
|
3e19595ea6bc19b512cf4be625ecf7fcce01be5b | 7,775 | java | Java | src/test/java/seedu/budgeteer/logic/commands/CommandTestUtil.java | frankquekch/main | 3e47187854744d02e31519bf59e3d0f2f14786f7 | [
"MIT"
] | 1 | 2019-03-21T02:38:54.000Z | 2019-03-21T02:38:54.000Z | src/test/java/seedu/budgeteer/logic/commands/CommandTestUtil.java | frankquekch/main | 3e47187854744d02e31519bf59e3d0f2f14786f7 | [
"MIT"
] | 65 | 2019-02-18T23:49:25.000Z | 2019-04-29T18:21:27.000Z | src/test/java/seedu/budgeteer/logic/commands/CommandTestUtil.java | frankquekch/main | 3e47187854744d02e31519bf59e3d0f2f14786f7 | [
"MIT"
] | 12 | 2019-02-12T04:30:57.000Z | 2019-04-09T07:28:38.000Z | 50.16129 | 116 | 0.703151 | 10,760 | package seedu.budgeteer.logic.commands;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static seedu.budgeteer.logic.parser.CliSyntax.PREFIX_CASHFLOW;
import static seedu.budgeteer.logic.parser.CliSyntax.PREFIX_DATE;
import static seedu.budgeteer.logic.parser.CliSyntax.PREFIX_NAME;
import static seedu.budgeteer.logic.parser.CliSyntax.PREFIX_TAG;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import seedu.budgeteer.commons.core.index.Index;
import seedu.budgeteer.logic.CommandHistory;
import seedu.budgeteer.logic.commands.exceptions.CommandException;
import seedu.budgeteer.model.EntriesBook;
import seedu.budgeteer.model.Model;
import seedu.budgeteer.model.entry.Entry;
import seedu.budgeteer.model.entry.NameContainsKeywordsPredicate;
import seedu.budgeteer.testutil.EditEntryDescriptorBuilder;
/**
* Contains helper methods for testing commands.
*/
public class CommandTestUtil {
public static final String VALID_NAME_AMY = "Allowance from Amy";
public static final String VALID_NAME_BOB = "Payment from Bob";
public static final String VALID_DATE_AMY = "11-10-2004";
public static final String VALID_DATE_BOB = "11-02-2004";
public static final String VALID_CASHFLOW_AMY = "+10.90";
public static final String VALID_CASHFLOW_BOB = "-11.50";
public static final String VALID_TAG_HUSBAND = "husband";
public static final String VALID_TAG_FRIEND = "friend";
public static final String NAME_DESC_AMY = " " + PREFIX_NAME + VALID_NAME_AMY;
public static final String NAME_DESC_BOB = " " + PREFIX_NAME + VALID_NAME_BOB;
public static final String DATE_DESC_AMY = " " + PREFIX_DATE + VALID_DATE_AMY;
public static final String DATE_DESC_BOB = " " + PREFIX_DATE + VALID_DATE_BOB;
public static final String CASHFLOW_DESC_AMY = " " + PREFIX_CASHFLOW + VALID_CASHFLOW_AMY;
public static final String CASHFLOW_DESC_BOB = " " + PREFIX_CASHFLOW + VALID_CASHFLOW_BOB;
public static final String TAG_DESC_FRIEND = " " + PREFIX_TAG + VALID_TAG_FRIEND;
public static final String TAG_DESC_HUSBAND = " " + PREFIX_TAG + VALID_TAG_HUSBAND;
public static final String INVALID_NAME_DESC = " " + PREFIX_NAME + "James&"; // '&' not allowed in names
public static final String INVALID_DATE_DESC = " " + PREFIX_DATE + "911a"; // alphabets not allowed in date
public static final String INVALID_CASHFLOW_DESC = " "
+ PREFIX_CASHFLOW + "11."; // missing digit after decimal point
public static final String INVALID_TAG_DESC = " " + PREFIX_TAG + "hubby*"; // '*' not allowed in tags
public static final String PREAMBLE_WHITESPACE = "\t \r \n";
public static final String PREAMBLE_NON_EMPTY = "NonEmptyPreamble";
public static final EditCommand.EditEntryDescriptor DESC_AMY;
public static final EditCommand.EditEntryDescriptor DESC_BOB;
static {
DESC_AMY = new EditEntryDescriptorBuilder().withName(VALID_NAME_AMY)
.withDate(VALID_DATE_AMY).withCashFlow(VALID_CASHFLOW_AMY).withTags(VALID_TAG_FRIEND).build();
DESC_BOB = new EditEntryDescriptorBuilder().withName(VALID_NAME_BOB)
.withDate(VALID_DATE_BOB).withCashFlow(VALID_CASHFLOW_BOB)
.withTags(VALID_TAG_HUSBAND, VALID_TAG_FRIEND).build();
}
/**
* Executes the given {@code command}, confirms that <br>
* - the result message matches {@code expectedMessage} <br>
* - the {@code actualModel} matches {@code expectedModel} <br>
* - the {@code actualCommandHistory} remains unchanged.
*/
public static void assertCommandSuccess(Command command, Model actualModel, CommandHistory actualCommandHistory,
String expectedMessage, Model expectedModel) {
CommandHistory expectedCommandHistory = new CommandHistory(actualCommandHistory);
try {
CommandResult result = command.execute(actualModel, actualCommandHistory);
assertEquals(expectedMessage, result.getFeedbackToUser());
assertEquals(expectedModel, actualModel);
assertEquals(expectedCommandHistory, actualCommandHistory);
} catch (CommandException ce) {
throw new AssertionError("Execution of command should not fail.", ce);
}
}
/**
* Executes the given {@code command}, confirms that <br>
* - the {@code actualModel} matches {@code expectedModel} <br>
* - the {@code actualCommandHistory} remains unchanged.
*/
public static void assertCommandSuccessWithoutString(Command command, Model actualModel,
CommandHistory actualCommandHistory,
Model expectedModel) {
CommandHistory expectedCommandHistory = new CommandHistory(actualCommandHistory);
try {
CommandResult result = command.execute(actualModel, actualCommandHistory);
assertEquals(expectedModel, actualModel);
assertEquals(expectedCommandHistory, actualCommandHistory);
} catch (CommandException ce) {
throw new AssertionError("Execution of command should not fail.", ce);
}
}
/**
* Executes the given {@code command}, confirms that <br>
* - a {@code CommandException} is thrown <br>
* - the CommandException message matches {@code expectedMessage} <br>
* - the budgeteer book and the filtered entry list in the {@code actualModel} remain unchanged <br>
* - {@code actualCommandHistory} remains unchanged.
*/
public static void assertCommandFailure(Command command, Model actualModel, CommandHistory actualCommandHistory,
String expectedMessage) {
// we are unable to defensively copy the model for comparison later, so we can
// only do so by copying its components.
EntriesBook expectedEntriesBook = new EntriesBook(actualModel.getAddressBook());
List<Entry> expectedFilteredList = new ArrayList<>(actualModel.getFilteredEntryList());
CommandHistory expectedCommandHistory = new CommandHistory(actualCommandHistory);
try {
command.execute(actualModel, actualCommandHistory);
throw new AssertionError("The expected CommandException was not thrown.");
} catch (CommandException e) {
assertEquals(expectedMessage, e.getMessage());
assertEquals(expectedEntriesBook, actualModel.getAddressBook());
assertEquals(expectedFilteredList, actualModel.getFilteredEntryList());
assertEquals(expectedCommandHistory, actualCommandHistory);
}
}
/**
* Updates {@code model}'s filtered list to show only the entry at the given {@code targetIndex} in the
* {@code model}'s budgeteer book.
*/
// TODO: Look at this code again
public static void showEntryAtIndex(Model model, Index targetIndex) {
assertTrue(targetIndex.getZeroBased() < model.getFilteredEntryList().size());
Entry entry = model.getFilteredEntryList().get(targetIndex.getZeroBased());
final String[] splitName = entry.getName().fullName.split("\\s+");
model.updateFilteredEntryList(new NameContainsKeywordsPredicate(Arrays.asList(splitName[0])));
assertEquals(1, model.getFilteredEntryList().size());
}
/**
* Deletes the first entry in {@code model}'s filtered list from {@code model}'s budgeteer book.
*/
public static void deleteFirstEntry(Model model) {
Entry firstEntry = model.getFilteredEntryList().get(0);
model.deleteEntry(firstEntry);
model.commitAddressBook();
}
}
|
3e1959722bfd085481d2b2775fc6cbdbfc05f2ba | 477 | java | Java | sql/core/target/java/org/apache/spark/sql/execution/UnaryExecNode$.java | Y-sir/spark-cn | 06a0459999131ee14864a69a15746c900e815a14 | [
"BSD-2-Clause",
"Apache-2.0",
"CC0-1.0",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | sql/core/target/java/org/apache/spark/sql/execution/UnaryExecNode$.java | Y-sir/spark-cn | 06a0459999131ee14864a69a15746c900e815a14 | [
"BSD-2-Clause",
"Apache-2.0",
"CC0-1.0",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | sql/core/target/java/org/apache/spark/sql/execution/UnaryExecNode$.java | Y-sir/spark-cn | 06a0459999131ee14864a69a15746c900e815a14 | [
"BSD-2-Clause",
"Apache-2.0",
"CC0-1.0",
"MIT",
"MIT-0",
"ECL-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | 47.7 | 174 | 0.748428 | 10,761 | package org.apache.spark.sql.execution;
public class UnaryExecNode$ implements scala.Serializable {
/**
* Static reference to the singleton instance of this Scala object.
*/
public static final UnaryExecNode$ MODULE$ = null;
public UnaryExecNode$ () { throw new RuntimeException(); }
public scala.Option<scala.Tuple2<org.apache.spark.sql.execution.SparkPlan, org.apache.spark.sql.execution.SparkPlan>> unapply (Object a) { throw new RuntimeException(); }
}
|
3e1959dd8869e206e134460df386255414f0cf68 | 11,007 | java | Java | java/common/src/test/java/org/apache/shindig/common/JsonSerializerTest.java | EdiaEducationTechnology/shindig | 38e3d6f6fedc977c81474dd8202a14c899f30442 | [
"Apache-2.0"
] | 16 | 2015-02-16T16:28:31.000Z | 2022-01-04T10:59:08.000Z | java/common/src/test/java/org/apache/shindig/common/JsonSerializerTest.java | EdiaEducationTechnology/shindig | 38e3d6f6fedc977c81474dd8202a14c899f30442 | [
"Apache-2.0"
] | 101 | 2016-02-29T10:58:07.000Z | 2016-02-29T16:01:57.000Z | java/common/src/test/java/org/apache/shindig/common/JsonSerializerTest.java | OpenDashboards/apache-shindig | 8f3c3d5c77f5324bad56a5a62da28657fe9112a0 | [
"Apache-2.0"
] | 26 | 2015-04-05T10:04:22.000Z | 2021-11-10T18:40:05.000Z | 32.95509 | 103 | 0.664305 | 10,762 | /*
* 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.shindig.common;
import static org.apache.shindig.common.JsonAssert.assertJsonEquals;
import static org.junit.Assert.assertEquals;
import com.google.common.base.Strings;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.LinkedHashMultimap;
/**
* Tests for JsonSerializer.
*
* This class may be executed to perform micro benchmarks comparing the performance of the
* serializer with that of json.org and net.sf.json.
*/
public class JsonSerializerTest {
private static final String JSON_POJO_AS_JSON = "{string:'string-value',integer:100,'simple!':3}";
@Test
public void serializeSimpleJsonObject() throws Exception {
String json = "{foo:'bar'}";
assertJsonEquals(json, JsonSerializer.serialize(new JSONObject(json)));
}
@Test
public void serializeSimpleMap() throws Exception {
Map<String, String> map = new HashMap<String, String>(3, 1);
map.put("hello", "world");
map.put("foo", "bar");
map.put("remove", null);
assertJsonEquals("{hello:'world',foo:'bar'}", JsonSerializer.serialize(map));
}
@Test
public void serializeSimpleMultimap() throws Exception {
Multimap<String, String> map = LinkedHashMultimap.create();
Set<String> methods = ImmutableSet.of("system.listMethods", "people.get");
map.putAll("hostEndpoint", methods);
assertJsonEquals("{hostEndpoint : ['system.listMethods', 'people.get']}",
JsonSerializer.serialize(map));
}
@Test
public void serializeSimpleCollection() throws Exception {
Collection<String> collection = Arrays.asList("foo", null, "bar", "baz", null);
assertJsonEquals("['foo','bar','baz']", JsonSerializer.serialize(collection));
}
@Test
public void serializeArray() throws Exception {
String[] array = {"foo", null, "bar", "baz"};
assertJsonEquals("['foo','bar','baz']", JsonSerializer.serialize(array));
}
@Test
public void serializeJsonArray() throws Exception {
JSONArray array = new JSONArray(new String[] {"foo", null, "bar", "baz"});
assertJsonEquals("['foo','bar','baz']", JsonSerializer.serialize(array));
}
@Test
public void serializeJsonObjectWithComplexArray() throws Exception {
JSONArray array = new JSONArray();
array.put(new JsonPojo());
JSONObject object = new JSONObject();
object.put("array", array);
assertJsonEquals("{'array': [" + JSON_POJO_AS_JSON + "]}", JsonSerializer.serialize(object));
}
@Test
public void serializeJsonObjectWithNullPropertyValue() throws Exception {
String json = "{foo:null}";
assertJsonEquals(json, JsonSerializer.serialize(new JSONObject(json)));
}
@Test
public void serializePrimitives() throws Exception {
assertEquals("null", JsonSerializer.serialize((Object) null));
assertEquals("\"hello\"", JsonSerializer.serialize("hello"));
assertEquals("100", JsonSerializer.serialize(100));
assertEquals("125.0", JsonSerializer.serialize(125.0f));
assertEquals("126.0", JsonSerializer.serialize(126.0));
assertEquals("1", JsonSerializer.serialize(1L));
assertEquals("\"RUNTIME\"", JsonSerializer.serialize(RetentionPolicy.RUNTIME));
assertEquals("\"string buf\"",
JsonSerializer.serialize(new StringBuilder().append("string").append(' ').append("buf")));
}
public static class JsonPojo {
public String getString() {
return "string-value";
}
@SuppressWarnings("unused")
private String getPrivateString() {
throw new UnsupportedOperationException();
}
public int getInteger() {
return 100;
}
@JsonProperty("simple!")
public int getSimpleName() {
return 3;
}
public Object getNullValue() {
return null;
}
@JsonProperty("simple!")
public void setSimpleName(int foo) {
}
@JsonProperty("invalid-setter-two-args")
public void setInvalidSetterTwoArgs(String foo, String bar) {
}
@JsonProperty("invalid-setter-no-args")
public void setInvalidSetterNoArgs() {
}
@JsonProperty("invalid-getter-args")
public String getInvalidGetterWithArgs(String foo) {
return "invalid";
}
}
@Test
public void serializePojo() throws Exception {
JsonPojo pojo = new JsonPojo();
assertJsonEquals(JSON_POJO_AS_JSON,
JsonSerializer.serialize(pojo));
}
@Test
public void serializeMixedObjects() throws Exception {
Map<String, ?> map = ImmutableMap.of(
"int", Integer.valueOf(3),
"double", Double.valueOf(2.7d),
"bool", Boolean.TRUE,
"map", ImmutableMap.of("hello", "world", "foo", "bar"),
"string", "hello!");
assertJsonEquals(
"{int:3,double:2.7,bool:true,map:{hello:'world',foo:'bar'},string:'hello!'}",
JsonSerializer.serialize(map));
}
@Test
public void serializeMixedArray() throws Exception {
Collection<Object> data = Arrays.asList(
Integer.valueOf(3),
Double.valueOf(2.7d),
Boolean.TRUE,
Arrays.asList("one", "two", "three"),
new JSONArray(new String[] {"foo", "bar"}),
"hello!");
assertJsonEquals(
"[3,2.7,true,['one','two','three'],['foo','bar'],'hello!']",
JsonSerializer.serialize(data));
}
@Test
public void emptyString() throws Exception {
StringBuilder builder = new StringBuilder();
JsonSerializer.appendString(builder, "");
assertEquals("\"\"", builder.toString());
}
@Test
public void escapeSequences() throws Exception {
StringBuilder builder = new StringBuilder();
JsonSerializer.appendString(builder, "\t\r value \\\foo\b\uFFFF\uBCAD\n\u0083");
assertEquals("\"\\t\\r value \\\\\\foo\\b\uFFFF\uBCAD\\n\\u0083\"", builder.toString());
}
@Test
public void escapeBrackets() throws Exception {
StringBuilder builder = new StringBuilder();
JsonSerializer.appendString(builder, "Hello<world>foo < bar");
assertEquals("\"Hello\\u003cworld\\u003efoo \\u003c bar\"", builder.toString());
// Quick sanity check to make sure that this converts back cleanly.
JSONObject obj = new JSONObject("{foo:" + builder + '}');
assertEquals("Hello<world>foo < bar", obj.get("foo"));
}
private static String avg(long start, long end, long runs) {
double delta = end - start;
return String.format("%f5", delta / runs);
}
private static String runJsonOrgTest(Map<String, Object> data, int iterations) {
org.json.JSONObject object = new org.json.JSONObject(data);
long start = System.currentTimeMillis();
String result = null;
for (int i = 0; i < iterations; ++i) {
result = object.toString();
}
System.out.println("json.org: " + avg(start, System.currentTimeMillis(), iterations) + "ms");
return result;
}
private static String runSerializerTest(Map<String, Object> data, int iterations) {
long start = System.currentTimeMillis();
String result = null;
for (int i = 0; i < iterations; ++i) {
result = JsonSerializer.serialize(data);
}
System.out.println("serializer: " + avg(start, System.currentTimeMillis(), iterations) + "ms");
return result;
}
// private static String runNetSfJsonTest(Map<String, Object> data, int iterations) {
// net.sf.json.JSONObject object = net.sf.json.JSONObject.fromObject(data);
// long start = System.currentTimeMillis();
// String result = null;
// for (int i = 0; i < iterations; ++i) {
// result = object.toString();
// }
// System.out.println("net.sf.json: " + avg(start, System.currentTimeMillis(), iterations) + "ms");
// return result;
// }
public static Map<String, Object> perfComparison100SmallValues() {
Map<String, Object> data = Maps.newHashMap();
for (int i = 0; i < 100; ++i) {
data.put("key-" + i, "small value");
}
return data;
}
public static Map<String, Object> perfComparison1000SmallValues() {
Map<String, Object> data = Maps.newHashMap();
for (int i = 0; i < 1000; ++i) {
data.put("key-" + i, "small value");
}
return data;
}
public static Map<String, Object> perfComparison100LargeValues() {
Map<String, Object> data = Maps.newHashMap();
for (int i = 0; i < 100; ++i) {
data.put("key-" + i, Strings.repeat("small value", 100));
}
return data;
}
public static Map<String, Object> perfComparison10LargeValuesAndEscapes() {
Map<String, Object> data = Maps.newHashMap();
for (int i = 0; i < 10; ++i) {
data.put("key-" + i, Strings.repeat("\tsmall\r value \\foo\b\uFFFF\uBCAD\n\u0083", 100));
}
return data;
}
public static Map<String, Object> perfComparison100Arrays() {
Map<String, Object> data = Maps.newHashMap();
String[] array = {
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"
};
for (int i = 0; i < 100; ++i) {
data.put("key-" + i, array);
}
return data;
}
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
int iterations = args.length > 0 ? Integer.parseInt(args[0]) : 1000;
System.out.println("Running tests with " + iterations + " iterations.");
for (Method method : JsonSerializerTest.class.getMethods()) {
if (method.getName().startsWith("perfComparison")) {
Map<String, Object> data = (Map<String, Object>)method.invoke(null);
System.out.println("Running: " + method.getName());
runJsonOrgTest(data, iterations);
runSerializerTest(data, iterations);
// if (!jsonEquals(jsonOrg, netSfJson)) {
// System.out.println("net.sf.json did not produce results matching the reference impl.");
// }
System.out.println("-----------------------");
}
}
System.out.println("Done");
}
}
|
3e1959ede2ac9ddb8d0df5b53698f4b95cb1180f | 1,081 | java | Java | src/module1/map_ex1.java | Zhao-DU/unfoldingmaps | 51417c7ef14f56e8391dcb83b9e6c25546d0c493 | [
"MIT"
] | null | null | null | src/module1/map_ex1.java | Zhao-DU/unfoldingmaps | 51417c7ef14f56e8391dcb83b9e6c25546d0c493 | [
"MIT"
] | null | null | null | src/module1/map_ex1.java | Zhao-DU/unfoldingmaps | 51417c7ef14f56e8391dcb83b9e6c25546d0c493 | [
"MIT"
] | null | null | null | 24.568182 | 72 | 0.625347 | 10,763 | package module1;
import processing.core.PApplet;
import de.fhpotsdam.unfolding.UnfoldingMap;
import de.fhpotsdam.unfolding.geo.Location;
import de.fhpotsdam.unfolding.providers.*;
import de.fhpotsdam.unfolding.utils.*;
public class map_ex1 extends PApplet{
UnfoldingMap map;
public void setup() {
size(800, 600);
map = new UnfoldingMap(this, new Microsoft.AerialProvider());
// Show map around the location in the given zoom level.
map.zoomAndPanTo(new Location(52.5f, 13.4f), 10);
// Add mouse and keyboard interactions
MapUtils.createDefaultEventDispatcher(this, map);
}
public void draw() {
map.draw();
Location location = map.getLocation(mouseX, mouseY);
fill(0);
/*
* @args:
* String: text to display
* float x: x coordinate of where text is to be displayed
* float y: y coordinate of where text is to be displayed
*/
text(location.getLat() + ", " + location.getLon(), mouseX, mouseY);
}
}
|
3e195b36d84298376501ed4b1191dae3bc09f89b | 1,161 | java | Java | logreport/src/main/java/com/wenming/library/upload/ILogUpload.java | bdxtx/CscUtils | 2f323be6f50e57f73408b46cb495ef0c368236f1 | [
"Apache-2.0"
] | null | null | null | logreport/src/main/java/com/wenming/library/upload/ILogUpload.java | bdxtx/CscUtils | 2f323be6f50e57f73408b46cb495ef0c368236f1 | [
"Apache-2.0"
] | null | null | null | logreport/src/main/java/com/wenming/library/upload/ILogUpload.java | bdxtx/CscUtils | 2f323be6f50e57f73408b46cb495ef0c368236f1 | [
"Apache-2.0"
] | null | null | null | 25.8 | 96 | 0.696813 | 10,764 | /*
* @(#)CrashListener.java Project: crash
* Date:2014-5-27
*
* Copyright (c) 2014 CFuture09, Institute of Software,
* Guangdong Ocean University, Zhanjiang, GuangDong, China.
* 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 com.wenming.library.upload;
import java.io.File;
/**
* 上传日志的接口
*/
public interface ILogUpload {
interface OnUploadFinishedListener {
void onSuceess();
void onError(String error);
}
/**
* 发送日志文件。
*
* @param file 发送的文件
*/
void sendFile(File file, String content, OnUploadFinishedListener onUploadFinishedListener);
} |
3e195b43486d20cb8372f237e644e1adb9dd0684 | 255 | java | Java | src/test/java/org/frankframework/frankdoc/testtarget/type/defaultElement/Master.java | ibissource/frank-doc | 0de43ff394817d38f193c4eb4fcab85caa04317f | [
"Apache-2.0"
] | null | null | null | src/test/java/org/frankframework/frankdoc/testtarget/type/defaultElement/Master.java | ibissource/frank-doc | 0de43ff394817d38f193c4eb4fcab85caa04317f | [
"Apache-2.0"
] | 68 | 2021-10-04T07:52:15.000Z | 2022-03-25T13:06:08.000Z | src/test/java/org/frankframework/frankdoc/testtarget/type/defaultElement/Master.java | ibissource/frank-doc | 0de43ff394817d38f193c4eb4fcab85caa04317f | [
"Apache-2.0"
] | 2 | 2021-10-04T07:41:00.000Z | 2022-03-14T07:35:51.000Z | 19.615385 | 67 | 0.788235 | 10,765 | package org.frankframework.frankdoc.testtarget.type.defaultElement;
public class Master {
public void registerA(IDefaultFromConflict child) {
}
public void registerB(IDefaultFromJavaDocTag child) {
}
public void registerC(INoDefault child) {
}
}
|
3e195bc8fafcb410c21de5979501451e5e453c88 | 14,798 | java | Java | db4o.j/db4o-core/bloat/src/EDU/purdue/cs/bloat/tree/PrintVisitor.java | iboxdb/db4o-gpl | 16a56c3517d9b69f7fd1f915f4fd5b2218ced1f0 | [
"Net-SNMP",
"Xnet"
] | 24 | 2019-08-25T12:58:07.000Z | 2022-03-04T11:20:37.000Z | db4o.j/db4o-core/bloat/src/EDU/purdue/cs/bloat/tree/PrintVisitor.java | iboxdb/db4o-gpl | 16a56c3517d9b69f7fd1f915f4fd5b2218ced1f0 | [
"Net-SNMP",
"Xnet"
] | null | null | null | db4o.j/db4o-core/bloat/src/EDU/purdue/cs/bloat/tree/PrintVisitor.java | iboxdb/db4o-gpl | 16a56c3517d9b69f7fd1f915f4fd5b2218ced1f0 | [
"Net-SNMP",
"Xnet"
] | 10 | 2019-08-30T10:25:41.000Z | 2022-02-13T17:40:23.000Z | 20.051491 | 81 | 0.58812 | 10,766 | /*
* All files in the distribution of BLOAT (Bytecode Level Optimization and
* Analysis tool for Java(tm)) are Copyright 1997-2001 by the Purdue
* Research Foundation of Purdue University. All rights reserved.
*
* This library 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 library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package EDU.purdue.cs.bloat.tree;
import java.io.*;
import java.util.*;
import EDU.purdue.cs.bloat.cfg.*;
/**
* PrintVistor traverses a Tree and prints some information about each visited
* Node to a stream.
*/
public class PrintVisitor extends TreeVisitor {
protected PrintWriter out; // The stream to which we are printing
/**
* Constructor. Prints to System.out.
*/
public PrintVisitor() {
this(System.out);
}
public PrintVisitor(final Writer out) {
this.out = new PrintWriter(out);
}
public PrintVisitor(final PrintStream out) {
this.out = new PrintWriter(out);
}
protected void println() {
out.println();
}
protected void println(final Object s) {
out.println(s);
}
protected void print(final Object s) {
out.print(s);
}
public void visitFlowGraph(final FlowGraph cfg) {
cfg.source().visit(this);
final Iterator e = cfg.trace().iterator();
while (e.hasNext()) {
final Block block = (Block) e.next();
block.visit(this);
}
cfg.sink().visit(this);
this.out.flush();
}
public void visitBlock(final Block block) {
println();
println(block);
final Handler handler = (Handler) block.graph().handlersMap()
.get(block);
if (handler != null) {
println("catches " + handler.catchType());
println("protects " + handler.protectedBlocks());
}
block.visitChildren(this);
}
public void visitExprStmt(final ExprStmt stmt) {
print("eval ");
stmt.expr().visit(this);
println();
}
public void visitIfZeroStmt(final IfZeroStmt stmt) {
print("if0 (");
stmt.expr().visit(this);
print(" ");
switch (stmt.comparison()) {
case IfStmt.EQ:
print("==");
break;
case IfStmt.NE:
print("!=");
break;
case IfStmt.GT:
print(">");
break;
case IfStmt.GE:
print(">=");
break;
case IfStmt.LT:
print("<");
break;
case IfStmt.LE:
print("<=");
break;
}
if (stmt.expr().type().isReference()) {
print(" null");
} else {
print(" 0");
}
print(") then " + stmt.trueTarget() + " else " + stmt.falseTarget());
println(" caught by " + stmt.catchTargets());
}
public void visitIfCmpStmt(final IfCmpStmt stmt) {
print("if (");
stmt.left().visit(this);
print(" ");
switch (stmt.comparison()) {
case IfStmt.EQ:
print("==");
break;
case IfStmt.NE:
print("!=");
break;
case IfStmt.GT:
print(">");
break;
case IfStmt.GE:
print(">=");
break;
case IfStmt.LT:
print("<");
break;
case IfStmt.LE:
print("<=");
break;
}
print(" ");
if (stmt.right() != null) {
stmt.right().visit(this);
}
print(") then " + stmt.trueTarget() + " else " + stmt.falseTarget());
println(" caught by " + stmt.catchTargets());
}
public void visitInitStmt(final InitStmt stmt) {
print("INIT");
final LocalExpr[] t = stmt.targets();
if (t != null) {
for (int i = 0; i < t.length; i++) {
if (t[i] != null) {
print(" ");
t[i].visit(this);
}
}
}
println();
}
public void visitGotoStmt(final GotoStmt stmt) {
print("goto " + stmt.target().label());
println(" caught by " + stmt.catchTargets());
}
public void visitLabelStmt(final LabelStmt stmt) {
if (stmt.label() != null) {
println(stmt.label());
}
}
public void visitMonitorStmt(final MonitorStmt stmt) {
if (stmt.kind() == MonitorStmt.ENTER) {
print("enter ");
} else {
print("exit ");
}
print("monitor (");
if (stmt.object() != null) {
stmt.object().visit(this);
}
println(")");
}
public void visitCatchExpr(final CatchExpr expr) {
print("Catch(" + expr.catchType() + ")");
}
public void visitStackManipStmt(final StackManipStmt stmt) {
print("(");
final StackExpr[] target = stmt.target();
if (target != null) {
for (int i = 0; i < target.length; i++) {
target[i].visit(this);
if (i != target.length - 1) {
print(", ");
}
}
}
final String[] str = new String[] { "swap", "dup", "dup_x1", "dup_x2",
"dup2", "dup2_x1", "dup2_x2" };
print(") := " + str[stmt.kind()] + "(");
final StackExpr[] source = stmt.source();
if (source != null) {
for (int i = 0; i < source.length; i++) {
source[i].visit(this);
if (i != source.length - 1) {
print(", ");
}
}
}
println(")");
}
public void visitPhiJoinStmt(final PhiJoinStmt stmt) {
if (stmt.target() != null) {
stmt.target().visit(this);
}
print(" := Phi(");
if (stmt.hasParent()) {
final Tree tree = (Tree) stmt.parent();
final Block block = tree.block();
final Iterator e = block.graph().preds(block).iterator();
while (e.hasNext()) {
final Block pred = (Block) e.next();
final Expr operand = stmt.operandAt(pred);
print(pred.label() + "=");
operand.visit(this);
if (e.hasNext()) {
print(", ");
}
}
} else {
final Iterator e = stmt.operands().iterator();
while (e.hasNext()) {
final Expr operand = (Expr) e.next();
operand.visit(this);
if (e.hasNext()) {
print(", ");
}
}
}
println(")");
}
public void visitPhiCatchStmt(final PhiCatchStmt stmt) {
if (stmt.target() != null) {
stmt.target().visit(this);
}
print(" := Phi-Catch(");
final Iterator e = stmt.operands().iterator();
while (e.hasNext()) {
final Expr operand = (Expr) e.next();
operand.visit(this);
if (e.hasNext()) {
print(", ");
}
}
println(")");
}
public void visitRetStmt(final RetStmt stmt) {
print("ret from " + stmt.sub());
println(" caught by " + stmt.catchTargets());
}
public void visitReturnExprStmt(final ReturnExprStmt stmt) {
print("return ");
if (stmt.expr() != null) {
stmt.expr().visit(this);
}
println(" caught by " + stmt.catchTargets());
}
public void visitReturnStmt(final ReturnStmt stmt) {
print("return");
println(" caught by " + stmt.catchTargets());
}
public void visitStoreExpr(final StoreExpr expr) {
print("(");
if (expr.target() != null) {
expr.target().visit(this);
}
print(" := ");
if (expr.expr() != null) {
expr.expr().visit(this);
}
print(")");
}
public void visitAddressStoreStmt(final AddressStoreStmt stmt) {
print("La");
if (stmt.sub() != null) {
print(new Integer(stmt.sub().returnAddress().index()));
} else {
print("???");
}
println(" := returnAddress");
}
public void visitJsrStmt(final JsrStmt stmt) {
print("jsr ");
if (stmt.sub() != null) {
print(stmt.sub().entry());
}
if (stmt.follow() != null) {
print(" ret to " + stmt.follow());
}
println(" caught by " + stmt.catchTargets());
}
public void visitSwitchStmt(final SwitchStmt stmt) {
print("switch (");
if (stmt.index() != null) {
stmt.index().visit(this);
}
print(")");
println(" caught by " + stmt.catchTargets());
if ((stmt.values() != null) && (stmt.targets() != null)) {
for (int i = 0; i < stmt.values().length; i++) {
println(" case " + stmt.values()[i] + ": "
+ stmt.targets()[i]);
}
}
println(" default: " + stmt.defaultTarget());
}
public void visitThrowStmt(final ThrowStmt stmt) {
print("throw ");
if (stmt.expr() != null) {
stmt.expr().visit(this);
}
println(" caught by " + stmt.catchTargets());
}
public void visitSCStmt(final SCStmt stmt) {
print("aswizzle ");
if (stmt.array() != null) {
stmt.array().visit(this);
}
if (stmt.index() != null) {
stmt.index().visit(this);
}
}
public void visitSRStmt(final SRStmt stmt) {
print("aswrange array: ");
if (stmt.array() != null) {
stmt.array().visit(this);
}
print(" start: ");
if (stmt.start() != null) {
stmt.start().visit(this);
}
print(" end: ");
if (stmt.end() != null) {
stmt.end().visit(this);
}
println("");
}
public void visitArithExpr(final ArithExpr expr) {
print("(");
if (expr.left() != null) {
expr.left().visit(this);
}
print(" ");
switch (expr.operation()) {
case ArithExpr.ADD:
print("+");
break;
case ArithExpr.SUB:
print("-");
break;
case ArithExpr.DIV:
print("/");
break;
case ArithExpr.MUL:
print("*");
break;
case ArithExpr.REM:
print("%");
break;
case ArithExpr.AND:
print("&");
break;
case ArithExpr.IOR:
print("|");
break;
case ArithExpr.XOR:
print("^");
break;
case ArithExpr.CMP:
print("<=>");
break;
case ArithExpr.CMPL:
print("<l=>");
break;
case ArithExpr.CMPG:
print("<g=>");
break;
}
print(" ");
if (expr.right() != null) {
expr.right().visit(this);
}
print(")");
}
public void visitArrayLengthExpr(final ArrayLengthExpr expr) {
if (expr.array() != null) {
expr.array().visit(this);
}
print(".length");
}
public void visitArrayRefExpr(final ArrayRefExpr expr) {
if (expr.array() != null) {
expr.array().visit(this);
}
print("[");
if (expr.index() != null) {
expr.index().visit(this);
}
print("]");
}
public void visitCallMethodExpr(final CallMethodExpr expr) {
if (expr.receiver() != null) {
expr.receiver().visit(this);
}
print(".");
if (expr.method() != null) {
print(expr.method().nameAndType().name());
}
print("(");
if (expr.params() != null) {
for (int i = 0; i < expr.params().length; i++) {
expr.params()[i].visit(this);
if (i != expr.params().length - 1) {
print(", ");
}
}
}
print(")");
}
public void visitCallStaticExpr(final CallStaticExpr expr) {
if (expr.method() != null) {
print(expr.method().declaringClass());
}
print(".");
if (expr.method() != null) {
print(expr.method().nameAndType().name());
}
print("(");
if (expr.params() != null) {
for (int i = 0; i < expr.params().length; i++) {
expr.params()[i].visit(this);
if (i != expr.params().length - 1) {
print(", ");
}
}
}
print(")");
}
public void visitCastExpr(final CastExpr expr) {
print("((" + expr.castType() + ") ");
if (expr.expr() != null) {
expr.expr().visit(this);
}
print(")");
}
public void visitConstantExpr(final ConstantExpr expr) {
if (expr.value() instanceof String) {
final StringBuffer sb = new StringBuffer();
final String s = (String) expr.value();
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
if (Character.isWhitespace(c) || ((0x20 <= c) && (c <= 0x7e))) {
sb.append(c);
} else {
sb.append("\\u");
sb.append(Integer.toHexString(c));
}
if (sb.length() > 50) {
sb.append("...");
break;
}
}
print("'" + sb.toString() + "'");
} else if (expr.value() instanceof Float) {
print(expr.value() + "F");
} else if (expr.value() instanceof Long) {
print(expr.value() + "L");
} else {
print(expr.value());
}
}
public void visitFieldExpr(final FieldExpr expr) {
if (expr.object() != null) {
expr.object().visit(this);
}
print(".");
if (expr.field() != null) {
print(expr.field().nameAndType().name());
}
}
public void visitInstanceOfExpr(final InstanceOfExpr expr) {
if (expr.expr() != null) {
expr.expr().visit(this);
}
print(" instanceof " + expr.checkType());
}
public void visitLocalExpr(final LocalExpr expr) {
if (expr.fromStack()) {
print("T");
} else {
print("L");
}
print(expr.type().shortName().toLowerCase());
print(Integer.toString(expr.index()));
final DefExpr def = expr.def();
if ((def == null) || (def.version() == -1)) {
print("_undef");
} else {
print("_" + def.version());
}
}
public void visitNegExpr(final NegExpr expr) {
print("-");
if (expr.expr() != null) {
expr.expr().visit(this);
}
}
public void visitNewArrayExpr(final NewArrayExpr expr) {
print("new " + expr.elementType() + "[");
if (expr.size() != null) {
expr.size().visit(this);
}
print("]");
}
public void visitNewExpr(final NewExpr expr) {
print("new " + expr.objectType());
}
public void visitNewMultiArrayExpr(final NewMultiArrayExpr expr) {
print("new " + expr.elementType());
if (expr.dimensions() != null) {
for (int i = 0; i < expr.dimensions().length; i++) {
print("[" + expr.dimensions()[i] + "]");
}
}
}
public void visitZeroCheckExpr(final ZeroCheckExpr expr) {
if (expr.expr().type().isReference()) {
print("notNull(");
} else {
print("notZero(");
}
if (expr.expr() != null) {
expr.expr().visit(this);
}
print(")");
}
public void visitRCExpr(final RCExpr expr) {
print("rc(");
if (expr.expr() != null) {
expr.expr().visit(this);
}
print(")");
}
public void visitUCExpr(final UCExpr expr) {
if (expr.kind() == UCExpr.POINTER) {
print("aupdate(");
} else {
print("supdate(");
}
if (expr.expr() != null) {
expr.expr().visit(this);
}
print(")");
}
public void visitReturnAddressExpr(final ReturnAddressExpr expr) {
print("returnAddress");
}
public void visitShiftExpr(final ShiftExpr expr) {
print("(");
if (expr.expr() != null) {
expr.expr().visit(this);
}
if (expr.dir() == ShiftExpr.LEFT) {
print("<<");
} else if (expr.dir() == ShiftExpr.RIGHT) {
print(">>");
} else if (expr.dir() == ShiftExpr.UNSIGNED_RIGHT) {
print(">>>");
}
if (expr.bits() != null) {
expr.bits().visit(this);
}
print(")");
}
public void visitStackExpr(final StackExpr expr) {
print("S" + expr.type().shortName().toLowerCase() + expr.index());
final DefExpr def = expr.def();
if ((def == null) || (def.version() == -1)) {
print("_undef");
} else {
print("_" + def.version());
}
}
public void visitStaticFieldExpr(final StaticFieldExpr expr) {
if (expr.field() != null) {
print(expr.field().declaringClass() + "."
+ expr.field().nameAndType().name());
}
}
public void visitExpr(final Expr expr) {
print("EXPR");
}
public void visitStmt(final Stmt stmt) {
print("STMT");
}
}
|
3e195c308f809e2d17a30e26cfed069e1f7b86ff | 37,305 | java | Java | CoreOpenGLDisplay/src/au/gov/asd/tac/constellation/visual/opengl/utilities/GLTools.java | CrucisGamma/constellation | 2a8cfee5e914f5909f114c69d588a9ea785e51c6 | [
"Apache-2.0"
] | 348 | 2019-08-15T00:04:17.000Z | 2022-03-31T04:51:43.000Z | CoreOpenGLDisplay/src/au/gov/asd/tac/constellation/visual/opengl/utilities/GLTools.java | CrucisGamma/constellation | 2a8cfee5e914f5909f114c69d588a9ea785e51c6 | [
"Apache-2.0"
] | 1,485 | 2019-08-17T11:09:38.000Z | 2022-03-31T00:08:26.000Z | CoreOpenGLDisplay/src/au/gov/asd/tac/constellation/visual/opengl/utilities/GLTools.java | CrucisGamma/constellation | 2a8cfee5e914f5909f114c69d588a9ea785e51c6 | [
"Apache-2.0"
] | 96 | 2019-08-15T09:01:10.000Z | 2021-12-28T01:20:12.000Z | 41.45 | 211 | 0.587401 | 10,767 | /*
* Copyright 2010-2021 Australian Signals Directorate
*
* 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 au.gov.asd.tac.constellation.visual.opengl.utilities;
import au.gov.asd.tac.constellation.utilities.graphics.Vector2f;
import au.gov.asd.tac.constellation.utilities.graphics.Vector3f;
import au.gov.asd.tac.constellation.utilities.icon.ConstellationIcon;
import au.gov.asd.tac.constellation.utilities.icon.DefaultIconProvider;
import au.gov.asd.tac.constellation.utilities.icon.IconManager;
import au.gov.asd.tac.constellation.utilities.text.SeparatorConstants;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2ES2;
import com.jogamp.opengl.GL2ES3;
import com.jogamp.opengl.GL3;
import com.jogamp.opengl.GL3ES3;
import com.jogamp.opengl.GLContext;
import com.jogamp.opengl.util.texture.Texture;
import com.jogamp.opengl.util.texture.TextureData;
import com.jogamp.opengl.util.texture.TextureIO;
import com.jogamp.opengl.util.texture.awt.AWTTextureIO;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openide.util.Utilities; //pulled in by Windows-DPI-Scaling
/**
* Tools for OpenGL and JOGL.
*
* @author algol
*/
public final class GLTools {
private static final Logger LOGGER = Logger.getLogger(GLTools.class.getName());
/**
* The maximum width of an icon.
*/
public static final int MAX_ICON_WIDTH = 256;
/**
* The maximum height of an icon.
*/
public static final int MAX_ICON_HEIGHT = 256;
/**
* No constructor.
*/
private GLTools() {
}
/**
* Get the OpenGL version.
*
* @param gl the current OpenGL context.
* @param version An int[2] to receive the version: version[0] contains
* GL_MAJOR_VERSION, version[1] contains GL_MINOR_VERSION.
*/
public static void getOpenGLVersion(final GL3 gl, int[] version) {
gl.glGetIntegerv(GL2ES3.GL_MAJOR_VERSION, version, 0);
gl.glGetIntegerv(GL2ES3.GL_MINOR_VERSION, version, 1);
}
/**
* Convert a Vector3f[] to a float[].
*
* @param vector The vector to be converted to an array.
*
* @return A float[] containing the same values as the vector.
*/
public static float[] toFloatArray(final Vector3f[] vector) {
final float[] f = new float[vector.length * 3];
int ix = 0;
for (final Vector3f v : vector) {
f[ix] = v.a[0];
f[ix + 1] = v.a[1];
f[ix + 2] = v.a[2];
ix += 3;
}
return f;
}
/**
* Convert a Vector2f[] to a float[].
*
* @param vector The vector to be converted to an array.
*
* @return A float[] containing the same values as the vector.
*/
public static float[] toFloatArray(final Vector2f[] vector) {
final float[] f = new float[vector.length * 2];
int ix = 0;
for (final Vector2f v : vector) {
f[ix] = v.a[0];
f[ix + 1] = v.a[1];
ix += 2;
}
return f;
}
public static String loadFile(final Class<?> refClass, final String resourceName) throws IOException {
final StringBuilder buf = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(refClass.getResourceAsStream(resourceName), StandardCharsets.UTF_8.name()))) {
String line;
while ((line = reader.readLine()) != null) {
buf.append(line);
buf.append(SeparatorConstants.NEWLINE);
}
}
return buf.toString();
}
public static void loadShaderSource(final GL3 gl, final String shaderSrc, final int shader) {
final String[] shaderParam = {shaderSrc};
gl.glShaderSource(shader, 1, shaderParam, null, 0);
}
public static String getShaderLog(final GL3 gl, final int shader) {
final int[] maxLength = new int[1];
gl.glGetShaderiv(shader, GL2ES2.GL_INFO_LOG_LENGTH, maxLength, 0);
if (maxLength[0] == 0) {
return "";
}
final byte[] buf = new byte[maxLength[0]];
final int[] length = new int[1];
gl.glGetShaderInfoLog(shader, maxLength[0], length, 0, buf, 0);
final String log = new String(buf);
return log.trim();
}
public static String getProgramLog(final GL3 gl, final int shader) {
final int[] maxLength = new int[1];
gl.glGetProgramiv(shader, GL2ES2.GL_INFO_LOG_LENGTH, maxLength, 0);
if (maxLength[0] == 0) {
return "";
}
final byte[] buf = new byte[maxLength[0]];
final int[] length = new int[1];
gl.glGetProgramInfoLog(shader, maxLength[0], length, 0, buf, 0);
final String log = new String(buf);
return log.trim();
}
public static int loadShaderSourceWithAttributes(final GL3 gl, final String label, final String vertexSrc, final String geometrySrc, final String fragmentSrc, final Object... args) {
// Temporary shader objects.
final int vertexShader = gl.glCreateShader(GL2ES2.GL_VERTEX_SHADER);
final int fragmentShader = gl.glCreateShader(GL2ES2.GL_FRAGMENT_SHADER);
final int geometryShader = geometrySrc != null ? gl.glCreateShader(GL3ES3.GL_GEOMETRY_SHADER) : -1;
final int[] testVal = new int[1];
// Load the shaders.
loadShaderSource(gl, vertexSrc, vertexShader);
LOGGER.log(Level.FINE, "VERTEXSHADERLOG::{0}::{1}", new Object[]{label, getShaderLog(gl, vertexShader)});
loadShaderSource(gl, fragmentSrc, fragmentShader);
LOGGER.log(Level.FINE, "FRAGMENTSHADERLOG::{0}::{1}", new Object[]{label, getShaderLog(gl, fragmentShader)});
if (geometryShader != -1) {
loadShaderSource(gl, geometrySrc, geometryShader);
LOGGER.log(Level.FINE, "GEOMETRYSHADERLOG::{0}::{1}", new Object[]{label, getShaderLog(gl, geometryShader)});
}
// Compile the shaders.
gl.glCompileShader(vertexShader);
gl.glCompileShader(fragmentShader);
if (geometryShader != -1) {
gl.glCompileShader(geometryShader);
}
// Check for compile errors.
gl.glGetShaderiv(vertexShader, GL2ES2.GL_COMPILE_STATUS, testVal, 0);
if (testVal[0] == GL.GL_FALSE) {
final String log = getShaderLog(gl, vertexShader);
gl.glDeleteShader(vertexShader);
gl.glDeleteShader(fragmentShader);
if (geometryShader != -1) {
gl.glDeleteShader(geometryShader);
}
throw new RenderException(String.format("Invalid vertex shader '%s':%n%n%s", label, log));
}
gl.glGetShaderiv(fragmentShader, GL2ES2.GL_COMPILE_STATUS, testVal, 0);
if (testVal[0] == GL.GL_FALSE) {
final String log = getShaderLog(gl, fragmentShader);
gl.glDeleteShader(vertexShader);
gl.glDeleteShader(fragmentShader);
if (geometryShader != -1) {
gl.glDeleteShader(geometryShader);
}
throw new RenderException(String.format("Invalid fragment shader '%s':%n%n%s", label, log));
}
if (geometryShader != -1) {
gl.glGetShaderiv(geometryShader, GL2ES2.GL_COMPILE_STATUS, testVal, 0);
if (testVal[0] == GL.GL_FALSE) {
final String log = getShaderLog(gl, geometryShader);
gl.glDeleteShader(vertexShader);
gl.glDeleteShader(fragmentShader);
gl.glDeleteShader(geometryShader);
throw new RenderException(String.format("Invalid geometry shader '%s':%n%n%s", label, log));
}
}
// Link.
final int progid = gl.glCreateProgram();
gl.glAttachShader(progid, vertexShader);
gl.glAttachShader(progid, fragmentShader);
if (geometryShader != -1) {
gl.glAttachShader(progid, geometryShader);
}
// Bind attributes from the args.
for (int i = 0; i < args.length;) {
final int index = (Integer) args[i++];
final String arg = (String) args[i++];
if (index >= ShaderManager.FRAG_BASE) {
final int fragDataLocation = index - ShaderManager.FRAG_BASE;
gl.glBindFragDataLocation(progid, fragDataLocation, arg);
} else {
gl.glBindAttribLocation(progid, index, arg);
}
}
gl.glLinkProgram(progid);
// These are no longer needed.
gl.glDeleteShader(vertexShader);
gl.glDeleteShader(fragmentShader);
if (geometryShader != -1) {
gl.glDeleteShader(geometryShader);
}
// Check for link errors.
gl.glGetProgramiv(progid, GL2ES2.GL_LINK_STATUS, testVal, 0);
if (testVal[0] == GL.GL_FALSE) {
final String log = getProgramLog(gl, progid);
gl.glDeleteProgram(progid);
throw new RenderException(String.format("Invalid program link '%s':%n%n%s", label, log));
}
LOGGER.log(Level.FINE, "PROGRAMLOG::{0}::{1}", new Object[]{label, getProgramLog(gl, progid)});
return progid;
}
/**
* Make a sphere.
*
* @param gl the current OpenGL context.
* @param sphereBatch the batch to store the vertices to.
* @param fRadius the radius of the sphere.
* @param iSlices the number of slices in the sphere.
* @param iStacks the number of stacks in the sphere.
*/
public static void makeSphere(final GL3 gl, final TriangleBatch sphereBatch, final float fRadius, final int iSlices, final int iStacks) {
float drho = (float) Math.PI / (float) iStacks;
float dtheta = 2.0f * (float) Math.PI / (float) iSlices;
float ds = 1.0f / (float) iSlices;
float dt = 1.0f / (float) iStacks;
float t = 1.0f;
float s;
sphereBatch.beginMesh(iSlices * iStacks * 6);
for (int i = 0; i < iStacks; i++) {
float rho = (float) i * drho;
float srho = (float) (Math.sin(rho));
float crho = (float) (Math.cos(rho));
float srhodrho = (float) (Math.sin(rho + drho));
float crhodrho = (float) (Math.cos(rho + drho));
// Many sources of OpenGL sphere drawing code uses a triangle fan
// for the caps of the sphere. This however introduces texturing
// artifacts at the poles on some OpenGL implementations.
s = 0.0f;
Vector3f[] vVertex = Vector3f.createArray(4);
Vector3f[] vNormal = Vector3f.createArray(4);
Vector2f[] vTexture = Vector2f.createArray(4);
for (int j = 0; j < iSlices; j++) {
float theta = j * dtheta;
float stheta = (float) (-Math.sin(theta));
float ctheta = (float) (Math.cos(theta));
float x = stheta * srho;
float y = ctheta * srho;
float z = crho;
vTexture[0].a[0] = s;
vTexture[0].a[1] = t;
vNormal[0].a[0] = x;
vNormal[0].a[1] = y;
vNormal[0].a[2] = z;
vVertex[0].a[0] = x * fRadius;
vVertex[0].a[1] = y * fRadius;
vVertex[0].a[2] = z * fRadius;
x = stheta * srhodrho;
y = ctheta * srhodrho;
z = crhodrho;
vTexture[1].a[0] = s;
vTexture[1].a[1] = t - dt;
vNormal[1].a[0] = x;
vNormal[1].a[1] = y;
vNormal[1].a[2] = z;
vVertex[1].a[0] = x * fRadius;
vVertex[1].a[1] = y * fRadius;
vVertex[1].a[2] = z * fRadius;
theta = ((j + 1) == iSlices) ? 0.0f : (j + 1) * dtheta;
stheta = (float) (-Math.sin(theta));
ctheta = (float) (Math.cos(theta));
x = stheta * srho;
y = ctheta * srho;
z = crho;
s += ds;
vTexture[2].a[0] = s;
vTexture[2].a[1] = t;
vNormal[2].a[0] = x;
vNormal[2].a[1] = y;
vNormal[2].a[2] = z;
vVertex[2].a[0] = x * fRadius;
vVertex[2].a[1] = y * fRadius;
vVertex[2].a[2] = z * fRadius;
x = stheta * srhodrho;
y = ctheta * srhodrho;
z = crhodrho;
vTexture[3].a[0] = s;
vTexture[3].a[1] = t - dt;
vNormal[3].a[0] = x;
vNormal[3].a[1] = y;
vNormal[3].a[2] = z;
vVertex[3].a[0] = x * fRadius;
vVertex[3].a[1] = y * fRadius;
vVertex[3].a[2] = z * fRadius;
sphereBatch.addTriangle(vVertex, vNormal, vTexture);
// Rearrange for next triangle.
vVertex[0].set(vVertex[1]);
vNormal[0].set(vNormal[1]);
vTexture[0].set(vTexture[1]);
vVertex[1].set(vVertex[3]);
vNormal[1].set(vNormal[3]);
vTexture[1].set(vTexture[3]);
sphereBatch.addTriangle(vVertex, vNormal, vTexture);
}
t -= dt;
}
sphereBatch.end(gl);
}
/**
* Draw a torus (doughnut) at z = fZVal... torus is in xy plane.
*
* @param gl the current OpenGL context.
* @param torusBatch the batch to store the vertices to.
* @param majorRadius the major radius of the torus.
* @param minorRadius the minor radius of the torus.
* @param numMajor the number of slices around the major radius.
* @param numMinor the number of slices around the minor radius.
*/
public static void makeTorus(final GL3 gl, final TriangleBatch torusBatch, final float majorRadius, final float minorRadius, final int numMajor, final int numMinor) {
final double majorStep = 2.0f * Math.PI / numMajor;
final double minorStep = 2.0f * Math.PI / numMinor;
torusBatch.beginMesh(numMajor * (numMinor + 1) * 6);
for (int i = 0; i < numMajor; i++) {
final double a0 = i * majorStep;
final double a1 = a0 + majorStep;
final float x0 = (float) Math.cos(a0);
final float y0 = (float) Math.sin(a0);
final float x1 = (float) Math.cos(a1);
final float y1 = (float) Math.sin(a1);
Vector3f[] vVertex = Vector3f.createArray(4);
Vector3f[] vNormal = Vector3f.createArray(4);
Vector2f[] vTexture = Vector2f.createArray(4);
for (int j = 0; j <= numMinor; j++) {
double b = j * minorStep;
float c = (float) Math.cos(b);
float r = minorRadius * c + majorRadius;
float z = minorRadius * (float) Math.sin(b);
// First point
vTexture[0].a[0] = (float) (i) / (float) (numMajor);
vTexture[0].a[1] = (float) (j) / (float) (numMinor);
vNormal[0].a[0] = x0 * c;
vNormal[0].a[1] = y0 * c;
vNormal[0].a[2] = z / minorRadius;
vNormal[0].normalize();
vVertex[0].a[0] = x0 * r;
vVertex[0].a[1] = y0 * r;
vVertex[0].a[2] = z;
// Second point
vTexture[1].a[0] = (float) (i + 1) / (float) (numMajor);
vTexture[1].a[1] = (float) (j) / (float) (numMinor);
vNormal[1].a[0] = x1 * c;
vNormal[1].a[1] = y1 * c;
vNormal[1].a[2] = z / minorRadius;
vNormal[1].normalize();
vVertex[1].a[0] = x1 * r;
vVertex[1].a[1] = y1 * r;
vVertex[1].a[2] = z;
// Next one over
b = (j + 1) * minorStep;
c = (float) Math.cos(b);
r = minorRadius * c + majorRadius;
z = minorRadius * (float) Math.sin(b);
// Third (based on first)
vTexture[2].a[0] = (float) (i) / (float) (numMajor);
vTexture[2].a[1] = (float) (j + 1) / (float) (numMinor);
vNormal[2].a[0] = x0 * c;
vNormal[2].a[1] = y0 * c;
vNormal[2].a[2] = z / minorRadius;
vNormal[2].normalize();
vVertex[2].a[0] = x0 * r;
vVertex[2].a[1] = y0 * r;
vVertex[2].a[2] = z;
// Fourth (based on second)
vTexture[3].a[0] = (float) (i + 1) / (float) (numMajor);
vTexture[3].a[1] = (float) (j + 1) / (float) (numMinor);
vNormal[3].a[0] = x1 * c;
vNormal[3].a[1] = y1 * c;
vNormal[3].a[2] = z / minorRadius;
vNormal[3].normalize();
vVertex[3].a[0] = x1 * r;
vVertex[3].a[1] = y1 * r;
vVertex[3].a[2] = z;
torusBatch.addTriangle(vVertex, vNormal, vTexture);
// Rearrange for next triangle.
vVertex[0].set(vVertex[1]);
vNormal[0].set(vNormal[1]);
vTexture[0].set(vTexture[1]);
vVertex[1].set(vVertex[3]);
vNormal[1].set(vNormal[3]);
vTexture[1].set(vTexture[3]);
torusBatch.addTriangle(vVertex, vNormal, vTexture);
}
}
torusBatch.end(gl);
}
// Load a TGA as a 2D Texture. Completely initialize the state
public static Texture loadTexture(final GL3 gl, final InputStream in, final String ext, final int minFilter, final int magFilter, final int wrapMode) throws IOException {
// NVS-415: Appears to be a bug in JOGL where texture provider for PNG files does not flip the texture.
// final TextureData data = TextureIO.newTextureData(gl.getGLProfile(), in, false, ext);
final TextureData data = TextureIO.newTextureData(gl.getGLProfile(), in, false, null);
final Texture tex = TextureIO.newTexture(data);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, wrapMode);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, wrapMode);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, minFilter);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, magFilter);
return tex;
}
/**
* Load a BufferedImage array into a texture array.
* <p>
* Each BufferedImage must be of type BufferedImage.TYPE_4BYTE_ABGR. The
* images will be loaded at 0,0 at each level of the texture array.
* <p>
* It appears that the images must have a row length that is a multiple of
* four. This is probably due to the particular format we're using, and
* could probably be worked around, but the simple fix is to check your row
* length.
*
* @param gl the current OpenGL context.
* @param textureName The name of the texture to bind to with BindTexture().
* @param images A List of BufferedImages of type
* BufferedImage.TYPE_4BYTE_ABGR.
* @param maxWidth The maximum width of the images.
* @param maxHeight The maximum height of the images.
* @param minFilter Texture selection with TEXTURE_MIN_FILTER.
* @param magFilter Texture selection with TEXTURE_MAG_FILTER.
* @param wrapMode texture wrap mode with TEXTURE_WRAP_S and TEXTURE_WRAP_T.
*/
public static void loadTextures(final GL3 gl, final int textureName, final List<BufferedImage> images, final int maxWidth, final int maxHeight, final int minFilter, final int magFilter, final int wrapMode) {
gl.glBindTexture(GL2ES3.GL_TEXTURE_2D_ARRAY, textureName);
gl.glTexParameteri(GL2ES3.GL_TEXTURE_2D_ARRAY, GL.GL_TEXTURE_WRAP_S, wrapMode);
gl.glTexParameteri(GL2ES3.GL_TEXTURE_2D_ARRAY, GL.GL_TEXTURE_WRAP_T, wrapMode);
gl.glTexParameteri(GL2ES3.GL_TEXTURE_2D_ARRAY, GL.GL_TEXTURE_MIN_FILTER, minFilter);
gl.glTexParameteri(GL2ES3.GL_TEXTURE_2D_ARRAY, GL.GL_TEXTURE_MAG_FILTER, magFilter);
// Call glTexImage3D() to create the buffer here: we've assumed the internalformat and format.
gl.glTexImage3D(GL2ES3.GL_TEXTURE_2D_ARRAY, 0, GL.GL_RGBA, maxWidth, maxHeight, images.size(), 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, null);
int i = 0;
for (BufferedImage image : images) {
try {
final TextureData data = AWTTextureIO.newTextureData(gl.getGLProfile(), image, false);
if (data.getWidth() > maxWidth || data.getHeight() > maxHeight) {
throw new RenderException(String.format("Image %d is too large", i));
}
// Images are always placed at 0,0.
final int xoffset = 0;
final int yoffset = 0;
final int zoffset = i;
gl.glTexSubImage3D(GL2ES3.GL_TEXTURE_2D_ARRAY, 0, xoffset, yoffset, zoffset, data.getWidth(), data.getHeight(), 1, data.getPixelFormat(), GL.GL_UNSIGNED_BYTE, data.getBuffer());
data.destroy();
} catch (final RuntimeException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
i++;
}
}
/**
* Load an array of icon textures.
* <p>
* We assume that the textures being loaded are icons, and therefore are
* roughly the same size (with a maximum of (width,height).
* <p>
* The array is limited to GL_MAX_ARRAY_TEXTURE_LAYERS layers. This can be
* fairly low (512 on low-end systems), so icons are loaded into an 8x8 icon
* matrix in each layer, thus giving a maximum of 512x8x8=32768 icons. (This
* assumes that GL_MAX_3D_TEXTURE_SIZE is big enough to take that many
* pixels. With the current icon size of 256x256, then
* GL_MAX_3D_TEXTURE_SIZE must be at least 2048.)
* <p>
* Icons that are smaller than (width,height) are offset so they are
* centred, so the shader can just draw the icons without worrying about
* where in the texture they are.
* <p>
* It appears that the images must have a row length that is a multiple of
* four. This is probably due to the particular format we're using, and
* could probably be worked around, but the simple fix is to check your row
* length.
*
* @param glCurrent the current OpenGL context.
* @param icons a list of icons that need to added to the buffer.
* @param width the width of each icon.
* @param height the height of each icon.
*
* @return the id of the texture buffer.
*/
public static int loadSharedIconTextures(final GL3 glCurrent, final List<ConstellationIcon> icons, final int width, final int height) {
final int[] v = new int[1];
glCurrent.glGetIntegerv(GL2ES3.GL_MAX_ARRAY_TEXTURE_LAYERS, v, 0);
final int maxIcons = v[0] * 64;
if (icons.size() > maxIcons) {
System.out.printf("****\n**** Warning: nIcons %d > GL_MAX_ARRAY_TEXTURE_LAYERS %d\n****\n", icons.size(), maxIcons);
}
final int nIcons = Math.min(icons.size(), maxIcons);
glCurrent.getContext().release();
final GL3 gl = (GL3) SharedDrawable.getSharedAutoDrawable().getGL();
final int result = gl.getContext().makeCurrent();
if (result == GLContext.CONTEXT_NOT_CURRENT) {
glCurrent.getContext().makeCurrent();
throw new RenderException("Could not make texture context current.");
}
final int[] textureName = new int[1];
try {
textureName[0] = SharedDrawable.getIconTextureName();
gl.glBindTexture(GL2ES3.GL_TEXTURE_2D_ARRAY, textureName[0]);
gl.glTexParameteri(GL2ES3.GL_TEXTURE_2D_ARRAY, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE);
gl.glTexParameteri(GL2ES3.GL_TEXTURE_2D_ARRAY, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE);
gl.glTexParameteri(GL2ES3.GL_TEXTURE_2D_ARRAY, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);
gl.glTexParameteri(GL2ES3.GL_TEXTURE_2D_ARRAY, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
gl.glTexImage3D(GL2ES3.GL_TEXTURE_2D_ARRAY, 0, GL.GL_RGBA, width * 8, height * 8, (nIcons + 63) / 64, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, null);
final Iterator<ConstellationIcon> iconIterator = icons.iterator();
for (int i = 0; i < nIcons; i++) {
final ConstellationIcon icon = iconIterator.next();
try {
BufferedImage iconImage = icon.buildBufferedImage();
if (iconImage != null) {
// Appears to be a bug in JOGL where texture provider for PNG files does not flip the texture.
final TextureData data = AWTTextureIO.newTextureData(gl.getGLProfile(), iconImage, false);
if (data.getWidth() > width || data.getHeight() > height) {
throw new RenderException(String.format("Image %d is too large (width %d>%d, height %d>%d)", i, data.getWidth(), width, data.getHeight(), height));
}
// Offset each icon into an 8x8 matrix.
// There are multiple icons in each
// Allow for icons that are smaller than width,height.
final int xoffset = (width - data.getWidth()) / 2 + (width * (i & 7));
final int yoffset = (height - data.getHeight()) / 2 + (height * ((i >>> 3) & 7));
final int zoffset = i >>> 6;
gl.glTexSubImage3D(GL2ES3.GL_TEXTURE_2D_ARRAY, 0, xoffset, yoffset, zoffset, data.getWidth(), data.getHeight(), 1, data.getPixelFormat(), GL.GL_UNSIGNED_BYTE, data.getBuffer());
data.destroy();
}
} catch (final RuntimeException ex) {
System.out.printf("##%n## GLTools.loadTextures() icon %d throwable: %s%n##%n", i, ex);
LOGGER.log(Level.SEVERE, null, ex);
}
}
} finally {
gl.getContext().release();
glCurrent.getContext().makeCurrent();
}
return textureName[0];
}
// These icons must be permanently present at these pre-defined indexes.
// The shaders expect them to be there.
public static final int HIGHLIGHTED_ICON_INDEX = 0;
public static final String HIGHLIGHTED_ICON = DefaultIconProvider.HIGHLIGHTED.getExtendedName();
public static final int UNKNOWN_ICON_INDEX = 1;
public static final String UNKNOWN_ICON = DefaultIconProvider.UNKNOWN.getExtendedName();
// Icons for drawing loops.
public static final int LOOP_DIRECTED_ICON_INDEX = 2;
public static final String LOOP_DIRECTED_ICON = DefaultIconProvider.LOOP_DIRECTED.getExtendedName();
public static final int LOOP_UNDIRECTED_ICON_INDEX = 3;
public static final String LOOP_UNDIRECTED_ICON = DefaultIconProvider.LOOP_UNDIRECTED.getExtendedName();
// Noise indicator to be drawn when there are too many icons for the texture array.
public static final int NOISE_ICON_INDEX = 4;
public static final String NOISE_ICON = DefaultIconProvider.NOISE.getExtendedName();
// Transparency.
public static final int TRANSPARENT_ICON_INDEX = 5;
public static final String TRANSPARENT_ICON = DefaultIconProvider.TRANSPARENT.getExtendedName();
/**
* Singleton holder of list of used icons.
* <p>
* As new icon names are seen in the graph, they are added to this data
* structure, which maintains a mapping between an icon name and its index.
* <p>
* Note: a LinkedHashMap is used here to maintain the insertion order.
* Because the texture array that uses this is shared between multiple
* drawables, and some icons must be at predefined indexes (for instance
* "highlighted" must be at index 0, "unknown" at index 1), the order of the
* icons must not change: a drawable that uses an icon at index 17 (for
* example) can't have that icon changing due to a different drawable being
* created. Therefore, whenever new icons are added, they are always
* appended.
*/
public static final class LoadedIconHelper {
private final LinkedHashMap<String, Integer> loadedIcons;
private boolean requiresReload;
// We use a texture array to store icons.
// If we have too many icons (more than GL_MAX_ARRAY_TEXTURE_LAYERS), then OpenGL won't like it.
// What happens next is probably driver/hardware dependent, but one possibility is just displaying
// whatever icon it feels like. Yuck.
// We don't want this to happen, so we have a maximum number of icons.
// If an attempt is made to add any more icons, you'll get the noise icon as an indicator if icon overflow.
private int maxNIcons;
private LoadedIconHelper() {
maxNIcons = Integer.MAX_VALUE;
loadedIcons = new LinkedHashMap<>();
// These icons are guaranteed to be in the iconMap in this order.
// They must be at these pre-defined indices so other code (in particular the shaders) can use them.
// See *_INDEX constants above.
for (final String iconName : new String[]{HIGHLIGHTED_ICON, UNKNOWN_ICON, LOOP_DIRECTED_ICON, LOOP_UNDIRECTED_ICON, NOISE_ICON, TRANSPARENT_ICON}) {
addIcon(iconName);
}
}
/**
* Add an icon label to the index map and return the index of that icon.
* <p>
* If the label already exists, return the existing index. Null labels
* and empty labels (ie "") return the index of the transparent icon.
* Therefore, a valid icon index (<=0 && >=MAX_ICON_INDEX)
* will always be returned.
*
* @param label The index of an icon.
*
* @return the index of the icon.
*/
public int addIcon(final String label) {
final Integer iconIndex = loadedIcons.get(label);
if (iconIndex == null) {
final int index = loadedIcons.size();
if (index >= maxNIcons) {
// Too many icons: return NOISE icon.
return NOISE_ICON_INDEX;
}
loadedIcons.put(label, index);
requiresReload = true;
return index;
}
return iconIndex;
}
public boolean isEmpty() {
return loadedIcons.isEmpty();
}
public int size() {
return loadedIcons.size();
}
public void reset() {
loadedIcons.clear();
requiresReload = false;
}
public int getMaximumIcons() {
return maxNIcons;
}
public void setMaximumTextureLayers(final int maxTextureLayers) {
this.maxNIcons = maxTextureLayers * 64;
}
}
public static final LoadedIconHelper LOADED_ICON_HELPER = new LoadedIconHelper();
/**
* Load the icon textures into a texture array.
* <p>
* This texture array is shared amongst all of the OpenGL drawables, so once
* an icon has been added to the list of icons, its index must not change.
*
* @param glCurrent the current OpenGL context.
* @param width the width of each icon.
* @param height the height of each icon.
*
* @return the id of the texture buffer.
*/
public static int loadSharedIconTextures(final GL3 glCurrent, final int width, final int height) {
// Do we have new icons to be loaded?
// If so, reload the lot.
if (LOADED_ICON_HELPER.requiresReload) {
final int nIcons = LOADED_ICON_HELPER.loadedIcons.size();
final List<ConstellationIcon> iconList = new ArrayList<>(nIcons);
for (int i = 0; i < nIcons; i++) {
iconList.add(null);
}
for (final Map.Entry<String, Integer> entry : LOADED_ICON_HELPER.loadedIcons.entrySet()) {
final String iconLabel = entry.getKey();
final int iconIndex = entry.getValue();
ConstellationIcon icon = IconManager.getIcon(iconLabel);
if (icon == null) {
icon = DefaultIconProvider.UNKNOWN;
}
iconList.set(iconIndex, icon);
}
LOADED_ICON_HELPER.requiresReload = false;
final long t0 = System.currentTimeMillis();
final int iconTextureArray = loadSharedIconTextures(glCurrent, iconList, width, height);
final long t1 = System.currentTimeMillis();
LOGGER.log(Level.FINE, "Time to load icon textures: {0} msec\n", (t1 - t0));
return iconTextureArray;
}
return SharedDrawable.getIconTextureName();
}
/**
* Obtain error information.
* <p>
* This is a low-level alternative to using a debug GL context. See the
* OpenGL specification 3.3 Core section 2.5.
*
* @param gl the current OpenGL context.
* @param msg the message that will be printed out if an error has occurred.
*/
public static void checkError(final GL3 gl, final String msg) {
while (true) {
final int err = gl.glGetError();
if (err == GL.GL_NO_ERROR || msg == null) {
return;
}
String errtext;
switch (err) {
case GL.GL_INVALID_ENUM:
errtext = "invalid enum";
break;
case GL.GL_INVALID_VALUE:
errtext = "invalid value";
break;
case GL.GL_INVALID_OPERATION:
errtext = "invalid operation";
break;
case GL.GL_OUT_OF_MEMORY:
errtext = "out of memory";
break;
case GL.GL_INVALID_FRAMEBUFFER_OPERATION:
errtext = "invalid framebuffer operation";
break;
default:
errtext = Integer.toString(err);
break;
}
LOGGER.log(Level.SEVERE, "OpenGL error {0}: {1} ({2})", new Object[]{msg, errtext, err});
}
}
/**
* Check that a framebuffer is complete.
* <p>
* See the OpenGL specification 3.3 Core section 4.4.4.
*
* @param gl the current OpenGL context.
* @param msg msg the message that will be printed out if an error has
* occurred.
*/
public static void checkFramebufferStatus(final GL3 gl, final String msg) {
int fboStatus = gl.glCheckFramebufferStatus(GL.GL_DRAW_FRAMEBUFFER);
if (fboStatus == GL.GL_FRAMEBUFFER_COMPLETE) {
return;
}
String errtext = "";
if (fboStatus == GL.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT) {
errtext = "framebuffer incomplete missing attachment";
} else if (fboStatus == GL.GL_FRAMEBUFFER_UNSUPPORTED) {
errtext = "framebuffer unsupported";
} else {
// Do nothing
}
LOGGER.log(Level.SEVERE, "**** Framebuffer error %{0}: %{1} ({2})", new Object[]{msg, errtext, fboStatus});
}
/**
* Windows-DPI-Scaling
*
* JOGL version 2.3.2 on Windows doesn't correctly support DPI
* scaling.setSurfaceScale() is not overridden in WindowsJAWTWindow so it is
* not possible to scale the the canvas and mouse events at this level. It
* should be noted that it is overridden in MacOSXJAWTWindow. Where manual
* scaling is required the caller will need to scale each GL viewport and
* ensure hit tests take that size into account.
*
* If JOGL is ever fixed or another solution is found, either change this
* function to return false or look for any code that calls it and remove
* it.
*
* @return
*/
public static boolean needsManualDPIScaling() {
return Utilities.isWindows();
}
}
|
3e195dbba9564a491fbbdc1975e7334d39aa8150 | 1,464 | java | Java | ninja-servlet/src/main/java/ninja/servlet/util/RequestExtractor.java | stefb965/ninja | 518513a677924836b5c67e2b03603f15c2b460e3 | [
"Apache-2.0"
] | null | null | null | ninja-servlet/src/main/java/ninja/servlet/util/RequestExtractor.java | stefb965/ninja | 518513a677924836b5c67e2b03603f15c2b460e3 | [
"Apache-2.0"
] | null | null | null | ninja-servlet/src/main/java/ninja/servlet/util/RequestExtractor.java | stefb965/ninja | 518513a677924836b5c67e2b03603f15c2b460e3 | [
"Apache-2.0"
] | null | null | null | 30.5 | 101 | 0.715847 | 10,768 | /**
* Copyright (C) 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ninja.servlet.util;
import javax.servlet.http.HttpServletRequest;
import ninja.Context;
import ninja.params.ArgumentExtractor;
import ninja.servlet.NinjaServletContext;
public class RequestExtractor implements ArgumentExtractor<HttpServletRequest> {
@Override
public HttpServletRequest extract(Context context) {
if (context instanceof NinjaServletContext) {
return ((NinjaServletContext) context).getHttpServletRequest();
} else {
throw new RuntimeException(
"RequestExtractor only works with Servlet container implementation of Context.");
}
}
@Override
public Class<HttpServletRequest> getExtractedType() {
return HttpServletRequest.class;
}
@Override
public String getFieldName() {
return null;
}
} |
3e195ddb416a0dac804c059f615e3b148d8b818c | 47,365 | java | Java | src/main/java/mat/server/service/impl/MeasureCloningServiceImpl.java | MeasureAuthoringTool/MeasureAuthoringTool | 0fc9955f5c22cc709636f327de5f3e6bac3dabfc | [
"CC0-1.0"
] | 10 | 2019-10-16T14:10:48.000Z | 2022-02-28T13:50:38.000Z | src/main/java/mat/server/service/impl/MeasureCloningServiceImpl.java | MeasureAuthoringTool/MeasureAuthoringTool | 0fc9955f5c22cc709636f327de5f3e6bac3dabfc | [
"CC0-1.0"
] | 115 | 2019-10-21T17:43:24.000Z | 2022-03-03T17:43:02.000Z | src/main/java/mat/server/service/impl/MeasureCloningServiceImpl.java | MeasureAuthoringTool/MeasureAuthoringTool | 0fc9955f5c22cc709636f327de5f3e6bac3dabfc | [
"CC0-1.0"
] | 7 | 2019-11-19T21:14:53.000Z | 2021-10-13T20:28:51.000Z | 45.282027 | 205 | 0.682318 | 10,769 | package mat.server.service.impl;
import mat.client.measure.ManageMeasureDetailModel;
import mat.client.measure.ManageMeasureSearchModel;
import mat.client.measure.service.CQLService;
import mat.client.shared.CQLWorkSpaceConstants;
import mat.client.shared.MatContext;
import mat.client.shared.MatException;
import mat.client.shared.MessageDelegate;
import mat.dao.FhirConversionHistoryDao;
import mat.dao.OrganizationDAO;
import mat.dao.UserDAO;
import mat.dao.clause.MeasureDAO;
import mat.dao.clause.MeasureSetDAO;
import mat.dao.clause.MeasureXMLDAO;
import mat.model.Author;
import mat.model.Organization;
import mat.model.User;
import mat.model.clause.ComponentMeasure;
import mat.model.clause.FhirConversionHistory;
import mat.model.clause.Measure;
import mat.model.clause.MeasureDeveloperAssociation;
import mat.model.clause.MeasureSet;
import mat.model.clause.MeasureTypeAssociation;
import mat.model.clause.MeasureXML;
import mat.model.clause.ModelTypeHelper;
import mat.model.cql.CQLParameter;
import mat.server.CQLLibraryService;
import mat.server.LoggedInUserUtil;
import mat.server.logging.LogFactory;
import mat.server.service.MeasureAuditService;
import mat.server.service.MeasureCloningService;
import mat.server.util.CQLValidationUtil;
import mat.server.util.MATPropertiesService;
import mat.server.util.ManageMeasureDetailModelConversions;
import mat.server.util.MeasureUtility;
import mat.server.util.XmlProcessor;
import mat.shared.ConstantMessages;
import mat.shared.SaveUpdateCQLResult;
import mat.shared.UUIDUtilClient;
import mat.shared.validator.measure.ManageMeasureModelValidator;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.springframework.stereotype.Service;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
public class MeasureCloningServiceImpl implements MeasureCloningService {
private static final Log logger = LogFactory.getLog(MeasureCloningServiceImpl.class);
private static final String QDM_BIRTHDATE_NON_DEFAULT = "birthdate";
private static final String MEASURE_DETAILS = "measureDetails";
private static final String MEASURE_GROUPING = "measureGrouping";
private static final String UU_ID = "uuid";
private static final String OID = "oid";
private static final String DATATYPE = "datatype";
private static final String VERSION = "version";
private static final String SUPPLEMENTAL_DATA_ELEMENTS = "supplementalDataElements";
private static final String RISK_ADJUSTMENT_VARIABLES = "riskAdjustmentVariables";
private static final String VERSION_ZERO = "0.0";
private static final String PATIENT_CHARACTERISTIC_BIRTH_DATE_OID = "21112-8";
private static final String PATIENT_CHARACTERISTIC_EXPIRED_OID = "419099009";
private static final String PATIENT_CHARACTERISTIC_BIRTH_DATE = "Patient Characteristic Birthdate";
private static final String PATIENT_CHARACTERISTIC_EXPIRED = "Patient Characteristic Expired";
private static final String TIMING_ELEMENT = "Timing ELement";
private static final String ORIGINAL_NAME = "originalName";
private static final String NAME = "name";
private static final String PROGRAM = "program";
private static final String RELEASE = "release";
private static final String TYPE = "type";
private static final String TAXONOMY = "taxonomy";
private static final String GROUPING = "Grouping";
private static final String EXTENSIONAL = "Extensional";
private final CQLLibraryService cqlLibraryService;
private final MeasureDAO measureDAO;
private final MeasureXMLDAO measureXmlDAO;
private final MeasureSetDAO measureSetDAO;
private final OrganizationDAO organizationDAO;
private final UserDAO userDAO;
private final CQLService cqlService;
private final MATPropertiesService propertiesService;
private final FhirConversionHistoryDao fhirConversionHIstoryDAO;
private final MeasureAuditService auditService;
public MeasureCloningServiceImpl(
MATPropertiesService propertiesService,
CQLLibraryService cqlLibraryService,
MeasureDAO measureDAO,
MeasureXMLDAO measureXmlDAO,
MeasureSetDAO measureSetDAO,
OrganizationDAO organizationDAO,
UserDAO userDAO,
CQLService cqlService, FhirConversionHistoryDao fhirConversionHIstoryDAO, MeasureAuditService auditService) {
this.propertiesService = propertiesService;
this.cqlLibraryService = cqlLibraryService;
this.measureDAO = measureDAO;
this.measureXmlDAO = measureXmlDAO;
this.measureSetDAO = measureSetDAO;
this.organizationDAO = organizationDAO;
this.userDAO = userDAO;
this.cqlService = cqlService;
this.fhirConversionHIstoryDAO = fhirConversionHIstoryDAO;
this.auditService = auditService;
}
/*
* 4 Scenarios are covered by this service:
* 1. QDM Draft -> QDM with bumped version in draft state
* 2. QDM Clone -> QDM with version reset in draft state
* 3. QDM to FHIR Conversion -> FHIR with version reset in draft state
* 4. FHIR Draft -> FHIR with bumped version in draft state
*
* boolean usage
* creatingDraft -> True, user is creating a draft of an existing FHIR or QDM Measure.
* False, user is Cloning existing QDM measure
*
* isFhir -> True, source measure is FHIR based.
* False, source measure is QDM based.
*
* convertingQdmToFhir -> True, user is converting source QDM measure to FHIR.
* False,
*
* boolean QDM Draft QDM Clone QDM->FHIR FHIR Draft
* creatingDraft T F T T
* isFhir F F T T
* convertingQdmToFhir F F T F
*/
@Override
public ManageMeasureSearchModel.Result clone(ManageMeasureDetailModel currentDetails) throws MatException {
return execute(currentDetails, false, false, false);
}
@Override
public ManageMeasureSearchModel.Result draft(ManageMeasureDetailModel currentDetails, boolean isFhir) throws MatException {
return execute(currentDetails, true, isFhir, false);
}
@Override
public ManageMeasureSearchModel.Result convert(ManageMeasureDetailModel currentDetails) throws MatException {
return execute(currentDetails, true, true, true);
}
private ManageMeasureSearchModel.Result execute(ManageMeasureDetailModel currentDetails,
boolean creatingDraft,
boolean isFhir,
boolean convertingQdmToFhir) throws MatException {
logger.debug("In MeasureCloningServiceImpl.execute() method...");
validateMeasure(currentDetails);
try {
Measure currentMeasure = measureDAO.find(currentDetails.getId());
if (checkNonCQLCloningValidation(currentMeasure, creatingDraft)) {
throw new MatException("Cannot clone this measure.");
}
Measure newMeasure = new Measure();
newMeasure.setMeasureModel(isFhir ? ModelTypeHelper.FHIR : currentDetails.getMeasureModel());
newMeasure.setReleaseVersion(currentMeasure.getReleaseVersion());
newMeasure.setDraft(Boolean.TRUE);
newMeasure.setPatientBased(currentDetails.isPatientBased());
newMeasure.setReleaseVersion(propertiesService.getCurrentReleaseVersion());
newMeasure.setPopulationBasis(currentDetails.getPopulationBasis());
newMeasure.setMeasureScoring(currentDetails.getMeasScoring() != null ? currentDetails.getMeasScoring() : currentMeasure.getMeasureScoring());
if (convertingQdmToFhir) {
newMeasure.seteMeasureId(currentDetails.geteMeasureId());
newMeasure.setaBBRName(currentDetails.getShortName() + "FHIR");
newMeasure.setDescription(currentDetails.getMeasureName() + "FHIR");
newMeasure.setCqlLibraryName(currentDetails.getCQLLibraryName() + "FHIR");
} else {
newMeasure.setaBBRName(currentDetails.getShortName());
newMeasure.setDescription(currentDetails.getMeasureName());
newMeasure.setCqlLibraryName(currentDetails.getCQLLibraryName());
}
if (isFhir) {
if (currentMeasure.getMeasurementPeriodFrom() == null || currentMeasure.getMeasurementPeriodTo() == null) {
newMeasure.setMeasurementPeriodFrom(getNextCalenderYearFromDate());
newMeasure.setMeasurementPeriodTo(getNextCalenderYearToDate());
} else {
newMeasure.setMeasurementPeriodFrom(currentMeasure.getMeasurementPeriodFrom());
newMeasure.setMeasurementPeriodTo(currentMeasure.getMeasurementPeriodTo());
}
newMeasure.setFhirVersion(propertiesService.getFhirVersion());
newMeasure.setSourceMeasureId(currentMeasure.getId());
} else {
newMeasure.setMeasurementPeriodFrom(getTimestampFromDateString(currentDetails.getMeasFromPeriod()));
newMeasure.setMeasurementPeriodTo(getTimestampFromDateString(currentDetails.getMeasToPeriod()));
newMeasure.setQdmVersion(propertiesService.getQdmVersion());
}
// Handle Component/Composite measures
if (CollectionUtils.isNotEmpty(currentMeasure.getComponentMeasures()) && Boolean.TRUE.equals(currentMeasure.getIsCompositeMeasure())) {
newMeasure.setIsCompositeMeasure(currentMeasure.getIsCompositeMeasure());
newMeasure.setCompositeScoring(currentMeasure.getCompositeScoring());
newMeasure.setComponentMeasures(cloneAndSetComponentMeasures(currentMeasure.getComponentMeasures(), newMeasure));
}
// when creating a draft of a shared version Measure then the Measure Owner should not change
if (creatingDraft) {
createDraftAndDetermineIfNonCQLAndPersist(convertingQdmToFhir, newMeasure, currentDetails, currentMeasure);
} else {
cloneMeasureAndPersist(newMeasure);
}
MeasureXML originalMeasureXml = measureXmlDAO.findForMeasure(currentDetails.getId());
createMeasureXmlAndPersist(currentDetails, creatingDraft, isFhir, currentMeasure, newMeasure, originalMeasureXml.getMeasureXMLAsString());
if (convertingQdmToFhir) {
createFhirConversionHistory(currentMeasure, newMeasure, userDAO.findByLoginId(LoggedInUserUtil.getLoggedUserName()));
auditService.recordMeasureEvent(currentMeasure.getId(),
"Converted QDM/CQL to FHIR",
newMeasure.getDescription() + " FHIR DRAFT 0.0.000 was created from QDM Version " + currentMeasure.getMatVersion(),
false);
}
String formattedVersionWithText = MeasureUtility.getVersionTextWithRevisionNumber(newMeasure.getVersion(),
newMeasure.getRevisionNumber(), newMeasure.isDraft());
ManageMeasureSearchModel.Result result = new ManageMeasureSearchModel.Result();
result.setId(newMeasure.getId());
result.setName(newMeasure.getDescription());
result.setShortName(newMeasure.getaBBRName());
result.setScoringType(currentDetails.getMeasScoring());
result.setVersion(formattedVersionWithText);
result.setMeasureModel(newMeasure.getMeasureModel());
result.setEditable(Boolean.TRUE);
result.setClonable(Boolean.TRUE);
result.setPatientBased(newMeasure.getPatientBased());
return result;
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new MatException(e.getMessage());
}
}
private void createFhirConversionHistory(Measure existingMeasure, Measure newFhirMeasure, User user) {
var h = new FhirConversionHistory();
h.setQdmSetId(existingMeasure.getMeasureSet().getId());
h.setFhirSetId(newFhirMeasure.getMeasureSet().getId());
h.setLastModifiedBy(user);
h.setLastModifiedOn(new Timestamp(System.currentTimeMillis()));
fhirConversionHIstoryDAO.save(h);
}
private void createMeasureXmlAndPersist(ManageMeasureDetailModel currentDetails, boolean creatingDraft, boolean isFhir, Measure measure, Measure clonedMeasure, String originalXml) throws MatException {
Document originalDoc = parseOriginalDocument(originalXml);
Document clonedDoc = originalDoc;
if (!creatingDraft) {
clearChildNodes(clonedDoc, MEASURE_DETAILS);
}
String formattedVersion = MeasureUtility.formatVersionText(clonedMeasure.getRevisionNumber(), clonedMeasure.getVersion());
SaveUpdateCQLResult saveUpdateCQLResult = cqlService.loadMeasureCql(measure, originalXml);
// Create the measureGrouping tag
clearChildNodes(clonedDoc, MEASURE_GROUPING);
clearChildNodes(clonedDoc, SUPPLEMENTAL_DATA_ELEMENTS);
clearChildNodes(clonedDoc, RISK_ADJUSTMENT_VARIABLES);
String clonedXMLString = convertDocumenttoString(clonedDoc);
MeasureXML clonedXml = new MeasureXML();
clonedXml.setMeasureXMLAsByteArray(clonedXMLString);
clonedXml.setMeasureId(clonedMeasure.getId());
XmlProcessor xmlProcessor = new XmlProcessor(clonedXml.getMeasureXMLAsString());
if (!isFhir) {
// Don't do this for fhir. The converted CQL will still have these and they they can't be found when
// generating the new mat xml.
List<String> usedCodeList = saveUpdateCQLResult.getUsedCQLArtifacts().getUsedCQLcodes();
xmlProcessor.removeUnusedDefaultCodes(usedCodeList);
}
removeMeasureDetailsNodes(xmlProcessor);
updateScoring(currentDetails, measure, clonedMeasure, xmlProcessor);
boolean isUpdatedForCQL = updateForCQLMeasure(xmlProcessor, clonedMeasure, isFhir);
xmlProcessor.clearValuesetVersionAttribute();
if (creatingDraft) {
updateCQLLookUpVersionOnDraft(xmlProcessor, formattedVersion);
} else {
resetVersionOnCloning(xmlProcessor);
}
// this means this is a CQL Measure to CQL Measure draft/clone.
if (!isUpdatedForCQL) {
updateForCqlMeasureDraftOrClone(isFhir, xmlProcessor);
}
updateCqlLibraryName(clonedMeasure, xmlProcessor);
clonedXml.setMeasureXMLAsByteArray(xmlProcessor.transform(xmlProcessor.getOriginalDoc()));
logger.debug("Final XML after cloning/draft " + clonedXml.getMeasureXMLAsString());
measureXmlDAO.save(clonedXml);
}
private void updateScoring(ManageMeasureDetailModel currentDetails, Measure measure, Measure clonedMeasure, XmlProcessor xmlProcessor) throws MatException {
if (!measure.getMeasureScoring().equals(currentDetails.getMeasScoring()) || currentDetails.isPatientBased()) {
String scoringTypeId = clonedMeasure.getMeasureScoring();
try {
xmlProcessor.removeNodesBasedOnScoring(scoringTypeId);
} catch (XPathExpressionException e) {
throw new MatException(e);
}
createNewNodesBasedOnScoring(xmlProcessor, scoringTypeId);
}
}
private void updateForCqlMeasureDraftOrClone(boolean creatingFhir, XmlProcessor xmlProcessor) throws MatException {
//create the default 4 CMS supplemental definitions
appendSupplementalDefinitions(xmlProcessor, false);
// Always set latest model version.
try {
MeasureUtility.updateModelVersion(xmlProcessor, creatingFhir);
} catch (XPathExpressionException e) {
throw new MatException(e);
}
}
private void updateCqlLibraryName(Measure clonedMeasure, XmlProcessor xmlProcessor) throws MatException {
// Update CQL Library Name from the UI field
try {
xmlProcessor.updateCQLLibraryName(clonedMeasure.getCqlLibraryName());
} catch (XPathExpressionException e) {
throw new MatException(e);
}
}
private Document parseOriginalDocument(String originalXml) throws MatException {
try {
InputSource oldXmlstream = new InputSource(new StringReader(originalXml));
DocumentBuilderFactory documentBuilderFactory = XMLUtility.getInstance().buildDocumentBuilderFactory();
DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
return docBuilder.parse(oldXmlstream);
} catch (ParserConfigurationException | IOException | SAXException e) {
throw new MatException(e);
}
}
private void validateMeasure(ManageMeasureDetailModel currentDetails) throws MatException {
ManageMeasureModelValidator validator = new ManageMeasureModelValidator();
List<String> messages = validator.validateMeasure(currentDetails);
if (!messages.isEmpty()) {
throw new MatException(MessageDelegate.GENERIC_ERROR_MESSAGE);
}
if (CQLValidationUtil.isCQLReservedWord(currentDetails.getCQLLibraryName())) {
throw new MatException(MessageDelegate.LIBRARY_NAME_IS_CQL_KEYWORD_ERROR);
}
if (cqlService.checkIfLibraryNameExists(currentDetails.getCQLLibraryName(), currentDetails.getMeasureSetId())) {
throw new MatException(MessageDelegate.DUPLICATE_LIBRARY_NAME);
}
}
public void removeMeasureDetailsNodes(XmlProcessor xmlProcessor) throws MatException {
removeNodeByPath(xmlProcessor, "/measure/measureDetails");
}
private Timestamp getTimestampFromDateString(String date) {
if (StringUtils.isEmpty(date)) {
return null;
}
try {
SimpleDateFormat datetimeFormatter1 = new SimpleDateFormat(
"MM/dd/yyyy");
Date fromDate = datetimeFormatter1.parse(date);
return new Timestamp(fromDate.getTime());
} catch (ParseException e) {
logger.error("Cant convert measure date");
return null;
}
}
private boolean isOrgPresentCheckByOID(String stewardOID) {
return organizationDAO.getAllOrganizations().stream().anyMatch(org -> String.valueOf(org.getOrganizationOID()).equals(stewardOID));
}
private boolean isOrgPresentCheckByID(String stewardID) {
return organizationDAO.getAllOrganizations().stream().anyMatch(org -> String.valueOf(org.getId()).equals(stewardID));
}
private void createMeasureDevelopers(Measure clonedMeasure, ManageMeasureDetailModel currentDetails) {
if (currentDetails.getAuthorSelectedList() != null) {
List<MeasureDeveloperAssociation> developerAssociations = currentDetails.getAuthorSelectedList().stream()
.map(author -> createMeasureDetailsAssociation(author, clonedMeasure))
.collect(Collectors.toList());
clonedMeasure.setMeasureDevelopers(developerAssociations);
}
}
private MeasureDeveloperAssociation createMeasureDetailsAssociation(Author author, Measure measure) {
String authorId = author.getId();
if (isOrgPresentCheckByOID(authorId) || isOrgPresentCheckByID(authorId)) {
Organization organization = organizationDAO.findByOidOrId(author.getId());
if (organization != null) {
return new MeasureDeveloperAssociation(measure, organization);
}
}
return null;
}
private void createMeasureType(Measure clonedMeasure, ManageMeasureDetailModel currentDetails) {
if (currentDetails.getMeasureTypeSelectedList() != null) {
List<MeasureTypeAssociation> typesAssociations = currentDetails.getMeasureTypeSelectedList().stream()
.map(type -> new MeasureTypeAssociation(clonedMeasure, type))
.collect(Collectors.toList());
clonedMeasure.setMeasureTypes(typesAssociations);
}
}
private List<ComponentMeasure> cloneAndSetComponentMeasures(List<ComponentMeasure> componentMeasures, Measure clonedMeasure) {
return componentMeasures.stream().map(f -> new ComponentMeasure(clonedMeasure, f.getComponentMeasure(), f.getAlias())).collect(Collectors.toList());
}
private boolean createDraftAndDetermineIfNonCQLAndPersist(boolean convertingQdmToFhir, Measure clonedMeasure, ManageMeasureDetailModel currentDetails, Measure measure) {
copyMeasureDetails(convertingQdmToFhir, clonedMeasure, currentDetails);
boolean isNonCQLtoCQLDraft = false;
clonedMeasure.setOwner(measure.getOwner());
// MAT-9206 changes
String draftVer;
if (MatContext.get().isCQLMeasure(measure.getReleaseVersion())) {
draftVer = measure.getVersion();
} else {
isNonCQLtoCQLDraft = true;
draftVer = getVersionOnNonCQLDraft(currentDetails.getVersionNumber());
}
if(convertingQdmToFhir) {
//For conversion create a new set id for FHIR.
MeasureSet measureSet = new MeasureSet();
measureSet.setId(UUID.randomUUID().toString());
measureSetDAO.save(measureSet);
clonedMeasure.setMeasureSet(measureSet);
clonedMeasure.setVersion(VERSION_ZERO);
} else {
clonedMeasure.setVersion(draftVer);
clonedMeasure.setMeasureSet(measure.getMeasureSet());
}
clonedMeasure.setRevisionNumber("000");
clonedMeasure.seteMeasureId(measure.geteMeasureId());
measureDAO.saveMeasure(clonedMeasure);
return isNonCQLtoCQLDraft;
}
private void copyMeasureDetails(boolean isQdmToFhir, Measure clonedMeasure, ManageMeasureDetailModel currentDetails) {
String stewardId = currentDetails.getStewardId();
if (isOrgPresentCheckByID(stewardId) || isOrgPresentCheckByOID(stewardId)) {
Organization organization = organizationDAO.findByOidOrId(currentDetails.getStewardId());
if (organization != null) {
clonedMeasure.setMeasureStewardId(String.valueOf(organization.getId()));
}
}
clonedMeasure.setNqfNumber(currentDetails.getNqfId());
ManageMeasureDetailModelConversions conversion = new ManageMeasureDetailModelConversions();
conversion.createMeasureDetails(isQdmToFhir, clonedMeasure, currentDetails);
createMeasureType(clonedMeasure, currentDetails);
createMeasureDevelopers(clonedMeasure, currentDetails);
}
private void cloneMeasureAndPersist(Measure clonedMeasure) {
// Clear the measureDetails tag
if (LoggedInUserUtil.getLoggedInUser() != null) {
User currentUser = userDAO.find(LoggedInUserUtil.getLoggedInUser());
clonedMeasure.setOwner(currentUser);
}
MeasureSet measureSet = new MeasureSet();
measureSet.setId(UUID.randomUUID().toString());
measureSetDAO.save(measureSet);
clonedMeasure.setMeasureSet(measureSet);
clonedMeasure.setVersion(VERSION_ZERO);
clonedMeasure.setRevisionNumber("000");
measureDAO.saveMeasure(clonedMeasure);
}
private boolean updateForCQLMeasure(XmlProcessor xmlProcessor, Measure clonedMeasure, boolean creatingFhir)
throws MatException {
Node cqlLookUpNode = findNode(xmlProcessor, "/measure/cqlLookUp");
if (cqlLookUpNode != null) {
// Update Model Version in Measure XMl for Draft and CQL Measures
Node modelVersionNode = findNode(xmlProcessor, "/measure/cqlLookUp/usingModelVersion");
if (modelVersionNode != null) {
modelVersionNode.setTextContent(creatingFhir ? propertiesService.getFhirVersion() : propertiesService.getQdmVersion());
}
// Update Model Type
Node modelNode = findNode(xmlProcessor, "/measure/cqlLookUp/usingModel");
if (modelNode != null) {
modelNode.setTextContent(creatingFhir ? ModelTypeHelper.FHIR : ModelTypeHelper.QDM);
}
return false;
}
removeNodeByPath(xmlProcessor, "/measure/populations");
removeNodeByPath(xmlProcessor, "/measure/measureObservations");
removeNodeByPath(xmlProcessor, "/measure/strata");
String scoringTypeId = clonedMeasure.getMeasureScoring();
createNewNodesBasedOnScoring(xmlProcessor, scoringTypeId);
generateCqlLookupTag(xmlProcessor, clonedMeasure, creatingFhir);
updateMeasureXmlWithQdm(xmlProcessor);
checkForDefaultCQLParametersAndAppend(xmlProcessor);
checkForDefaultCQLDefinitionsAndAppend(xmlProcessor);
return true;
}
private void generateCqlLookupTag(XmlProcessor xmlProcessor, Measure clonedMeasure, boolean isFhir) {
// This section generates CQL Look Up tag from CQLXmlTemplate.xml
XmlProcessor cqlXmlProcessor = cqlLibraryService.loadCQLXmlTemplateFile(isFhir);
String libraryName = clonedMeasure.getDescription();
String version = clonedMeasure.getVersion();
String cqlLookUpTag = cqlLibraryService.getCQLLookUpXml((MeasureUtility.cleanString(libraryName)),
version,
cqlXmlProcessor,
"//measure",
isFhir);
if (cqlLookUpTag != null && StringUtils.isNotBlank(cqlLookUpTag)) {
try {
xmlProcessor.appendNode(cqlLookUpTag, "cqlLookUp", "/measure");
} catch (SAXException | IOException e) {
logger.debug("Measure lookup failed:" + e.getMessage(), e);
}
}
}
private void createNewNodesBasedOnScoring(XmlProcessor xmlProcessor, String scoringTypeId) throws MatException {
try {
xmlProcessor.createNewNodesBasedOnScoring(scoringTypeId);
} catch (XPathExpressionException e) {
throw new MatException(e);
}
}
private void removeNodeByPath(XmlProcessor xmlProcessor, String xPath) throws MatException {
Node node = findNode(xmlProcessor, xPath);
if (node != null) {
Node parentNode = node.getParentNode();
parentNode.removeChild(node);
}
}
private Node findNode(XmlProcessor xmlProcessor, String xPath) throws MatException {
try {
return xmlProcessor.findNode(xmlProcessor.getOriginalDoc(), xPath);
} catch (XPathExpressionException e) {
throw new MatException(e);
}
}
private NodeList findNodeList(XmlProcessor xmlProcessor, String xPath) throws MatException {
try {
return xmlProcessor.findNodeList(xmlProcessor.getOriginalDoc(), xPath);
} catch (XPathExpressionException e) {
throw new MatException(e);
}
}
private void updateMeasureXmlWithQdm(XmlProcessor xmlProcessor) throws MatException {
// copy qdm to cqlLookup/valuesets
NodeList qdmNodes = findNodeList(xmlProcessor, "/measure/elementLookUp/qdm");
Node cqlValuesetsNode = findNode(xmlProcessor, "/measure/cqlLookUp/valuesets");
List<Node> qdmNodeList = new ArrayList<>();
List<Node> cqlValuesetsNodeList = new ArrayList<>();
if (cqlValuesetsNode != null) {
populateQdmNodeList(xmlProcessor, qdmNodes, cqlValuesetsNode, qdmNodeList);
populateCqlValueSets(xmlProcessor, cqlValuesetsNode, cqlValuesetsNodeList);
}
removeAllDuplicateValueSets(cqlValuesetsNodeList);
removeAllUnclonableQdmElements(qdmNodeList);
}
private void populateQdmNodeList(XmlProcessor xmlProcessor, NodeList qdmNodes, Node cqlValuesetsNode, List<Node> qdmNodeList) {
/**
* We need to capture old "Patient Characteristic Expired"(oid=419099009) and "Patient Characteristic Birthdate"(oid=21112-8)
* and remove them. Also we need to remove qdm with name="Birthdate' and 'Expired' which are non default qdms along with Occurrence
* qdm elements.
* Further below, when checkForTimingElementsAndAppend() is called, it will add back the above 2 elements with new properties.
* For ex: "Patient Characteristic Expired" had an old name of "Expired", but the new name is "Dead".
*/
for (int i = 0; i < qdmNodes.getLength(); i++) {
Node qdmNode = qdmNodes.item(i);
populateQdmNodeListWithNode(xmlProcessor, cqlValuesetsNode, qdmNodeList, qdmNode);
}
}
private void populateQdmNodeListWithNode(XmlProcessor xmlProcessor, Node cqlValuesetsNode, List<Node> qdmNodeList, Node qdmNode) {
String oid = qdmNode.getAttributes().getNamedItem(OID).getNodeValue();
String qdmName = qdmNode.getAttributes().getNamedItem(NAME).getNodeValue();
String dataType = qdmNode.getAttributes().getNamedItem(DATATYPE).getNodeValue();
boolean isCloneable = calculateNodeCloneableAndPopulateToQdmNodeList(qdmNodeList, qdmNode, oid, qdmName, dataType);
if (isCloneable) {
adjustCqlValueSetsNodeOnClonable(xmlProcessor, cqlValuesetsNode, qdmNode);
}
}
private boolean calculateNodeCloneableAndPopulateToQdmNodeList(List<Node> qdmNodeList, Node qdmNode, String oid, String qdmName, String dataType) {
boolean isCloneable = true;
if (oid.equals(PATIENT_CHARACTERISTIC_BIRTH_DATE_OID)) {
isCloneable = false;
} else if (oid.equals(PATIENT_CHARACTERISTIC_EXPIRED_OID) ||
qdmName.equalsIgnoreCase(QDM_BIRTHDATE_NON_DEFAULT) ||
dataType.equalsIgnoreCase(PATIENT_CHARACTERISTIC_BIRTH_DATE) ||
dataType.equalsIgnoreCase(PATIENT_CHARACTERISTIC_EXPIRED) ||
dataType.equalsIgnoreCase(TIMING_ELEMENT)) {
qdmNodeList.add(qdmNode);
isCloneable = false;
}
// Remove Specific Occurrence of QDM
if (qdmNode.getAttributes().getNamedItem("instance") != null) {
qdmNodeList.add(qdmNode);
isCloneable = false;
}
return isCloneable;
}
private void adjustCqlValueSetsNodeOnClonable(XmlProcessor xmlProcessor, Node cqlValuesetsNode, Node qdmNode) {
// MAT-8729 : Drafting of non-CQL to CQL measures - force version to be 1.0 if its value is 1.
String qdmAppliedVersion = qdmNode.getAttributes().getNamedItem(VERSION).getNodeValue();
if (qdmAppliedVersion.equals("1")) {
qdmNode.getAttributes().getNamedItem(VERSION).setNodeValue("1.0");
}
Node clonedqdmNode = qdmNode.cloneNode(true);
xmlProcessor.getOriginalDoc().renameNode(clonedqdmNode, null, "valueset");
// MAT-8770
if (clonedqdmNode.getAttributes().getNamedItem(DATATYPE) != null) {
clonedqdmNode.getAttributes().removeNamedItem(DATATYPE);
}
cqlValuesetsNode.appendChild(clonedqdmNode);
}
private void populateCqlValueSets(XmlProcessor xmlProcessor, Node cqlValuesetsNode, List<Node> cqlValuesetsNodeList) {
for (int i = 0; i < cqlValuesetsNode.getChildNodes().getLength(); i++) {
Node valueSetNode = cqlValuesetsNode.getChildNodes().item(i);
addOriginalNameAttributeIfNotPresent(valueSetNode, xmlProcessor);
addProgramAttributeIfNotPresent(valueSetNode, xmlProcessor);
addReleaseAttributeIfNotPresent(valueSetNode, xmlProcessor);
addVSACTypeAttributeIfNotPresent(valueSetNode, xmlProcessor);
cqlValuesetsNodeList.add(valueSetNode);
}
}
private void removeAllDuplicateValueSets(List<Node> cqlValuesetsNodeList) {
// Remove all duplicate value sets for new Value Sets workspace.
if (cqlValuesetsNodeList != null && !cqlValuesetsNodeList.isEmpty()) {
List<String> cqlVSACValueSets = new ArrayList<>();
List<String> cqlUserDefValueSets = new ArrayList<>();
for (int i = 0; i < cqlValuesetsNodeList.size(); i++) {
Node cqlNode = cqlValuesetsNodeList.get(i);
Node parentNode = cqlNode.getParentNode();
String valuesetName = cqlNode.getAttributes().getNamedItem(NAME).getTextContent();
processValueSet(cqlVSACValueSets, cqlUserDefValueSets, cqlNode, parentNode, valuesetName);
}
// Loop through user Defined and remove if it exists already in VSAC list
removeValueSetsIfExistsInVsacList(cqlValuesetsNodeList, cqlVSACValueSets, cqlUserDefValueSets);
cqlVSACValueSets.clear();
cqlUserDefValueSets.clear();
}
}
private void processValueSet(List<String> cqlVSACValueSets, List<String> cqlUserDefValueSets, Node cqlNode, Node parentNode, String valuesetName) {
if (!isUserDefinedValueSet(cqlNode.getAttributes().getNamedItem(OID).getTextContent())) {
if (!cqlVSACValueSets.contains(valuesetName)) {
cqlVSACValueSets.add(valuesetName);
} else {
parentNode.removeChild(cqlNode);
}
} else {
if (!cqlUserDefValueSets.contains(valuesetName)) {
cqlUserDefValueSets.add(valuesetName);
} else {
parentNode.removeChild(cqlNode);
}
}
}
private void removeValueSetsIfExistsInVsacList(List<Node> cqlValuesetsNodeList, List<String> cqlVSACValueSets, List<String> cqlUserDefValueSets) {
for (int i = 0; i < cqlValuesetsNodeList.size(); i++) {
Node cqlNode = cqlValuesetsNodeList.get(i);
Node parentNode = cqlNode.getParentNode();
if (isUserDefinedValueSet(cqlNode.getAttributes().getNamedItem(OID).getTextContent())) {
for (String userDefName : cqlUserDefValueSets) {
if (cqlVSACValueSets.contains(userDefName)) {
parentNode.removeChild(cqlNode);
}
}
}
}
}
private void removeAllUnclonableQdmElements(List<Node> qdmNodeList) {
// Remove all unclonable QDM's collected above in For Loop from elementLookUp tag.
if (qdmNodeList != null && !qdmNodeList.isEmpty()) {
for (int i = 0; i < qdmNodeList.size(); i++) {
Node qNode = qdmNodeList.get(i);
Node parentNode = qNode.getParentNode();
parentNode.removeChild(qNode);
}
}
}
private boolean isUserDefinedValueSet(String valuesetOID) {
return valuesetOID.equals(ConstantMessages.USER_DEFINED_QDM_OID);
}
private void addOriginalNameAttributeIfNotPresent(Node valueSetNode, XmlProcessor xmlProcessor) {
addAttributeIfNotPresent(ORIGINAL_NAME, valueSetNode.getAttributes().getNamedItem(NAME).getNodeValue(), valueSetNode, xmlProcessor);
}
private void addProgramAttributeIfNotPresent(Node nodeToUpdate, XmlProcessor xmlProcessor) {
addAttributeIfNotPresent(PROGRAM, StringUtils.EMPTY, nodeToUpdate, xmlProcessor);
}
private void addReleaseAttributeIfNotPresent(Node nodeToUpdate, XmlProcessor xmlProcessor) {
addAttributeIfNotPresent(RELEASE, StringUtils.EMPTY, nodeToUpdate, xmlProcessor);
}
private void addVSACTypeAttributeIfNotPresent(Node valueSetNode, XmlProcessor xmlProcessor) {
String valueSetType = getVSACTypeBasedOnTaxonomy(valueSetNode);
addAttributeIfNotPresent(TYPE, valueSetType, valueSetNode, xmlProcessor);
}
private void addAttributeIfNotPresent(String attributeName, String value, Node nodeToUpdate, XmlProcessor xmlProcessor) {
Node attribute = nodeToUpdate.getAttributes().getNamedItem(attributeName);
if (attribute == null) {
createDefaultAttr(attributeName, value, nodeToUpdate, xmlProcessor);
}
}
private void createDefaultAttr(String name, String value, Node nodeToUpdate, XmlProcessor xmlProcessor) {
Attr attr = xmlProcessor.getOriginalDoc().createAttribute(name);
attr.setNodeValue(value);
nodeToUpdate.getAttributes().setNamedItem(attr);
}
private String getVSACTypeBasedOnTaxonomy(Node valueset) {
if (isUserDefinedValueSet(valueset.getAttributes().getNamedItem(OID).getNodeValue())) {
return "";
}
return GROUPING.equals(valueset.getAttributes().getNamedItem(TAXONOMY).getNodeValue()) ? GROUPING : EXTENSIONAL;
}
/**
* Append cql definitions.
*
* @param xmlProcessor the xml processor
*/
private void checkForDefaultCQLDefinitionsAndAppend(XmlProcessor xmlProcessor) {
NodeList defaultCQLDefNodeList = findDefaultDefinitions(xmlProcessor);
if (defaultCQLDefNodeList != null && defaultCQLDefNodeList.getLength() == 4) {
logger.debug("All Default definition elements present in the measure while cloning.");
logger.debug("Check if SupplementalDataElement present in the measure while cloning.");
// This checks if SDE holds child elements ,if not then append it.
String defaultSDE = "/measure/supplementalDataElements";
try {
Node sdeNode = findNode(xmlProcessor, defaultSDE);
if (sdeNode != null && !sdeNode.hasChildNodes()) {
appendSupplementalDefinitions(xmlProcessor, true);
}
} catch (MatException e) {
logger.error("checkForDefaultCQLDefinitionsAndAppend:" + e.getMessage(), e);
}
return;
}
String defStr = cqlService.getSupplementalDefinitions();
logger.debug("defStr:" + defStr);
try {
xmlProcessor.appendNode(defStr, "definition", "/measure/cqlLookUp/definitions");
appendSupplementalDefinitions(xmlProcessor, true);
} catch (SAXException | IOException | MatException e) {
logger.error("checkForDefaultCQLDefinitionsAndAppend:" + e.getMessage(), e);
}
}
private void appendSupplementalDefinitions(XmlProcessor xmlProcessor, boolean createNewIds) throws MatException {
Node supplementalDataNode = findNode(xmlProcessor, "/measure/supplementalDataElements");
while (supplementalDataNode.hasChildNodes()) {
supplementalDataNode.removeChild(supplementalDataNode.getFirstChild());
}
NodeList supplementalDefnNodes = findNodeList(xmlProcessor, "/measure/cqlLookUp/definitions/definition[@supplDataElement='true']");
if (supplementalDefnNodes != null) {
for (int i = 0; i < supplementalDefnNodes.getLength(); i++) {
Node supplNode = supplementalDefnNodes.item(i);
if (createNewIds) {
supplNode.getAttributes().getNamedItem("id").setNodeValue(UUIDUtilClient.uuid());
}
Element cqlDefinitionRefNode = xmlProcessor.getOriginalDoc().createElement("cqldefinition");
cqlDefinitionRefNode.setAttribute("displayName", supplNode.getAttributes().getNamedItem(NAME).getNodeValue());
cqlDefinitionRefNode.setAttribute(UU_ID, supplNode.getAttributes().getNamedItem("id").getNodeValue());
supplementalDataNode.appendChild(cqlDefinitionRefNode);
}
}
}
/**
* This method will look into XPath "/measure/cqlLookUp/definitions/" and try and NodeList for Definitions with the following names;
* 'SDE Ethnicity','SDE Payer','SDE Race','SDE Sex'.
*
* @param xmlProcessor
* @return
*/
private NodeList findDefaultDefinitions(XmlProcessor xmlProcessor) {
try {
String defaultDefinitionsXPath = "/measure/cqlLookUp/definitions/definition[@name ='SDE Ethnicity' or @name='SDE Payer' or @name='SDE Race' or @name='SDE Sex']";
return findNodeList(xmlProcessor, defaultDefinitionsXPath);
} catch (MatException e) {
logger.error(e.getMessage(), e);
}
return null;
}
/**
* Check for default cql parameters and append.
*
* @param xmlProcessor the xml processor
*/
private void checkForDefaultCQLParametersAndAppend(XmlProcessor xmlProcessor) {
List<String> missingDefaultCQLParameters = xmlProcessor.checkForDefaultParameters();
if (missingDefaultCQLParameters.isEmpty()) {
logger.debug("All Default parameter elements present in the measure while cloning.");
return;
}
logger.debug("While cloning, found the following Default parameter elements missing:" + missingDefaultCQLParameters);
CQLParameter parameter = new CQLParameter();
parameter.setId(UUID.randomUUID().toString());
parameter.setName(CQLWorkSpaceConstants.CQL_DEFAULT_MEASUREMENTPERIOD_PARAMETER_NAME);
parameter.setLogic(CQLWorkSpaceConstants.CQL_DEFAULT_MEASUREMENTPERIOD_PARAMETER_LOGIC);
parameter.setReadOnly(true);
String parStr = cqlService.createParametersXML(parameter);
try {
xmlProcessor.appendNode(parStr, "parameter", "/measure/cqlLookUp/parameters");
} catch (SAXException | IOException e) {
logger.debug("checkForDefaultCQLParametersAndAppend:" + e.getMessage());
}
}
private void clearChildNodes(Document clonedDoc, String nodeName) {
NodeList nodeList = clonedDoc.getElementsByTagName(nodeName);
Node parentNode = nodeList.item(0);
if (parentNode != null) {
while (parentNode.hasChildNodes()) {
parentNode.removeChild(parentNode.getFirstChild());
}
}
}
/**
* Method to check If a user is trying to Clone a measure whose release version is not
* v5.xx.
* If the version is v4.xxx or v3.xxx or is NULL, then the method returns true, indicating cloning is not
* allowed for this measure.
*
* @param measure
* @param creatingDraft
* @return
*/
private boolean checkNonCQLCloningValidation(Measure measure,
boolean creatingDraft) {
if (creatingDraft) {
return false;
}
boolean returnValue = false;
String measureReleaseVersion = StringUtils.trimToEmpty(measure.getReleaseVersion());
if (measureReleaseVersion.length() == 0 || measureReleaseVersion.startsWith("v4") || measureReleaseVersion.startsWith("v3")) {
returnValue = true;
}
return returnValue;
}
private String convertDocumenttoString(Document doc) throws MatException {
try {
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = XMLUtility.getInstance().buildTransformerFactory();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
} catch (TransformerException e) {
throw new MatException(e);
}
}
private String getVersionOnNonCQLDraft(String version) {
String ver = StringUtils.substringAfterLast(version, "v");
if (StringUtils.countMatches(ver, ".") == 2) {
ver = StringUtils.substringBeforeLast(ver, ".");
}
String major = StringUtils.substringBeforeLast(ver, ".");
String minor = StringUtils.substringAfterLast(ver, ".");
return major + "." + StringUtils.leftPad(minor, 3, "0");
}
private void resetVersionOnCloning(XmlProcessor processor) {
javax.xml.xpath.XPath xPath = XPathFactory.newInstance().newXPath();
String cqlVersionXPath = "//cqlLookUp/version";
try {
Node node = (Node) xPath.evaluate(cqlVersionXPath, processor.getOriginalDoc().getDocumentElement(), XPathConstants.NODE);
if (node != null) {
node.setTextContent("0.0.000");
}
} catch (XPathExpressionException e) {
logger.error(e.getMessage());
}
}
private void updateCQLLookUpVersionOnDraft(XmlProcessor processor, String version) {
javax.xml.xpath.XPath xPath = XPathFactory.newInstance().newXPath();
String cqlVersionXPath = "//cqlLookUp/version";
try {
Node node = (Node) xPath.evaluate(cqlVersionXPath, processor.getOriginalDoc().getDocumentElement(), XPathConstants.NODE);
if (node != null) {
node.setTextContent(version);
}
} catch (XPathExpressionException e) {
logger.error(e.getMessage());
}
}
private Timestamp getNextCalenderYearFromDate() {
Timestamp timestamp = null;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
int year = Calendar.getInstance().get(Calendar.YEAR);
Date fromDate = dateFormat.parse("01/01/" + ++year);
timestamp = new java.sql.Timestamp(fromDate.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
return timestamp;
}
private Timestamp getNextCalenderYearToDate() {
Timestamp timestamp = null;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
int year = Calendar.getInstance().get(Calendar.YEAR);
Date fromDate = dateFormat.parse("12/31/" + ++year);
timestamp = new java.sql.Timestamp(fromDate.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
return timestamp;
}
}
|
3e195dea783602d83585bf01613695d0ceb986a5 | 3,526 | java | Java | app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCE.java | OneToolsCollection/appsmithorg-appsmith | ce23d338556d07cd0c11cf384902fa595b845aab | [
"Apache-2.0"
] | 1 | 2022-03-26T14:26:04.000Z | 2022-03-26T14:26:04.000Z | app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCE.java | OneToolsCollection/appsmithorg-appsmith | ce23d338556d07cd0c11cf384902fa595b845aab | [
"Apache-2.0"
] | 4 | 2022-02-15T05:24:13.000Z | 2022-03-25T20:54:22.000Z | app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/NewPageServiceCE.java | OneToolsCollection/appsmithorg-appsmith | ce23d338556d07cd0c11cf384902fa595b845aab | [
"Apache-2.0"
] | null | null | null | 43 | 131 | 0.754112 | 10,770 | package com.appsmith.server.services.ce;
import com.appsmith.server.acl.AclPermission;
import com.appsmith.server.domains.ApplicationMode;
import com.appsmith.server.domains.Layout;
import com.appsmith.server.domains.NewPage;
import com.appsmith.server.dtos.ApplicationPagesDTO;
import com.appsmith.server.dtos.PageDTO;
import com.appsmith.server.services.CrudService;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.List;
public interface NewPageServiceCE extends CrudService<NewPage, String> {
Mono<PageDTO> getPageByViewMode(NewPage newPage, Boolean viewMode);
Mono<NewPage> findById(String pageId, AclPermission aclPermission);
Mono<PageDTO> findPageById(String pageId, AclPermission aclPermission, Boolean view);
Flux<PageDTO> findByApplicationId(String applicationId, AclPermission permission, Boolean view);
Flux<NewPage> findNewPagesByApplicationId(String applicationId, AclPermission permission);
Mono<PageDTO> saveUnpublishedPage(PageDTO page);
Mono<PageDTO> createDefault(PageDTO object);
Mono<PageDTO> findByIdAndLayoutsId(String pageId, String layoutId, AclPermission aclPermission, Boolean view);
Mono<PageDTO> findByNameAndViewMode(String name, AclPermission permission, Boolean view);
Mono<Void> deleteAll();
Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewModeAndBranch(String applicationId,
String branchName,
Boolean view,
boolean markApplicationAsRecentlyAccessed);
Mono<ApplicationPagesDTO> findApplicationPages(String applicationId, String pageId, String branchName, ApplicationMode mode);
Mono<ApplicationPagesDTO> findApplicationPagesByApplicationIdViewMode(
String applicationId, Boolean view, boolean markApplicationAsRecentlyAccessed
);
Layout createDefaultLayout();
Mono<ApplicationPagesDTO> findNamesByApplicationNameAndViewMode(String applicationName, Boolean view);
Mono<PageDTO> findByNameAndApplicationIdAndViewMode(String name, String applicationId, AclPermission permission, Boolean view);
Mono<List<NewPage>> archivePagesByApplicationId(String applicationId, AclPermission permission);
Mono<List<String>> findAllPageIdsInApplication(String applicationId, AclPermission permission, Boolean view);
Mono<PageDTO> updatePage(String pageId, PageDTO page);
Mono<PageDTO> updatePageByDefaultPageIdAndBranch(String defaultPageId, PageDTO page, String branchName);
Mono<NewPage> save(NewPage page);
Mono<NewPage> archive(NewPage page);
Mono<NewPage> archiveById(String id);
Flux<NewPage> saveAll(List<NewPage> pages);
Mono<String> getNameByPageId(String pageId, boolean isPublishedName);
Mono<NewPage> findByBranchNameAndDefaultPageId(String branchName, String defaultPageId, AclPermission permission);
Mono<String> findBranchedPageId(String branchName, String defaultPageId, AclPermission permission);
Mono<String> findRootApplicationIdFromNewPage(String branchName, String defaultPageId);
Mono<NewPage> findByGitSyncIdAndDefaultApplicationId(String defaultApplicationId, String gitSyncId, AclPermission permission);
Flux<NewPage> findPageSlugsByApplicationIds(List<String> applicationIds, AclPermission aclPermission);
}
|
3e195dff3588678d6991876c5e8d08b9effcbc85 | 2,597 | java | Java | xrpl4j-model/src/test/java/org/xrpl/xrpl4j/model/ledger/PayChannelObjectJsonTests.java | xdvsf/xrpl4j | 9f7d74e5371d6726503ec8a066900cdcd731d523 | [
"0BSD"
] | 50 | 2020-12-04T00:30:11.000Z | 2022-03-29T16:53:39.000Z | xrpl4j-model/src/test/java/org/xrpl/xrpl4j/model/ledger/PayChannelObjectJsonTests.java | xdvsf/xrpl4j | 9f7d74e5371d6726503ec8a066900cdcd731d523 | [
"0BSD"
] | 210 | 2020-12-03T21:11:26.000Z | 2022-03-31T22:19:09.000Z | xrpl4j-model/src/test/java/org/xrpl/xrpl4j/model/ledger/PayChannelObjectJsonTests.java | xdvsf/xrpl4j | 9f7d74e5371d6726503ec8a066900cdcd731d523 | [
"0BSD"
] | 24 | 2020-12-03T21:46:00.000Z | 2022-03-07T16:43:02.000Z | 46.375 | 108 | 0.709665 | 10,771 | package org.xrpl.xrpl4j.model.ledger;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.primitives.UnsignedInteger;
import com.google.common.primitives.UnsignedLong;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.xrpl.xrpl4j.model.AbstractJsonTest;
import org.xrpl.xrpl4j.model.transactions.Address;
import org.xrpl.xrpl4j.model.transactions.Hash256;
import org.xrpl.xrpl4j.model.transactions.XrpCurrencyAmount;
public class PayChannelObjectJsonTests extends AbstractJsonTest {
@Test
public void testJson() throws JsonProcessingException, JSONException {
PayChannelObject object = PayChannelObject.builder()
.account(Address.of("rBqb89MRQJnMPq8wTwEbtz4kvxrEDfcYvt"))
.destination(Address.of("rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn"))
.amount(XrpCurrencyAmount.ofDrops(4325800))
.balance(XrpCurrencyAmount.ofDrops(2323423))
.publicKey("32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A")
.settleDelay(UnsignedLong.valueOf(3600))
.expiration(UnsignedLong.valueOf(536027313))
.cancelAfter(UnsignedLong.valueOf(536891313))
.sourceTag(UnsignedInteger.ZERO)
.destinationTag(UnsignedInteger.valueOf(1002341))
.ownerNode("0000000000000000")
.previousTransactionId(Hash256.of("F0AB71E777B2DA54B86231E19B82554EF1F8211F92ECA473121C655BFC5329BF"))
.previousTransactionLedgerSequence(UnsignedInteger.valueOf(14524914))
.index(Hash256.of("96F76F27D8A327FC48753167EC04A46AA0E382E6F57F32FD12274144D00F1797"))
.build();
String json = "{\n" +
" \"Account\": \"rBqb89MRQJnMPq8wTwEbtz4kvxrEDfcYvt\",\n" +
" \"Destination\": \"rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn\",\n" +
" \"Amount\": \"4325800\",\n" +
" \"Balance\": \"2323423\",\n" +
" \"PublicKey\": \"32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A\",\n" +
" \"SettleDelay\": 3600,\n" +
" \"Expiration\": 536027313,\n" +
" \"CancelAfter\": 536891313,\n" +
" \"SourceTag\": 0,\n" +
" \"DestinationTag\": 1002341,\n" +
" \"Flags\": 0,\n" +
" \"LedgerEntryType\": \"PayChannel\",\n" +
" \"OwnerNode\": \"0000000000000000\",\n" +
" \"PreviousTxnID\": \"F0AB71E777B2DA54B86231E19B82554EF1F8211F92ECA473121C655BFC5329BF\",\n" +
" \"PreviousTxnLgrSeq\": 14524914,\n" +
" \"index\": \"96F76F27D8A327FC48753167EC04A46AA0E382E6F57F32FD12274144D00F1797\"\n" +
"}";
assertCanSerializeAndDeserialize(object, json);
}
}
|
3e195e0f8ff837b0333e2cce6d25b3f406ae2a66 | 407 | java | Java | sample/src/main/java/xyz/bboylin/demo/AppRuntimeForTestMultiProvider.java | bboylin/Pigeon | be8f4ace34c7c0dd250b24d69ec71be8d6e74e43 | [
"Apache-2.0"
] | 6 | 2019-03-15T15:44:30.000Z | 2021-02-11T14:57:46.000Z | sample/src/main/java/xyz/bboylin/demo/AppRuntimeForTestMultiProvider.java | bboylin/Pigeon | be8f4ace34c7c0dd250b24d69ec71be8d6e74e43 | [
"Apache-2.0"
] | null | null | null | sample/src/main/java/xyz/bboylin/demo/AppRuntimeForTestMultiProvider.java | bboylin/Pigeon | be8f4ace34c7c0dd250b24d69ec71be8d6e74e43 | [
"Apache-2.0"
] | 1 | 2020-12-24T07:54:30.000Z | 2020-12-24T07:54:30.000Z | 20.35 | 68 | 0.749386 | 10,772 | package xyz.bboylin.demo;
import android.content.Context;
import xyz.bboylin.anothersamplelib.IAppRuntime;
import xyz.bboylin.pigeon.annotation.Provider;
//@Provider
public class AppRuntimeForTestMultiProvider implements IAppRuntime {
@Override
public Context getAppContext() {
return null;
}
@Override
public void showUniversalToast(Context context, String text) {
}
}
|
3e195f22f519a279cbbe02585c90edfedc4b71e1 | 3,907 | java | Java | scribble-core/src/main/java/org/scribble/ast/local/LDo.java | keigoi/scribble-ocaml | 09081f5a119b064b18262c999c60fca1c4c5f60f | [
"Apache-2.0"
] | 1 | 2018-04-16T04:55:21.000Z | 2018-04-16T04:55:21.000Z | scribble-core/src/main/java/org/scribble/ast/local/LDo.java | keigoi/scribble-ocaml | 09081f5a119b064b18262c999c60fca1c4c5f60f | [
"Apache-2.0"
] | null | null | null | scribble-core/src/main/java/org/scribble/ast/local/LDo.java | keigoi/scribble-ocaml | 09081f5a119b064b18262c999c60fca1c4c5f60f | [
"Apache-2.0"
] | 1 | 2020-04-01T08:54:04.000Z | 2020-04-01T08:54:04.000Z | 31.256 | 193 | 0.760942 | 10,773 | /**
* Copyright 2008 The Scribble Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.scribble.ast.local;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import org.antlr.runtime.tree.CommonTree;
import org.scribble.ast.AstFactory;
import org.scribble.ast.Do;
import org.scribble.ast.NonRoleArgList;
import org.scribble.ast.RoleArgList;
import org.scribble.ast.context.ModuleContext;
import org.scribble.ast.name.qualified.LProtocolNameNode;
import org.scribble.ast.name.qualified.ProtocolNameNode;
import org.scribble.del.ScribDel;
import org.scribble.main.JobContext;
import org.scribble.main.RuntimeScribbleException;
import org.scribble.main.ScribbleException;
import org.scribble.type.Message;
import org.scribble.type.kind.Local;
import org.scribble.type.name.LProtocolName;
import org.scribble.type.name.Role;
import org.scribble.visit.context.ProjectedChoiceSubjectFixer;
public class LDo extends Do<Local> implements LSimpleInteractionNode
{
public LDo(CommonTree source, RoleArgList roleinstans, NonRoleArgList arginstans, LProtocolNameNode proto)
{
super(source, roleinstans, arginstans, proto);
}
@Override
protected LDo copy()
{
return new LDo(this.source, this.roles, this.args, getProtocolNameNode());
}
@Override
public LDo clone(AstFactory af)
{
RoleArgList roles = this.roles.clone(af);
NonRoleArgList args = this.args.clone(af);
LProtocolNameNode proto = this.getProtocolNameNode().clone(af);
return af.LDo(this.source, roles, args, proto);
}
@Override
public LDo reconstruct(RoleArgList roles, NonRoleArgList args, ProtocolNameNode<Local> proto)
{
ScribDel del = del();
LDo ld = new LDo(this.source, roles, args, (LProtocolNameNode) proto);
ld = (LDo) ld.del(del);
return ld;
}
@Override
public LProtocolNameNode getProtocolNameNode()
{
return (LProtocolNameNode) this.proto;
}
@Override
public LProtocolName getTargetProtocolDeclFullName(ModuleContext mcontext)
{
return (LProtocolName) super.getTargetProtocolDeclFullName(mcontext);
}
@Override
public LProtocolDecl getTargetProtocolDecl(JobContext jcontext, ModuleContext mcontext)
{
return (LProtocolDecl) super.getTargetProtocolDecl(jcontext, mcontext);
}
@Override
public Role inferLocalChoiceSubject(ProjectedChoiceSubjectFixer fixer)
{
ModuleContext mc = fixer.getModuleContext();
JobContext jc = fixer.job.getContext();
Role subj = getTargetProtocolDecl(jc, mc).getDef().getBlock()
.getInteractionSeq().getInteractions().get(0).inferLocalChoiceSubject(fixer);
// FIXME: need equivalent of (e.g) rec X { continue X; } pruning (cf GRecursion.prune) for irrelevant recursive-do (e.g. proto(A, B, C) { choice at A {A->B.do Proto(A,B,C)} or {A->B.B->C} }))
Iterator<Role> roleargs = this.roles.getRoles().iterator();
for (Role decl : getTargetProtocolDecl(jc, mc).header.roledecls.getRoles())
{
Role arg = roleargs.next();
if (decl.equals(subj))
{
return arg;
}
}
throw new RuntimeException("Shouldn't get here: " + this);
}
@Override
public LInteractionNode merge(AstFactory af, LInteractionNode ln) throws ScribbleException
{
throw new RuntimeScribbleException("Invalid merge on LDo: " + this);
}
@Override
public boolean canMerge(LInteractionNode ln)
{
return false;
}
@Override
public Set<Message> getEnabling()
{
return Collections.emptySet();
}
}
|
3e195f24ce8c30813cd2a7d556748c94e4cc9f91 | 2,555 | java | Java | cluster-boost-ignite/src/main/java/com/technologicgroup/boost/chain/ChainBeanCommon.java | technologicgroup/cluster-boost | 3cbf617707387c8f8dd8b9d104da4d32e9d0f3d7 | [
"MIT"
] | 5 | 2020-06-17T14:14:11.000Z | 2021-12-24T08:46:51.000Z | cluster-boost-ignite/src/main/java/com/technologicgroup/boost/chain/ChainBeanCommon.java | technologicgroup/cluster-boost | 3cbf617707387c8f8dd8b9d104da4d32e9d0f3d7 | [
"MIT"
] | 2 | 2020-07-11T09:49:08.000Z | 2020-07-11T09:56:57.000Z | cluster-boost-ignite/src/main/java/com/technologicgroup/boost/chain/ChainBeanCommon.java | technologicgroup/cluster-boost | 3cbf617707387c8f8dd8b9d104da4d32e9d0f3d7 | [
"MIT"
] | null | null | null | 36.5 | 163 | 0.715068 | 10,774 | package com.technologicgroup.boost.chain;
import com.technologicgroup.boost.core.Cluster;
import com.technologicgroup.boost.core.ClusterTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import java.sql.Timestamp;
import java.util.Optional;
/**
* ChainBean implementation contains execution for chain steps
* Every step represents a Spring bean that will be executed on a local node
* @param <A> is a class of the first chain step's argument
* @param <R> is a class of the result of the chain tasks
*/
@Slf4j
@Service
class ChainBeanCommon<A, R> extends ChainBean<A, R> {
protected final ApplicationContext context;
public ChainBeanCommon(Cluster cluster, ApplicationContext context) {
super(cluster);
this.context = context;
}
/**
* Returns a Spring bean for a bean class
* @param bean is a class of a bean
* @param <T> is a class of a bean
* @return a Spring bean
*/
@Override
protected <T> T getBean(Class<T> bean) {
return context.getBean(bean);
}
/**
* Writes results to the log on a bean execution finished
* @param trackingId is the tracking identifier
* @param start is the start execution timestamp
* @param end is the end of execution timestamp
* @param message is a failure message if execution fails and {#code=null} otherwise
* @param detailedMessage is a detailed failure message
* @param bean is a bean that was finished execution on local node
*/
@Override
protected void onFinishBean(String trackingId, Timestamp start, Timestamp end, String message, String detailedMessage, Class<? extends ClusterTask<?, ?>> bean) {
if (message == null) {
log.info("{}", String.format("Bean %s on node %s has finished. TrackingId: %s", bean, cluster.getLocalNode(), trackingId));
} else {
log.error("{}", String.format("Bean %s on node %s has failed with message %s, cause: %s. TrackingId: %s",
bean, cluster.getLocalNode(), message, Optional.ofNullable(detailedMessage).orElse("unknown"), trackingId));
}
}
/**
* Writes to the log on bean execution starts
* @param trackingId is the tracking identifier
* @param start is the start execution timestamp
* @param bean is a bean that was finished execution on local node
*/
@Override
protected void onStartBean(String trackingId, Timestamp start, Class<? extends ClusterTask<?, ?>> bean) {
log.info("Bean {} on node {} has started", bean, cluster.getLocalNode());
}
}
|
3e195fe8b34b317e44836da7571ac6f540cf1c4a | 725 | java | Java | playscript-java/src/main/play/Variable.java | darklost/play_with_compiler | 9931b72c4f8c4c8995a76bfa9c5b7ce1449b38d5 | [
"Apache-2.0"
] | null | null | null | playscript-java/src/main/play/Variable.java | darklost/play_with_compiler | 9931b72c4f8c4c8995a76bfa9c5b7ce1449b38d5 | [
"Apache-2.0"
] | null | null | null | playscript-java/src/main/play/Variable.java | darklost/play_with_compiler | 9931b72c4f8c4c8995a76bfa9c5b7ce1449b38d5 | [
"Apache-2.0"
] | null | null | null | 20.714286 | 82 | 0.622069 | 10,775 | package play;
import org.antlr.v4.runtime.ParserRuleContext;
public class Variable extends Symbol {
//变量类型
protected Type type = null;
//// 作为parameter的变量的属性
//缺省值
protected Object defaultValue = null;
//是否允许多次重复,这是一个创新的参数机制
protected Integer multiplicity = 1;
protected Variable(String name, Scope enclosingScope, ParserRuleContext ctx) {
this.name = name;
this.enclosingScope = enclosingScope;
this.ctx = ctx;
}
/**
* 是不是类的属性
* @return
*/
public boolean isClassMember(){
return enclosingScope instanceof Class;
}
@Override
public String toString(){
return "Variable " + name + " -> "+ type;
}
} |
3e195fed95218be1768ffa3c85a45cea6e087179 | 205 | java | Java | src/main/java/application/repository/PlayerRepository.java | matiaslugo/TorneosUNQ | 9d07d53457b9c4476d28e6d76a4179a65604999d | [
"MIT"
] | null | null | null | src/main/java/application/repository/PlayerRepository.java | matiaslugo/TorneosUNQ | 9d07d53457b9c4476d28e6d76a4179a65604999d | [
"MIT"
] | null | null | null | src/main/java/application/repository/PlayerRepository.java | matiaslugo/TorneosUNQ | 9d07d53457b9c4476d28e6d76a4179a65604999d | [
"MIT"
] | null | null | null | 22.777778 | 71 | 0.839024 | 10,776 | package application.repository;
import application.domain.Player;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PlayerRepository extends JpaRepository<Player, Long> {
}
|
3e1960aeefacec6173671f1350a6efa41fe92cc5 | 3,013 | java | Java | src/main/java/net/akirakoyasu/aws/r53tools/R53Command.java | akirakoyasu/r53tools | 25da88c3373df7d2b7154de15355ea0740fb7653 | [
"BSD-3-Clause"
] | 2 | 2016-05-04T20:57:40.000Z | 2016-08-04T17:22:44.000Z | src/main/java/net/akirakoyasu/aws/r53tools/R53Command.java | akirakoyasu/r53tools | 25da88c3373df7d2b7154de15355ea0740fb7653 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/net/akirakoyasu/aws/r53tools/R53Command.java | akirakoyasu/r53tools | 25da88c3373df7d2b7154de15355ea0740fb7653 | [
"BSD-3-Clause"
] | null | null | null | 29.831683 | 84 | 0.725855 | 10,777 | package net.akirakoyasu.aws.r53tools;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
abstract public class R53Command {
public static final String ENV_ACCESSKEY_ID = "R53TOOLS_ACCESSKEY_ID";
public static final String ENV_SECRET_ACCESSKEY = "R53TOOLS_SECRET_ACCESSKEY";
protected AWSCredentials credential;
private final String cmdOptionsSyntax;
private final String cmdDesc;
protected R53Command(String cmdOptionsSyntax) {
this(cmdOptionsSyntax, "");
}
protected R53Command(String cmdOptionsSyntax, String cmdDesc) {
this.cmdOptionsSyntax = cmdOptionsSyntax;
this.cmdDesc = cmdDesc;
}
protected CommandLine parse(String[] args) {
return parse(new Options(), args);
}
@SuppressWarnings("static-access") // commons-cli
protected CommandLine parse(Options options, String[] args) {
options.addOption(OptionBuilder
.withDescription("AWS accesskey id, instead of env " + ENV_ACCESSKEY_ID)
.hasArg()
.withArgName("id")
.withLongOpt("id")
.create("i"));
options.addOption(OptionBuilder
.withDescription("AWS secret accesskey, instead of env " + ENV_SECRET_ACCESSKEY)
.hasArg()
.withArgName("secret")
.withLongOpt("secret")
.create("s"));
options.addOption("h", "help", false, "Print help");
options.addOption("v", "verbose", false, "In verbose, showing requests");
CommandLineParser parser = new PosixParser();
try {
CommandLine cl = parser.parse(options, args);
if (cl.hasOption("h")) {
printHelp(options);
return null;
}
Logger awsLogger = Logger.getLogger("com.amazonaws");
if (cl.hasOption("v")) {
awsLogger.setLevel(Level.FINE);
awsLogger.addHandler(new ConsoleHandler(){{
setOutputStream(System.out);
setLevel(Level.FINE);
}});
}
String id = cl.getOptionValue("i", System.getenv(ENV_ACCESSKEY_ID));
checkArgument(id != null, "accesskey id must be set");
String secret = cl.getOptionValue("s",
System.getenv(ENV_SECRET_ACCESSKEY));
checkArgument(secret != null, "secret accesskey must be set");
credential = new BasicAWSCredentials(id, secret);
return cl;
} catch (ParseException e) {
System.err.println(e.getMessage());
printHelp(options);
return null;
}
}
protected void printHelp(Options options) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(this.getClass().getSimpleName()
+ " [-i <id>] [-s <secret>] [-v] " + cmdOptionsSyntax, cmdDesc, options, "");
}
}
|
3e19620a775f58e14866e22245e581dea7cef36f | 5,050 | java | Java | src/main/java/com/kendelong/util/spring/JmxExportingAspectPostProcessor.java | kenwdelong/stability-utils | 71cd831409ff328a41338c0cde12be21c4ba525d | [
"MIT"
] | 5 | 2015-08-14T02:45:08.000Z | 2019-04-16T01:39:47.000Z | src/main/java/com/kendelong/util/spring/JmxExportingAspectPostProcessor.java | kenwdelong/stability-utils | 71cd831409ff328a41338c0cde12be21c4ba525d | [
"MIT"
] | 1 | 2022-03-31T19:59:17.000Z | 2022-03-31T19:59:17.000Z | src/main/java/com/kendelong/util/spring/JmxExportingAspectPostProcessor.java | kenwdelong/stability-utils | 71cd831409ff328a41338c0cde12be21c4ba525d | [
"MIT"
] | null | null | null | 29.705882 | 129 | 0.736436 | 10,778 | package com.kendelong.util.spring;
import java.util.Map;
import javax.management.ObjectName;
import org.aopalliance.aop.Advice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AbstractAspectJAdvice;
import org.springframework.aop.framework.Advised;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.jmx.export.MBeanExportException;
import org.springframework.jmx.export.MBeanExporter;
import com.kendelong.util.monitoring.webservice.ExternalNameElementComputer;
/**
* This bean can export AspectJ-style aspects to JMX when registered. For example:
*
* <pre>
* {@code
<bean class="com.kendelong.util.circuitbreaker.CircuitBreakerAspect" scope="prototype"/>
<bean class="com.kendelong.util.spring.JmxExportingAspectPostProcessor" lazy-init="false">
<property name="mbeanExporter" ref="mbeanExporter"/>
<property name="annotationToServiceNames">
<map>
<entry key="com.kendelong.util.circuitbreaker.CircuitBreakerAspect" value="circuitbreaker"/>
</map>
</property>
<property name="jmxDomain" value="app.mystuff"/>
</bean>
}
</pre>
*
* Important properties to set are the jmxDomain to use for the ONames of the MBeans,
* and the value of the map which will be also used for the OName. OName structure is
* jmxDomain:service=[map value],bean=[original advised bean name]
*
* @author Ken DeLong
*
*/
public class JmxExportingAspectPostProcessor implements BeanPostProcessor
{
private MBeanExporter mbeanExporter;
private Map<Class<?>, String> annotationToServiceNames;
private String jmxDomain;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final ExternalNameElementComputer nameElementComputer = new ExternalNameElementComputer();
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException
{
boolean advised = bean instanceof Advised;
if(advised)
{
Advised advisedBean = (Advised) bean;
Advisor[] advisors = advisedBean.getAdvisors();
for(Advisor advisor : advisors)
{
Advice advice = advisor.getAdvice();
if(advice instanceof AbstractAspectJAdvice)
{
AbstractAspectJAdvice aaja = (AbstractAspectJAdvice) advice;
Class<?> aspectPojoClass = aaja.getAspectJAdviceMethod().getDeclaringClass();
String serviceType = annotationToServiceNames.get(aspectPojoClass);
if(serviceType != null)
{
ObjectName oname;
String onameString = getDomain(bean) + "." + serviceType + ":bean=" + beanName;
try
{
/* as long as the aspect is marked prototype, each advised bean
* gets a new instance, as seen by the return value of this next
* method call. I've also checked that successive calls to the
* getAspectInstance() method return the same object.
*/
Object target = aaja.getAspectInstanceFactory().getAspectInstance();
oname = new ObjectName(onameString);
registerMBean(oname, target, beanName);
}
catch(Exception e)
{
logger.error("Cannot register mbean with oname [" + onameString +"]", e);
}
}
}
}
}
return bean;
}
private String getDomain(Object bean)
{
String webserviceNameElement = nameElementComputer.computeExternalNameElement(bean.getClass());
if(webserviceNameElement == null)
return jmxDomain;
else
return jmxDomain + ".webservice." + webserviceNameElement;
}
protected void registerMBean(ObjectName oname, Object target, String beanName)
{
try
{
// For some reason, we some objects (notably controllers) get registered 2-3 times. Subsequent registrations throw exceptions.
// unregisterManagedResource() is very tolerant and won't blow up if the object isn't registered.
// With this "last one wins" strategy, your dev environment stays clean when JRebel reloads the web context.
mbeanExporter.unregisterManagedResource(oname);
mbeanExporter.registerManagedResource(target, oname);
logger.info("Exported " + beanName + " to JMX as " + oname.toString());
}
catch(MBeanExportException e)
{
logger.warn("Error registering MBean [" + oname + "]; cause: [" + e.getCause() + "]");
}
}
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException
{
return bean;
}
public MBeanExporter getMbeanExporter()
{
return mbeanExporter;
}
public void setMbeanExporter(MBeanExporter mbeanExporter)
{
this.mbeanExporter = mbeanExporter;
}
public Map<Class<?>, String> getAnnotationToServiceNames()
{
return annotationToServiceNames;
}
public void setAnnotationToServiceNames(Map<Class<?>, String> annotationToServiceNames)
{
this.annotationToServiceNames = annotationToServiceNames;
}
public String getJmxDomain()
{
return jmxDomain;
}
public void setJmxDomain(String jmxDomain)
{
this.jmxDomain = jmxDomain;
}
}
|
3e1962f57792f183aed497b4a4d28479a6a4e2b2 | 2,526 | java | Java | src/main/java/io/dataspaceconnector/service/resource/type/AgreementService.java | catenax/DataspaceConnector | f85448041333f4ef5635121f8d08b03f4155a360 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/dataspaceconnector/service/resource/type/AgreementService.java | catenax/DataspaceConnector | f85448041333f4ef5635121f8d08b03f4155a360 | [
"Apache-2.0"
] | 3 | 2020-10-09T17:51:15.000Z | 2020-10-09T17:54:14.000Z | src/main/java/io/dataspaceconnector/service/resource/type/AgreementService.java | catenax/DataspaceConnector | f85448041333f4ef5635121f8d08b03f4155a360 | [
"Apache-2.0"
] | null | null | null | 39.46875 | 96 | 0.679731 | 10,779 | /*
* Copyright 2020-2022 Fraunhofer Institute for Software and Systems Engineering
*
* 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.dataspaceconnector.service.resource.type;
import io.dataspaceconnector.model.agreement.Agreement;
import io.dataspaceconnector.model.agreement.AgreementDesc;
import io.dataspaceconnector.model.base.AbstractFactory;
import io.dataspaceconnector.repository.AgreementRepository;
import io.dataspaceconnector.repository.BaseEntityRepository;
import io.dataspaceconnector.service.resource.base.BaseEntityService;
/**
* Handles the basic logic for contracts.
*/
public class AgreementService extends BaseEntityService<Agreement, AgreementDesc> {
/**
* Constructor.
*
* @param repository The underlying agreement repo.
* @param factory The factory for the agreement logic.
*/
public AgreementService(
final BaseEntityRepository<Agreement> repository,
final AbstractFactory<Agreement, AgreementDesc> factory) {
super(repository, factory);
}
/**
* Compares the agreement with the persisted one. If they are equal the agreement will be
* confirmed.
*
* @param agreement The agreement that should be confirmed.
* @return true - if the was unconfirmed and has been changed to confirmed.
* @throws io.dataspaceconnector.common.exception.ResourceNotFoundException if the agreement
* does no longer
* exist.
*/
public boolean confirmAgreement(final Agreement agreement) {
final var persisted = this.get(agreement.getId());
var isConfirmed = false;
if (persisted.equals(agreement)) {
final var repo = (AgreementRepository) getRepository();
repo.confirmAgreement(agreement.getId());
isConfirmed = true;
}
return isConfirmed;
}
}
|
3e196318fb047b35bd98b477be987702f8d658c2 | 773 | java | Java | project/dive-in-spring-boot/spring-boot-autoconfigure/src/main/java/com/bebopze/diveinspringboot/service/Java8CalculateService.java | bebopze/note | 32605b8e21f56b3e344797d167f311d3193cf522 | [
"Apache-2.0"
] | 7 | 2021-02-07T05:51:48.000Z | 2022-01-24T06:32:57.000Z | project/dive-in-spring-boot/spring-boot-autoconfigure/src/main/java/com/bebopze/diveinspringboot/service/Java8CalculateService.java | skirodev/note | a2025a5a1c64eecf2733585d74f004b9db9b994d | [
"Apache-2.0"
] | 3 | 2021-06-08T09:33:12.000Z | 2021-06-08T09:33:13.000Z | project/dive-in-spring-boot/spring-boot-autoconfigure/src/main/java/com/bebopze/diveinspringboot/service/Java8CalculateService.java | skirodev/note | a2025a5a1c64eecf2733585d74f004b9db9b994d | [
"Apache-2.0"
] | 4 | 2020-12-26T04:22:24.000Z | 2022-02-13T07:05:48.000Z | 24.935484 | 80 | 0.690815 | 10,780 | package com.bebopze.diveinspringboot.service;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import java.util.stream.Stream;
/**
* Java 8 Lambda 实现 {@link CalculateService}
*
* @author bebopze
* @since 2018/5/15
*/
@Profile("Java8")
@Service
public class Java8CalculateService implements CalculateService {
@Override
public Integer sum(Integer... values) {
System.out.println("Java 8 Lambda 实现");
int sum = Stream.of(values).reduce(0, Integer::sum);
return sum;
}
public static void main(String[] args) {
CalculateService calculateService = new Java8CalculateService();
System.out.println(calculateService.sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
}
}
|
3e19631fc66f2e569986fcba1e0e22998f000c2f | 355 | java | Java | app/utils/ObjectMapperUtil.java | abhilashdindalkop/tummfil | 5c9d5a928298ff8b978523deadff9de54952f347 | [
"Apache-2.0"
] | null | null | null | app/utils/ObjectMapperUtil.java | abhilashdindalkop/tummfil | 5c9d5a928298ff8b978523deadff9de54952f347 | [
"Apache-2.0"
] | null | null | null | app/utils/ObjectMapperUtil.java | abhilashdindalkop/tummfil | 5c9d5a928298ff8b978523deadff9de54952f347 | [
"Apache-2.0"
] | null | null | null | 20.882353 | 77 | 0.808451 | 10,781 | package utils;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ObjectMapperUtil {
public static ObjectMapper getInstance() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper;
}
}
|
3e1963746e0e3dd8caf348fa9b96aa2c3326df8f | 834 | java | Java | spring-security-core/src/main/java/com/xh/security/core/authentiation/oauth2/support/cache/AuthStateCache.java | ht16519/spring-security-parent | 8fc39b169fa9d77292ec1ce2fda19ced965152f8 | [
"MIT"
] | null | null | null | spring-security-core/src/main/java/com/xh/security/core/authentiation/oauth2/support/cache/AuthStateCache.java | ht16519/spring-security-parent | 8fc39b169fa9d77292ec1ce2fda19ced965152f8 | [
"MIT"
] | null | null | null | spring-security-core/src/main/java/com/xh/security/core/authentiation/oauth2/support/cache/AuthStateCache.java | ht16519/spring-security-parent | 8fc39b169fa9d77292ec1ce2fda19ced965152f8 | [
"MIT"
] | null | null | null | 17.375 | 64 | 0.552758 | 10,782 | package com.xh.security.core.authentiation.oauth2.support.cache;
/**
* <p>
* State缓存接口,方便用户扩展
* </p>
*
* @author yangkai.shen
* @since 1.10.0
*/
public interface AuthStateCache {
/**
* 存入缓存
*
* @param key 缓存key
* @param value 缓存内容
*/
void cache(String key, String value);
/**
* 存入缓存
*
* @param key 缓存key
* @param value 缓存内容
* @param timeout 指定缓存过期时间(毫秒)
*/
void cache(String key, String value, long timeout);
/**
* 获取缓存内容
*
* @param key 缓存key
* @return 缓存内容
*/
String get(String key);
/**
* 是否存在key,如果对应key的value值已过期,也返回false
*
* @param key 缓存key
* @return true:存在key,并且value没过期;false:key不存在或者已过期
*/
boolean containsKey(String key);
/** 移除*/
void remove(String key);
}
|
3e1963cb762153001019dd17badf589b2f366e73 | 443 | java | Java | Client/src/client/SocketParent.java | joaoofreitas/socket-proxy | 2540390b4c4a7b6e60104565a805c8cae7dd8fbb | [
"Unlicense"
] | null | null | null | Client/src/client/SocketParent.java | joaoofreitas/socket-proxy | 2540390b4c4a7b6e60104565a805c8cae7dd8fbb | [
"Unlicense"
] | null | null | null | Client/src/client/SocketParent.java | joaoofreitas/socket-proxy | 2540390b4c4a7b6e60104565a805c8cae7dd8fbb | [
"Unlicense"
] | null | null | null | 17.72 | 52 | 0.557562 | 10,783 | package client;
public abstract class SocketParent extends Thread{
private final int PORT;
private final String serverIP;
public SocketParent(int PORT, String serverIP) {
this.PORT = PORT;
this.serverIP = serverIP;
}
public int getPORT() {
return PORT;
}
@Override
public String toString() {
return "Socket{" +
"PORT=" + PORT +
'}';
}
}
|
3e1963f790a945fb06cb49453d5d03106d851297 | 1,236 | java | Java | app/src/main/java/com/sky/xposed/rimet/plugin/interfaces/XVersionManager.java | SuzukazeHaruka/xposed-rimet | bb44ba572ea33a422f70028e4f303ab28c660df0 | [
"Apache-2.0"
] | 589 | 2019-03-15T01:41:34.000Z | 2022-03-29T10:36:12.000Z | app/src/main/java/com/sky/xposed/rimet/plugin/interfaces/XVersionManager.java | shaowYe/xposed-rimet | bb44ba572ea33a422f70028e4f303ab28c660df0 | [
"Apache-2.0"
] | 58 | 2019-05-22T01:28:24.000Z | 2022-03-25T03:55:09.000Z | app/src/main/java/com/sky/xposed/rimet/plugin/interfaces/XVersionManager.java | shaowYe/xposed-rimet | bb44ba572ea33a422f70028e4f303ab28c660df0 | [
"Apache-2.0"
] | 157 | 2019-03-22T02:27:18.000Z | 2022-03-31T00:47:23.000Z | 20.262295 | 75 | 0.631877 | 10,784 | /*
* Copyright (c) 2019 The sky Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sky.xposed.rimet.plugin.interfaces;
import java.util.Set;
/**
* Created by sky on 2019/3/12.
*/
public interface XVersionManager {
/**
* 获取当前版本名
* @return
*/
String getVersionName();
/**
* 获取当前版本号
* @return
*/
int getVersionCode();
/**
* 判断Hook是否支持当前版本
* @return
*/
boolean isSupportVersion();
/**
* 获取支持版本的配置信息,如果没有适配到返回Null
* @return
*/
XConfig getSupportConfig();
/**
* 获取插件支持的版本
* @return
*/
Set<String> getSupportVersion();
/**
* 清除配置版本配置
*/
void clearVersionConfig();
}
|
3e19644b6d3aaa8f3066d43b62043d73f19cd97b | 4,381 | java | Java | src/main/java/kernel/IntVariable.java | nandofioretto/dcop_sim | 1285c08b08ba3cb067f388d19a31f7e9e712c939 | [
"MIT"
] | null | null | null | src/main/java/kernel/IntVariable.java | nandofioretto/dcop_sim | 1285c08b08ba3cb067f388d19a31f7e9e712c939 | [
"MIT"
] | null | null | null | src/main/java/kernel/IntVariable.java | nandofioretto/dcop_sim | 1285c08b08ba3cb067f388d19a31f7e9e712c939 | [
"MIT"
] | null | null | null | 26.551515 | 104 | 0.627711 | 10,785 | /*
* Copyright (c) 2015.
*
* 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 kernel;
import java.util.ArrayList;
import java.util.Random;
/**
* Created by ffiorett on 7/7/15.
*/
public class IntVariable implements Variable {
private String name;
long ID;
private Domain domain;
private int value;
private int type;
AgentState ownerAgentState;
ArrayList<Constraint> participatingConstraints;
Random rand;
public IntVariable(String name, long ID, int min, int max) {
this.name = name;
this.ID = ID;
this.domain = new BoundDomain(min, max);
this.value = domain.getMin();
this.rand = new Random();
this.type = Variable.DECISION_VAR;
participatingConstraints = new ArrayList<Constraint>();
}
public IntVariable(String name, long ID, int min, int max, int type) {
this.name = name;
this.ID = ID;
this.domain = new BoundDomain(min, max);
this.value = domain.getMin();
this.rand = new Random();
setType(type);
participatingConstraints = new ArrayList<Constraint>();
}
@Override
public int getType() {
return type;
}
@Override
public void setType(int type) {
assert(type == Variable.DECISION_VAR || type == Variable.AUX1_VAR || type == Variable.AUX2_VAR);
this.type = type;
}
@Override
public Domain getDomain() {
return domain;
}
@Override
public void setDomain(Domain domain) {
this.domain = domain;
}
@Override
public long getID() {
return ID;
}
@Override
public void setID(long ID) {
this.ID = ID;
}
@Override
public int getValue() {
return value;
}
@Override
public void setValue(int value) {
this.value = value;
}
@Override
public void setValueAtRandom() {
this.value = rand.nextInt(domain.getMax() - domain.getMin() + 1) + domain.getMin();
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public void registerOwnerAgent(AgentState ownerAgentState) {
this.ownerAgentState = ownerAgentState;
}
@Override
public AgentState getOwnerAgent() {
return ownerAgentState;
}
@Override
public void registerParticipatingConstraint(Constraint constraint) {
participatingConstraints.add(constraint);
ownerAgentState.registerConstraint(constraint);
}
@Override
public ArrayList<Constraint> getParticipatingConstraints() {
return participatingConstraints;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IntVariable that = (IntVariable) o;
return ID == that.ID;
}
@Override
public int hashCode() {
return (int) (ID ^ (ID >>> 32));
}
@Override
public String toString() {
return "IntVariable{" +
name + " " + ID + " ' type=" + type + "' " +
"domain=" + domain +
", value=" + value +
", Owner=" + ownerAgentState.getName() +
'}';
}
}
|
3e1964d95e803a9f4d9b8a9c7f95770f9f446228 | 547 | java | Java | common/src/main/java/com/dcy/common/constant/RedisConstant.java | SSJLYY/privateStudyProject | e89972b20b2d5045e921c72ea15df80ddad40808 | [
"Apache-2.0"
] | null | null | null | common/src/main/java/com/dcy/common/constant/RedisConstant.java | SSJLYY/privateStudyProject | e89972b20b2d5045e921c72ea15df80ddad40808 | [
"Apache-2.0"
] | null | null | null | common/src/main/java/com/dcy/common/constant/RedisConstant.java | SSJLYY/privateStudyProject | e89972b20b2d5045e921c72ea15df80ddad40808 | [
"Apache-2.0"
] | null | null | null | 17.09375 | 63 | 0.570384 | 10,786 | package com.dcy.common.constant;
/**
* @Author:dcy
* @Description:
* @Date: 2021/11/19 9:35
*/
public interface RedisConstant {
/**
* 角色数据权限
*/
String REDIS_ROLE_DATA_SCOPE = "role:data-scope";
/**
* 角色数据权限标识
*/
String REDIS_ROLE_DATA_SCOPE_FLAG = "role:data-scope-flag";
/**
* 用户角色
*/
String REDIS_USER_ROLE = "user:role";
/**
* 用户资源
*/
String REDIS_USER_RESOURCE = "user:resource";
/**
* 资源路由
*/
String REDIS_RESOURCE_ROUTER = "resource:router";
}
|
3e19652abf33592ec3501c11a5eae10a3e327b2b | 272 | java | Java | fccclient/src/main/java/org/nvijaykarthik/fccclient/actionservice/FccOnDemandTrafficActionProcessor.java | nvijaykarthik/FeatureControlCenter | 266bbd3242dc1eefc84700a3f997786b3e3c902f | [
"MIT"
] | null | null | null | fccclient/src/main/java/org/nvijaykarthik/fccclient/actionservice/FccOnDemandTrafficActionProcessor.java | nvijaykarthik/FeatureControlCenter | 266bbd3242dc1eefc84700a3f997786b3e3c902f | [
"MIT"
] | 1 | 2021-12-20T16:35:13.000Z | 2021-12-20T16:35:13.000Z | fccclient/src/main/java/org/nvijaykarthik/fccclient/actionservice/FccOnDemandTrafficActionProcessor.java | nvijaykarthik/FeatureControlCenter | 266bbd3242dc1eefc84700a3f997786b3e3c902f | [
"MIT"
] | null | null | null | 22.666667 | 78 | 0.731618 | 10,787 | package org.nvijaykarthik.fccclient.actionservice;
public class FccOnDemandTrafficActionProcessor implements FCCActionProcessor {
@Override
public boolean processAction(String json) {
// TODO Auto-generated method stub
return false;
}
}
|
3e1965a1de86d2b12653b435d3556b26c9bb2495 | 2,179 | java | Java | src/main/java/com/springbootcamp/ecommerceapp/controllers/SellerController.java | sirraghavgupta/ecommerce-app | 8a710c181d8ebf2e9f9713d247874fe09881c182 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/springbootcamp/ecommerceapp/controllers/SellerController.java | sirraghavgupta/ecommerce-app | 8a710c181d8ebf2e9f9713d247874fe09881c182 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/springbootcamp/ecommerceapp/controllers/SellerController.java | sirraghavgupta/ecommerce-app | 8a710c181d8ebf2e9f9713d247874fe09881c182 | [
"Apache-2.0"
] | null | null | null | 38.910714 | 142 | 0.770996 | 10,788 | package com.springbootcamp.ecommerceapp.controllers;
import com.springbootcamp.ecommerceapp.dtos.AddressDto;
import com.springbootcamp.ecommerceapp.dtos.SellerViewProfileDto;
import com.springbootcamp.ecommerceapp.services.SellerService;
import com.springbootcamp.ecommerceapp.services.UserService;
import com.springbootcamp.ecommerceapp.utils.ResponseVO;
import com.springbootcamp.ecommerceapp.utils.BaseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.security.Principal;
import java.util.Date;
@RestController
public class SellerController {
@Autowired
SellerService sellerService;
@Autowired
UserService userService;
@GetMapping("/seller/home")
public ResponseEntity<ResponseVO> getsellerHome(){
String data = "seller home";
ResponseVO<String> response = new ResponseVO<>(data, null, new Date());
return new ResponseEntity<ResponseVO>(response, HttpStatus.OK);
}
@GetMapping("/seller/profile")
public ResponseEntity<BaseVO> getProfileDetails(HttpServletRequest request){
Principal principal = request.getUserPrincipal();
String username = principal.getName();
return sellerService.getUserProfile(username);
}
@PatchMapping("/seller/profile")
public ResponseEntity<BaseVO> updateProfileDetails(@RequestBody SellerViewProfileDto profileDto, HttpServletRequest request){
Principal principal = request.getUserPrincipal();
String username = principal.getName();
return sellerService.updateUserProfile(username, profileDto);
}
@PatchMapping("/seller/addresses/{id}")
public ResponseEntity<BaseVO> updateAddress(@Valid @RequestBody AddressDto addressDto, @PathVariable Long id, HttpServletRequest request){
Principal principal = request.getUserPrincipal();
String username = principal.getName();
return userService.updateAddressById(username, id, addressDto);
}
}
|
3e1965f11a856f6edbea0acc6d12bb853d046ffd | 1,180 | java | Java | Chapter 23 Observer/sample02/LoginValidatorB.java | pipisun/DesignPatternJavaCode | 461a985de09b7a3e4b94c82262f781ce425181fb | [
"Apache-2.0"
] | 475 | 2016-05-04T07:09:50.000Z | 2022-03-29T04:15:06.000Z | Chapter 23 Observer/sample02/LoginValidatorB.java | pipisun/DesignPatternJavaCode | 461a985de09b7a3e4b94c82262f781ce425181fb | [
"Apache-2.0"
] | 2 | 2016-08-23T03:04:18.000Z | 2018-12-23T15:42:13.000Z | Chapter 23 Observer/sample02/LoginValidatorB.java | pipisun/DesignPatternJavaCode | 461a985de09b7a3e4b94c82262f781ce425181fb | [
"Apache-2.0"
] | 316 | 2016-05-04T05:06:05.000Z | 2022-02-20T12:17:34.000Z | 25.106383 | 129 | 0.722881 | 10,789 | import javax.swing.*;
import java.awt.*;
public class LoginValidatorB extends JFrame implements LoginEventListener
{
private JPanel p;
private LoginBean lb;
private JLabel lblLogo;
public LoginValidatorB()
{
super("China Mobile");
p=new JPanel();
this.getContentPane().add(p);
lb=new LoginBean();
lb.addLoginEventListener(this);
Font f=new Font("Times New Roman",Font.BOLD,30);
lblLogo=new JLabel("China Mobile");
lblLogo.setFont(f);
lblLogo.setForeground(Color.blue);
p.setLayout(new GridLayout(2,1));
p.add(lblLogo);
p.add(lb);
p.setBackground(new Color(163,185,255));
this.setSize(600,200);
this.setVisible(true);
}
public void validateLogin(LoginEvent event)
{
String userName=event.getUserName();
String password=event.getPassword();
if(userName.equals(password))
{
JOptionPane.showMessageDialog(this,new String("Username must be different from password!"),"alert",JOptionPane.ERROR_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(this,new String("Rigth details!"),"alert",JOptionPane.INFORMATION_MESSAGE);
}
}
public static void main(String args[])
{
new LoginValidatorB().setVisible(true);
}
} |
3e1968be985d4567c4b2fcfe4f288d455999b9e3 | 3,404 | java | Java | SpringBootMvcAndRestSecurityExample/src/main/java/com/espark/adarsh/configuration/web/WebMvcConfiguration.java | dinesh2021992/dinesh7 | ecc3a857e78fadba076bd1175b042bbbe5590ca9 | [
"MIT"
] | null | null | null | SpringBootMvcAndRestSecurityExample/src/main/java/com/espark/adarsh/configuration/web/WebMvcConfiguration.java | dinesh2021992/dinesh7 | ecc3a857e78fadba076bd1175b042bbbe5590ca9 | [
"MIT"
] | null | null | null | SpringBootMvcAndRestSecurityExample/src/main/java/com/espark/adarsh/configuration/web/WebMvcConfiguration.java | dinesh2021992/dinesh7 | ecc3a857e78fadba076bd1175b042bbbe5590ca9 | [
"MIT"
] | null | null | null | 46 | 103 | 0.772914 | 10,790 | /*
* Copyright (c) 2015 Espark And ©Adarsh Development Services @copyright All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Espark nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.espark.adarsh.configuration.web;
import com.espark.adarsh.configuration.persistance.PersistenceConfiguration;
import com.espark.adarsh.configuration.security.WebSecurityConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
* @author Adarsh Kumar
* @author $LastChangedBy: Adarsh Kumar$
* @version $Revision: 0001 $, $Date:: 1/1/10 0:00 AM#$
* @Espark @copyright all right reserve
*/
@EnableWebMvc
@Configuration
@ComponentScan({"com.espark.adarsh"})
@Import({WebSecurityConfiguration.class, PersistenceConfiguration.class})
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
private static final String[] RESOURCE_LOCATIONS = {
"classpath:/static/"};
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**/js/**","/**/css/**").addResourceLocations(RESOURCE_LOCATIONS);
}
} |
3e19690e53c571f9831ec04647d01853bb7f4cbb | 3,090 | java | Java | flink-connector-mysql-cdc/src/main/java/com/ververica/cdc/connectors/mysql/source/split/MySqlSplit.java | liaooo/flink-cdc-connectors | e79ac93f28cb8026873de4cec438aa2ef0faed3c | [
"Apache-2.0"
] | 17 | 2020-07-18T02:31:13.000Z | 2021-09-13T00:44:19.000Z | flink-connector-mysql-cdc/src/main/java/com/ververica/cdc/connectors/mysql/source/split/MySqlSplit.java | luoyuxia/flink-cdc-connectors | bf9fb45b40c690997cd6be0e6bf271f9d0f253c6 | [
"Apache-2.0"
] | null | null | null | flink-connector-mysql-cdc/src/main/java/com/ververica/cdc/connectors/mysql/source/split/MySqlSplit.java | luoyuxia/flink-cdc-connectors | bf9fb45b40c690997cd6be0e6bf271f9d0f253c6 | [
"Apache-2.0"
] | 4 | 2020-07-26T03:09:33.000Z | 2021-04-24T00:23:33.000Z | 32.1875 | 91 | 0.68479 | 10,791 | /*
* 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 com.ververica.cdc.connectors.mysql.source.split;
import org.apache.flink.api.connector.source.SourceSplit;
import org.apache.flink.table.types.logical.RowType;
import io.debezium.relational.TableId;
import io.debezium.relational.history.TableChanges.TableChange;
import java.util.Map;
import java.util.Objects;
/** The split of table comes from a Table that splits by primary key. */
public abstract class MySqlSplit implements SourceSplit {
protected final String splitId;
protected final RowType splitKeyType;
protected final Map<TableId, TableChange> tableSchemas;
public MySqlSplit(
String splitId, RowType splitKeyType, Map<TableId, TableChange> tableSchemas) {
this.splitId = splitId;
this.splitKeyType = splitKeyType;
this.tableSchemas = tableSchemas;
}
/** Checks whether this split is a snapshot split. */
public final boolean isSnapshotSplit() {
return getClass() == MySqlSnapshotSplit.class;
}
/** Checks whether this split is a binlog split. */
public final boolean isBinlogSplit() {
return getClass() == MySqlBinlogSplit.class;
}
/** Casts this split into a {@link MySqlSnapshotSplit}. */
public final MySqlSnapshotSplit asSnapshotSplit() {
return (MySqlSnapshotSplit) this;
}
/** Casts this split into a {@link MySqlBinlogSplit}. */
public final MySqlBinlogSplit asBinlogSplit() {
return (MySqlBinlogSplit) this;
}
@Override
public String splitId() {
return splitId;
}
public RowType getSplitKeyType() {
return splitKeyType;
}
public Map<TableId, TableChange> getTableSchemas() {
return tableSchemas;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MySqlSplit that = (MySqlSplit) o;
return Objects.equals(splitId, that.splitId)
&& Objects.equals(splitKeyType, that.splitKeyType)
&& Objects.equals(tableSchemas, that.tableSchemas);
}
@Override
public int hashCode() {
return Objects.hash(splitId, splitKeyType, tableSchemas);
}
}
|
3e19696621149c8990b9533ef753bb3887db2459 | 1,636 | java | Java | main/plugins/org.talend.designer.components.libs/libs_src/Netsuite_Client/src/main/java/com/netsuite/webservices/platform/messages/AsyncSearchRequest.java | bgunics-talend/tdi-studio-se | 3f54f55acb4d214f2d02532667bae98420068170 | [
"Apache-2.0"
] | 114 | 2015-03-05T15:34:59.000Z | 2022-02-22T03:48:44.000Z | main/plugins/org.talend.designer.components.libs/libs_src/Netsuite_Client/src/main/java/com/netsuite/webservices/platform/messages/AsyncSearchRequest.java | bgunics-talend/tdi-studio-se | 3f54f55acb4d214f2d02532667bae98420068170 | [
"Apache-2.0"
] | 1,137 | 2015-03-04T01:35:42.000Z | 2022-03-29T06:03:17.000Z | main/plugins/org.talend.designer.components.libs/libs_src/Netsuite_Client/src/main/java/com/netsuite/webservices/platform/messages/AsyncSearchRequest.java | bgunics-talend/tdi-studio-se | 3f54f55acb4d214f2d02532667bae98420068170 | [
"Apache-2.0"
] | 219 | 2015-01-21T10:42:18.000Z | 2022-02-17T07:57:20.000Z | 25.5625 | 118 | 0.659535 | 10,792 |
package com.netsuite.webservices.platform.messages;
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 com.netsuite.webservices.platform.core.SearchRecord;
/**
* <p>Java class for AsyncSearchRequest complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="AsyncSearchRequest">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="searchRecord" type="{urn:core_2014_2.platform.webservices.netsuite.com}SearchRecord"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AsyncSearchRequest", propOrder = {
"searchRecord"
})
public class AsyncSearchRequest {
@XmlElement(required = true)
protected SearchRecord searchRecord;
/**
* Gets the value of the searchRecord property.
*
* @return
* possible object is
* {@link SearchRecord }
*
*/
public SearchRecord getSearchRecord() {
return searchRecord;
}
/**
* Sets the value of the searchRecord property.
*
* @param value
* allowed object is
* {@link SearchRecord }
*
*/
public void setSearchRecord(SearchRecord value) {
this.searchRecord = value;
}
}
|
3e196a81742424969d46b393cf7f63e26c6bcce1 | 2,838 | java | Java | java/gadgets/src/main/java/org/apache/shindig/gadgets/uri/AllJsIframeVersioner.java | fortune/Hello-Shindig | 820bf8a6c25f983ec152d41380beefb997b364b2 | [
"Apache-2.0"
] | 1 | 2018-09-25T09:05:18.000Z | 2018-09-25T09:05:18.000Z | java/gadgets/src/main/java/org/apache/shindig/gadgets/uri/AllJsIframeVersioner.java | fortune/Hello-Shindig | 820bf8a6c25f983ec152d41380beefb997b364b2 | [
"Apache-2.0"
] | null | null | null | java/gadgets/src/main/java/org/apache/shindig/gadgets/uri/AllJsIframeVersioner.java | fortune/Hello-Shindig | 820bf8a6c25f983ec152d41380beefb997b364b2 | [
"Apache-2.0"
] | null | null | null | 38.876712 | 77 | 0.756871 | 10,793 | /*
* 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.shindig.gadgets.uri;
import org.apache.shindig.common.uri.Uri;
import org.apache.shindig.common.util.HashUtil;
import org.apache.shindig.gadgets.features.FeatureRegistry;
import org.apache.shindig.gadgets.features.FeatureResource;
import org.apache.shindig.gadgets.uri.IframeUriManager.Versioner;
import com.google.inject.Inject;
/**
* Simple, but naive, implementation of an IFRAME version generator that
* returns the same version value for all renders: the hash of all JS in the
* feature system. This serves as an implicit version of the whole build.
*
* While often a reasonable heuristic, use of this versioner completely
* ignores code changes. For instance, a rewriter may be deployed, yet
* if no JS changed, it would never run since a generated/versioned URL
* would cache the previously-generated render.
*
* More sophisticated Versioner implementations may take these sorts of
* scenarios into consideration, and even go further, retrieving the
* referenced gadget from the GadgetSpecFactory. Such an implementation's
* performance is highly installation-specific, however, so is left as
* an exercise to integrators to achieve effectively.
*/
public class AllJsIframeVersioner implements Versioner {
private final String allJsChecksum;
@Inject
public AllJsIframeVersioner(FeatureRegistry registry) {
StringBuilder jsBuf = new StringBuilder();
for (FeatureResource resource : registry.getAllFeatures()) {
jsBuf.append(resource.getContent()).append(resource.getDebugContent());
}
allJsChecksum = HashUtil.checksum(jsBuf.toString().getBytes());
}
public String version(Uri gadgetUri, String container) {
return allJsChecksum;
}
public UriStatus validate(Uri gadgetUri, String container, String value) {
if (value == null || value.length() == 0) {
return UriStatus.VALID_UNVERSIONED;
}
if (value.equals(allJsChecksum)) {
return UriStatus.VALID_VERSIONED;
}
return UriStatus.INVALID_VERSION;
}
}
|
3e196a84eeb736b24f94d6e4aaf3a2548c1d4a84 | 134 | java | Java | _src/four/maven/ChapterFour/src/main/java/org/springaop/chapter/four/util/Constants.java | paullewallencom/spring-978-1-8471-9402-2 | 2292afc1882aaf7694fe1fbfcfd4b3bcbdf7f994 | [
"Apache-2.0"
] | null | null | null | _src/four/maven/ChapterFour/src/main/java/org/springaop/chapter/four/util/Constants.java | paullewallencom/spring-978-1-8471-9402-2 | 2292afc1882aaf7694fe1fbfcfd4b3bcbdf7f994 | [
"Apache-2.0"
] | null | null | null | _src/four/maven/ChapterFour/src/main/java/org/springaop/chapter/four/util/Constants.java | paullewallencom/spring-978-1-8471-9402-2 | 2292afc1882aaf7694fe1fbfcfd4b3bcbdf7f994 | [
"Apache-2.0"
] | null | null | null | 22.333333 | 64 | 0.776119 | 10,794 | package org.springaop.chapter.four.util;
public class Constants {
public static final String LOG_NAME = "logfile_application";
}
|
3e196a9bd86e01ddfa720493194d93d669d655d1 | 6,227 | java | Java | integration-test/src/main/java/com/sequenceiq/it/cloudbreak/cloud/v4/openstack/OpenStackProperties.java | rohithsharmaks/cloudbreak | eaeae14d015ee218d792b87e8bf99ec3c3231ed9 | [
"Apache-2.0"
] | null | null | null | integration-test/src/main/java/com/sequenceiq/it/cloudbreak/cloud/v4/openstack/OpenStackProperties.java | rohithsharmaks/cloudbreak | eaeae14d015ee218d792b87e8bf99ec3c3231ed9 | [
"Apache-2.0"
] | 1 | 2019-05-27T12:58:48.000Z | 2019-05-27T12:58:48.000Z | integration-test/src/main/java/com/sequenceiq/it/cloudbreak/cloud/v4/openstack/OpenStackProperties.java | rohithsharmaks/cloudbreak | eaeae14d015ee218d792b87e8bf99ec3c3231ed9 | [
"Apache-2.0"
] | null | null | null | 22.893382 | 75 | 0.57347 | 10,795 | package com.sequenceiq.it.cloudbreak.cloud.v4.openstack;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "integrationtest.openstack")
public class OpenStackProperties {
private String defaultBlueprintName;
private String availabilityZone;
private String region;
private String location;
private String publicNetId;
private String networkingOption;
private final Instance instance = new Instance();
private final Credential credential = new Credential();
private final Prewarmed prewarmed = new Prewarmed();
public String getAvailabilityZone() {
return availabilityZone;
}
public void setAvailabilityZone(String availabilityZone) {
this.availabilityZone = availabilityZone;
}
public String getDefaultBlueprintName() {
return defaultBlueprintName;
}
public void setDefaultBlueprintName(String defaultBlueprintName) {
this.defaultBlueprintName = defaultBlueprintName;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getPublicNetId() {
return publicNetId;
}
public void setPublicNetId(String publicNetId) {
this.publicNetId = publicNetId;
}
public String getNetworkingOption() {
return networkingOption;
}
public void setNetworkingOption(String networkingOption) {
this.networkingOption = networkingOption;
}
public Instance getInstance() {
return instance;
}
public Credential getCredential() {
return credential;
}
public Prewarmed getPrewarmed() {
return prewarmed;
}
public static class Instance {
private String type;
private Integer volumeSize;
private Integer volumeCount;
private String volumeType;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getVolumeSize() {
return volumeSize;
}
public void setVolumeSize(Integer volumeSize) {
this.volumeSize = volumeSize;
}
public Integer getVolumeCount() {
return volumeCount;
}
public void setVolumeCount(Integer volumeCount) {
this.volumeCount = volumeCount;
}
public String getVolumeType() {
return volumeType;
}
public void setVolumeType(String volumeType) {
this.volumeType = volumeType;
}
}
public static class Credential {
private String endpoint;
private String tenant;
private String userName;
private String password;
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getTenant() {
return tenant;
}
public void setTenant(String tenant) {
this.tenant = tenant;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public static class Prewarmed {
private final Hdp hdp = new Hdp();
private final Hdf hdf = new Hdf();
public Hdp getHdp() {
return hdp;
}
public Hdf getHdf() {
return hdf;
}
public static class Hdp {
private String version;
private Boolean enabled;
private List<String> hostGroups;
private String scaleGroup;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public List<String> getHostGroups() {
return hostGroups;
}
public void setHostGroups(List<String> hostGroups) {
this.hostGroups = hostGroups;
}
public String getScaleGroup() {
return scaleGroup;
}
public void setScaleGroup(String scaleGroup) {
this.scaleGroup = scaleGroup;
}
}
public static class Hdf {
private List<String> blueprintNames;
private Boolean enabled;
private List<String> hostGroups;
private String scaleGroup;
public List<String> getBlueprintNames() {
return blueprintNames;
}
public void setBlueprintNames(List<String> blueprintNames) {
this.blueprintNames = blueprintNames;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public List<String> getHostGroups() {
return hostGroups;
}
public void setHostGroups(List<String> hostGroups) {
this.hostGroups = hostGroups;
}
public String getScaleGroup() {
return scaleGroup;
}
public void setScaleGroup(String scaleGroup) {
this.scaleGroup = scaleGroup;
}
}
}
}
|
3e196b45741ab820b81b34de8963cf5ba1d57d3d | 105 | java | Java | src/java/test/org/burroloco/donkey/trebuchet/DonkeyShell.java | steshaw/donkey | 8924e3d3da73c99ce748a4b123679b58f5053446 | [
"BSD-3-Clause"
] | 2 | 2017-12-11T03:42:35.000Z | 2017-12-11T07:36:14.000Z | src/java/test/org/burroloco/donkey/trebuchet/DonkeyShell.java | dbastin/donkey | 2a50609d6eb5b295aa3cbc4b0c3aada5c0f9d010 | [
"BSD-3-Clause"
] | null | null | null | src/java/test/org/burroloco/donkey/trebuchet/DonkeyShell.java | dbastin/donkey | 2a50609d6eb5b295aa3cbc4b0c3aada5c0f9d010 | [
"BSD-3-Clause"
] | null | null | null | 17.5 | 39 | 0.771429 | 10,796 | package org.burroloco.donkey.trebuchet;
public interface DonkeyShell {
void run(String goOption);
}
|
3e196bf0909bf0bbb90a12658b88179b54004ec5 | 3,923 | java | Java | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/GroupHelper.java | zalitskiy/java_project | 0969a5ae1fca44bab0b1079fbae09badf59051cd | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/GroupHelper.java | zalitskiy/java_project | 0969a5ae1fca44bab0b1079fbae09badf59051cd | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/GroupHelper.java | zalitskiy/java_project | 0969a5ae1fca44bab0b1079fbae09badf59051cd | [
"Apache-2.0"
] | null | null | null | 29.276119 | 110 | 0.618149 | 10,797 | package ru.stqa.pft.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import ru.stqa.pft.addressbook.model.GroupData;
import ru.stqa.pft.addressbook.model.Groups;
import java.util.ArrayList;
import java.util.List;
public class GroupHelper extends BaseHelper {
public GroupHelper(WebDriver wd) {
super(wd);
}
public void submitGroupCreation() {
click(By.name("submit"));
}
public void fillGroupForm(GroupData groupData) {
type(By.name("group_name"), groupData.getName());
type(By.name("group_header"), groupData.getHeader());
type(By.name("group_footer"), groupData.getFooter());
}
public void initGroupCreation() {
click(By.name("new"));
}
public void deleteSelectedGroups() {
click(By.name("delete"));
}
public void selectGroupById(int id) {
wd.findElement(By.xpath("//span[@class='group']/input[@value='" + id + "']")).click();
}
public void initGroupModification() {
click(By.name("edit"));
}
public void submitGroupModification() {
click(By.name("update"));
}
public void create(GroupData group) {
initGroupCreation();
fillGroupForm(group);
submitGroupCreation();
groupCache = null;
returnToGroupPage();
}
public void delete(GroupData group) {
selectGroupById(group.getId());
deleteSelectedGroups();
groupCache = null;
returnToGroupPage();
}
public void modify(GroupData group) {
selectGroupById(group.getId());
initGroupModification();
fillGroupForm(group);
submitGroupModification();
groupCache = null;
returnToGroupPage();
}
public void returnToGroupPage() {
get("http://localhost/addressbook/group.php");
}
public boolean isThereAGroup() {
return isElementPresent(By.name("selected[]"));
}
public int count() {
return wd.findElements(By.name("selected[]")).size();
}
private Groups groupCache = null;
public Groups all() {
if (groupCache != null) {
return new Groups(groupCache);
}
groupCache = new Groups();
List<WebElement> elements = wd.findElements(By.xpath("//span[@class='groups']"));
for (WebElement element : elements) {
String name = element.getText();
//System.out.println(name);
int id = Integer.parseInt(element.findElement(By.tagName("input")).getAttribute("value"));
//System.out.println(id);
groupCache.add(new GroupData().withId(id).withName(name));
}
return new Groups(groupCache);
}
public int getGroupCount() {
return wd.findElements(By.name("selected[]")).size();
}
public void selectGroup(int index) {
wd.findElements(By.name("selected[]")).get(index).click();
}
public List<GroupData> getGroupList() {
List<GroupData> groups = new ArrayList<>();
List<WebElement> elements = wd.findElements(By.xpath("//span[@class='groups']"));
for(WebElement element : elements) {
String name = element.getText();
GroupData group = new GroupData().withName(name).withHeader(null).withFooter(null);
groups.add(group);
}
return groups;
}
public void clickOnGroup(GroupData group) {
wd.findElement(By.xpath(String.format("//i/a[@href='./index.php?group=%s']", group.getId()))).click();
}
public void selectGroupFromList(GroupData group) {
new Select(wd.findElement(By.name("to_group"))).selectByVisibleText(group.getName());
}
public void clickOnAddTo() {
wd.findElement(By.xpath("//input[@name='add']")).click();
}
}
|
3e196c0a5ddea27a687cdaf94729f98a5d4d37ba | 7,108 | java | Java | src/config/XMLGenerator.java | sumervardhan/CellularAutomatonSimulations | f49ee56ea67c1cc46499407d723edbfa8d5eddb8 | [
"MIT"
] | null | null | null | src/config/XMLGenerator.java | sumervardhan/CellularAutomatonSimulations | f49ee56ea67c1cc46499407d723edbfa8d5eddb8 | [
"MIT"
] | null | null | null | src/config/XMLGenerator.java | sumervardhan/CellularAutomatonSimulations | f49ee56ea67c1cc46499407d723edbfa8d5eddb8 | [
"MIT"
] | null | null | null | 44.425 | 121 | 0.607766 | 10,798 | package config;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* This class generates the XML file to be saved by the user; though the functionality is not yet implemented, it is also
* meant to generate the XML file that will be implemented when the user puts in configuration parameters at the start of
* the program. Currently, the class assumes that the file to be saved is the first scene of Game of Life; this is used
* to test that the XMLGenerator actually works.
* @author Ha Nguyen
*/
public class XMLGenerator {
private Document myXMLDocument;
private Element myRoot;
private File myFileToSaveAs;
private String mySimulationTypeValue;
private String myXMLNumRows;
private String myXMLNumCols;
private String myXMLNumNeighbors;
private String myXMLNeighborsConfiguration;
private Map<String, String> myParametersMap;
private Map<String, String> myStatesColorsMap;
/**
* Creates xml file using current simulation and saves it
* Assumes file receives data for a simulation. If the user cancels the request to save a file, then the exception
* is caught and the program continues on.
*
* @param fileToSaveAs the file name that the user
*/
public XMLGenerator(File fileToSaveAs) {
myFileToSaveAs = fileToSaveAs;
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = docFactory.newDocumentBuilder();
myXMLDocument = documentBuilder.newDocument();
} catch (ParserConfigurationException e) {
//do nothing
}
}
/**
* Currently generates a hardcoded simulation, but in future would generate an xml file from current state of
* simulation to be passed in
* through the parser, and read in through the current state of the grid
* Assumes 20 rows, 20 cols, 8 neighbors, and a specific neighbor configuration
*/
public void generateSimulationXMLDocument() {
myRoot = myXMLDocument.createElement("simulation");
myXMLDocument.appendChild(myRoot);
addAttribute(myRoot, "simulationType", "Game of Life");
addColorsNode();
Map<String, String> rowsColumnsNeighbors = new HashMap<>() {{
put("num_rows", "20");
put("num_cols", "20");
put("num_neighbors", "8");
put("neighbor_configuration", "-1 3 0 3 1 3");
}};
for (Map.Entry<String, String> entry : rowsColumnsNeighbors.entrySet()) {
addChildNodeHelper(myRoot, entry.getKey(), entry.getValue());
}
addParametersNode();
addGridNode();
writeContentToXML();
}
private void addAttribute(Element parent, String attributeName, String attributeValue) {
Attr attribute = myXMLDocument.createAttribute(attributeName);
attribute.setValue(attributeValue);
parent.setAttributeNode(attribute);
}
private void addParametersNode() {
Element parametersNode = myXMLDocument.createElement("parameters");
Map<String, String> parametersMap = new HashMap<>() {{
put("min_population_threshold", "min_population_threshold:2");
put("max_population_threshold", "max_population_threshold:3");
}};
for (Map.Entry<String, String> entry : parametersMap.entrySet()) {
addChildNodeHelper(parametersNode, entry.getKey(), entry.getValue());
}
myRoot.appendChild(parametersNode);
}
private void addGridNode() {
Element gridNode = myXMLDocument.createElement("initial_rectangular_grid");
gridNode.setNodeValue("0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" +
" 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0\n" +
" 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0\n" +
" 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0\n" +
" 0 2 2 2 2 1 1 1 2 2 2 1 1 1 2 2 2 2 2 0\n" +
" 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0\n" +
" 0 2 2 1 2 2 2 2 1 2 1 2 2 2 2 1 2 2 2 0\n" +
" 0 2 2 1 2 2 2 2 1 2 1 2 2 2 2 1 2 2 2 0\n" +
" 0 2 2 1 2 2 2 2 1 2 1 2 2 2 2 1 2 2 2 0\n" +
" 0 2 2 2 2 1 1 1 2 2 2 1 1 1 2 2 2 2 2 0\n" +
" 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0\n" +
" 0 2 2 2 2 1 1 1 2 2 2 1 1 1 2 2 2 2 2 0\n" +
" 0 2 2 1 2 2 2 2 1 2 1 2 2 2 2 1 2 2 2 0\n" +
" 0 2 2 1 2 2 2 2 1 2 1 2 2 2 2 1 2 2 2 0\n" +
" 0 2 2 1 2 2 2 2 1 2 1 2 2 2 2 1 2 2 2 0\n" +
" 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0\n" +
" 0 2 2 2 2 1 1 1 2 2 2 1 1 1 2 2 2 2 2 0\n" +
" 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0\n" +
" 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0\n" +
" 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0");
myRoot.appendChild(gridNode);
}
private void addColorsNode() {
Element colorsNode = myXMLDocument.createElement("colors");
Map<String, String> statesColorsMap = new HashMap<>() {{
put("empty", "White");
put("live", "Blue");
put("dead", "Yellow");
}};
for (String key : statesColorsMap.keySet()) {
addChildNodeHelper(colorsNode, key, statesColorsMap.get(key));
}
myRoot.appendChild(colorsNode);
}
private void addChildNodeHelper(Element parent, String childTagName, String textContent) {
Element child = myXMLDocument.createElement(childTagName);
child.setTextContent(textContent);
parent.appendChild(child);
}
private void writeContentToXML() {
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(myXMLDocument);
StreamResult result = new StreamResult(myFileToSaveAs);
transformer.transform(source, result);
} catch (TransformerException e) {
// this was implemented near the end of the project, so we have not had the chance to figure out the
// error handling for this yet.
} catch (NullPointerException e) {
// this was implemented near the end of the project, so we have not had the chance to figure out the
// error handling for this yet.
}
}
}
|
3e196c2cb6ad6b866c3429a44b734aba55deff7b | 3,996 | java | Java | src/main/java/org/cxio/tools/ValidatorTools.java | cmzmasek/cxio | ed86ea642fb17ed89455897597c0520f5a10be25 | [
"BSD-4-Clause-UC"
] | 2 | 2015-07-27T16:18:26.000Z | 2015-08-11T16:37:43.000Z | src/main/java/org/cxio/tools/ValidatorTools.java | cmzmasek/cxio | ed86ea642fb17ed89455897597c0520f5a10be25 | [
"BSD-4-Clause-UC"
] | 5 | 2016-06-29T22:47:00.000Z | 2021-12-09T19:59:12.000Z | src/main/java/org/cxio/tools/ValidatorTools.java | cytoscape/cxio | ed86ea642fb17ed89455897597c0520f5a10be25 | [
"BSD-4-Clause-UC"
] | null | null | null | 31.21875 | 167 | 0.605105 | 10,799 | package org.cxio.tools;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.cxio.core.CxReader;
import org.cxio.core.interfaces.AspectElement;
import org.cxio.core.interfaces.AspectFragmentReader;
import org.cxio.misc.Status;
import org.cxio.util.CxioUtil;
public final class ValidatorTools {
private SortedMap<String, Integer> _aspect_element_counts;
private String[] _aspects;
private String _error;
private long _total_time;
private int _pre_meta_data_elements;
private int _post_meta_data_elements;
private Status _status;
public final static ValidatorTools getInstance() {
return new ValidatorTools();
}
private ValidatorTools() {
init();
}
public final SortedMap<String, Integer> getAspectElementCounts() {
return _aspect_element_counts;
}
public final String[] getAspectNames() {
return _aspects;
}
public final String getError() {
return _error;
}
public final int getNumberOfAspects() {
return _aspects.length;
}
public final long getTotalTimeMillis() {
return _total_time;
}
public int getPreMetaDataElementCount() {
return _pre_meta_data_elements;
}
public int getPostMetaDataElementCount() {
return _post_meta_data_elements;
}
public Status getStatus() {
return _status;
}
private final void init() {
_error = "";
_total_time = 0;
_aspects = new String[0];
_aspect_element_counts = new TreeMap<String, Integer>();
_pre_meta_data_elements = 0;
_post_meta_data_elements = 0;
_status = null;
}
public final boolean validate(final InputStream in) {
final Set<AspectFragmentReader> readers = CxioUtil.getAllAvailableAspectFragmentReaders();
return validate(in, true, readers);
}
public final boolean validate(final InputStream in, final boolean allow_anonymous_readers, final Set<AspectFragmentReader> readers) {
init();
try {
final long t0 = System.currentTimeMillis();
final CxReader cxr = makeReader(in, allow_anonymous_readers, readers);
while (cxr.hasNext()) {
final List<AspectElement> aspects = cxr.getNext();
if ((aspects != null) && !aspects.isEmpty()) {
final String name = aspects.get(0).getAspectName();
if (!_aspect_element_counts.containsKey(name)) {
_aspect_element_counts.put(name, aspects.size());
}
else {
_aspect_element_counts.put(name, _aspect_element_counts.get(name) + aspects.size());
}
}
}
if (cxr.getPreMetaData() != null) {
_pre_meta_data_elements = cxr.getPreMetaData().size();
}
if (cxr.getPostMetaData() != null) {
_post_meta_data_elements = cxr.getPostMetaData().size();
}
_status = cxr.getStatus();
_total_time = System.currentTimeMillis() - t0;
}
catch (final Exception e) {
_error = e.getMessage();
return false;
}
_aspects = new String[_aspect_element_counts.size()];
int i = 0;
for (final String aspect : _aspect_element_counts.keySet()) {
_aspects[i++] = aspect;
}
return true;
}
private final static CxReader makeReader(final InputStream in, final boolean allow_anonymous_readers, final Set<AspectFragmentReader> readers) throws IOException {
return CxReader.createInstance(in, allow_anonymous_readers, false, readers);
}
}
|
3e196dba8905468b7d73ce3bc890210d25774247 | 3,330 | java | Java | app/src/main/java/com/example/coolweather/util/Utility.java | rongyidev/coolweather | 49e8b323e3a0dbd68fa76aa1c317191c2e3e198f | [
"Apache-2.0"
] | 1 | 2018-11-30T02:49:00.000Z | 2018-11-30T02:49:00.000Z | app/src/main/java/com/example/coolweather/util/Utility.java | rongyidev/coolweather | 49e8b323e3a0dbd68fa76aa1c317191c2e3e198f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/coolweather/util/Utility.java | rongyidev/coolweather | 49e8b323e3a0dbd68fa76aa1c317191c2e3e198f | [
"Apache-2.0"
] | null | null | null | 33.979592 | 79 | 0.556156 | 10,800 | package com.example.coolweather.util;
import android.text.TextUtils;
import com.example.coolweather.db.City;
import com.example.coolweather.db.County;
import com.example.coolweather.db.Province;
import com.example.coolweather.gson.Weather;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Utility {
/*
* 解析和处理服务器返回的省级数据
* */
public static boolean handleProvinceResponse(String response){
if(!TextUtils.isEmpty(response)){
try{
JSONArray allProvinces = new JSONArray(response);
for(int i=0;i<allProvinces.length();i++){
JSONObject provinceObject = allProvinces.getJSONObject(i);
Province province = new Province();
province.setProvinceName(provinceObject.getString("name"));
province.setProvinceCode(provinceObject.getInt("id"));
province.save();//将数据存储到数据库中
}
return true;
}catch (JSONException e){
e.printStackTrace();
}
}
return false;
}
/**
* 解析和处理服务器返回的市级数据
* */
public static boolean handleCityResponse(String response,int provinceId){
if(!TextUtils.isEmpty(response)){
try{
JSONArray allCities = new JSONArray(response);
for(int i=0;i<allCities.length();i++){
JSONObject cityObject = allCities.getJSONObject(i);
City city = new City();
city.setCityName(cityObject.getString("name"));
city.setCityCode(cityObject.getInt("id"));
city.setProvinceId(provinceId);
city.save();
}
return true;
}catch (JSONException e){
e.printStackTrace();
}
}
return false;
}
/**
* 解析和处理服务器返回的县级数据
* */
public static boolean handleCountyResponse(String response,int cityId){
if(!TextUtils.isEmpty(response)){
try{
JSONArray allCounties = new JSONArray(response);
for(int i=0;i<allCounties.length();i++){
JSONObject countyObject = allCounties.getJSONObject(i);
County county = new County();
county.setCountyName(countyObject.getString("name"));
county.setWeatherId(countyObject.getString("weather_id"));
county.setCityId(cityId);
county.save();
}
return true;
}catch (JSONException e){
e.printStackTrace();
}
}
return false;
}
/*
* 将返回的JSON数据解析成Weather实体类
*
* */
public static Weather handleWeatherResponse(String response){
try{
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.optJSONArray("HeWeather");
String weatherContent = jsonArray.getJSONObject(0).toString();
return new Gson().fromJson(weatherContent,Weather.class);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
|
3e196fbd3238440bff6ebabf5246bd14ef7ef6e1 | 119 | java | Java | src/main/java/io/runidle/async/channel/ServerChannel.java | runidle/runidle-async | 161221716b05991827cac405e700fdb6f27260a7 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/runidle/async/channel/ServerChannel.java | runidle/runidle-async | 161221716b05991827cac405e700fdb6f27260a7 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/runidle/async/channel/ServerChannel.java | runidle/runidle-async | 161221716b05991827cac405e700fdb6f27260a7 | [
"Apache-2.0"
] | null | null | null | 17 | 79 | 0.781513 | 10,801 | package io.runidle.async.channel;
public interface ServerChannel<C extends ServerChannel<C>> extends Channel<C> {
}
|
3e19711469e16ba817492480481a67ac5ec3bf19 | 6,655 | java | Java | geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/ConnectionManagerTest.java | jgallimore/geronimo-txmanager | e9291012b3605fd45cbd34e7b3a4057a385d64be | [
"Apache-2.0"
] | 5 | 2015-03-19T07:58:22.000Z | 2021-11-09T21:15:46.000Z | geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/ConnectionManagerTest.java | jgallimore/geronimo-txmanager | e9291012b3605fd45cbd34e7b3a4057a385d64be | [
"Apache-2.0"
] | 2 | 2021-02-14T08:02:34.000Z | 2021-04-12T18:14:22.000Z | geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/ConnectionManagerTest.java | jgallimore/geronimo-txmanager | e9291012b3605fd45cbd34e7b3a4057a385d64be | [
"Apache-2.0"
] | 14 | 2015-04-15T08:36:26.000Z | 2021-11-09T21:15:35.000Z | 54.105691 | 176 | 0.721563 | 10,802 | /**
* 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.geronimo.connector.outbound;
import org.apache.geronimo.connector.mock.MockXAResource;
import org.apache.geronimo.connector.mock.ConnectionExtension;
import org.apache.geronimo.connector.outbound.connectiontracking.DefaultInterceptor;
import org.apache.geronimo.connector.outbound.connectiontracking.ConnectorInstanceContext;
import org.apache.geronimo.transaction.GeronimoUserTransaction;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class ConnectionManagerTest extends ConnectionManagerTestUtils {
public void testSingleTransactionCall() throws Throwable {
transactionManager.begin();
defaultComponentInterceptor.invoke(connectorInstanceContext);
MockXAResource mockXAResource = (MockXAResource) mockManagedConnection.getXAResource();
assertEquals("XAResource should know one xid", 1, mockXAResource.getKnownXids().size());
assertNull("Should not be committed", mockXAResource.getCommitted());
transactionManager.commit();
assertNotNull("Should be committed", mockXAResource.getCommitted());
}
public void testNoTransactionCall() throws Throwable {
defaultComponentInterceptor.invoke(connectorInstanceContext);
MockXAResource mockXAResource = (MockXAResource) mockManagedConnection.getXAResource();
assertEquals("XAResource should know 0 xid", 0, mockXAResource.getKnownXids().size());
assertNull("Should not be committed", mockXAResource.getCommitted());
}
public void testOneTransactionTwoCalls() throws Throwable {
transactionManager.begin();
defaultComponentInterceptor.invoke(connectorInstanceContext);
MockXAResource mockXAResource = (MockXAResource) mockManagedConnection.getXAResource();
assertEquals("XAResource should know one xid", 1, mockXAResource.getKnownXids().size());
assertNull("Should not be committed", mockXAResource.getCommitted());
defaultComponentInterceptor.invoke(connectorInstanceContext);
assertEquals("Expected same XAResource", mockXAResource, mockManagedConnection.getXAResource());
assertEquals("XAResource should know one xid", 1, mockXAResource.getKnownXids().size());
assertNull("Should not be committed", mockXAResource.getCommitted());
transactionManager.commit();
assertNotNull("Should be committed", mockXAResource.getCommitted());
}
public void testUserTransactionEnlistingExistingConnections() throws Throwable {
mockComponent = new DefaultInterceptor() {
public Object invoke(ConnectorInstanceContext newConnectorInstanceContext) throws Throwable {
ConnectionExtension mockConnection = (ConnectionExtension) connectionFactory.getConnection();
mockManagedConnection = mockConnection.getManagedConnection();
userTransaction.begin();
MockXAResource mockXAResource = (MockXAResource) mockManagedConnection.getXAResource();
assertEquals("XAResource should know one xid", 1, mockXAResource.getKnownXids().size());
assertNull("Should not be committed", mockXAResource.getCommitted());
userTransaction.commit();
assertNotNull("Should be committed", mockXAResource.getCommitted());
mockConnection.close();
return null;
}
};
userTransaction = new GeronimoUserTransaction(transactionManager);
defaultComponentInterceptor.invoke(connectorInstanceContext);
MockXAResource mockXAResource = (MockXAResource) mockManagedConnection.getXAResource();
assertEquals("XAResource should know 1 xid", 1, mockXAResource.getKnownXids().size());
assertNotNull("Should be committed", mockXAResource.getCommitted());
mockXAResource.clear();
}
public void testConnectionCloseReturnsCxAfterUserTransaction() throws Throwable {
for (int i = 0; i < maxSize + 1; i++) {
testUserTransactionEnlistingExistingConnections();
}
}
public void testUnshareableConnections() throws Throwable {
unshareableResources.add(name);
mockComponent = new DefaultInterceptor() {
public Object invoke(ConnectorInstanceContext newConnectorInstanceContext) throws Throwable {
ConnectionExtension mockConnection1 = (ConnectionExtension) connectionFactory.getConnection();
mockManagedConnection = mockConnection1.getManagedConnection();
ConnectionExtension mockConnection2 = (ConnectionExtension) connectionFactory.getConnection();
//the 2 cx are for the same RM, so tm will call commit only one one (the first)
//mockManagedConnection = mockConnection2.getManagedConnection();
assertNotNull("Expected non-null managedconnection 1", mockConnection1.getManagedConnection());
assertNotNull("Expected non-null managedconnection 2", mockConnection2.getManagedConnection());
assertTrue("Expected different managed connections for each unshared handle", mockConnection1.getManagedConnection() != mockConnection2.getManagedConnection());
mockConnection1.close();
mockConnection2.close();
return null;
}
};
transactionManager.begin();
defaultComponentInterceptor.invoke(connectorInstanceContext);
MockXAResource mockXAResource = (MockXAResource) mockManagedConnection.getXAResource();
assertEquals("XAResource should know one xid", 1, mockXAResource.getKnownXids().size());
assertNull("Should not be committed", mockXAResource.getCommitted());
transactionManager.commit();
assertNotNull("Should be committed", mockXAResource.getCommitted());
}
}
|
3e197159f4b632950047b47e2b22fcb1aa89150b | 3,666 | java | Java | src/main/java/com/compomics/mslims/db/conversiontool/implementations/Remove_fragmention_redundancy_StepImpl.java | nielshulstaert/ms-lims | 99fc7670236631034eba8a2abb58f0d22cebc2eb | [
"Apache-2.0"
] | 2 | 2015-11-23T10:15:58.000Z | 2017-02-23T14:46:50.000Z | src/main/java/com/compomics/mslims/db/conversiontool/implementations/Remove_fragmention_redundancy_StepImpl.java | nielshulstaert/ms-lims | 99fc7670236631034eba8a2abb58f0d22cebc2eb | [
"Apache-2.0"
] | null | null | null | src/main/java/com/compomics/mslims/db/conversiontool/implementations/Remove_fragmention_redundancy_StepImpl.java | nielshulstaert/ms-lims | 99fc7670236631034eba8a2abb58f0d22cebc2eb | [
"Apache-2.0"
] | null | null | null | 42.137931 | 151 | 0.63257 | 10,803 | package com.compomics.mslims.db.conversiontool.implementations;
import org.apache.log4j.Logger;
import com.compomics.mslims.db.accessors.Fragmention;
import com.compomics.mslims.db.conversiontool.interfaces.DBConverterStep;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashSet;
/**
* Created by IntelliJ IDEA. User: kenny Date: Aug 18, 2009 Time: 6:26:45 PM
* <p/>
* This class
*/
public class Remove_fragmention_redundancy_StepImpl implements DBConverterStep {
// Class specific log4j logger for Remove_fragmention_redundancy_StepImpl instances.
private static Logger logger = Logger.getLogger(Remove_fragmention_redundancy_StepImpl.class);
public Remove_fragmention_redundancy_StepImpl() {
}
public boolean performConversionStep(Connection aConn) {
logger.info("\tStarting to remove redundant fragmentions by identificationids..");
boolean error = false;
// We'll have to ensure that, for each spectrum that does not yet have
// a total intensity or highest peak, that these two columns are populated.
int lIdentificationID;
int lSuccess = 0;
double lThreshold = 10000;
try {
// First locate all relevant spectrum rows.
PreparedStatement lPrepearedStatementIdentifications = aConn.prepareStatement("SELECT identificationid FROM identification");
ResultSet rsOuter = lPrepearedStatementIdentifications.executeQuery();
while (rsOuter.next()) {
// Iterate over all IdentificationIDs.
lIdentificationID = rsOuter.getInt(1);
// Create the select statement to fetch all fragmentions of this identificationID.
PreparedStatement lPreparedStatementFragmentions = aConn.prepareStatement("select * from fragmention where l_identificationid=?");
lPreparedStatementFragmentions.setInt(1, lIdentificationID);
// Create an inner resultset to iterate over the fragmentions.
ResultSet rsInner = lPreparedStatementFragmentions.executeQuery();
// Use a HashSet to filter unique values of the fragmentions.
HashSet lSet = new HashSet();
while (rsInner.next()) {
Fragmention lFragmention = new Fragmention(rsInner);
boolean isNewElement = lSet.add(lFragmention.toString());
// If the toString (ionType,ionNumber and mZ) is not new in the HashSet,
if (!isNewElement) {
// then delete this element.
lSuccess += lFragmention.delete(aConn);
logger.info("Deleted redundant fragmention " + lFragmention.toString() + " for identificationid '" + lIdentificationID + "'.");
lSuccess++;
}
}
if ((((double) lSuccess) % lThreshold) == 0) {
}
logger.info("Successfully deleted " + "'" + lSuccess + "' redundant ions!");
rsInner.close();
lPreparedStatementFragmentions.close();
}
rsOuter.close();
lPrepearedStatementIdentifications.close();
logger.info("\tSuccessfully removed " + lSuccess + " redundant fragmentions.");
} catch (Exception e) {
logger.error("\n\nError while removing redundant fragmentions:");
logger.error(e.getMessage());
logger.error(e.getMessage(), e);
error = true;
}
return error;
}
}
|
3e19716abbb6d1af3f416a2af3b765c497138f7c | 108 | java | Java | clients/android/app/src/main/java/com/wemakestuff/teracast/media/event/StopEvent.java | wemakestuff/Teracast | c3f48bbbe981314d52888bd51dcc7920e8bffc00 | [
"Apache-2.0"
] | 1 | 2015-05-12T09:30:46.000Z | 2015-05-12T09:30:46.000Z | clients/android/app/src/main/java/com/wemakestuff/teracast/media/event/StopEvent.java | wemakestuff/Teracast | c3f48bbbe981314d52888bd51dcc7920e8bffc00 | [
"Apache-2.0"
] | null | null | null | clients/android/app/src/main/java/com/wemakestuff/teracast/media/event/StopEvent.java | wemakestuff/Teracast | c3f48bbbe981314d52888bd51dcc7920e8bffc00 | [
"Apache-2.0"
] | null | null | null | 13.5 | 45 | 0.712963 | 10,804 | package com.wemakestuff.teracast.media.event;
/**
* Marker class for Otto.
*/
public class StopEvent {
}
|
3e197181e0f3eab0a95fda88acc9c8c53571df60 | 1,710 | java | Java | src/com/cdl/kata/main/CdlKataMain.java | virajvyas/cdl_kata | faf764d0c7ea08c941e9738a10e1db7162a44087 | [
"MIT"
] | null | null | null | src/com/cdl/kata/main/CdlKataMain.java | virajvyas/cdl_kata | faf764d0c7ea08c941e9738a10e1db7162a44087 | [
"MIT"
] | null | null | null | src/com/cdl/kata/main/CdlKataMain.java | virajvyas/cdl_kata | faf764d0c7ea08c941e9738a10e1db7162a44087 | [
"MIT"
] | null | null | null | 35.625 | 162 | 0.762573 | 10,805 | package com.cdl.kata.main;
import java.util.Scanner;
import com.cdl.kata.model.Basket;
import com.cdl.kata.model.ProductAndOfferInventory;
import com.cdl.kata.model.ProductItem;
import com.cdl.kata.services.InventoryGeneratorService;
import com.cdl.kata.services.ProductAndOfferInventoryService;
import com.cdl.kata.services.ProductItemService;
import com.cdl.kata.services.ShopingBasketService;
public class CdlKataMain {
private static final String EXIT_STRING = "exit";
public static void main(String[] args) {
try (Scanner inputScanner = new Scanner(System.in)) {
ProductAndOfferInventory productAndOfferInventory = InventoryGeneratorService.generateInitialInventories();
System.out.println("Please enter product that you want to buy.");
Basket basket = new Basket();
String inputproduct = null;
while (!EXIT_STRING.equals(inputproduct)) {
System.out.println("Your product from [" + ProductAndOfferInventoryService.getAllProductName(productAndOfferInventory) +"]. For checkout type: "+EXIT_STRING);
inputproduct = inputScanner.nextLine();
ProductItem productIterm = ProductItemService.getProductItem(inputproduct, productAndOfferInventory);
if(productIterm == null) {
System.out.println("Please enter valid product");
System.out.println("All Valid products are: " + ProductAndOfferInventoryService.getAllProductName(productAndOfferInventory));
} else if (!EXIT_STRING.equals(inputproduct)) {
basket = ShopingBasketService.calculateNewBasket(productIterm, basket, productAndOfferInventory);
}
}
System.out.println("Your product total is : " + ShopingBasketService.getBasketTotal(basket));
}
}
}
|
3e19723ce910454feceba7f7928109cd3a6ac747 | 18,237 | java | Java | kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/KiteRequestHandler.java | RohanGala/javakiteconnect | 292ea87f0a36e5a17347aef645e3505e244ccf08 | [
"MIT"
] | null | null | null | kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/KiteRequestHandler.java | RohanGala/javakiteconnect | 292ea87f0a36e5a17347aef645e3505e244ccf08 | [
"MIT"
] | null | null | null | kiteconnect/src/com/zerodhatech/kiteconnect/kitehttp/KiteRequestHandler.java | RohanGala/javakiteconnect | 292ea87f0a36e5a17347aef645e3505e244ccf08 | [
"MIT"
] | null | null | null | 60.58804 | 772 | 0.71843 | 10,806 | package src.com.zerodhatech.kiteconnect.kitehttp;
import java.io.IOException;
import java.net.Proxy;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import src.com.zerodhatech.kiteconnect.KiteConnect;
import src.com.zerodhatech.kiteconnect.kitehttp.exceptions.KiteException;
/**
* Request handler for all Http requests
*/
public class KiteRequestHandler {
private OkHttpClient client;
private String USER_AGENT = "javakiteconnect/3.0.0";
private String authorizationToken = "enctoken aimagX8VpjAZ0g0ygstduoTEr5a4NLiPgaX1mHO2DeU1oX+45PDV2JlpIT/wZtbkou5bpd/qQN9lMJaFmWSxgnPt70vV5Q==";
/** Initialize request handler.
* @param proxy to be set for making requests.*/
public KiteRequestHandler(Proxy proxy) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(10000, TimeUnit.MILLISECONDS);
if(proxy != null) {
builder.proxy(proxy);
}
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
if(KiteConnect.ENABLE_LOGGING) {
client = builder.addInterceptor(logging).build();
}else {
client = builder.build();
}
}
/** Makes a GET request.
* @return JSONObject which is received by Kite Trade.
* @param url is the endpoint to which request has to be sent.
* @param apiKey is the api key of the Kite Connect app.
* @param accessToken is the access token obtained after successful login process.
* @throws IOException is thrown when there is a connection related error.
* @throws KiteException is thrown for all Kite Trade related errors.
* @throws JSONException is thrown for parsing errors.*/
public JSONObject getRequest(String url, String apiKey, String accessToken) throws IOException, KiteException, JSONException {
Request request = createGetRequest(url, apiKey, accessToken);
Response response = client.newCall(request).execute();
String body = response.body().string();
return new KiteResponseHandler().handle(response, body);
}
/** Makes a GET request.
* @return JSONObject which is received by Kite Trade.
* @param url is the endpoint to which request has to be sent.
* @param apiKey is the api key of the Kite Connect app.
* @param accessToken is the access token obtained after successful login process.
* @param params is the map of params which has to be sent as query params.
* @throws IOException is thrown when there is a connection related error.
* @throws KiteException is thrown for all Kite Trade related errors.
* @throws JSONException is thrown for parsing errors.*/
public JSONObject getRequest(String url, Map<String, Object> params, String apiKey, String accessToken) throws IOException, KiteException, JSONException {
Request request = createGetRequest(url,params,apiKey, accessToken);
Response response = client.newCall(request).execute();
String body = response.body().string();
return new KiteResponseHandler().handle(response, body);
}
/** Makes a POST request.
* @return JSONObject which is received by Kite Trade.
* @param url is the endpoint to which request has to be sent.
* @param apiKey is the api key of the Kite Connect app.
* @param accessToken is the access token obtained after successful login process.
* @param params is the map of params which has to be sent in the body.
* @throws IOException is thrown when there is a connection related error.
* @throws KiteException is thrown for all Kite Trade related errors.
* @throws JSONException is thrown for parsing errors.*/
public JSONObject postRequest(String url, Map<String, Object> params, String apiKey, String accessToken) throws IOException, KiteException, JSONException {
Request request = createPostRequest(url, params, apiKey, accessToken);
Response response = client.newCall(request).execute();
String body = response.body().string();
return new KiteResponseHandler().handle(response, body);
}
/** Make a JSON POST request.
* @param url is the endpoint to which request has to be sent.
* @param apiKey is the api key of the Kite Connect app.
* @param accessToken is the access token obtained after successful login process.
* @param jsonArray is the JSON array of params which has to be sent in the body.
* @throws IOException is thrown when there is a connection related error.
* @throws KiteException is thrown for all Kite Trade related errors.
* @throws JSONException is thrown for parsing errors.
* */
public JSONObject postRequestJSON(String url, JSONArray jsonArray, String apiKey, String accessToken) throws IOException, KiteException, JSONException {
Request request = createJsonPostRequest(url, jsonArray, apiKey, accessToken);
Response response = client.newCall(request).execute();
String body = response.body().string();
return new KiteResponseHandler().handle(response, body);
}
/** Makes a PUT request.
* @return JSONObject which is received by Kite Trade.
* @param url is the endpoint to which request has to be sent.
* @param apiKey is the api key of the Kite Connect app.
* @param accessToken is the access token obtained after successful login process.
* @param params is the map of params which has to be sent in the body.
* @throws IOException is thrown when there is a connection related error.
* @throws KiteException is thrown for all Kite Trade related errors.
* @throws JSONException is thrown for parsing errors.*/
public JSONObject putRequest(String url, Map<String, Object> params, String apiKey, String accessToken) throws IOException, KiteException, JSONException {
Request request = createPutRequest(url, params, apiKey, accessToken);
Response response = client.newCall(request).execute();
String body = response.body().string();
return new KiteResponseHandler().handle(response, body);
}
/** Makes a DELETE request.
* @return JSONObject which is received by Kite Trade.
* @param url is the endpoint to which request has to be sent.
* @param apiKey is the api key of the Kite Connect app.
* @param accessToken is the access token obtained after successful login process.
* @param params is the map of params which has to be sent in the query params.
* @throws IOException is thrown when there is a connection related error.
* @throws KiteException is thrown for all Kite Trade related errors.
* @throws JSONException is thrown for parsing errors.*/
public JSONObject deleteRequest(String url, Map<String, Object> params, String apiKey, String accessToken) throws IOException, KiteException, JSONException {
Request request = createDeleteRequest(url, params, apiKey, accessToken);
Response response = client.newCall(request).execute();
String body = response.body().string();
return new KiteResponseHandler().handle(response, body);
}
/** Makes a GET request.
* @return JSONObject which is received by Kite Trade.
* @param url is the endpoint to which request has to be sent.
* @param apiKey is the api key of the Kite Connect app.
* @param accessToken is the access token obtained after successful login process.
* @param commonKey is the key that has to be sent in query param for quote calls.
* @param values is the values that has to be sent in query param like 265, 256265, NSE:INFY.
* @throws IOException is thrown when there is a connection related error.
* @throws KiteException is thrown for all Kite Trade related errors.
* @throws JSONException is thrown for parsing errors.
* */
public JSONObject getRequest(String url, String commonKey, String[] values, String apiKey, String accessToken) throws IOException, KiteException, JSONException {
Request request = createGetRequest(url, commonKey, values, apiKey, accessToken);
Response response = client.newCall(request).execute();
String body = response.body().string();
return new KiteResponseHandler().handle(response, body);
}
/** Makes GET request to fetch CSV dump.
* @return String which is received from server.
* @param url is the endpoint to which request has to be done.
* @param apiKey is the api key of the Kite Connect app.
* @param accessToken is the access token obtained after successful login process.
* @throws IOException is thrown when there is a connection related error.
* @throws KiteException is thrown for all Kite Trade related errors.
* */
public String getCSVRequest(String url, String apiKey, String accessToken) throws IOException, KiteException, JSONException {
Request request = new Request.Builder().url(url).header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken).build();
Response response = client.newCall(request).execute();
String body = response.body().string();
return new KiteResponseHandler().handle(response, body, "csv");
}
/** Creates a GET request.
* @param url is the endpoint to which request has to be done.
* @param apiKey is the api key of the Kite Connect app.
* @param accessToken is the access token obtained after successful login process.
* */
public Request createGetRequest(String url, String apiKey, String accessToken) {
HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
return new Request.Builder().url(httpBuilder.build()).header("User-Agent", USER_AGENT)
.header("X-Kite-Version", "2.8.0").header("x-kite-userid", "ZG8743").header("authorization",authorizationToken)
.header("cookie", "_ga=GA1.2.370087298.1588256450; WZRK_G=c6fe6b8f8b1d47f7a05174eb79f4e52e; mp_7b1e06d0192feeac86689b5599a4b024_mixpanel=%7B%22distinct_id%22%3A%20%2258203f0e081e8e6ab1e47bdb%22%2C%22%24device_id%22%3A%20%221728eee483f0-0de0b08dad0176-1b3a6256-13c680-1728eee4840288%22%2C%22%24user_id%22%3A%20%2258203f0e081e8e6ab1e47bdb%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%7D; __cfduid=daad658f726166cab5741081ce2964de21602938735; kf_session=x53faP91FD3dti5cQ7bnvsCgT3pMNqTb; user_id=PR5116; public_token=CsarApVvWd7NmunUalcrjtu7MvxvBPOu; enctoken=OTD/8o31Rc95cFH4oOs/nifRezgVI6r+1gyT1fWMchRqpj0Zf56Pe2RySexQl4vcGWml9MIrOtKDQBfDsKsGjT+6+e7SLw==; _gid=GA1.2.1763442148.1603862735")
.build();
}
/** Creates a GET request.
* @param url is the endpoint to which request has to be done.
* @param apiKey is the api key of the Kite Connect app.
* @param accessToken is the access token obtained after successful login process.
* @param params is the map of data that has to be sent in query params.
* */
public Request createGetRequest(String url, Map<String, Object> params, String apiKey, String accessToken) {
HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
for(Map.Entry<String, Object> entry: params.entrySet()){
httpBuilder.addQueryParameter(entry.getKey(), entry.getValue().toString());
}
return new Request.Builder().url(httpBuilder.build()).header("User-Agent", USER_AGENT)
.header("X-Kite-Version", "2.8.0").header("x-kite-userid", "ZG8743").header("authorization",authorizationToken)
//.header("cookie", "_ga=GA1.2.370087298.1588256450; WZRK_G=c6fe6b8f8b1d47f7a05174eb79f4e52e; mp_7b1e06d0192feeac86689b5599a4b024_mixpanel=%7B%22distinct_id%22%3A%20%2258203f0e081e8e6ab1e47bdb%22%2C%22%24device_id%22%3A%20%221728eee483f0-0de0b08dad0176-1b3a6256-13c680-1728eee4840288%22%2C%22%24user_id%22%3A%20%2258203f0e081e8e6ab1e47bdb%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%7D; __cfduid=daad658f726166cab5741081ce2964de21602938735; kf_session=x53faP91FD3dti5cQ7bnvsCgT3pMNqTb; user_id=PR5116; public_token=CsarApVvWd7NmunUalcrjtu7MvxvBPOu; enctoken=OTD/8o31Rc95cFH4oOs/nifRezgVI6r+1gyT1fWMchRqpj0Zf56Pe2RySexQl4vcGWml9MIrOtKDQBfDsKsGjT+6+e7SLw==; _gid=GA1.2.1763442148.1603862735")
.build();
}
/** Creates a GET request.
* @param url is the endpoint to which request has to be done.
* @param apiKey is the api key of the Kite Connect app.
* @param accessToken is the access token obtained after successful login process.
* @param commonKey is the key that has to be sent in query param for quote calls.
* @param values is the values that has to be sent in query param like 265, 256265, NSE:INFY.
* */
public Request createGetRequest(String url, String commonKey, String[] values, String apiKey, String accessToken) {
HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
for(int i = 0; i < values.length; i++) {
httpBuilder.addQueryParameter(commonKey, values[i]);
}
return new Request.Builder().url(httpBuilder.build()).header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken).build();
}
/** Creates a POST request.
* @param url is the endpoint to which request has to be done.
* @param apiKey is the api key of the Kite Connect app.
* @param accessToken is the access token obtained after successful login process.
* @param params is the map of data that has to be sent in the body.
* */
public Request createPostRequest(String url, Map<String, Object> params, String apiKey, String accessToken) {
FormBody.Builder builder = new FormBody.Builder();
for(Map.Entry<String, Object> entry: params.entrySet()){
builder.add(entry.getKey(), entry.getValue().toString());
}
RequestBody requestBody = builder.build();
Request request = new Request.Builder().url(url).post(requestBody).header("User-Agent", USER_AGENT).header("X-Kite-Version", "2.6.1").header("x-kite-userid", "PR5116").header("authorization",authorizationToken)
.header("cookie", "_ga=GA1.2.370087298.1588256450; WZRK_G=c6fe6b8f8b1d47f7a05174eb79f4e52e; mp_7b1e06d0192feeac86689b5599a4b024_mixpanel=%7B%22distinct_id%22%3A%20%2258203f0e081e8e6ab1e47bdb%22%2C%22%24device_id%22%3A%20%221728eee483f0-0de0b08dad0176-1b3a6256-13c680-1728eee4840288%22%2C%22%24user_id%22%3A%20%2258203f0e081e8e6ab1e47bdb%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%7D; __cfduid=daad658f726166cab5741081ce2964de21602938735; kf_session=x53faP91FD3dti5cQ7bnvsCgT3pMNqTb; user_id=PR5116; public_token=CsarApVvWd7NmunUalcrjtu7MvxvBPOu; enctoken=OTD/8o31Rc95cFH4oOs/nifRezgVI6r+1gyT1fWMchRqpj0Zf56Pe2RySexQl4vcGWml9MIrOtKDQBfDsKsGjT+6+e7SLw==; _gid=GA1.2.1763442148.1603862735").build();
return request;
}
/** Create a POST request with body type JSON.
* @param url is the endpoint to which request has to be done.
* @param apiKey is the api key of the Kite Connect app.
* @param accessToken is the access token obtained after successful login process.
* @param jsonArray is the JSONArray of data that has to be sent in the body.
* */
public Request createJsonPostRequest(String url, JSONArray jsonArray, String apiKey, String accessToken) {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(jsonArray.toString(), JSON);
Request request = new Request.Builder()
.url(url)
.header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken)
.post(body)
.build();
return request;
}
/** Creates a PUT request.
* @param url is the endpoint to which request has to be done.
* @param apiKey is the api key of the Kite Connect app.
* @param accessToken is the access token obtained after successful login process.
* @param params is the map of data that has to be sent in the body.
* */
public Request createPutRequest(String url, Map<String, Object> params, String apiKey, String accessToken){
FormBody.Builder builder = new FormBody.Builder();
for(Map.Entry<String, Object> entry: params.entrySet()){
builder.add(entry.getKey(), entry.getValue().toString());
}
RequestBody requestBody = builder.build();
Request request = new Request.Builder().url(url).put(requestBody).header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken).build();
return request;
}
/** Creates a DELETE request.
* @param url is the endpoint to which request has to be done.
* @param apiKey is the api key of the Kite Connect app.
* @param accessToken is the access token obtained after successful login process.
* @param params is the map of data that has to be sent in the query params.
* */
public Request createDeleteRequest(String url, Map<String, Object> params, String apiKey, String accessToken){
HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
for(Map.Entry<String, Object> entry: params.entrySet()){
httpBuilder.addQueryParameter(entry.getKey(), entry.getValue().toString());
}
Request request = new Request.Builder().url(httpBuilder.build()).delete().header("User-Agent", USER_AGENT).header("X-Kite-Version", "3").header("Authorization", "token "+apiKey+":"+accessToken).build();
return request;
}
} |
3e1972ca1c207f94e2d0960f1a1ac96113e5d948 | 6,362 | java | Java | jfreechart-1.0.14/tests/org/jfree/chart/junit/StrokeMapTests.java | Kongaloosh/Ticker | 77a85e4b19156882243e888426b1c86fad640587 | [
"Apache-2.0"
] | null | null | null | jfreechart-1.0.14/tests/org/jfree/chart/junit/StrokeMapTests.java | Kongaloosh/Ticker | 77a85e4b19156882243e888426b1c86fad640587 | [
"Apache-2.0"
] | null | null | null | jfreechart-1.0.14/tests/org/jfree/chart/junit/StrokeMapTests.java | Kongaloosh/Ticker | 77a85e4b19156882243e888426b1c86fad640587 | [
"Apache-2.0"
] | null | null | null | 28.529148 | 79 | 0.575134 | 10,807 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library 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 library 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -------------------
* StrokeMapTests.java
* -------------------
* (C) Copyright 2006-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 27-Sep-2006 : Version 1 (DG);
*
*/
package org.jfree.chart.junit;
import java.awt.BasicStroke;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jfree.chart.StrokeMap;
/**
* Some tests for the {@link StrokeMap} class.
*/
public class StrokeMapTests extends TestCase {
/**
* Returns the tests as a test suite.
*
* @return The test suite.
*/
public static Test suite() {
return new TestSuite(StrokeMapTests.class);
}
/**
* Constructs a new set of tests.
*
* @param name the name of the tests.
*/
public StrokeMapTests(String name) {
super(name);
}
/**
* Some checks for the getStroke() method.
*/
public void testGetStroke() {
StrokeMap m1 = new StrokeMap();
assertEquals(null, m1.getStroke("A"));
m1.put("A", new BasicStroke(1.1f));
assertEquals(new BasicStroke(1.1f), m1.getStroke("A"));
m1.put("A", null);
assertEquals(null, m1.getStroke("A"));
// a null key should throw an IllegalArgumentException
boolean pass = false;
try {
m1.getStroke(null);
}
catch (IllegalArgumentException e) {
pass = true;
}
assertTrue(pass);
}
/**
* Some checks for the put() method.
*/
public void testPut() {
StrokeMap m1 = new StrokeMap();
m1.put("A", new BasicStroke(1.1f));
assertEquals(new BasicStroke(1.1f), m1.getStroke("A"));
// a null key should throw an IllegalArgumentException
boolean pass = false;
try {
m1.put(null, new BasicStroke(1.1f));
}
catch (IllegalArgumentException e) {
pass = true;
}
assertTrue(pass);
}
/**
* Some checks for the equals() method.
*/
public void testEquals() {
StrokeMap m1 = new StrokeMap();
StrokeMap m2 = new StrokeMap();
assertTrue(m1.equals(m1));
assertTrue(m1.equals(m2));
assertFalse(m1.equals(null));
assertFalse(m1.equals("ABC"));
m1.put("K1", new BasicStroke(1.1f));
assertFalse(m1.equals(m2));
m2.put("K1", new BasicStroke(1.1f));
assertTrue(m1.equals(m2));
m1.put("K2", new BasicStroke(2.2f));
assertFalse(m1.equals(m2));
m2.put("K2", new BasicStroke(2.2f));
assertTrue(m1.equals(m2));
m1.put("K2", null);
assertFalse(m1.equals(m2));
m2.put("K2", null);
assertTrue(m1.equals(m2));
}
/**
* Some checks for cloning.
*/
public void testCloning() {
StrokeMap m1 = new StrokeMap();
StrokeMap m2 = null;
try {
m2 = (StrokeMap) m1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(m1.equals(m2));
m1.put("K1", new BasicStroke(1.1f));
m1.put("K2", new BasicStroke(2.2f));
try {
m2 = (StrokeMap) m1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(m1.equals(m2));
}
/**
* A check for serialization.
*/
public void testSerialization1() {
StrokeMap m1 = new StrokeMap();
StrokeMap m2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(m1);
out.close();
ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(
buffer.toByteArray()));
m2 = (StrokeMap) in.readObject();
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
assertEquals(m1, m2);
}
/**
* A check for serialization.
*/
public void testSerialization2() {
StrokeMap m1 = new StrokeMap();
m1.put("K1", new BasicStroke(1.1f));
m1.put("K2", new BasicStroke(2.2f));
StrokeMap m2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(m1);
out.close();
ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(
buffer.toByteArray()));
m2 = (StrokeMap) in.readObject();
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
assertEquals(m1, m2);
}
}
|
3e19734a35331d78ca611bafa6351baec45ad095 | 2,433 | java | Java | powerauth-webflow-authentication-mtoken/src/main/java/io/getlime/security/powerauth/lib/webflow/authentication/mtoken/model/request/QrCodeAuthenticationRequest.java | lime-company/powerauth-webflow | 72deefb79177ccb55d357527a585f7c91490eb93 | [
"Apache-2.0"
] | 2 | 2018-01-16T22:36:07.000Z | 2018-03-24T16:37:54.000Z | powerauth-webflow-authentication-mtoken/src/main/java/io/getlime/security/powerauth/lib/webflow/authentication/mtoken/model/request/QrCodeAuthenticationRequest.java | lime-company/powerauth-webflow | 72deefb79177ccb55d357527a585f7c91490eb93 | [
"Apache-2.0"
] | 202 | 2017-09-21T18:03:08.000Z | 2018-07-03T21:20:26.000Z | powerauth-webflow-authentication-mtoken/src/main/java/io/getlime/security/powerauth/lib/webflow/authentication/mtoken/model/request/QrCodeAuthenticationRequest.java | lime-company/powerauth-webflow | 72deefb79177ccb55d357527a585f7c91490eb93 | [
"Apache-2.0"
] | 2 | 2017-11-14T16:40:21.000Z | 2018-02-23T09:53:20.000Z | 27.1 | 86 | 0.681837 | 10,808 | /*
* PowerAuth Web Flow and related software components
* Copyright (C) 2017 Wultra s.r.o.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.getlime.security.powerauth.lib.webflow.authentication.mtoken.model.request;
import io.getlime.security.powerauth.lib.nextstep.model.enumeration.AuthInstrument;
import io.getlime.security.powerauth.lib.webflow.authentication.base.AuthStepRequest;
import java.util.Collections;
import java.util.List;
/**
* Request for QR code based authentication in offline mode for mobile token.
*
* @author Roman Strobl, kenaa@example.com
*/
public class QrCodeAuthenticationRequest extends AuthStepRequest {
private String activationId;
private String authCode;
private String nonce;
/**
* Get activation ID.
* @return Activation ID.
*/
public String getActivationId() {
return activationId;
}
/**
* Set activation ID.
* @param activationId Activation ID.
*/
public void setActivationId(String activationId) {
this.activationId = activationId;
}
/**
* Get authorization code.
* @return Authorization code.
*/
public String getAuthCode() {
return authCode;
}
/**
* Set authorization code.
* @param authCode Authorization code.
*/
public void setAuthCode(String authCode) {
this.authCode = authCode;
}
/**
* Get nonce.
* @return Nonce.
*/
public String getNonce() {
return nonce;
}
/**
* Set nonce.
* @param nonce Nonce.
*/
public void setNonce(String nonce) {
this.nonce = nonce;
}
@Override
public List<AuthInstrument> getAuthInstruments() {
return Collections.singletonList(AuthInstrument.POWERAUTH_TOKEN);
}
}
|
3e197400a5cd75f6ec013f62a9a005750cc0c96e | 5,983 | java | Java | robozonky-strategy-natural/src/test/java/com/github/robozonky/strategy/natural/UtilTest.java | vvvlc/robozonky | 8026ac3c583d76e95a9c6a0f62c1d003453ff7a7 | [
"Apache-2.0"
] | null | null | null | robozonky-strategy-natural/src/test/java/com/github/robozonky/strategy/natural/UtilTest.java | vvvlc/robozonky | 8026ac3c583d76e95a9c6a0f62c1d003453ff7a7 | [
"Apache-2.0"
] | null | null | null | robozonky-strategy-natural/src/test/java/com/github/robozonky/strategy/natural/UtilTest.java | vvvlc/robozonky | 8026ac3c583d76e95a9c6a0f62c1d003453ff7a7 | [
"Apache-2.0"
] | null | null | null | 47.110236 | 115 | 0.643156 | 10,809 | /*
* Copyright 2019 The RoboZonky Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.robozonky.strategy.natural;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.github.robozonky.api.remote.enums.Rating;
import com.github.robozonky.api.strategies.PortfolioOverview;
import com.github.robozonky.test.AbstractRoboZonkyTest;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.SoftAssertions.assertSoftly;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
class UtilTest extends AbstractRoboZonkyTest {
private static PortfolioOverview preparePortfolio(final BigDecimal ratingA, final BigDecimal ratingB,
final BigDecimal ratingC) {
final PortfolioOverview portfolioOverview = mockPortfolioOverview(10_000);
when(portfolioOverview.getShareOnInvestment(eq(Rating.A))).thenReturn(ratingA);
when(portfolioOverview.getShareOnInvestment(eq(Rating.B))).thenReturn(ratingB);
when(portfolioOverview.getShareOnInvestment(eq(Rating.C))).thenReturn(ratingC);
return portfolioOverview;
}
private static void assertOrder(final Stream<Rating> result, final Rating... ratingsOrderedDown) {
assertOrder(result.collect(Collectors.toList()), ratingsOrderedDown);
}
private static void assertOrder(final List<Rating> result, final Rating... ratingsOrderedDown) {
final Rating first = result.get(0);
final Rating last = result.get(ratingsOrderedDown.length - 1);
assertSoftly(softly -> {
softly.assertThat(first).isGreaterThan(last);
softly.assertThat(first).isEqualTo(ratingsOrderedDown[0]);
softly.assertThat(last).isEqualTo(ratingsOrderedDown[ratingsOrderedDown.length - 1]);
});
}
private static void assertOrder(final Stream<Rating> result, final Rating r) {
assertOrder(result.collect(Collectors.toList()), r);
}
private static void assertOrder(final List<Rating> result, final Rating r) {
assertThat(result.get(0)).isEqualTo(r);
}
@Test
void properRankingOfRatings() {
final int targetShareA = 1;
final int targetShareB = targetShareA * 5;
final int targetShareC = targetShareB * 5;
final ParsedStrategy parsedStrategy = new ParsedStrategy(new DefaultValues(DefaultPortfolio.EMPTY),
Arrays.asList(
new PortfolioShare(Rating.A, targetShareA,
targetShareA),
new PortfolioShare(Rating.B, targetShareB,
targetShareB),
new PortfolioShare(Rating.C, targetShareC,
targetShareC)),
Collections.emptyMap());
// all ratings have zero share; C > B > A
final Set<Rating> ratings = EnumSet.of(Rating.A, Rating.B, Rating.C);
PortfolioOverview portfolio = preparePortfolio(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO);
assertOrder(Util.rankRatingsByDemand(parsedStrategy, ratings, portfolio), Rating.C, Rating.B, Rating.A);
// A only; B, C overinvested
portfolio = preparePortfolio(BigDecimal.ZERO, BigDecimal.valueOf(10), BigDecimal.valueOf(30));
assertOrder(Util.rankRatingsByDemand(parsedStrategy, ratings, portfolio), Rating.A);
// B > C > A
portfolio = preparePortfolio(BigDecimal.valueOf(0.0099), BigDecimal.ZERO, BigDecimal.valueOf(0.249));
assertOrder(Util.rankRatingsByDemand(parsedStrategy, ratings, portfolio), Rating.B, Rating.C, Rating.A);
}
@Test
void acceptable() {
final ParsedStrategy s = mock(ParsedStrategy.class);
when(s.getMinimumBalance()).thenReturn(999l);
when(s.getMaximumInvestmentSizeInCzk()).thenReturn(1000l);
final PortfolioOverview p = mockPortfolioOverview(1_000);
when(p.getCzkInvested()).thenReturn(BigDecimal.valueOf(999));
assertThat(Util.isAcceptable(s, p)).isTrue();
}
@Test
void unacceptableDueToCeiling() {
final ParsedStrategy s = mock(ParsedStrategy.class);
when(s.getMinimumBalance()).thenReturn(0l);
when(s.getMaximumInvestmentSizeInCzk()).thenReturn(10_000l);
final PortfolioOverview p = mockPortfolioOverview(10_000);
when(p.getCzkInvested()).thenReturn(BigDecimal.valueOf(10_000));
assertThat(Util.isAcceptable(s, p)).isFalse();
}
@Test
void unacceptableDueToLowBalance() {
final ParsedStrategy s = mock(ParsedStrategy.class);
when(s.getMinimumBalance()).thenReturn(1000l);
final PortfolioOverview p = mockPortfolioOverview(1000);
assertThat(Util.isAcceptable(s, p)).isFalse();
}
}
|
3e1975b957b2949fc643d216564cfc32fa665fe6 | 3,856 | java | Java | src/main/java/tags/Argument.java | seanstappas/prometheus-ai | 2a28567467ceab09be6cedbb2f5d5271b76e4dfb | [
"MIT"
] | 2 | 2018-05-24T18:35:14.000Z | 2021-12-19T11:59:43.000Z | src/main/java/tags/Argument.java | seanstappas/prometheus-ai | 2a28567467ceab09be6cedbb2f5d5271b76e4dfb | [
"MIT"
] | null | null | null | src/main/java/tags/Argument.java | seanstappas/prometheus-ai | 2a28567467ceab09be6cedbb2f5d5271b76e4dfb | [
"MIT"
] | 6 | 2018-01-02T21:42:28.000Z | 2019-10-04T19:50:45.000Z | 27.347518 | 80 | 0.493257 | 10,810 | package tags;
/**
* Arguments are composed of a name and symbol.
*/
public abstract class Argument {
private String name;
private ArgType symbol;
/**
* Constructor for Argument
* <p>
* Attempts to split an argument string (e.g. height=10) on the mathematical
* symbol (in this case 10), assigns name to first token, if there are
* multiple tokens
*
* @param tokens argument string split on mathematical symbols
*/
Argument(final String[] tokens) {
if (tokens.length > 1) {
this.name = tokens[0];
} else {
this.name = "";
}
}
/**
* @return the name of the argument
*/
public final String getName() {
return name;
}
/**
* Sets the name of the argument.
*
* @param name the name
*/
final void setName(final String name) {
this.name = name;
}
/**
* @return the symbol of the argument
*/
public final ArgType getSymbol() {
return symbol;
}
/**
* Sets the symbol of the argument.
*
* @param symbol the symbol
*/
final void setSymbol(final ArgType symbol) {
this.symbol = symbol;
}
/**
* Compares two arguments, calling appropriate overloaded method.
*
* @param inputFact argument from rule-set
* @return true if two arguments match
*/
final boolean matches(final Argument inputFact) {
switch (this.symbol) {
case STRING:
if (inputFact.symbol.equals(ArgType.VAR)) {
return true;
}
if (inputFact.symbol.equals(ArgType.STRING)
|| inputFact.symbol.equals(ArgType.VAR)) {
return ((StringArgument) this)
.matches((StringArgument) inputFact);
}
return (inputFact.symbol.equals(ArgType.MATCHONE));
case EQ:
case GT:
case LT:
case INT:
if (inputFact.symbol.equals(ArgType.VAR)) {
return true;
}
if (inputFact.symbol.equals(ArgType.INT)
|| inputFact.symbol.equals(ArgType.EQ)
|| inputFact.symbol.equals(ArgType.LT)
|| inputFact.symbol.equals(ArgType.GT)) {
return ((NumericArgument) this)
.matches((NumericArgument) inputFact);
}
return (inputFact.symbol.equals(ArgType.MATCHONE));
case MATCHONE:
return !inputFact.symbol.equals(ArgType.VAR);
case VAR:
return false;
default:
return false;
}
}
/**
* Argument type.
*/
public enum ArgType {
/**
* Argument is made up of a string (e.g. tall).
*/
STRING,
/**
* Argument is a name equal to an integer (e.g. height = 10).
*/
EQ,
/**
* Argument is a name greater than an integer (e.g. height > 10).
*/
GT,
/**
* Argument is a name less that an integer (e.g. height < 10).
*/
LT,
/**
* Argument getMatchResult on a corresponding argument in a fact with
* same predicate name (see BASH '?').
*/
MATCHONE,
/**
* Argument is a variable integer (e.g. height = {@literal &x}).
*/
VAR,
/**
* Argument getMatchResult on > 0 arguments in a fact with same
* predicate name (see BASH '*').
*/
MATCHALL,
/**
* Argument is made up of an integer value (e.g. 10).
*/
INT
}
}
|
3e19764e6cae97450eeb32ba5b7ec4d299626c5a | 4,843 | java | Java | src/main/java/com/gisquest/webgis/modules/sys/entity/Analy.java | guotao0628/giser | caeeca7a61fa9b8a112b3246e0838bcf19ecd3c1 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/gisquest/webgis/modules/sys/entity/Analy.java | guotao0628/giser | caeeca7a61fa9b8a112b3246e0838bcf19ecd3c1 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/gisquest/webgis/modules/sys/entity/Analy.java | guotao0628/giser | caeeca7a61fa9b8a112b3246e0838bcf19ecd3c1 | [
"Apache-2.0"
] | null | null | null | 19.607287 | 56 | 0.572992 | 10,811 | /**
*
*/
package com.gisquest.webgis.modules.sys.entity;
/**
* 作用:封装analyManager.java中的参数
*
* @author yedy
*
*/
public class Analy {
/** 操作标签 */
private String mTag;
/** ID */
private String analyId;
/** 标签 */
private String analyLable;
/** 类型 */
private String analyType;
/** 报表地址 */
private String analyReport;
/** 年份 */
private String analyYear;
/** 参数 */
private String analyParam;
/** 标签 */
private String analyParent;
/** 引用 */
private String analyRel;
/** 加载状态 */
private String analyChecked;
/** 显示顺序 */
private String showIndex;
/** tocID */
private String tocIds;
/** tocShowIndexs */
private String tocShowIndexs;
/** 是否自动获取行政区 */
private Boolean isAutoGetXZQ;
/** 行政区代码 */
private String xzqCode;
/** 是否使用管制区 */
private Boolean isUseGZX;
/** 是否使用用途区 */
private Boolean isUseYTQ;
/** 是否使用规划分析 */
private Boolean isUseGHYT;
/** 是否使用规划基期 */
private Boolean isUseGHJQ;
public String getmTag() {
return mTag;
}
public void setmTag(String mTag) {
this.mTag = mTag;
}
public String getAnalyId() {
return analyId;
}
public void setAnalyId(String analyId) {
this.analyId = analyId;
}
public String getAnalyLable() {
return analyLable;
}
public void setAnalyLable(String analyLable) {
this.analyLable = analyLable;
}
public String getAnalyType() {
return analyType;
}
public void setAnalyType(String analyType) {
this.analyType = analyType;
}
public String getAnalyReport() {
return analyReport;
}
public void setAnalyReport(String analyReport) {
this.analyReport = analyReport;
}
public String getAnalyYear() {
return analyYear;
}
public void setAnalyYear(String analyYear) {
this.analyYear = analyYear;
}
public String getAnalyParam() {
return analyParam;
}
public void setAnalyParam(String analyParam) {
this.analyParam = analyParam;
}
public String getAnalyParent() {
return analyParent;
}
public void setAnalyParent(String analyParent) {
this.analyParent = analyParent;
}
public String getAnalyRel() {
return analyRel;
}
public void setAnalyRel(String analyRel) {
this.analyRel = analyRel;
}
public String getAnalyChecked() {
return analyChecked;
}
public void setAnalyChecked(String analyChecked) {
this.analyChecked = analyChecked;
}
public String getShowIndex() {
return showIndex;
}
public void setShowIndex(String showIndex) {
this.showIndex = showIndex;
}
public String getTocIds() {
return tocIds;
}
public void setTocIds(String tocIds) {
this.tocIds = tocIds;
}
public String getTocShowIndexs() {
return tocShowIndexs;
}
public void setTocShowIndexs(String tocShowIndexs) {
this.tocShowIndexs = tocShowIndexs;
}
/**
* @return the isAutoGetXZQ
*/
public Boolean getIsAutoGetXZQ() {
return isAutoGetXZQ;
}
/**
* @param isAutoGetXZQ
* the isAutoGetXZQ to set
*/
public void setIsAutoGetXZQ(Boolean isAutoGetXZQ) {
this.isAutoGetXZQ = isAutoGetXZQ;
}
/**
* @return the xzqCode
*/
public String getXzqCode() {
return xzqCode;
}
/**
* @param xzqCode
* the xzqCode to set
*/
public void setXzqCode(String xzqCode) {
this.xzqCode = xzqCode;
}
/**
* @return the isUseGZX
*/
public Boolean getIsUseGZX() {
return isUseGZX;
}
/**
* @param isUseGZX
* the isUseGZX to set
*/
public void setIsUseGZX(Boolean isUseGZX) {
this.isUseGZX = isUseGZX;
}
/**
* @return the isUseYTQ
*/
public Boolean getIsUseYTQ() {
return isUseYTQ;
}
/**
* @param isUseYTQ
* the isUseYTQ to set
*/
public void setIsUseYTQ(Boolean isUseYTQ) {
this.isUseYTQ = isUseYTQ;
}
/**
* @return the isUseGHYT
*/
public Boolean getIsUseGHYT() {
return isUseGHYT;
}
/**
* @param isUseGHYT
* the isUseGHYT to set
*/
public void setIsUseGHYT(Boolean isUseGHYT) {
this.isUseGHYT = isUseGHYT;
}
/**
* @return the isUseGHJQ
*/
public Boolean getIsUseGHJQ() {
return isUseGHJQ;
}
/**
* @param isUseGHJQ
* the isUseGHJQ to set
*/
public void setIsUseGHJQ(Boolean isUseGHJQ) {
this.isUseGHJQ = isUseGHJQ;
}
}
|
3e19773dc741122411e21544708a8eafa5a5ee6a | 6,378 | java | Java | mystique/src/main/java/xyz/designabc/mystique/util/transition/MorphTransform.java | vipulyaara/Mystique | 3d3751d387eedb4dfe6654df91e5965dae7cec58 | [
"MIT"
] | 1 | 2019-05-29T08:05:12.000Z | 2019-05-29T08:05:12.000Z | mystique/src/main/java/xyz/designabc/mystique/util/transition/MorphTransform.java | vipulyaara/Mystique | 3d3751d387eedb4dfe6654df91e5965dae7cec58 | [
"MIT"
] | null | null | null | mystique/src/main/java/xyz/designabc/mystique/util/transition/MorphTransform.java | vipulyaara/Mystique | 3d3751d387eedb4dfe6654df91e5965dae7cec58 | [
"MIT"
] | null | null | null | 40.884615 | 100 | 0.669175 | 10,812 | /*
* Copyright 2015 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 xyz.designabc.mystique.util.transition;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.transition.ChangeBounds;
import android.transition.TransitionValues;
import android.view.View;
import android.view.ViewGroup;
/**
* An extension to {@link ChangeBounds} that also morphs the views background (color & corner
* radius).
*/
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public class MorphTransform extends ChangeBounds {
private static final String EXTRA_SHARED_ELEMENT_START_COLOR =
"EXTRA_SHARED_ELEMENT_START_COLOR";
private static final String EXTRA_SHARED_ELEMENT_START_CORNER_RADIUS =
"EXTRA_SHARED_ELEMENT_START_CORNER_RADIUS";
private static final long DEFAULT_DURATION = 300L;
private final int startColor;
private final int endColor;
private final int startCornerRadius;
private final int endCornerRadius;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public MorphTransform(@ColorInt int startColor, @ColorInt int endColor,
int startCornerRadius, int endCornerRadius) {
this.startColor = startColor;
this.endColor = endColor;
this.startCornerRadius = startCornerRadius;
this.endCornerRadius = endCornerRadius;
setDuration(DEFAULT_DURATION);
setPathMotion(new GravityArcMotion());
}
/**
* Configure {@code intent} with the extras needed to initialize this transition.
*/
public static void addExtras(@NonNull Intent intent,
@ColorInt int startColor,
int startCornerRadius) {
intent.putExtra(EXTRA_SHARED_ELEMENT_START_COLOR, startColor);
intent.putExtra(EXTRA_SHARED_ELEMENT_START_CORNER_RADIUS, startCornerRadius);
}
/**
* Configure {@link MorphTransform}s & set as {@code activity}'s shared element enter and return
* transitions.
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public static void setup(@NonNull Activity activity,
@Nullable View target,
@ColorInt int endColor,
int endCornerRadius) {
final Intent intent = activity.getIntent();
if (intent == null
|| !intent.hasExtra(EXTRA_SHARED_ELEMENT_START_COLOR)
|| !intent.hasExtra(EXTRA_SHARED_ELEMENT_START_CORNER_RADIUS)) return;
final int startColor = activity.getIntent().
getIntExtra(EXTRA_SHARED_ELEMENT_START_COLOR, Color.TRANSPARENT);
final int startCornerRadius =
intent.getIntExtra(EXTRA_SHARED_ELEMENT_START_CORNER_RADIUS, 0);
final MorphTransform sharedEnter =
new MorphTransform(startColor, endColor, startCornerRadius, endCornerRadius);
// Reverse the start/end params for the return transition
final MorphTransform sharedReturn =
new MorphTransform(endColor, startColor, endCornerRadius, startCornerRadius);
if (target != null) {
sharedEnter.addTarget(target);
sharedReturn.addTarget(target);
}
activity.getWindow().setSharedElementEnterTransition(sharedEnter);
activity.getWindow().setSharedElementReturnTransition(sharedReturn);
}
@Nullable
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public Animator createAnimator(@NonNull final ViewGroup sceneRoot,
final TransitionValues startValues,
@NonNull final TransitionValues endValues) {
final Animator changeBounds = super.createAnimator(sceneRoot, startValues, endValues);
if (changeBounds == null) return null;
TimeInterpolator interpolator = getInterpolator();
if (interpolator == null) {
interpolator = AnimUtils.getFastOutSlowInInterpolator(sceneRoot.getContext());
}
final MorphDrawable background = new MorphDrawable(startColor, startCornerRadius);
endValues.view.setBackground(background);
final Animator color = ObjectAnimator.ofArgb(background, MorphDrawable.COLOR, endColor);
final Animator corners =
ObjectAnimator.ofFloat(background, MorphDrawable.CORNER_RADIUS, endCornerRadius);
// ease in the dialog's child views (fade in & staggered slide up)
if (endValues.view instanceof ViewGroup) {
final ViewGroup vg = (ViewGroup) endValues.view;
final long duration = getDuration() / 2;
float offset = vg.getHeight() / 3;
for (int i = 0; i < vg.getChildCount(); i++) {
View v = vg.getChildAt(i);
v.setTranslationY(offset);
v.setAlpha(0f);
v.animate()
.alpha(1f)
.translationY(0f)
.setDuration(duration)
.setStartDelay(duration)
.setInterpolator(interpolator);
offset *= 1.8f;
}
}
final AnimatorSet transition = new AnimatorSet();
transition.playTogether(changeBounds, corners, color);
transition.setDuration(getDuration());
transition.setInterpolator(interpolator);
return transition;
}
}
|
3e197902e18077cd1d4394cf50638a8ab99a1e01 | 5,431 | java | Java | src/org/lockss/exporter/counter/BaseCounterReportsTitle.java | rondinelisaad/lockss-daemon | 563a3bcd106908b0967f510ee4cf88525a48651a | [
"BSD-3-Clause"
] | 51 | 2015-09-02T22:50:09.000Z | 2022-03-14T23:53:58.000Z | src/org/lockss/exporter/counter/BaseCounterReportsTitle.java | rondinelisaad/lockss-daemon | 563a3bcd106908b0967f510ee4cf88525a48651a | [
"BSD-3-Clause"
] | 5 | 2016-03-22T06:10:02.000Z | 2020-09-24T17:18:47.000Z | src/main/java/org/lockss/exporter/counter/BaseCounterReportsTitle.java | lockss/lockss-core | defe3cb2319eb3dd00f89f2d85e7b9a322dc5632 | [
"BSD-3-Clause"
] | 13 | 2016-01-28T16:40:22.000Z | 2022-03-03T20:04:22.000Z | 27.291457 | 80 | 0.685877 | 10,813 | /*
* $Id$
*/
/*
Copyright (c) 2012-2014 Board of Trustees of Leland Stanford Jr. University,
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
STANFORD UNIVERSITY 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.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.exporter.counter;
import java.util.Collection;
/**
* A title used in COUNTER reports.
*
* @version 1.0
*
*/
public abstract class BaseCounterReportsTitle implements CounterReportsTitle {
// The DOI of the title.
private final String doi;
// The name of the title.
private final String name;
// The name of the publisher of the title.
private final String publisherName;
// The name of the publishing platform.
private final String publishingPlatform;
// The proprietary identifiers.
private final Collection<String> proprietaryIds;
// The ISBN of a book.
protected String isbn = null;
// The ISSN of a book.
protected String issn = null;
// The online ISSN of a journal.
protected String onlineIssn = null;
// The print ISSN of a journal.
protected String printIssn = null;
/**
* Constructor.
*
* @param name
* A String with the name of the title.
* @param publisherName
* A String with the name of the publisher of the title.
* @param publishingPlatform
* A String with the name of the publishing platform.
* @param doi
* A String with the DOI of the title.
* @param proprietaryIds
* A Collection<String> with the proprietary identifiers.
* @throws IllegalArgumentException
* if the name of the title is empty.
*/
protected BaseCounterReportsTitle(String name, String publisherName,
String publishingPlatform, String doi, Collection<String> proprietaryIds)
throws IllegalArgumentException {
if (name == null || name.trim().length() == 0) {
throw new IllegalArgumentException("Name cannot be empty.");
}
this.name = name;
this.publisherName = publisherName;
this.publishingPlatform = publishingPlatform;
this.doi = doi;
this.proprietaryIds = proprietaryIds;
}
/**
* Provides the DOI of the title.
*
* @return a String with the DOI of the title.
*/
@Override
public String getDoi() {
return doi;
}
/**
* Provides the ISBN of the title if it is a book.
*
* @return a String with the ISBN of the title.
*/
@Override
public String getIsbn() {
return isbn;
}
/**
* Provides the ISSN of the title if it is a book.
*
* @return a String with the ISSN of the title.
*/
@Override
public String getIssn() {
return issn;
}
/**
* Provides the name of the title.
*
* @return a String with the name of the title.
*/
@Override
public String getName() {
return name;
}
/**
* Provides the online ISSN of the title if it is a journal.
*
* @return a String with the online ISSN of the title.
*/
@Override
public String getOnlineIssn() {
return onlineIssn;
}
/**
* Provides the print ISSN of the title if it is a journal.
*
* @return a String with the print ISSN of the title.
*/
@Override
public String getPrintIssn() {
return printIssn;
}
/**
* Provides the proprietary identifiers of the title.
*
* @return a Collection<String> with the proprietary identifiers of the title.
*/
@Override
public Collection<String> getProprietaryIds() {
return proprietaryIds;
}
/**
* Provides the publisher name of the title.
*
* @return a String with the publisher name of the title.
*/
@Override
public String getPublisherName() {
return publisherName;
}
/**
* Provides the publishing platform name of the title.
*
* @return a String with the publishing platform name of the title.
*/
@Override
public String getPublishingPlatform() {
return publishingPlatform;
}
@Override
public String toString() {
return "BaseCounterReportsTitle [doi=" + doi + ", name=" + name
+ ", publisherName=" + publisherName + ", publishingPlatform="
+ publishingPlatform + ", proprietaryIds=" + proprietaryIds + ", isbn="
+ isbn + ", issn=" + issn + ", onlineIssn=" + onlineIssn
+ ", printIssn=" + printIssn + "]";
}
}
|
3e1979e0f950766f079b8fe4593dd36b344fb049 | 761 | java | Java | designpattern/src/main/java/adapter/MediaAdapter.java | malinghan/java-learning | 80619909260a8bfebf1073d0c9371e56e8edd5ed | [
"MIT"
] | null | null | null | designpattern/src/main/java/adapter/MediaAdapter.java | malinghan/java-learning | 80619909260a8bfebf1073d0c9371e56e8edd5ed | [
"MIT"
] | null | null | null | designpattern/src/main/java/adapter/MediaAdapter.java | malinghan/java-learning | 80619909260a8bfebf1073d0c9371e56e8edd5ed | [
"MIT"
] | null | null | null | 29.269231 | 60 | 0.647832 | 10,814 | package adapter;
/**
* Created by mlh on 2017/12/24.
*/
public class MediaAdapter implements MediaPlayer {//新的接口
private AdvancedMediaPlayer advancedMusicPlayer;//私有的旧的类
//新的构造函数
public MediaAdapter(String audioType){
if(audioType.equalsIgnoreCase("vlc")){
advancedMusicPlayer = new VlcPlayer();//旧的对象实例
}else if(audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer=new Mp4Player();
}
}
//新的方法
@Override
public void play(String audioType, String fileName) {
if(audioType.equalsIgnoreCase("vlc")){
advancedMusicPlayer.playVlc(fileName);
}else if(audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer.playMp4(fileName);
}
}
}
|
3e197a4e7767b733e7c3adc045672e02b5b38f0f | 103 | java | Java | lecture_1/lec_1/src/lec1/Subtract.java | GopiR-Canton/UMB | 1195f68ee53dcbca5241f58332b2425582801833 | [
"MIT"
] | null | null | null | lecture_1/lec_1/src/lec1/Subtract.java | GopiR-Canton/UMB | 1195f68ee53dcbca5241f58332b2425582801833 | [
"MIT"
] | null | null | null | lecture_1/lec_1/src/lec1/Subtract.java | GopiR-Canton/UMB | 1195f68ee53dcbca5241f58332b2425582801833 | [
"MIT"
] | null | null | null | 12.875 | 42 | 0.669903 | 10,815 | package lec1;
public class Subtract{
public static int subtract(int i, int j){
return i - j;
}
} |
3e197a657010ded661e4c902f7eda0eced1b7c8f | 979 | java | Java | Computer Science/Programming Languages/Java/Project Euler/Problem74.java | itteerde/OpenCourseWare | 1bc11b396c80595675a2f3d08a500ad87e47553d | [
"Unlicense"
] | null | null | null | Computer Science/Programming Languages/Java/Project Euler/Problem74.java | itteerde/OpenCourseWare | 1bc11b396c80595675a2f3d08a500ad87e47553d | [
"Unlicense"
] | null | null | null | Computer Science/Programming Languages/Java/Project Euler/Problem74.java | itteerde/OpenCourseWare | 1bc11b396c80595675a2f3d08a500ad87e47553d | [
"Unlicense"
] | null | null | null | 15.790323 | 49 | 0.570991 | 10,816 | package de.itter.euler;
import java.util.Vector;
public class Problem74 {
public static void main(String[] args) {
int count = 0;
for(int i = 1; i<1000000;i++){
Vector<Integer> chain = new Vector<Integer>();
chain.add(new Integer(i));
for(;;){
int next = facSum(chain.lastElement());
if(chain.contains(next)){
if(chain.size()==60){
System.out.println(chain);
count++;
}
break;
}
chain.add(next);
}
}
System.out.println(count);
}
public static int facSum(int i){
Vector<Integer> digits = digits(i);
int sum = 0;
for(int j: digits){
sum += fac(j);
}
return sum;
}
public static Vector<Integer> digits(int i){
Vector<Integer> digits = new Vector<Integer>();
for(;;i/=10){
int digit = i % 10;
digits.add(new Integer(digit));
if(i<10){
return digits;
}
}
}
public static int fac(int n){
int fac = 1;
for(;n>1;n--){
fac*=n;
}
return fac;
}
}
|
3e197aa6c76f0dfc9ea14ab7246fc7150f1c51f3 | 7,916 | java | Java | src/main/java/com/airportflightplanner/adapters/impl/SteerPointsConvertAdapterImpl.java | Gsyltc/airportflightplanner | f159f5074535e2cb4fc70cc5bf1660d5c5c7ea30 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/airportflightplanner/adapters/impl/SteerPointsConvertAdapterImpl.java | Gsyltc/airportflightplanner | f159f5074535e2cb4fc70cc5bf1660d5c5c7ea30 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/airportflightplanner/adapters/impl/SteerPointsConvertAdapterImpl.java | Gsyltc/airportflightplanner | f159f5074535e2cb4fc70cc5bf1660d5c5c7ea30 | [
"Apache-2.0"
] | null | null | null | 33.260504 | 122 | 0.637317 | 10,817 | /*
* @(#)SteerPointsConvertAdapterImpl.java
*
* Goubaud Sylvain
* Created : 2016
* Modified : 16 août 2016.
*
* This code may be freely used and modified on any personal or professional
* project. It comes with no warranty.
*
*/
package com.airportflightplanner.adapters.impl;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.measure.unit.NonSI;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jscience.geography.coordinates.Altitude;
import org.jscience.geography.coordinates.LatLong;
import com.airportflightplanner.adapters.api.SteerPointsConvertAdapter;
import com.airportflightplanner.common.domaintypes.BankingAngle;
import com.airportflightplanner.common.domaintypes.Heading;
import com.airportflightplanner.common.domaintypes.Speed;
import com.airportflightplanner.common.types.AltitudeType;
import com.airportflightplanner.common.types.FormationType;
import com.airportflightplanner.models.steerpoints.SteerPointModel;
import com.airportflightplanner.models.steerpoints.api.bean.SteerPointReader;
import fr.gsyltc.framework.adapters.AbstractAdapterImpl;
/**
* @author Goubaud Sylvain
*
*/
public class SteerPointsConvertAdapterImpl extends AbstractAdapterImpl implements SteerPointsConvertAdapter {
/** The logger of this class. */
private static final Logger LOGGER = LogManager.getLogger(SteerPointsConvertAdapterImpl.class);
/**
*
*/
private static final long serialVersionUID = 8439855875388796503L;
/** */
private static final int MIN_LENGTH = 6;
/** */
private static final int LATITUDE_KEY = 0;
/** */
private static final int LONGITUDE_KEY = 1;
/** */
private static final int ALTITUDE_KEY = 2;
/** */
private static final int ALTTYPE_KEY = 3;
/** */
private static final int SPEED_KEY = 4;
/** */
private static final int MAX_BANKING_ANGLE_KEY = 5;
/** */
private static final int HEADING_KEY = 6;
/** */
private static final int FORMATION_KEY = 8;
/** */
private static final int WAYPOINT_NAME_KEY = 9;
/** */
private static final Object SPACE = " ";
/**
*
* {@inheritDoc}.
*/
@Override
public void init() {
// TODO Auto-generated method stub
}
/**
*
* {@inheritDoc}.
*/
@Override
public List<SteerPointModel> convertSteerPoints(final List<String> value) {
final List<SteerPointModel> result = new ArrayList<SteerPointModel>();
for (final String datas : value) {
final SteerPointModel steerPoint = convertSteerPoint(datas);
if (null != steerPoint) {
result.add(steerPoint);
}
}
return result;
}
/**
*
* {@inheritDoc}.
*/
@Override
public SteerPointModel convertSteerPoint(final String datas) {
SteerPointModel result = null;
if (validateSteerpoints(datas)) {
result = (SteerPointModel) getSteerPoint(datas);
} else {
if (LOGGER.isErrorEnabled()) {
LOGGER.error("Steer point not valid : " + datas);
}
}
return result;
}
/**
*
* {@inheritDoc}.
*/
@Override
public String convertSteerPointToString(final SteerPointReader steerPoint) {
final StringBuilder result = new StringBuilder();
final DecimalFormat speedFormatter = new DecimalFormat("###");
final String speed = speedFormatter.format(steerPoint.getSpeed().getValue(NonSI.KNOT));
result.append(steerPoint.getLatLong().latitudeValue(NonSI.DEGREE_ANGLE)).append(SPACE) //
.append(steerPoint.getLatLong().longitudeValue(NonSI.DEGREE_ANGLE)).append(SPACE) //
.append(steerPoint.getAltitude().longValue(NonSI.FOOT)).append(SPACE) //
.append(steerPoint.getAltType().name()).append(SPACE) //
.append(speed).append(SPACE) //
.append(steerPoint.getMaxBankingAngle().intValue(NonSI.DEGREE_ANGLE)).append(SPACE) //
.append(steerPoint.getHeading().getSIValue()).append(SPACE).append("-1").append(SPACE) //
.append(steerPoint.getFormation().name()).append(SPACE) //
.append(steerPoint.getName());
return result.toString();
}
/**
*
* @param steerpointsString
* steer point string formatted.
* @return Steer point.
*/
public SteerPointReader getSteerPoint(final String steerpointsString) {
final SteerPointModel steerPoint = new SteerPointModel();
final Pattern pattern = Pattern.compile(" +");
// séparation en sous-chaînes
final String[] items = pattern.split(steerpointsString, 10);
steerPoint.setLatLong(LatLong.valueOf(Double.valueOf(items[LATITUDE_KEY]), //
Double.valueOf(items[LONGITUDE_KEY]), NonSI.DEGREE_ANGLE));
steerPoint.setAltitude(Altitude.valueOf(Double.valueOf(items[ALTITUDE_KEY]), NonSI.FOOT));
steerPoint.setAltType(AltitudeType.valueOf(items[ALTTYPE_KEY]));
steerPoint.setSpeed(new Speed(Double.valueOf(items[SPEED_KEY]), NonSI.KNOT));
steerPoint.setMaxBankingAngle(new BankingAngle(Double.valueOf(items[MAX_BANKING_ANGLE_KEY]), NonSI.DEGREE_ANGLE));
steerPoint.setHeading(new Heading(Double.valueOf(items[HEADING_KEY]), NonSI.DEGREE_ANGLE));
steerPoint.setFormation(FormationType.valueFrom(items[FORMATION_KEY]));
steerPoint.setName(items[WAYPOINT_NAME_KEY]);
return steerPoint;
}
/**
*
* @param steerPointDatas
* @return
*/
public boolean validateSteerpoints(final String steerPointDatas) {
boolean result = true;
final String[] datas = steerPointDatas.split(" +");
// Check number of param
if (datas.length >= MIN_LENGTH) {
result &= isPositionValid(datas[LATITUDE_KEY]);
result &= isPositionValid(datas[LONGITUDE_KEY]);
result &= isAltitudeValid(datas[ALTITUDE_KEY]);
result &= AltitudeType.isValid(datas[ALTTYPE_KEY]);
result &= isSpeedValid(datas[SPEED_KEY]);
result &= isMaxBankAngleValid(datas[MAX_BANKING_ANGLE_KEY]);
result &= FormationType.isValid(datas[FORMATION_KEY]);
result &= null != datas[WAYPOINT_NAME_KEY];
}
if (!result && LOGGER.isErrorEnabled()) {
LOGGER.error("steerpoint datas not valid : " + steerPointDatas);
}
return result;
}
/**
*
* @param value
* @return
*/
private boolean isPositionValid(final String value) {
final Pattern pattern = Pattern.compile("^[+-]?\\d{1,3}+\\.?\\d{0,10}$");
final Matcher matcher = pattern.matcher(value);
return matcher.matches();
}
/**
*
* @param value
* @return
*/
private boolean isAltitudeValid(final String value) {
final Pattern pattern = Pattern.compile("^\\d{1,5}$");
final Matcher matcher = pattern.matcher(value);
return matcher.matches();
}
/**
*
* @param value
* @return
*/
private boolean isSpeedValid(final String value) {
final Pattern pattern = Pattern.compile("^\\d{1,3}$");
final Matcher matcher = pattern.matcher(value);
return matcher.matches();
}
/**
*
* @param value
* @return
*/
private boolean isMaxBankAngleValid(final String value) {
final Pattern pattern = Pattern.compile("^\\d{1,2}$");
final Matcher matcher = pattern.matcher(value);
return matcher.matches();
}
}
|
3e197ab1f2d25b67b9ec3fbb05d743f4549b0134 | 372 | java | Java | zeromall-order/src/main/java/com/hpr/zeromall/order/dao/PaymentInfoDao.java | zero-unicorn/zeroMall | 036ed16f37735f8d313f8d94119f615a3f2b00ac | [
"Apache-2.0"
] | null | null | null | zeromall-order/src/main/java/com/hpr/zeromall/order/dao/PaymentInfoDao.java | zero-unicorn/zeroMall | 036ed16f37735f8d313f8d94119f615a3f2b00ac | [
"Apache-2.0"
] | null | null | null | zeromall-order/src/main/java/com/hpr/zeromall/order/dao/PaymentInfoDao.java | zero-unicorn/zeroMall | 036ed16f37735f8d313f8d94119f615a3f2b00ac | [
"Apache-2.0"
] | null | null | null | 20.611111 | 71 | 0.762803 | 10,818 | package com.hpr.zeromall.order.dao;
import com.hpr.zeromall.order.entity.PaymentInfoEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 支付信息表
*
* @author hpr
* @email lyhxr@example.com
* @date 2020-06-10 18:28:15
*/
@Mapper
public interface PaymentInfoDao extends BaseMapper<PaymentInfoEntity> {
}
|
3e197b5fe858283bb3c6a3b475abfd8735ce593a | 1,600 | java | Java | jprelude-core/src/main/java/jprelude/core/util/function/CheckedPredicate.java | mcjazzyfunky/j-prelude | 938351408d3b94bb3270d1b4e5853a401471c90b | [
"BSD-3-Clause"
] | null | null | null | jprelude-core/src/main/java/jprelude/core/util/function/CheckedPredicate.java | mcjazzyfunky/j-prelude | 938351408d3b94bb3270d1b4e5853a401471c90b | [
"BSD-3-Clause"
] | null | null | null | jprelude-core/src/main/java/jprelude/core/util/function/CheckedPredicate.java | mcjazzyfunky/j-prelude | 938351408d3b94bb3270d1b4e5853a401471c90b | [
"BSD-3-Clause"
] | null | null | null | 27.586207 | 94 | 0.575625 | 10,819 |
package jprelude.core.util.function;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Objects;
import java.util.function.Predicate;
@FunctionalInterface
public interface CheckedPredicate<T, E extends Exception> {
boolean test(T t) throws E;
default CheckedPredicate<T, E> and(final CheckedPredicate<? super T, ? extends E> other) {
Objects.requireNonNull(other);
return t -> this.test(t) && other.test(t);
}
default CheckedPredicate<T, E> negate() {
return t -> !this.test(t);
}
default CheckedPredicate<T, E> or(CheckedPredicate<? super T, ? extends E> other) {
Objects.requireNonNull(other);
return t -> this.test(t) || other.test(t);
}
/*
static <T> CheckedPredicate<T, E> isEqual(final Object targetRef) {
Objects.nonNull(targetRef);
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
*/
default Predicate<T> unchecked() {
return value -> {
boolean ret;
try {
ret = CheckedPredicate.this.test(value);
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new RuntimeException(e);
}
return ret;
};
}
static <T> Predicate<T> unchecked(final CheckedPredicate<T, ?> predicate) {
Objects.requireNonNull(predicate);
return predicate.unchecked();
}
}
|
3e197b89d4060640bb0f6ac12d6d4d99fdacc418 | 2,954 | java | Java | core/cas-server-core-authentication-api/src/main/java/org/apereo/cas/authentication/DefaultAuthenticationSystemSupport.java | PavlikPolivka/cas | 091f8b386c2ff79e66131afba5f12f8552941246 | [
"Apache-2.0"
] | 2 | 2019-05-23T15:45:42.000Z | 2021-07-01T01:49:54.000Z | core/cas-server-core-authentication-api/src/main/java/org/apereo/cas/authentication/DefaultAuthenticationSystemSupport.java | PavlikPolivka/cas | 091f8b386c2ff79e66131afba5f12f8552941246 | [
"Apache-2.0"
] | 1 | 2020-07-23T06:09:26.000Z | 2020-07-23T06:09:26.000Z | core/cas-server-core-authentication-api/src/main/java/org/apereo/cas/authentication/DefaultAuthenticationSystemSupport.java | PavlikPolivka/cas | 091f8b386c2ff79e66131afba5f12f8552941246 | [
"Apache-2.0"
] | 1 | 2020-10-14T04:44:19.000Z | 2020-10-14T04:44:19.000Z | 42.2 | 149 | 0.723426 | 10,820 | package org.apereo.cas.authentication;
import org.apereo.cas.authentication.principal.Service;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.val;
import java.util.Objects;
import java.util.stream.Stream;
/**
* This is {@link DefaultAuthenticationSystemSupport}.
*
* @author Misagh Moayyed
* @author Dmitriy Kopylenko
* @since 4.2.0
*/
@Getter
@RequiredArgsConstructor
public class DefaultAuthenticationSystemSupport implements AuthenticationSystemSupport {
private final AuthenticationTransactionManager authenticationTransactionManager;
private final PrincipalElectionStrategy principalElectionStrategy;
@Override
public AuthenticationResultBuilder handleInitialAuthenticationTransaction(final Service service,
final Credential... credential) throws AuthenticationException {
val builder = new DefaultAuthenticationResultBuilder();
if (credential != null) {
Stream.of(credential).filter(Objects::nonNull).forEach(builder::collect);
}
return this.handleAuthenticationTransaction(service, builder, credential);
}
@Override
public AuthenticationResultBuilder establishAuthenticationContextFromInitial(final Authentication authentication, final Credential credentials) {
return establishAuthenticationContextFromInitial(authentication).collect(credentials);
}
@Override
public AuthenticationResultBuilder establishAuthenticationContextFromInitial(final Authentication authentication) {
return new DefaultAuthenticationResultBuilder().collect(authentication);
}
@Override
public AuthenticationResultBuilder handleAuthenticationTransaction(final Service service,
final AuthenticationResultBuilder authenticationResultBuilder,
final Credential... credential) throws AuthenticationException {
val transaction = DefaultAuthenticationTransaction.of(service, credential);
this.authenticationTransactionManager.handle(transaction, authenticationResultBuilder);
return authenticationResultBuilder;
}
@Override
public AuthenticationResult finalizeAllAuthenticationTransactions(final AuthenticationResultBuilder authenticationResultBuilder,
final Service service) {
return authenticationResultBuilder.build(principalElectionStrategy, service);
}
@Override
public AuthenticationResult handleAndFinalizeSingleAuthenticationTransaction(final Service service, final Credential... credential)
throws AuthenticationException {
return finalizeAllAuthenticationTransactions(handleInitialAuthenticationTransaction(service, credential), service);
}
}
|
3e197bca9ee9f863b3efd984f6a47fe695678872 | 1,077 | java | Java | hradmin-system/src/main/java/com/wensenma/modules/system/service/mapstruct/DictSmallMapper.java | mawensen/HRAdmin-Backend | 162d3dceb5d8d7d996765218a34851e20906f8a8 | [
"Apache-2.0"
] | 12 | 2021-02-11T06:05:00.000Z | 2021-02-14T20:29:24.000Z | hradmin-system/src/main/java/com/wensenma/modules/system/service/mapstruct/DictSmallMapper.java | WensenMa-Git/HRAdmin-Backend | 162d3dceb5d8d7d996765218a34851e20906f8a8 | [
"Apache-2.0"
] | null | null | null | hradmin-system/src/main/java/com/wensenma/modules/system/service/mapstruct/DictSmallMapper.java | WensenMa-Git/HRAdmin-Backend | 162d3dceb5d8d7d996765218a34851e20906f8a8 | [
"Apache-2.0"
] | 3 | 2021-02-11T12:19:15.000Z | 2021-02-13T19:26:13.000Z | 34.741935 | 80 | 0.765088 | 10,821 | /*
* Copyright 2019-2020 Wensen Ma
*
* 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.wensenma.modules.system.service.mapstruct;
import com.wensenma.base.BaseMapper;
import com.wensenma.modules.system.domain.Dict;
import com.wensenma.modules.system.service.dto.DictSmallDto;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author Wensen Ma
* @date 2019-04-10
*/
@Mapper(componentModel = "spring",unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface DictSmallMapper extends BaseMapper<DictSmallDto, Dict> {
} |
3e197c2c21c8887e5102a5ffd5b2e7cbbb46117a | 2,692 | java | Java | src/operativos/Selector.java | tocloff/ALotOfCupCakes | d48e01ab01730c5eeecc19de48d87d9e903842ad | [
"MIT"
] | null | null | null | src/operativos/Selector.java | tocloff/ALotOfCupCakes | d48e01ab01730c5eeecc19de48d87d9e903842ad | [
"MIT"
] | null | null | null | src/operativos/Selector.java | tocloff/ALotOfCupCakes | d48e01ab01730c5eeecc19de48d87d9e903842ad | [
"MIT"
] | null | null | null | 18.438356 | 119 | 0.682392 | 10,822 | /**
* MA-ITG ALotOfCupcakes Web Application
* Author: Thomas Enrique Mejia Anaya
*/
package operativos;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.org.apache.regexp.internal.RE;
/**
* Servlet implementation class Selector
*/
public class Selector extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String tmp = request.getParameter("accion");
String accion = (tmp != null) ? tmp : "index";
response.setContentType("text/html");
String destino=null;
RequestDispatcher despachador;
switch (accion) {
case "index":
case "productos":
destino = "CargadorProductos";
break;
case "ficha":
destino="CargadorProducto";
break;
case "login":
destino="Login";
break;
case "salir":
destino="CerrarSesion";
break;
case "config":
destino="Configuracion";
break;
case "registrar":
destino="Registrar";
break;
case "carrito":
destino="Carrito";
break;
case "Pagar":
destino="Pagar";
break;
case "cobrar":
destino="Cobrador";
break;
case "admin":
destino="PanelAdmin";
break;
case "gestorProductos":
destino="GestorProductos";
break;
case "gestorFotos":
destino="GestorFotos";
break;
}
if(destino!=null){
despachador = request.getRequestDispatcher(destino);
despachador.include(request, response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String tmp = request.getParameter("accion");
String accion = (tmp != null) ? tmp : "index";
response.setContentType("text/html");
String destino=null;
RequestDispatcher despachador;
//por aqui van las llamadas protegidas
switch (accion) {
case "login":
destino="Login";
break;
case "config":
destino="Configuracion";
break;
case "registrar":
destino="Registrar";
break;
case "Pagar":
destino="Pagar";
break;
case "cobrar":
destino="Cobrador";
break;
case "gestorProductos":
destino="GestorProductos";
break;
case "gestorFotos":
destino="GestorFotos";
break;
}
if(destino!=null){
despachador = request.getRequestDispatcher(destino);
despachador.include(request, response);
}
}
}
|
3e197c4630ce228097059eca351958c59158493f | 1,672 | java | Java | src/main/java/com/nullfish/lib/vfs/impl/root/RootFileName.java | r-koubou/filefish-vfs- | c6b6c6975e2cbf5f9d33a5f712a3dacc2f722508 | [
"BSD-2-Clause"
] | null | null | null | src/main/java/com/nullfish/lib/vfs/impl/root/RootFileName.java | r-koubou/filefish-vfs- | c6b6c6975e2cbf5f9d33a5f712a3dacc2f722508 | [
"BSD-2-Clause"
] | null | null | null | src/main/java/com/nullfish/lib/vfs/impl/root/RootFileName.java | r-koubou/filefish-vfs- | c6b6c6975e2cbf5f9d33a5f712a3dacc2f722508 | [
"BSD-2-Clause"
] | null | null | null | 17.061224 | 212 | 0.657895 | 10,823 | /*
* 作成日: 2003/11/07
*
*/
package com.nullfish.lib.vfs.impl.root;
import java.net.URI;
import java.net.URISyntaxException;
import com.nullfish.lib.vfs.FileName;
import com.nullfish.lib.vfs.UserInfo;
/**
* @author shunji
*
*/
public class RootFileName extends FileName {
/**
* スキーマ
*/
public static final String SCHEME = "root";
URI uri = null;
private static final RootFileName instance = new RootFileName();
/**
* コンストラクタ
* @param fileNames
* @param baseFileName
*/
private RootFileName() {
super(
SCHEME,
null,
new String[0],
null,
"",
-1,
"",
"");
}
/* (非 Javadoc)
* @see com.sexyprogrammer.lib.vfs.FileName#doGetAbsolutePath()
*/
public String doGetAbsolutePath() {
return "root:///";
}
/**
* ユーザー情報抜きのパスを返す。
*/
public String getSecurePath() {
return getAbsolutePath();
}
/* (非 Javadoc)
* @see com.sexyprogrammer.lib.vfs.FileName#getURI()
*/
public URI getURI() throws URISyntaxException {
if(uri == null) {
uri = new URI("root:///");
}
return uri;
}
/* (非 Javadoc)
* @see com.sexyprogrammer.lib.vfs.FileName#createFileName(com.sexyprogrammer.lib.vfs.FileName, java.lang.String[], com.sexyprogrammer.lib.vfs.UserInfo, java.lang.String, int, java.lang.String, java.lang.String)
*/
public FileName doCreateFileName(
String scheme,
FileName baseFileName,
String[] path,
UserInfo userInfo,
String host,
int port,
String query,
String fragment) {
return new RootFileName();
}
/**
* パスのセパレータ文字を返す。
* @return
*/
public String getSeparator() {
return SEPARATOR;
}
public static RootFileName getInstance() {
return instance;
}
}
|
3e197c4c4a2d2e1ff5405f3ece36d64d8520782b | 1,075 | java | Java | spring-xd-codec/src/main/java/org/springframework/xd/dirt/integration/bus/serializer/kryo/KryoNullRegistrar.java | thomasdarimont/spring-xd | f37087a25f86b561c007842f9bf2f9e237b78c1c | [
"Apache-2.0"
] | null | null | null | spring-xd-codec/src/main/java/org/springframework/xd/dirt/integration/bus/serializer/kryo/KryoNullRegistrar.java | thomasdarimont/spring-xd | f37087a25f86b561c007842f9bf2f9e237b78c1c | [
"Apache-2.0"
] | null | null | null | spring-xd-codec/src/main/java/org/springframework/xd/dirt/integration/bus/serializer/kryo/KryoNullRegistrar.java | thomasdarimont/spring-xd | f37087a25f86b561c007842f9bf2f9e237b78c1c | [
"Apache-2.0"
] | null | null | null | 26.875 | 75 | 0.748837 | 10,824 | /*
* Copyright 2014 the original author or authors.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.xd.dirt.integration.bus.serializer.kryo;
import org.springframework.beans.factory.FactoryBean;
/**
* @author David Turanski
*/
public class KryoNullRegistrar implements FactoryBean<KryoRegistrar> {
@Override
public KryoRegistrar getObject() throws Exception {
return null;
}
@Override
public Class<?> getObjectType() {
return KryoNullRegistrar.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
|
3e197c8d97691399e7c234d4c3dd761bb501b433 | 4,126 | java | Java | src/main/java/it/linksmt/cts2/plugin/sti/service/AbstractStiService.java | iit-rende/sti-service | c3f2f8961d2553fc45977f6eb91afd91ea67071a | [
"Apache-2.0"
] | null | null | null | src/main/java/it/linksmt/cts2/plugin/sti/service/AbstractStiService.java | iit-rende/sti-service | c3f2f8961d2553fc45977f6eb91afd91ea67071a | [
"Apache-2.0"
] | null | null | null | src/main/java/it/linksmt/cts2/plugin/sti/service/AbstractStiService.java | iit-rende/sti-service | c3f2f8961d2553fc45977f6eb91afd91ea67071a | [
"Apache-2.0"
] | null | null | null | 33.274194 | 110 | 0.809016 | 10,825 | package it.linksmt.cts2.plugin.sti.service;
import java.util.Hashtable;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import edu.mayo.cts2.framework.core.config.ConfigConstants;
import edu.mayo.cts2.framework.core.config.RefreshableServerContext;
import edu.mayo.cts2.framework.core.plugin.PluginConfigManager;
import edu.mayo.cts2.framework.core.url.UrlConstructor;
import edu.mayo.cts2.framework.model.core.CodeSystemReference;
import edu.mayo.cts2.framework.model.core.CodeSystemVersionReference;
import edu.mayo.cts2.framework.model.core.NameAndMeaningReference;
import edu.mayo.cts2.framework.model.core.OpaqueData;
import edu.mayo.cts2.framework.model.core.SourceReference;
import edu.mayo.cts2.framework.model.service.core.DocumentedNamespaceReference;
import edu.mayo.cts2.framework.model.util.ModelUtils;
import edu.mayo.cts2.framework.service.profile.BaseService;
import it.linksmt.cts2.plugin.sti.service.util.StiAppConfig;
import it.linksmt.cts2.plugin.sti.service.util.StiServiceUtil;
public abstract class AbstractStiService implements BaseService, InitializingBean {
private static Logger log = Logger.getLogger(AbstractStiService.class);
private static final String LINKS = "Links MT";
protected String buildVersion = "1.0";
protected String buildName = "STI - CTS-2";
protected String buildDescription = "Implementazione CTS per il Servizio Terminologico";
@javax.annotation.Resource
private PluginConfigManager pluginConfigManager;
private UrlConstructor urlConstructor;
public UrlConstructor getUrlConstructor() {
return urlConstructor;
}
public CodeSystemVersionReference buildCodeSystemVersionReference(
final String codeSystemName, final String codeSystemVersionName){
CodeSystemVersionReference ref = new CodeSystemVersionReference();
ref.setCodeSystem(this.buildCodeSystemReference(codeSystemName,
getUrlConstructor().createCodeSystemUrl(codeSystemName)));
NameAndMeaningReference version = new NameAndMeaningReference();
version.setContent(codeSystemVersionName);
version.setUri(getUrlConstructor().createCodeSystemVersionUrl(codeSystemName, codeSystemVersionName));
version.setHref(getUrlConstructor().createCodeSystemVersionUrl(codeSystemName, codeSystemVersionName));
ref.setVersion(version);
return ref;
}
public CodeSystemReference buildCodeSystemReference(final String codeSystemName, final String codeSystemURI){
CodeSystemReference codeSystemReference = new CodeSystemReference();
String codeSystemPath = getUrlConstructor().createCodeSystemUrl(codeSystemName);
codeSystemReference.setContent(codeSystemName);
codeSystemReference.setHref(codeSystemPath);
codeSystemReference.setUri(codeSystemURI);
return codeSystemReference;
}
@Override
public void afterPropertiesSet() throws Exception {
// Override Server Root
String serverRoot = StiServiceUtil.trimStr(StiAppConfig.getProperty(
StiServiceConfiguration.CTS2_STI_SERVER_ADDRESS));
if ((!StiServiceUtil.isNull(serverRoot)) &&
(this.pluginConfigManager.getServerContext() instanceof RefreshableServerContext)) {
RefreshableServerContext rc = (RefreshableServerContext)
this.pluginConfigManager.getServerContext();
Hashtable<String, String> rs = new Hashtable<String, String>();
rs.put(ConfigConstants.SERVER_ROOT_PROPERTY, serverRoot);
rc.updated(rs);
this.urlConstructor = new UrlConstructor(rc);
}
else {
this.urlConstructor = new UrlConstructor(this.pluginConfigManager.getServerContext());
}
}
@Override
public String getServiceVersion() {
return buildVersion;
}
@Override
public SourceReference getServiceProvider() {
SourceReference ref = new SourceReference();
ref.setContent(LINKS);
return ref;
}
@Override
public OpaqueData getServiceDescription() {
return ModelUtils.createOpaqueData(buildDescription);
}
@Override
public String getServiceName() {
return this.getClass().getSimpleName() + " - " + buildName;
}
@Override
public List<DocumentedNamespaceReference> getKnownNamespaceList() {
return null;
}
}
|
3e197ca6e140388203bb64ccfe15080e9470b619 | 10,099 | java | Java | MAME4all/trunk/Android/MAME4droid/src/com/seleuco/mame4all/GLRenderer.java | lofunz/mieme | 4226c2960b46121ec44fa8eab9717d2d644bff04 | [
"Unlicense"
] | 51 | 2015-11-22T14:53:28.000Z | 2021-12-14T07:17:42.000Z | MAME4all/trunk/Android/MAME4droid/src/com/seleuco/mame4all/GLRenderer.java | lofunz/mieme | 4226c2960b46121ec44fa8eab9717d2d644bff04 | [
"Unlicense"
] | 8 | 2018-01-14T07:19:06.000Z | 2021-08-22T15:29:59.000Z | Android/MAME4droid/src/com/seleuco/mame4all/GLRenderer.java | raytlin/iMameAtariArcadeDuo | 24adc56d1a6080822a6c9d1770ddbc607814373a | [
"Unlicense"
] | 35 | 2017-02-15T09:39:00.000Z | 2021-12-14T07:17:43.000Z | 32.682848 | 121 | 0.636202 | 10,826 | /*
* This file is part of MAME4droid.
*
* Copyright (C) 2011-2013 David Valdeita (Seleuco)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses>.
*
* Linking MAME4droid statically or dynamically with other modules is
* making a combined work based on MAME4droid. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* In addition, as a special exception, the copyright holders of MAME4droid
* give you permission to combine MAME4droid with free software programs
* or libraries that are released under the GNU LGPL and with code included
* in the standard release of MAME under the MAME License (or modified
* versions of such code, with unchanged license). You may copy and
* distribute such a system following the terms of the GNU GPL for MAME4droid
* and the licenses of the other code concerned, provided that you include
* the source code of that other code when and as the GNU GPL requires
* distribution of source code.
*
* Note that people who make modified versions of MAME4droid are not
* obligated to grant this special exception for their modified versions; it
* is their choice whether to do so. The GNU General Public License
* gives permission to release a modified version without this exception;
* this exception also makes it possible to release a modified version
* which carries forward this exception.
*
* MAME4droid is dual-licensed: Alternatively, you can license MAME4droid
* under a MAME license, as set out in http://mamedev.org/
*/
package com.seleuco.mame4all;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
import android.opengl.GLSurfaceView.Renderer;
import android.util.Log;
public class GLRenderer implements Renderer {
protected int mTex = -1;
protected int[] mtexBuf = new int[1];
private final int[] mCrop;
private final int[] mTextureName;
protected ShortBuffer shortBuffer = null;
private FloatBuffer mFVertexBuffer;
private FloatBuffer mTexBuffer;
private ShortBuffer mIndexBuffer;
protected boolean textureInit = false;
protected boolean force10 = false;
protected boolean smooth = false;
protected MAME4all mm = null;
public void setMAME4all(MAME4all mm) {
this.mm = mm;
}
public GLRenderer()
{
mTextureName = new int[1];
mCrop = new int[4];
}
public void changedEmulatedSize(){
Log.v("mm","changedEmulatedSize "+shortBuffer+" "+Emulator.getScreenBuffer());
if(Emulator.getScreenBuffer()==null)return;
shortBuffer = Emulator.getScreenBuffer().asShortBuffer();
textureInit = false;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
Log.v("mm","onSurfaceCreated ");
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
gl.glClearColor(0.5f, 0.5f, 0.5f, 1);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glShadeModel(GL10.GL_FLAT);
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glDisable(GL10.GL_DITHER);
gl.glDisable(GL10.GL_LIGHTING);
gl.glDisable(GL10.GL_BLEND);
gl.glDisable(GL10.GL_CULL_FACE);
gl.glDisable(GL10.GL_DEPTH_TEST);
gl.glDisable(GL10.GL_MULTISAMPLE);
if(!(gl instanceof GL11Ext) || force10)
{
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}
textureInit=false;
}
public void onSurfaceChanged(GL10 gl, int w, int h) {
Log.v("mm","sizeChanged: ==> new Viewport: ["+w+","+h+"]");
gl.glViewport(0, 0, w, h);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof (0f, w, h, 0f, -1f,1f);
gl.glFrontFace(GL10.GL_CCW);
gl.glClearColor(0.5f, 0.5f, 0.5f, 1);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
textureInit=false;
}
protected boolean isSmooth(){
return Emulator.isFrameFiltering();
}
protected int loadTexture(final GL10 gl) {
int textureName = -1;
if (gl != null) {
gl.glGenTextures(1, mTextureName, 0);
textureName = mTextureName[0];
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName);
smooth = isSmooth();
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
smooth ? GL10.GL_LINEAR : GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL10.GL_REPLACE);
final int error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
Log.e("SpriteMethodTest", "Texture Load GLError: " + error);
}
}
return textureName;
}
public void initVertexes(GL10 gl) {
if(gl instanceof GL11Ext && !force10)
return;
int width = Emulator.getEmulatedWidth();
int height = Emulator.getEmulatedHeight();
ByteBuffer vbb = ByteBuffer.allocateDirect(4 * 3 * 4);
vbb.order(ByteOrder.nativeOrder());
mFVertexBuffer = vbb.asFloatBuffer();
ByteBuffer tbb = ByteBuffer.allocateDirect(4 * 2 * 4);
tbb.order(ByteOrder.nativeOrder());
mTexBuffer = tbb.asFloatBuffer();
ByteBuffer ibb = ByteBuffer.allocateDirect(4 * 2);
ibb.order(ByteOrder.nativeOrder());
mIndexBuffer = ibb.asShortBuffer();
float scaleX = (float) Emulator.getWindow_width()/Emulator.getEmulatedWidth();
float scaleY = (float) Emulator.getWindow_height()/Emulator.getEmulatedHeight();
float[] coords = {
// X, Y, Z
(int) ((float) width * scaleX), 0, 0,
(int) ((float) width * scaleX),(int) ((float) height * scaleY), 0,
0, 0, 0,
0,(int) ((float) height * scaleY), 0 };
int width_p2 = Emulator.getEmulatedWidth() > 512 ? 1024 : 512;
int height_p2 = 512;
// Texture coords
float[] texturCoords = new float[] {
1f / ((float) width_p2 / width), 0f, 0,
1f / ((float) width_p2 / width),
1f / ((float) height_p2 / height), 0, 0f, 0f, 0, 0f,
1f / ((float) height_p2 / height), 0 };
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3; j++) {
mFVertexBuffer.put(coords[i * 3 + j]);
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 2; j++) {
mTexBuffer.put(texturCoords[i * 3 + j]);
}
}
for (int i = 0; i < 4; i++) {
mIndexBuffer.put((short) i);
}
mFVertexBuffer.position(0);
mTexBuffer.position(0);
mIndexBuffer.position(0);
}
private void releaseTexture(GL10 gl) {
if (mTex != -1) {
gl.glDeleteTextures(1, new int[] { mTex }, 0);
}
}
public void dispose(GL10 gl) {
releaseTexture(gl);
}
public void onDrawFrame(GL10 gl) {
// Log.v("mm","onDrawFrame called "+shortBuffer);
if(shortBuffer==null){
ByteBuffer buf = Emulator.getScreenBuffer();
if(buf==null)return;
shortBuffer = buf.asShortBuffer();
}
if(mTex==-1 || smooth!=isSmooth())
mTex = loadTexture(gl);
gl.glActiveTexture(mTex);
gl.glClientActiveTexture(mTex);
shortBuffer.rewind();
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTex);
if(!textureInit)
{
initVertexes(gl);
gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, GL10.GL_RGB,
Emulator.getEmulatedWidth() > 512 ? 1024 : 512,512, 0, GL10.GL_RGB,
GL10.GL_UNSIGNED_SHORT_5_6_5 , shortBuffer);
textureInit = true;
}
/*
gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, GL10.GL_RGB,
Emulator.getEmulatedWidth(),Emulator.getEmulatedHeight(), 0, GL10.GL_RGB,
GL10.GL_UNSIGNED_SHORT_5_6_5, shortBuffer);
*/
int width = Emulator.getEmulatedWidth();
int height = Emulator.getEmulatedHeight();
gl.glTexSubImage2D(GL11.GL_TEXTURE_2D, 0, 0, 0, width, height, GL10.GL_RGB, GL10.GL_UNSIGNED_SHORT_5_6_5, shortBuffer);
if((gl instanceof GL11Ext) && !force10)
{
mCrop[0] = 0; // u
mCrop[1] = height; // v
mCrop[2] = width; // w
mCrop[3] = -height; // h
((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D,GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCrop, 0);
((GL11Ext) gl).glDrawTexiOES(0, 0, 0, Emulator.getWindow_width()/*+1*/,Emulator.getWindow_height()/*+1*/);
}
else
{
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer);
gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, 4,
GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
}
}
} |
3e197e06f44996883970ed1ba9815f4b7456a5b3 | 2,886 | java | Java | src/main/java/com/rmh/guitar/bestposition/settings/OptionsFactory.java | rhythm-melody-harmony/guitar-best-position | 3be28aade9231c1135001b0e568f755ac86efb1b | [
"Apache-2.0"
] | 1 | 2017-01-26T15:35:55.000Z | 2017-01-26T15:35:55.000Z | src/main/java/com/rmh/guitar/bestposition/settings/OptionsFactory.java | rhythm-melody-harmony/guitar-best-position | 3be28aade9231c1135001b0e568f755ac86efb1b | [
"Apache-2.0"
] | 15 | 2016-05-17T09:27:33.000Z | 2021-05-07T16:07:43.000Z | src/main/java/com/rmh/guitar/bestposition/settings/OptionsFactory.java | rhythm-melody-harmony/guitar-best-position | 3be28aade9231c1135001b0e568f755ac86efb1b | [
"Apache-2.0"
] | 1 | 2016-07-05T14:53:20.000Z | 2016-07-05T14:53:20.000Z | 42.441176 | 126 | 0.700624 | 10,827 | package com.rmh.guitar.bestposition.settings;
import com.rmh.guitar.bestposition.domain.request.options.FretboardSettings;
import com.rmh.guitar.bestposition.domain.request.options.SearchOptions;
import com.rmh.guitar.bestposition.domain.request.Options;
import com.rmh.guitar.bestposition.domain.request.options.WeightOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class OptionsFactory {
private final FretBoardSettingsFactory fretBoardSettingsFactory;
private final SearchOptionsFactory searchOptionsFactory;
@Autowired
public OptionsFactory(FretBoardSettingsFactory fretBoardSettingsFactory, SearchOptionsFactory searchOptionsFactory) {
this.fretBoardSettingsFactory = fretBoardSettingsFactory;
this.searchOptionsFactory = searchOptionsFactory;
}
public Options create(Options model) {
FretboardSettings fretboardSettings = fretBoardSettingsFactory.create();
SearchOptions searchOptions = searchOptionsFactory.createSearchOptions();
WeightOptions weightOptions = searchOptionsFactory.createWeightOptions();
if (model != null) {
if (model.getFretboardSettings() != null) {
if (model.getFretboardSettings().getNumberOfFrets() > 0) {
fretboardSettings.setNumberOfFrets(model.getFretboardSettings().getNumberOfFrets());
}
if (model.getFretboardSettings().getNumberOfStrings() > 0) {
fretboardSettings.setNumberOfStrings(model.getFretboardSettings().getNumberOfStrings());
}
if (model.getFretboardSettings().getTuning() != null && model.getFretboardSettings().getTuning().length > 0) {
fretboardSettings.setTuning(model.getFretboardSettings().getTuning());
}
}
if (model.getSearchOptions() != null) {
searchOptions.setUseOpenStrings(model.getSearchOptions().isUseOpenStrings());
searchOptions.setUseThumbFinger(model.getSearchOptions().isUseThumbFinger());
}
if (model.getWeightOptions() != null) {
weightOptions.setEveryPick(model.getWeightOptions().getEveryPick());
weightOptions.setFingerDistance(model.getWeightOptions().getFingerDistance());
weightOptions.setFingerDistanceFromIndex(model.getWeightOptions().getFingerDistanceFromIndex());
weightOptions.setFretDistance(model.getWeightOptions().getFretDistance());
weightOptions.setStringDistance(model.getWeightOptions().getStringDistance());
}
}
return new Options(fretboardSettings, searchOptions, weightOptions);
}
public Options createDefault() {
return create(null);
}
}
|
3e197ed3ff7d2981ea3cff86c357c8e4b2136655 | 1,142 | java | Java | mina.netty/src/main/java/org/kaazing/mina/netty/ChannelIoService.java | ZachBray/kgw-aeron-poc | 1c2654a0470acaaae24efb9e353708bf4b257f72 | [
"Apache-2.0"
] | 157 | 2015-04-16T17:39:08.000Z | 2022-01-18T14:07:48.000Z | mina.netty/src/main/java/org/kaazing/mina/netty/ChannelIoService.java | ZachBray/kgw-aeron-poc | 1c2654a0470acaaae24efb9e353708bf4b257f72 | [
"Apache-2.0"
] | 567 | 2015-03-04T17:44:25.000Z | 2021-02-23T22:59:43.000Z | mina.netty/src/main/java/org/kaazing/mina/netty/ChannelIoService.java | ZachBray/kgw-aeron-poc | 1c2654a0470acaaae24efb9e353708bf4b257f72 | [
"Apache-2.0"
] | 133 | 2015-03-04T19:11:33.000Z | 2020-12-02T14:32:18.000Z | 34.606061 | 117 | 0.774956 | 10,828 | /**
* Copyright 2007-2016, Kaazing Corporation. 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 org.kaazing.mina.netty;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.session.IoSessionInitializer;
import org.jboss.netty.channel.Channel;
import org.kaazing.mina.core.service.IoServiceEx;
public interface ChannelIoService extends IoServiceEx {
ChannelIoSession<?> createSession(Channel channel);
IoSessionIdleTracker getSessionIdleTracker();
void initializeSession(ChannelIoSession<?> session, IoFuture future, IoSessionInitializer<?> sessionInitializer);
}
|
3e19803339a9e06ca27f95eb9925e6d3d701c298 | 8,044 | java | Java | me/shatteredhej/railhack/railhackmod/modules/combat/Surround.java | kisman2000/RailHack-Ratted- | 6e9854b45e95a2b97534958a91193e07e1690059 | [
"MIT"
] | 3 | 2021-10-16T12:53:20.000Z | 2022-02-02T16:02:40.000Z | me/shatteredhej/railhack/railhackmod/modules/combat/Surround.java | kisman2000/RailHack-Ratted- | 6e9854b45e95a2b97534958a91193e07e1690059 | [
"MIT"
] | 2 | 2021-11-07T12:23:26.000Z | 2022-02-08T18:32:17.000Z | me/shatteredhej/railhack/railhackmod/modules/combat/Surround.java | kisman2000/RailHack-Ratted- | 6e9854b45e95a2b97534958a91193e07e1690059 | [
"MIT"
] | 2 | 2021-10-16T12:53:21.000Z | 2022-02-08T05:45:55.000Z | 47.880952 | 401 | 0.583665 | 10,829 | //Deobfuscated with https://github.com/SimplyProgrammer/Minecraft-Deobfuscator3000 using mappings "C:\Users\Admin\Desktop\Minecraft-Deobfuscator3000-1.2.2\1.12 stable mappings"!
//Decompiled by Procyon!
package me.shatteredhej.railhack.railhackmod.modules.combat;
import me.shatteredhej.railhack.railhackmod.module.*;
import me.shatteredhej.railhack.railhackmod.guiscreen.settings.*;
import me.shatteredhej.railhack.railhackmod.category.*;
import net.minecraft.util.math.*;
import net.minecraft.entity.*;
import net.minecraft.entity.item.*;
import me.shatteredhej.railhack.railhackmod.util.block.*;
import java.util.*;
import net.minecraft.item.*;
import net.minecraft.block.*;
import net.minecraft.util.*;
import net.minecraft.network.play.client.*;
import net.minecraft.network.*;
public class Surround extends Module
{
Setting rotate;
Setting hybrid;
Setting triggerable;
Setting center;
Setting block_head;
Setting tick_for_place;
Setting tick_timeout;
Setting swing;
Setting iron;
private int y_level;
private int tick_runs;
private int offset_step;
private Vec3d center_block;
Vec3d[] surround_targets;
Vec3d[] surround_targets_face;
public Surround() {
super(Category.Combat);
this.rotate = this.register("Rotate", "SurroundSmoth", true);
this.hybrid = this.register("Hybrid", "SurroundHybrid", true);
this.triggerable = this.register("Toggle", "SurroundToggle", true);
this.center = this.register("Center", "SurroundCenter", false);
this.block_head = this.register("Block Face", "SurroundBlockFace", false);
this.tick_for_place = this.register("Blocks per tick", "SurroundTickToPlace", 2, 1, 8);
this.tick_timeout = this.register("Ticks til timeout", "SurroundTicks", 20, 10, 50);
this.swing = this.register("Swing", "SurroundSwing", "Mainhand", this.combobox(new String[] { "Mainhand", "Offhand", "Both", "None" }));
this.iron = this.register("Iron", "Iron", false);
this.y_level = 0;
this.tick_runs = 0;
this.offset_step = 0;
this.center_block = Vec3d.ZERO;
this.surround_targets = new Vec3d[] { new Vec3d(1.0, 0.0, 0.0), new Vec3d(0.0, 0.0, 1.0), new Vec3d(-1.0, 0.0, 0.0), new Vec3d(0.0, 0.0, -1.0), new Vec3d(1.0, -1.0, 0.0), new Vec3d(0.0, -1.0, 1.0), new Vec3d(-1.0, -1.0, 0.0), new Vec3d(0.0, -1.0, -1.0), new Vec3d(0.0, -1.0, 0.0) };
this.surround_targets_face = new Vec3d[] { new Vec3d(1.0, 1.0, 0.0), new Vec3d(0.0, 1.0, 1.0), new Vec3d(-1.0, 1.0, 0.0), new Vec3d(0.0, 1.0, -1.0), new Vec3d(1.0, 0.0, 0.0), new Vec3d(0.0, 0.0, 1.0), new Vec3d(-1.0, 0.0, 0.0), new Vec3d(0.0, 0.0, -1.0), new Vec3d(1.0, -1.0, 0.0), new Vec3d(0.0, -1.0, 1.0), new Vec3d(-1.0, -1.0, 0.0), new Vec3d(0.0, -1.0, -1.0), new Vec3d(0.0, -1.0, 0.0) };
this.name = "Surround";
this.tag = "Surround";
this.description = "surround urself with obi and such";
}
public void onEnable() {
if (this.find_in_hotbar() == -1) {
this.setDisable();
return;
}
if (Surround.mc.player != null) {
this.y_level = (int)Math.round(Surround.mc.player.posY);
this.center_block = this.get_center(Surround.mc.player.posX, Surround.mc.player.posY, Surround.mc.player.posZ);
if (this.center.getValue(true)) {
Surround.mc.player.motionX = 0.0;
Surround.mc.player.motionZ = 0.0;
}
}
}
public void onUpdate() {
if (Surround.mc.player != null) {
if (this.center_block != Vec3d.ZERO && this.center.getValue(true)) {
final double x_diff = Math.abs(this.center_block.x - Surround.mc.player.posX);
final double z_diff = Math.abs(this.center_block.z - Surround.mc.player.posZ);
if (x_diff <= 0.1 && z_diff <= 0.1) {
this.center_block = Vec3d.ZERO;
}
else {
final double motion_x = this.center_block.x - Surround.mc.player.posX;
final double motion_z = this.center_block.z - Surround.mc.player.posZ;
Surround.mc.player.motionX = motion_x / 2.0;
Surround.mc.player.motionZ = motion_z / 2.0;
}
}
if ((int)Math.round(Surround.mc.player.posY) != this.y_level && this.hybrid.getValue(true)) {
this.setDisable();
return;
}
if (!this.triggerable.getValue(true) && this.tick_runs >= this.tick_timeout.getValue(1)) {
this.tick_runs = 0;
this.setDisable();
return;
}
int blocks_placed = 0;
while (blocks_placed < this.tick_for_place.getValue(1)) {
if (this.offset_step >= (this.block_head.getValue(true) ? this.surround_targets_face.length : this.surround_targets.length)) {
this.offset_step = 0;
break;
}
final BlockPos offsetPos = new BlockPos(this.block_head.getValue(true) ? this.surround_targets_face[this.offset_step] : this.surround_targets[this.offset_step]);
final BlockPos targetPos = new BlockPos(Surround.mc.player.getPositionVector()).add(offsetPos.getX(), offsetPos.getY(), offsetPos.getZ());
boolean try_to_place = true;
if (!Surround.mc.world.getBlockState(targetPos).getMaterial().isReplaceable()) {
try_to_place = false;
}
for (final Entity entity : Surround.mc.world.getEntitiesWithinAABBExcludingEntity((Entity)null, new AxisAlignedBB(targetPos))) {
if (!(entity instanceof EntityItem)) {
if (entity instanceof EntityXPOrb) {
continue;
}
try_to_place = false;
break;
}
}
if (try_to_place && BlockUtil.placeBlock(targetPos, this.find_in_hotbar(), this.rotate.getValue(true), this.rotate.getValue(true), this.swing)) {
++blocks_placed;
}
if (this.iron.getValue(true)) {}
++this.offset_step;
}
++this.tick_runs;
}
}
private int find_in_hotbar() {
for (int i = 0; i < 9; ++i) {
final ItemStack stack = Surround.mc.player.inventory.getStackInSlot(i);
if (stack != ItemStack.EMPTY && stack.getItem() instanceof ItemBlock) {
final Block block = ((ItemBlock)stack.getItem()).getBlock();
if (block instanceof BlockEnderChest) {
return i;
}
if (block instanceof BlockObsidian) {
return i;
}
}
}
return -1;
}
public static void rightClickBlock(final BlockPos pos, final Vec3d vec, final EnumHand hand, final EnumFacing direction, final boolean packet) {
if (packet) {
final float f = (float)(vec.x - pos.getX());
final float f2 = (float)(vec.y - pos.getY());
final float f3 = (float)(vec.z - pos.getZ());
Surround.mc.player.connection.sendPacket((Packet)new CPacketPlayerTryUseItemOnBlock(pos, direction, hand, f, f2, f3));
}
else {
Surround.mc.playerController.processRightClickBlock(Surround.mc.player, Surround.mc.world, pos, direction, vec, hand);
}
Surround.mc.player.swingArm(EnumHand.MAIN_HAND);
Surround.mc.rightClickDelayTimer = 4;
}
public Vec3d get_center(final double posX, final double posY, final double posZ) {
final double x = Math.floor(posX) + 0.5;
final double y = Math.floor(posY);
final double z = Math.floor(posZ) + 0.5;
return new Vec3d(x, y, z);
}
}
|
3e19803a03a6341f34ebde925de6c74c1a916894 | 812 | java | Java | app/src/main/java/com/suzei/racoon/ui/worldlist/WorldPresenter.java | adrianseraspi12/Racoon | b033136f0e34c6acad7d23a2a9e337fa69680c7b | [
"Apache-2.0"
] | 4 | 2018-09-07T15:00:31.000Z | 2019-08-18T17:47:31.000Z | app/src/main/java/com/suzei/racoon/ui/worldlist/WorldPresenter.java | akkim31/Racoon | b033136f0e34c6acad7d23a2a9e337fa69680c7b | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/suzei/racoon/ui/worldlist/WorldPresenter.java | akkim31/Racoon | b033136f0e34c6acad7d23a2a9e337fa69680c7b | [
"Apache-2.0"
] | 3 | 2019-12-26T02:21:52.000Z | 2020-12-07T12:58:21.000Z | 26.193548 | 75 | 0.740148 | 10,830 | package com.suzei.racoon.ui.worldlist;
import com.suzei.racoon.ui.base.Contract;
import com.suzei.racoon.ui.worldlist.WorldAdapter;
import com.suzei.racoon.ui.worldlist.WorldInteractor;
public class WorldPresenter implements Contract.Listener<WorldAdapter> {
private Contract.AdapterView<WorldAdapter> adapterView;
private WorldInteractor worldInteractor;
public WorldPresenter(Contract.AdapterView<WorldAdapter> adapterView) {
this.adapterView = adapterView;
worldInteractor = new WorldInteractor(this);
}
public void start() {
worldInteractor.performFirebaseDatabaseLoad();
}
@Override
public void onLoadSuccess(WorldAdapter data) {
adapterView.setAdapter(data);
}
@Override
public void onLoadFailed(String message) {
}
}
|
3e1980c12d04b4bef4a6edb448ae2d720cbd0885 | 13,723 | java | Java | tony-core/src/test/java/com/linkedin/tony/util/TestUtils.java | UWFrankGu/TonY | e6ecccd37a7aa833cf15e6c6045572369ddb13d5 | [
"BSD-2-Clause"
] | 33 | 2021-08-14T13:06:24.000Z | 2022-03-30T09:27:37.000Z | tony-core/src/test/java/com/linkedin/tony/util/TestUtils.java | UWFrankGu/TonY | e6ecccd37a7aa833cf15e6c6045572369ddb13d5 | [
"BSD-2-Clause"
] | 45 | 2021-08-16T05:33:44.000Z | 2022-03-25T10:54:30.000Z | tony-core/src/test/java/com/linkedin/tony/util/TestUtils.java | UWFrankGu/TonY | e6ecccd37a7aa833cf15e6c6045572369ddb13d5 | [
"BSD-2-Clause"
] | 9 | 2021-08-30T08:10:42.000Z | 2022-02-17T14:13:30.000Z | 38.547753 | 103 | 0.700138 | 10,831 | /**
* Copyright 2018 LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license.
* See LICENSE in the project root for license information.
*/
package com.linkedin.tony.util;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkedin.tony.models.JobContainerRequest;
import com.linkedin.tony.TonyConfig;
import java.io.File;
import java.io.IOException;
import java.net.SocketException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.testng.annotations.Test;
import static com.linkedin.tony.Constants.JOBS_SUFFIX;
import static com.linkedin.tony.Constants.LOGS_SUFFIX;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
public class TestUtils {
@Test
public void testParseMemoryString() {
assertEquals(Utils.parseMemoryString("2g"), "2048");
assertEquals(Utils.parseMemoryString("2M"), "2");
assertEquals(Utils.parseMemoryString("3"), "3");
}
@Test
public void testPoll() {
assertTrue(Utils.poll(() -> true, 1, 1));
assertFalse(Utils.poll(() -> false, 1, 1));
}
@Test
public void testUnzipArchive() {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("test.zip").getFile());
try {
Utils.unzipArchive(file.getPath(), "venv/");
Path unzippedFilePath = Paths.get("venv/123.xml");
assertTrue(Files.exists(unzippedFilePath));
Files.deleteIfExists(Paths.get("venv/123.xml"));
Files.deleteIfExists(Paths.get("venv/"));
} catch (IOException e) {
fail(e.toString());
}
}
@Test
public void testParseContainerRequests() {
Configuration conf = new Configuration();
conf.addResource("tony-default.xml");
conf.setInt("tony.worker.instances", 3);
conf.setInt("tony.evaluator.instances", 1);
conf.setInt("tony.worker.gpus", 1);
conf.setInt("tony.evaluator.vcores", 2);
conf.setInt("tony.chief.gpus", 1);
conf.setInt("tony.db.instances", 1);
conf.setInt("tony.dbwriter.instances", 1);
conf.setStrings("tony.application.prepare-stage", "dbwriter, db");
conf.setStrings("tony.application.untracked.jobtypes", "db");
Map<String, JobContainerRequest> requests = Utils.parseContainerRequests(conf);
assertEquals(requests.get("worker").getNumInstances(), 3);
assertEquals(requests.get("evaluator").getNumInstances(), 1);
assertEquals(requests.get("worker").getGPU(), 1);
assertEquals(requests.get("evaluator").getVCores(), 2);
// Check default value.
assertEquals(requests.get("worker").getMemory(), 2048);
// Check job does not exist if no instances are configured.
assertFalse(requests.containsKey("chief"));
assertEquals(requests.get("worker").getDependsOn(), new ArrayList<>(Arrays.asList("dbwriter")));
assertEquals(requests.get("evaluator").getDependsOn(), new ArrayList<>(Arrays.asList("dbwriter")));
assertEquals(requests.get("db").getDependsOn(), new ArrayList<>());
assertEquals(requests.get("dbwriter").getDependsOn(), new ArrayList<>());
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testParseContainerRequestsShouldFail() {
Configuration conf = new Configuration();
conf.addResource("tony-default.xml");
conf.setInt("tony.worker.instances", 3);
conf.setInt("tony.evaluator.instances", 1);
conf.setInt("tony.worker.gpus", 1);
conf.setInt("tony.evaluator.vcores", 2);
conf.setInt("tony.chief.gpus", 1);
conf.setInt("tony.db.instances", 1);
conf.setInt("tony.dbwriter.instances", 1);
conf.setStrings("tony.application.prepare-stage", "dbwriter,db");
conf.setStrings("tony.application.untracked.jobtypes", "db");
conf.setStrings("tony.application.training-stage", "chief, evaluator, worker");
Utils.parseContainerRequests(conf);
}
@Test
public void testIsArchive() {
ClassLoader classLoader = getClass().getClassLoader();
File file1 = new File(classLoader.getResource("test.zip").getFile());
File file2 = new File(classLoader.getResource("test.tar").getFile());
File file3 = new File(classLoader.getResource("test.tar.gz").getFile());
assertTrue(Utils.isArchive(file1.getAbsolutePath()));
assertTrue(Utils.isArchive(file2.getAbsolutePath()));
assertTrue(Utils.isArchive(file3.getAbsolutePath()));
}
@Test
public void testIsNotArchive() {
ClassLoader classLoader = getClass().getClassLoader();
File file1 = new File(classLoader.getResource("scripts/exit_0.py").getFile());
assertFalse(Utils.isArchive(file1.getAbsolutePath()));
}
@Test
public void testRenameFile() throws IOException {
File tempFile = File.createTempFile("testRenameFile-", "-suffix");
tempFile.deleteOnExit();
boolean result = Utils.renameFile(tempFile.getAbsolutePath(),
tempFile.getAbsolutePath() + "bak");
assertTrue(Files.exists(Paths.get(tempFile.getAbsolutePath() + "bak")));
assertTrue(result);
Files.deleteIfExists(Paths.get(tempFile.getAbsolutePath() + "bak"));
}
@Test
public void testConstructTFConfig() throws IOException {
String spec = "{\"worker\":[\"host0:1234\", \"host1:1234\"], \"ps\":[\"host2:1234\"]}";
String tfConfig = Utils.constructTFConfig(spec, "worker", 1);
ObjectMapper mapper = new ObjectMapper();
TonyConfig config = mapper.readValue(tfConfig, new TypeReference<TonyConfig>() { });
assertEquals(config.getTask().getType(), "worker");
assertEquals(config.getTask().getIndex(), 1);
assertEquals(config.getCluster().get("worker").get(0), "host0:1234");
assertEquals(config.getCluster().get("worker").get(1), "host1:1234");
assertEquals(config.getCluster().get("ps").get(0), "host2:1234");
spec = "{\"worker\":[\"host0:1234\", \"host1:1234\"], "
+ "\"ps\":[\"host2:1234\"],\"evaluator\":[\"host3:1234\"]}";
tfConfig = Utils.constructTFConfig(spec, "worker", 0);
config = mapper.readValue(tfConfig, new TypeReference<TonyConfig>() { });
assertEquals(config.getTask().getType(), "worker");
assertEquals(config.getTask().getIndex(), 0);
assertEquals(config.getCluster().size(), 2);
assertNotNull(config.getCluster().get("ps"));
assertNotNull(config.getCluster().get("worker"));
assertNull(config.getCluster().get("evaluator"));
assertEquals(config.getCluster().get("worker").get(0), "host0:1234");
assertEquals(config.getCluster().get("worker").get(1), "host1:1234");
assertEquals(config.getCluster().get("ps").get(0), "host2:1234");
tfConfig = Utils.constructTFConfig(spec, "evaluator", 0);
config = mapper.readValue(tfConfig, new TypeReference<TonyConfig>() { });
assertEquals(config.getTask().getType(), "evaluator");
assertEquals(config.getTask().getIndex(), 0);
assertEquals(config.getCluster().size(), 3);
assertNotNull(config.getCluster().get("ps"));
assertNotNull(config.getCluster().get("worker"));
assertNotNull(config.getCluster().get("evaluator"));
assertEquals(config.getCluster().get("evaluator").get(0), "host3:1234");
}
@Test
public void testBuildRMUrl() {
Configuration yarnConf = mock(Configuration.class);
when(yarnConf.get(YarnConfiguration.RM_WEBAPP_ADDRESS)).thenReturn("testrmaddress");
String expected = "http://testrmaddress/cluster/app/1";
assertEquals(Utils.buildRMUrl(yarnConf, "1"), expected);
}
@Test
public void testPollTillNonNull() {
assertNull(Utils.pollTillNonNull(() -> null, 1, 1));
assertTrue(Utils.pollTillNonNull(() -> true, 1, 1));
}
@Test
public void testConstructUrl() {
assertEquals(Utils.constructUrl("foobar"), "http://foobar");
assertEquals(Utils.constructUrl("http://foobar"), "http://foobar");
}
@Test
public void testConstructContainerUrl() {
Container container = mock(Container.class);
assertNotNull(Utils.constructContainerUrl(container));
assertNotNull(Utils.constructContainerUrl("foo", null));
}
@Test
public void testParseKeyValue() {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("bar", "");
hashMap.put("foo", "1");
hashMap.put("baz", "3");
assertEquals(Utils.parseKeyValue(null), new HashMap<>());
assertEquals(Utils.parseKeyValue(
new String[]{"foo=1", "bar", "baz=3"}), hashMap);
}
@Test
public void testExecuteShell() throws IOException, InterruptedException {
assertEquals(Utils.executeShell("foo", 0, null), 127);
}
@Test
public void testGetCurrentHostName() {
assertNull(Utils.getCurrentHostName());
}
@Test
public void testGetHostNameOrIpFromTokenConf()
throws SocketException, YarnException {
Configuration conf = mock(Configuration.class);
when(conf.getBoolean(
CommonConfigurationKeys.HADOOP_SECURITY_TOKEN_SERVICE_USE_IP,
CommonConfigurationKeys
.HADOOP_SECURITY_TOKEN_SERVICE_USE_IP_DEFAULT))
.thenReturn(false);
assertNull(Utils.getHostNameOrIpFromTokenConf(conf));
}
@Test
public void testGetAllJobTypes() {
Configuration conf = new Configuration();
conf.addResource("tony-default.xml");
conf.setInt("tony.worker.instances", 3);
conf.setInt("tony.evaluator.instances", 1);
conf.setInt("tony.worker.gpus", 1);
conf.setInt("tony.evaluator.vcores", 2);
conf.setInt("tony.chief.gpus", 1);
assertEquals(Utils.getAllJobTypes(conf),
new HashSet(Arrays.asList("worker", "evaluator")));
}
@Test
public void testGetNumTotalTasks() {
Configuration conf = new Configuration();
conf.addResource("tony-default.xml");
conf.setInt("tony.worker.instances", 3);
conf.setInt("tony.evaluator.instances", 1);
conf.setInt("tony.worker.gpus", 1);
conf.setInt("tony.evaluator.vcores", 2);
conf.setInt("tony.chief.gpus", 1);
assertEquals(Utils.getNumTotalTasks(conf), 4);
}
@Test
public void testGetTaskType() {
assertNull(Utils.getTaskType("foo"));
assertEquals(Utils.getTaskType("tony.evaluator.instances"),
"evaluator");
}
@Test
public void testGetClientResourcesPath() {
assertEquals(Utils.getClientResourcesPath("foo", "bar"),
"foo-bar");
}
@Test
public void testGetUntrackedJobTypes() {
Configuration conf = new Configuration();
conf.addResource("tony-default.xml");
conf.setInt("tony.worker.instances", 3);
conf.setInt("tony.evaluator.instances", 1);
conf.setInt("tony.worker.gpus", 1);
conf.setInt("tony.evaluator.vcores", 2);
conf.setInt("tony.chief.gpus", 1);
assertEquals(Utils.getUntrackedJobTypes(conf),
new String[]{"ps"}, "Arrays do not match");
}
@Test
public void testIsJobTypeTracked() {
Configuration conf = new Configuration();
conf.addResource("tony-default.xml");
conf.setInt("tony.worker.instances", 3);
conf.setInt("tony.evaluator.instances", 1);
conf.setInt("tony.worker.gpus", 1);
conf.setInt("tony.evaluator.vcores", 2);
conf.setInt("tony.chief.gpus", 1);
assertTrue(Utils.isJobTypeMonitored("tony.worker.gpus", conf));
}
@Test
public void testLinksToBeDisplayedOnPage() {
assertEquals(Utils.linksToBeDisplayedOnPage(null), new TreeMap<>());
Map<String, String> linksToBeDisplayed = Utils.linksToBeDisplayedOnPage("fakeJobId");
assertEquals(linksToBeDisplayed.size(), 2);
assertEquals(linksToBeDisplayed.get("Logs"), "/" + LOGS_SUFFIX + "/" + "fakeJobId");
assertEquals(linksToBeDisplayed.get("Events"), "/" + JOBS_SUFFIX + "/" + "fakeJobId");
}
@Test
public void testGetAllGroupJobTypes() {
Configuration conf = new Configuration();
conf.addResource("tony-default.xml");
conf.set("tony.application.group.A", "worker,chief");
conf.set("tony.application.group.B", "evaluator");
Map<String, List<String>> groupIndex = Utils.getAllGroupJobTypes(conf);
assertTrue(groupIndex.containsKey("A"));
assertTrue(groupIndex.containsKey("B"));
assertEquals(groupIndex.get("A"), Arrays.asList("worker", "chief"));
assertEquals(groupIndex.get("B"), Arrays.asList("evaluator"));
}
@Test
public void testGetGroupDependencies() {
Configuration conf = new Configuration();
conf.addResource("tony-default.xml");
conf.set("tony.application.dependency.A.timeout.after.B", "3600");
conf.set("tony.application.dependency.B.timeout.after.C", "3600");
Map<String, Pair<String, Long>> dependenciesIndex = Utils.getJobTypeDependentGrps(conf);
assertTrue(dependenciesIndex.containsKey("A"));
assertTrue(dependenciesIndex.containsKey("B"));
assertEquals(dependenciesIndex.get("A").getKey(), "B");
assertEquals(dependenciesIndex.get("A").getValue(), Long.valueOf("3600"));
assertEquals(dependenciesIndex.get("B").getKey(), "C");
assertEquals(dependenciesIndex.get("B").getValue(), Long.valueOf("3600"));
}
}
|
3e1980c95263b4e8d06d9d9ace092fc4c423efa3 | 15,778 | java | Java | tez-mapreduce/src/main/java/org/apache/tez/mapreduce/hadoop/MultiStageMRConfToTezTranslator.java | Altiscale/incubator-tez | e2e1aa36d5d140afeec2cf81f1cc2bfabb6d9b18 | [
"Apache-2.0"
] | null | null | null | tez-mapreduce/src/main/java/org/apache/tez/mapreduce/hadoop/MultiStageMRConfToTezTranslator.java | Altiscale/incubator-tez | e2e1aa36d5d140afeec2cf81f1cc2bfabb6d9b18 | [
"Apache-2.0"
] | null | null | null | tez-mapreduce/src/main/java/org/apache/tez/mapreduce/hadoop/MultiStageMRConfToTezTranslator.java | Altiscale/incubator-tez | e2e1aa36d5d140afeec2cf81f1cc2bfabb6d9b18 | [
"Apache-2.0"
] | null | null | null | 40.352941 | 90 | 0.682723 | 10,832 | /**
* 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.tez.mapreduce.hadoop;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.LimitedPrivate;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapred.JobConf;
import org.apache.tez.common.TezJobConfig;
import org.apache.tez.mapreduce.combine.MRCombiner;
import org.apache.tez.mapreduce.hadoop.DeprecatedKeys.MultiStageKeys;
import org.apache.tez.mapreduce.partition.MRPartitioner;
import com.google.common.base.Preconditions;
public class MultiStageMRConfToTezTranslator {
private static final Log LOG = LogFactory.getLog(MultiStageMRConfToTezTranslator.class);
private enum DeprecationReason {
DEPRECATED_DIRECT_TRANSLATION, DEPRECATED_MULTI_STAGE
}
// FIXME Add unit tests.
// This will convert configs to tez.<vertexName>.<OriginalProperty> for
// properties which it understands. Doing this for the initial and final task
// as well to verify functionality.
//
/**
* Converts a single completely configured MR* job to something that can be
* understood by the Tez MR runtime.
*
* @param srcConf
* the configuration for the entire MR* job. Configs for the first
* and last stage are expected to be set at root level. Configs for
* intermediate stages will be prefixed with the stage number.
* @return A translated MR* config with keys translated over to Tez.
*/
// TODO Set the cause properly.
public static Configuration convertMRToLinearTez(Configuration srcConf) {
Configuration newConf = new Configuration(srcConf);
int numIntermediateStages = MultiStageMRConfigUtil
.getNumIntermediateStages(srcConf);
boolean hasFinalReduceStage = (srcConf.getInt(MRJobConfig.NUM_REDUCES, 0) > 0);
// Assuming no 0 map jobs, and the first stage is always a map.
int totalStages = numIntermediateStages + (hasFinalReduceStage ? 2 : 1);
int numEdges = totalStages - 1;
Configuration[] allConfs = extractStageConfs(newConf, numEdges);
for (int i = 0; i < allConfs.length; i++) {
setStageKeysFromBaseConf(allConfs[i], srcConf, Integer.toString(i));
processDirectConversion(allConfs[i]);
}
for (int i = 0; i < allConfs.length - 1; i++) {
translateMultiStageWithSuccessor(allConfs[i], allConfs[i + 1]);
}
// Unset unnecessary keys in the last stage. Will end up being called for
// single stage as well which should be harmless.
translateMultiStageWithSuccessor(allConfs[allConfs.length - 1], null);
for (int i = 0; i < allConfs.length; i++) {
String vertexName;
if (i == 0) {
vertexName = MultiStageMRConfigUtil.getInitialMapVertexName();
} else if (i == allConfs.length - 1) {
vertexName = MultiStageMRConfigUtil.getFinalReduceVertexName();
} else {
// Intermediate vertices start at 1
vertexName = MultiStageMRConfigUtil.getIntermediateStageVertexName(i);
}
MultiStageMRConfigUtil.addConfigurationForVertex(newConf, vertexName,
allConfs[i]);
}
return newConf;
}
/**
* Translates MR keys to Tez for the provided vertex conf. The conversion is
* done in place.
*
* This method should be called for each stage config of the MR* job. The call
* for the first vertex should set the predecessorConf as null.
*
* Since there's no separation of input / output params at the moment, the
* config generated by this can be set as the configuration for Tez
* Input/Output and Processor.
*
* @param conf
* Configuration for the vertex being configured.
* @param predecessorConf
* Configuration for the previous vertex in the MR* chain
*/
@LimitedPrivate("Hive, Pig")
@Unstable
public static void translateVertexConfToTez(Configuration conf,
Configuration predecessorConf) {
convertVertexConfToTez(conf, predecessorConf);
}
/**
* Given a source and destination vertex, returns the config which should be
* used for the Output on this edge. The configs must be configured with tez
* keys - or run through translateVertexConfToTez.
*
* @param srcVertex
* The tez configuration for the source vertex.
* @param destVertex
* The tez configuration for the destination vertex.
* @return the output Configuration object for the edge
*/
@LimitedPrivate("Hive, Pig")
@Unstable
public static Configuration getOutputConfOnEdge(Configuration srcVertex,
Configuration destVertex) {
Preconditions.checkNotNull(srcVertex, "srcVertex cannot be null for an edge");
Preconditions.checkNotNull(destVertex, "destVertex cannot be null for an edge");
return srcVertex;
}
/**
* Given a source and destination vertex, returns the config which should be
* used for the Input on this edge. The configs must be configured with tez
* keys - or run through translateVertexConfToTez.
*
* @param srcVertex
* The tez configuration for the source vertex.
* @param destVertex
* The tez configuration for the destination vertex.
* @return the input Configuration object for the edge
*/
@LimitedPrivate("Hive, Pig")
@Unstable
public static Configuration getInputConfOnEdge(Configuration srcVertex,
Configuration destVertex) {
Preconditions.checkNotNull(srcVertex, "srcVertex cannot be null for an edge");
Preconditions.checkNotNull(destVertex, "destVertex cannot be null for an edge");
return destVertex;
}
private static void convertVertexConfToTez(Configuration vertexConf,
Configuration predecessorConf) {
setStageKeysFromBaseConf(vertexConf, vertexConf, "unknown");
processDirectConversion(vertexConf);
translateMultiStageWithPredecessor(vertexConf, predecessorConf);
}
/**
* Constructs a list containing individual configuration for each stage of the
* linear MR job, including the first map and last reduce if applicable.
*
* Generates basic configurations - i.e. without inheriting any keys from the
* top level conf. // TODO Validate this comment.
*/
private static Configuration[] extractStageConfs(Configuration conf,
int totalEdges) {
int numStages = totalEdges + 1;
Configuration confs[] = new Configuration[numStages];
// TODO Make moer efficient instead of multiple scans.
Configuration nonIntermediateConf = MultiStageMRConfigUtil
.getAndRemoveBasicNonIntermediateStageConf(conf);
if (numStages == 1) {
confs[0] = nonIntermediateConf;
} else {
confs[0] = nonIntermediateConf;
confs[numStages - 1] = new Configuration(nonIntermediateConf);
}
if (numStages > 2) {
for (int i = 1; i < numStages - 1; i++) {
confs[i] = MultiStageMRConfigUtil
.getAndRemoveBasicIntermediateStageConf(conf, i);
}
}
return confs;
}
/**
* Given a single base MRR config, returns a list of complete stage
* configurations.
*
* @param conf
* @return list of complete stage configurations given Conifiguration
*/
@Private
public static Configuration[] getStageConfs(Configuration conf) {
int numIntermediateStages = MultiStageMRConfigUtil
.getNumIntermediateStages(conf);
boolean hasFinalReduceStage = (conf.getInt(MRJobConfig.NUM_REDUCES, 0) > 0);
// Assuming no 0 map jobs, and the first stage is always a map.
int numStages = numIntermediateStages + (hasFinalReduceStage ? 2 : 1);
// Read split info from HDFS
conf.setBoolean(MRJobConfig.MR_TEZ_SPLITS_VIA_EVENTS, false);
// Setup Tez partitioner class
conf.set(TezJobConfig.TEZ_RUNTIME_PARTITIONER_CLASS,
MRPartitioner.class.getName());
// Setup Tez Combiner class if required.
// This would already have been set since the call is via JobClient
boolean useNewApi = conf.getBoolean("mapred.mapper.new-api", false);
if (useNewApi) {
if (conf.get(MRJobConfig.COMBINE_CLASS_ATTR) != null) {
conf.set(TezJobConfig.TEZ_RUNTIME_COMBINER_CLASS, MRCombiner.class.getName());
}
} else {
if (conf.get("mapred.combiner.class") != null) {
conf.set(TezJobConfig.TEZ_RUNTIME_COMBINER_CLASS, MRCombiner.class.getName());
}
}
Configuration confs[] = new Configuration[numStages];
Configuration nonItermediateConf = MultiStageMRConfigUtil.extractStageConf(
conf, "");
if (numStages == 1) {
confs[0] = nonItermediateConf;
confs[0].setBoolean(MRConfig.IS_MAP_PROCESSOR, true);
} else {
confs[0] = nonItermediateConf;
confs[numStages - 1] = new Configuration(nonItermediateConf);
confs[numStages -1].setBoolean(MRConfig.IS_MAP_PROCESSOR, false);
}
if (numStages > 2) {
for (int i = 1; i < numStages - 1; i++) {
confs[i] = MultiStageMRConfigUtil.extractStageConf(conf,
MultiStageMRConfigUtil.getPropertyNameForIntermediateStage(i, ""));
confs[i].setBoolean(MRConfig.IS_MAP_PROCESSOR, false);
}
}
return confs;
}
private static void processDirectConversion(Configuration conf) {
for (Entry<String, String> dep : DeprecatedKeys.getMRToTezRuntimeParamMap()
.entrySet()) {
if (conf.get(dep.getKey()) != null) {
// TODO Deprecation reason does not seem to reflect in the config ?
// The ordering is important in case of keys which are also deprecated.
// Unset will unset the deprecated keys and all it's variants.
final String mrValue = conf.get(dep.getKey());
final String tezValue = conf.get(dep.getValue());
conf.unset(dep.getKey());
if (tezValue == null) {
conf.set(dep.getValue(), mrValue,
DeprecationReason.DEPRECATED_DIRECT_TRANSLATION.name());
}
if (LOG.isDebugEnabled()) {
LOG.debug("Config: mr(unset):" + dep.getKey() + ", mr initial value="
+ mrValue + ", tez:" + dep.getValue() + "=" + conf.get(dep.getValue()));
}
}
}
}
/**
* Takes as parameters configurations for the vertex and it's predecessor
* (already translated to Tez). Modifies the vertex conf in place.
*/
private static void translateMultiStageWithPredecessor(
Configuration vertexConf, Configuration predecessorConf) {
Preconditions.checkNotNull(vertexConf,
"Configuration for vertex being translated cannot be null");
for (Entry<String, Map<MultiStageKeys, String>> dep : DeprecatedKeys
.getMultiStageParamMap().entrySet()) {
if (vertexConf.get(dep.getKey()) != null) {
String value = vertexConf.get(dep.getKey());
vertexConf.unset(dep.getKey());
if (vertexConf.get(dep.getValue().get(MultiStageKeys.OUTPUT)) == null) {
vertexConf.set(dep.getValue().get(MultiStageKeys.OUTPUT), value,
DeprecationReason.DEPRECATED_MULTI_STAGE.name());
if (LOG.isDebugEnabled()) {
LOG.debug("Config: mr(unset):" + dep.getKey() + ", mr initial value="
+ value + ", tez:" + dep.getValue().get(MultiStageKeys.OUTPUT) + "="
+ vertexConf.get(dep.getValue().get(MultiStageKeys.OUTPUT)));
}
}
}
// Set keys from the predecessor conf.
if (predecessorConf != null) {
String expPredecessorKey = dep.getValue().get(MultiStageKeys.OUTPUT);
if (predecessorConf.get(expPredecessorKey) != null) {
String value = predecessorConf.get(expPredecessorKey);
vertexConf.set(dep.getValue().get(MultiStageKeys.INPUT), value);
}
}
}
}
/**
* Takes as parameters configurations for the vertex and it's successor.
* Modifies both in place.
*/
private static void translateMultiStageWithSuccessor(Configuration srcVertexConf,
Configuration destVertexConf) {
// All MR keys which need such translation are specified at src - hence,
// this is ok.
// No key exists in which the map is inferring something based on the reduce
// value.
for (Entry<String, Map<MultiStageKeys, String>> dep : DeprecatedKeys
.getMultiStageParamMap().entrySet()) {
if (srcVertexConf.get(dep.getKey()) != null) {
if (destVertexConf != null) {
String value = srcVertexConf.get(dep.getKey());
srcVertexConf.unset(dep.getKey());
srcVertexConf.set(dep.getValue().get(MultiStageKeys.OUTPUT), value,
DeprecationReason.DEPRECATED_MULTI_STAGE.name());
destVertexConf.set(dep.getValue().get(MultiStageKeys.INPUT), value,
DeprecationReason.DEPRECATED_MULTI_STAGE.name());
if (LOG.isDebugEnabled()) {
LOG.debug("Config: mr(unset):" + dep.getKey() + ", mr initial value="
+ value + ", tez:" + dep.getValue() + "="
+ destVertexConf.get(dep.getValue().get(MultiStageKeys.INPUT)));
}
} else { // Last stage. Just remove the key reference.
srcVertexConf.unset(dep.getKey());
}
}
}
}
/**
* Pulls in specific keys from the base configuration, if they are not set at
* the stage level. An explicit list of keys is copied over (not all), which
* require translation to tez keys.
*/
private static void setStageKeysFromBaseConf(Configuration conf,
Configuration baseConf, String stage) {
JobConf jobConf = new JobConf(baseConf);
// Don't clobber explicit tez config.
if (conf.get(TezJobConfig.TEZ_RUNTIME_INTERMEDIATE_OUTPUT_KEY_CLASS) == null) {
// If this is set, but the comparator is not set, and their types differ -
// the job will break.
if (conf.get(MRJobConfig.MAP_OUTPUT_KEY_CLASS) == null) {
// Pull this in from the baseConf
conf.set(MRJobConfig.MAP_OUTPUT_KEY_CLASS, jobConf
.getMapOutputKeyClass().getName());
if (LOG.isDebugEnabled()) {
LOG.debug("Setting " + MRJobConfig.MAP_OUTPUT_KEY_CLASS
+ " for stage: " + stage
+ " based on job level configuration. Value: "
+ conf.get(MRJobConfig.MAP_OUTPUT_KEY_CLASS));
}
}
}
if (conf.get(TezJobConfig.TEZ_RUNTIME_INTERMEDIATE_OUTPUT_VALUE_CLASS) == null) {
if (conf.get(MRJobConfig.MAP_OUTPUT_VALUE_CLASS) == null) {
conf.set(MRJobConfig.MAP_OUTPUT_VALUE_CLASS, jobConf
.getMapOutputValueClass().getName());
if (LOG.isDebugEnabled()) {
LOG.debug("Setting " + MRJobConfig.MAP_OUTPUT_VALUE_CLASS
+ " for stage: " + stage
+ " based on job level configuration. Value: "
+ conf.get(MRJobConfig.MAP_OUTPUT_VALUE_CLASS));
}
}
}
}
}
|
3e19814777974d92ba8c6a5f1f10d3250cf3d50a | 434 | java | Java | src/com/main/Main.java | camilleAmaury/ProjetGraphesEtReseaux2 | 58557fade73a27710a24a61d1d8eb7e851f623dc | [
"Artistic-1.0-cl8"
] | null | null | null | src/com/main/Main.java | camilleAmaury/ProjetGraphesEtReseaux2 | 58557fade73a27710a24a61d1d8eb7e851f623dc | [
"Artistic-1.0-cl8"
] | null | null | null | src/com/main/Main.java | camilleAmaury/ProjetGraphesEtReseaux2 | 58557fade73a27710a24a61d1d8eb7e851f623dc | [
"Artistic-1.0-cl8"
] | null | null | null | 24.111111 | 75 | 0.5553 | 10,833 | package com.main;
import com.classes.Util;
public class Main {
public static void main(String[] args) {
try{
long begin_time = System.nanoTime();
Util.ResolveBinIm(args[0], args[1], false);
long end_time = System.nanoTime();
System.out.println((end_time - begin_time) / 1000000 + " ms");
}catch (Exception e){
e.printStackTrace();
}
}
}
|
3e198183e3615d540d83ae0ae3aa387f45adec9d | 4,152 | java | Java | api/src/test/java/io/opentelemetry/metrics/DoubleCounterTest.java | gradle-update/opentelemetry-java | cb6fec211a0dedad41ec180ca901f499b8a0a36e | [
"Apache-2.0"
] | null | null | null | api/src/test/java/io/opentelemetry/metrics/DoubleCounterTest.java | gradle-update/opentelemetry-java | cb6fec211a0dedad41ec180ca901f499b8a0a36e | [
"Apache-2.0"
] | 1 | 2022-03-02T00:13:28.000Z | 2022-03-02T00:13:28.000Z | api/src/test/java/io/opentelemetry/metrics/DoubleCounterTest.java | gradle-update/opentelemetry-java | cb6fec211a0dedad41ec180ca901f499b8a0a36e | [
"Apache-2.0"
] | null | null | null | 29.870504 | 95 | 0.695328 | 10,834 | /*
* Copyright 2019, OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.opentelemetry.metrics;
import static org.junit.jupiter.api.Assertions.assertThrows;
import io.opentelemetry.OpenTelemetry;
import io.opentelemetry.common.Labels;
import io.opentelemetry.internal.StringUtils;
import io.opentelemetry.metrics.DoubleCounter.BoundDoubleCounter;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
class DoubleCounterTest {
private static final String NAME = "name";
private static final String DESCRIPTION = "description";
private static final String UNIT = "1";
private static final Meter meter = OpenTelemetry.getMeter("DoubleCounterTest");
@Test
void preventNull_Name() {
assertThrows(NullPointerException.class, () -> meter.doubleCounterBuilder(null), "name");
}
@Test
void preventEmpty_Name() {
assertThrows(
IllegalArgumentException.class,
() -> meter.doubleCounterBuilder("").build(),
DefaultMeter.ERROR_MESSAGE_INVALID_NAME);
}
@Test
void preventNonPrintableName() {
assertThrows(
IllegalArgumentException.class,
() -> meter.doubleCounterBuilder("\2").build(),
DefaultMeter.ERROR_MESSAGE_INVALID_NAME);
}
@Test
void preventTooLongName() {
char[] chars = new char[StringUtils.METRIC_NAME_MAX_LENGTH + 1];
Arrays.fill(chars, 'a');
String longName = String.valueOf(chars);
assertThrows(
IllegalArgumentException.class,
() -> meter.doubleCounterBuilder(longName).build(),
DefaultMeter.ERROR_MESSAGE_INVALID_NAME);
}
@Test
void preventNull_Description() {
assertThrows(
NullPointerException.class,
() -> meter.doubleCounterBuilder("metric").setDescription(null).build(),
"description");
}
@Test
void preventNull_Unit() {
assertThrows(
NullPointerException.class,
() -> meter.doubleCounterBuilder("metric").setUnit(null).build(),
"unit");
}
@Test
void add_preventNullLabels() {
assertThrows(
NullPointerException.class,
() -> meter.doubleCounterBuilder("metric").build().add(1.0, null),
"labels");
}
@Test
void add_DoesNotThrow() {
DoubleCounter doubleCounter =
meter.doubleCounterBuilder(NAME).setDescription(DESCRIPTION).setUnit(UNIT).build();
doubleCounter.add(1.0, Labels.empty());
doubleCounter.add(1.0);
}
@Test
void add_PreventNegativeValue() {
DoubleCounter doubleCounter =
meter.doubleCounterBuilder(NAME).setDescription(DESCRIPTION).setUnit(UNIT).build();
assertThrows(
IllegalArgumentException.class,
() -> doubleCounter.add(-1.0, Labels.empty()),
"Counters can only increase");
}
@Test
void bound_PreventNullLabels() {
assertThrows(
NullPointerException.class,
() -> meter.doubleCounterBuilder("metric").build().bind(null),
"labels");
}
@Test
void bound_DoesNotThrow() {
DoubleCounter doubleCounter =
meter.doubleCounterBuilder(NAME).setDescription(DESCRIPTION).setUnit(UNIT).build();
BoundDoubleCounter bound = doubleCounter.bind(Labels.empty());
bound.add(1.0);
bound.unbind();
}
@Test
void bound_PreventNegativeValue() {
DoubleCounter doubleCounter =
meter.doubleCounterBuilder(NAME).setDescription(DESCRIPTION).setUnit(UNIT).build();
BoundDoubleCounter bound = doubleCounter.bind(Labels.empty());
try {
assertThrows(
IllegalArgumentException.class, () -> bound.add(-1.0), "Counters can only increase");
} finally {
bound.unbind();
}
}
}
|
3e1982aab97732b86f7709ecac7574d5aeebc6d9 | 330 | java | Java | springboot-api/src/main/java/io/shangan23/springboot/SpringbootApiApplication.java | shangan23/spring-boot-api | d3b7d645d852c034d77645a3739b09a18347ae52 | [
"Apache-2.0"
] | null | null | null | springboot-api/src/main/java/io/shangan23/springboot/SpringbootApiApplication.java | shangan23/spring-boot-api | d3b7d645d852c034d77645a3739b09a18347ae52 | [
"Apache-2.0"
] | null | null | null | springboot-api/src/main/java/io/shangan23/springboot/SpringbootApiApplication.java | shangan23/spring-boot-api | d3b7d645d852c034d77645a3739b09a18347ae52 | [
"Apache-2.0"
] | null | null | null | 23.571429 | 68 | 0.830303 | 10,835 | package io.shangan23.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootApiApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApiApplication.class, args);
}
}
|
3e19846990e0de91cb4ac766fc8c761542f2161c | 2,676 | java | Java | polocloud-modules/sign-module/src/main/java/de/polocloud/signs/plugin/listeners/CollectivesSpigotListener.java | McMaxDE/cloudsystem | 3ce223a53c19b7a5a6b7f99e76f34740a057cd20 | [
"MIT"
] | null | null | null | polocloud-modules/sign-module/src/main/java/de/polocloud/signs/plugin/listeners/CollectivesSpigotListener.java | McMaxDE/cloudsystem | 3ce223a53c19b7a5a6b7f99e76f34740a057cd20 | [
"MIT"
] | null | null | null | polocloud-modules/sign-module/src/main/java/de/polocloud/signs/plugin/listeners/CollectivesSpigotListener.java | McMaxDE/cloudsystem | 3ce223a53c19b7a5a6b7f99e76f34740a057cd20 | [
"MIT"
] | null | null | null | 48.654545 | 172 | 0.730194 | 10,836 | package de.polocloud.signs.plugin.listeners;
import de.polocloud.api.PoloCloudAPI;
import de.polocloud.api.player.ICloudPlayer;
import de.polocloud.signs.bootstraps.PluginBootstrap;
import de.polocloud.signs.sign.base.IGameServerSign;
import org.bukkit.Material;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
public class CollectivesSpigotListener implements Listener {
@EventHandler
public void handle(SignChangeEvent event){
Sign sign = (Sign) event.getBlock().getState();
IGameServerSign gameServerSign = PluginBootstrap.getInstance().getSignService().getGameServerSignManager().getGameSignBySign(sign);
if(gameServerSign != null){
gameServerSign.reloadSign(sign);
gameServerSign.updateSign();
event.setCancelled(true);
}
}
@EventHandler
public void handle(PlayerInteractEvent event) {
if (!(event.getAction().equals(Action.RIGHT_CLICK_BLOCK) || event.getAction().equals(Action.LEFT_CLICK_BLOCK)))
return;
if (event.getClickedBlock() == null || !event.getClickedBlock().getType().equals(Material.WALL_SIGN)) return;
IGameServerSign gameServerSign = PluginBootstrap.getInstance().getSignService().getGameServerSignManager().getSignByLocation(event.getClickedBlock().getLocation());
if (gameServerSign == null || gameServerSign.getGameServer() == null) return;
Player player = event.getPlayer();
if (gameServerSign.getTemplate().isMaintenance()) {
player.sendMessage(PluginBootstrap.getInstance().getSignService().getCurrentGlobalConfig().getSignMessages().getMaintenanceConnected());
return;
}
ICloudPlayer cloudPlayer = PoloCloudAPI.getInstance().getCloudPlayerManager().getCached(player.getName());
if (cloudPlayer.getMinecraftServer().getSnowflake() == gameServerSign.getGameServer().getSnowflake()) {
player.sendMessage(PluginBootstrap.getInstance().getSignService().getCurrentGlobalConfig().getSignMessages().getAlreadySameService());
return;
}
if(gameServerSign.getGameServer().getOnlinePlayers() >= gameServerSign.getGameServer().getMaxPlayers()){
player.sendMessage(PluginBootstrap.getInstance().getSignService().getCurrentGlobalConfig().getSignMessages().getConnectedIfServiceIsFull());
return;
}
cloudPlayer.sendTo(gameServerSign.getGameServer());
}
}
|
3e198473b237f91695203ed05ef8259afb6ec37c | 1,671 | java | Java | shared/arbitrate/src/main/java/com/alibaba/otter/shared/arbitrate/ArbitrateEventService.java | Delibit/otter | ac287f8225ced8dc9836a8991d493545c8ac92ac | [
"Apache-2.0"
] | 7,113 | 2015-01-04T02:49:19.000Z | 2022-03-31T08:23:20.000Z | shared/arbitrate/src/main/java/com/alibaba/otter/shared/arbitrate/ArbitrateEventService.java | Delibit/otter | ac287f8225ced8dc9836a8991d493545c8ac92ac | [
"Apache-2.0"
] | 987 | 2015-01-05T04:40:43.000Z | 2022-03-30T11:12:19.000Z | shared/arbitrate/src/main/java/com/alibaba/otter/shared/arbitrate/ArbitrateEventService.java | Delibit/otter | ac287f8225ced8dc9836a8991d493545c8ac92ac | [
"Apache-2.0"
] | 2,403 | 2015-01-05T09:24:38.000Z | 2022-03-31T06:43:37.000Z | 34.8125 | 76 | 0.786355 | 10,837 | /*
* Copyright (C) 2010-2101 Alibaba Group Holding Limited.
*
* 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.otter.shared.arbitrate;
import com.alibaba.otter.shared.arbitrate.impl.setl.ExtractArbitrateEvent;
import com.alibaba.otter.shared.arbitrate.impl.setl.LoadArbitrateEvent;
import com.alibaba.otter.shared.arbitrate.impl.setl.MainStemArbitrateEvent;
import com.alibaba.otter.shared.arbitrate.impl.setl.SelectArbitrateEvent;
import com.alibaba.otter.shared.arbitrate.impl.setl.TerminArbitrateEvent;
import com.alibaba.otter.shared.arbitrate.impl.setl.ToolArbitrateEvent;
import com.alibaba.otter.shared.arbitrate.impl.setl.TransformArbitrateEvent;
/**
* 仲裁器事件处理的service,使用者可关注相应的await/single两个方法
*
* @author jianghang 2011-8-9 下午04:39:49
*/
public interface ArbitrateEventService {
public MainStemArbitrateEvent mainStemEvent();
public SelectArbitrateEvent selectEvent();
public ExtractArbitrateEvent extractEvent();
public TransformArbitrateEvent transformEvent();
public LoadArbitrateEvent loadEvent();
public TerminArbitrateEvent terminEvent();
public ToolArbitrateEvent toolEvent();
}
|
3e1984f25bb58b7ba2bbd9f3648c0eec65c29bcb | 1,495 | java | Java | chapter10b7/src/main/java/com/actionbazaar/buslogic/WinningBidWrapper.java | kge96/actionbazaar | a98cd4aa6d3e5e34cbbe65ce16e86f7bf2142ff3 | [
"Apache-2.0"
] | 8 | 2016-11-14T02:41:09.000Z | 2020-12-20T11:59:54.000Z | chapter10b7/src/main/java/com/actionbazaar/buslogic/WinningBidWrapper.java | kge96/actionbazaar | a98cd4aa6d3e5e34cbbe65ce16e86f7bf2142ff3 | [
"Apache-2.0"
] | null | null | null | chapter10b7/src/main/java/com/actionbazaar/buslogic/WinningBidWrapper.java | kge96/actionbazaar | a98cd4aa6d3e5e34cbbe65ce16e86f7bf2142ff3 | [
"Apache-2.0"
] | 14 | 2015-09-28T08:49:44.000Z | 2021-09-21T12:57:42.000Z | 19.415584 | 107 | 0.616054 | 10,838 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.actionbazaar.buslogic;
import java.math.BigDecimal;
/**
*
* @author rcuprak
*/
public class WinningBidWrapper {
/**
* first name
*/
private String username;
/**
* Amount
*/
private BigDecimal amount;
/**
* Item name
*/
private String itemName;
/**
* Item description
*/
private String itemDescription;
public WinningBidWrapper(String username, BigDecimal amount, String itemName, String itemDescription) {
this.username = username;
this.amount = amount;
this.itemName = itemName;
this.itemDescription = itemDescription;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
@Override
public String toString() {
return itemName;
}
}
|
3e1985072c4df0785042ccee4e8983da894eeceb | 5,232 | java | Java | core/src/com/mbresson/betaform/LevelBlockMoving.java | mbresson/Betaform | 3c2693a9e14753724f7a5b397855f0e806f031fb | [
"MIT"
] | null | null | null | core/src/com/mbresson/betaform/LevelBlockMoving.java | mbresson/Betaform | 3c2693a9e14753724f7a5b397855f0e806f031fb | [
"MIT"
] | null | null | null | core/src/com/mbresson/betaform/LevelBlockMoving.java | mbresson/Betaform | 3c2693a9e14753724f7a5b397855f0e806f031fb | [
"MIT"
] | null | null | null | 25.773399 | 109 | 0.675459 | 10,839 | package com.mbresson.betaform;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.physics.box2d.*;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.JsonValue;
import com.badlogic.gdx.utils.JsonWriter;
public class LevelBlockMoving extends LevelBlock implements ObjectMovable, CanHandlePlayerContact {
public String getType() { return "moving"; }
public static class Size {
private int width, height;
public Size() {
width = 1;
height = 1;
}
public Size(Size size) {
width = size.width;
height = size.height;
}
}
// size contains the number of horizontal and vertical blocks constituting the final moving block
// default width: 1, default height: 1
private Size size = new Size();
private BehaviorAutomated behavior;
public LevelBlockMoving() {
super();
this.type = "moving";
}
public LevelBlockMoving(LevelBlockMoving moving) {
super(moving);
this.size = new Size(moving.size);
this.behavior = moving.behavior;// FIX clone instead of copying the reference
}
@Override
public void update(float deltaTime) {
super.update(deltaTime);
this.behavior.behave(this);
}
@Override
public void move(float x, float y) {
this.body.setLinearVelocity(
x,
y
);
}
@Override
public void changeDirection(Direction direction) {
// nothing to do
}
@Override
public void stop() {
}
/**
* Shoud be called only once, after loading external resources,
* because creating the physical body requires to know some information
* about the graphics.
*/
@Override
protected void initPhysics() {
/**
* The initPhysics method of LevelBlockMoving differs from the one
* of the LevelBlock class because a moving block can be constituted of several blocks
* put together (so the physic shape will be bigger, and the sprite will have to be drawn several times).
*/
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.KinematicBody;
bodyDef.position.set(
this.sprite.getX() / Configuration.Physics.WORLD_UNIT_TO_PIXELS,
this.sprite.getY() / Configuration.Physics.WORLD_UNIT_TO_PIXELS
);
GameInstance gameRef = Betaform.getGameRef();
if(gameRef == null) {
return;
}
this.body = gameRef.getWorld().createBody(bodyDef);
this.body.setUserData(this);
PolygonShape shape = new PolygonShape();
float baseWidth = (this.sprite.getWidth()/2) / Configuration.Physics.WORLD_UNIT_TO_PIXELS;
float baseHeight = (this.sprite.getHeight()/2) / Configuration.Physics.WORLD_UNIT_TO_PIXELS;
float centerX = baseWidth * this.size.width;
float centerY = baseHeight * this.size.height;
shape.setAsBox(
baseWidth * this.size.width,
baseHeight * this.size.height,
new Vector2(baseWidth * (this.size.width - 1), baseHeight * (this.size.height-1)),
0
);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.friction = 0f;
fixtureDef.shape = shape;
Fixture fixture = this.body.createFixture(fixtureDef);
shape.dispose();
this.syncGraphicsFromPhysics();
}
@Override
public void display(SpriteBatch batch) {
float baseX = this.sprite.getX();
float baseY = this.sprite.getY();
float baseWidth = this.sprite.getWidth();
float baseHeight = this.sprite.getHeight();
for(int i = 0; i < this.size.width; i++) {
float x = baseX + i * baseWidth;
for(int j = 0; j < this.size.height; j++) {
float y = baseY + j * baseHeight;
batch.draw(sprite, x, y);
}
}
}
@Override
public float getHeight() {
return super.getHeight() * size.height;
}
@Override
public float getWidth() {
return super.getWidth() * size.width;
}
@Override
public Vector2 getPhysicsPosition() {
Vector2 position = new Vector2(
sprite.getWidth() / Configuration.Physics.WORLD_UNIT_TO_PIXELS * (size.width - 1) / 2f,
sprite.getHeight() / Configuration.Physics.WORLD_UNIT_TO_PIXELS * (size.height - 1) / 2f
);
position.x += super.getPhysicsPosition().x;
position.y += super.getPhysicsPosition().y;
return position;
}
@Override
public void handlePlayerContactBegin(Player player, Contact contact) {
Vector2 playerPos = player.getPhysicsPosition();
Vector2 blockPos = this.getPhysicsPosition();
float yRadius = this.getHeight()/2 + player.getHeight()/2 - 0.1f;
contact.setFriction(0f);
if((playerPos.y - blockPos.y) >= yRadius) {
float xRadius = this.getWidth()/2 + player.getWidth();
if(Math.abs(playerPos.x - blockPos.x) < xRadius) {
contact.setFriction(1f);
}
}
}
@Override
public void handlePlayerContactEnd(Player player, Contact contact) {
}
@Override
public void write(Json json) {
super.write(json);
json.writeValue("size", this.size);
json.writeValue("behavior", this.behavior);
}
@Override
public void read(Json json, JsonValue jsonMap) {
json.readFields(this, jsonMap);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.