blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
c530b641642230dc766636b67c41c2dfb7f2edea
|
Java
|
shiyang0915/pullToRefreshDemo
|
/pull_to_refresh/src/main/java/com/sunkaisens/pull_to_refresh/PullToRefresh.java
|
UTF-8
| 9,480
| 2.3125
| 2
|
[] |
no_license
|
package com.sunkaisens.pull_to_refresh;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import androidx.annotation.RequiresApi;
/**
* @author:shiyang
* @date:2020-08-10
* @email:shiyang@sunkaisens.com
* @Description: 自定义下拉刷新框架
*/
public class PullToRefresh extends LinearLayout {
//android 事件的消费会优先让子view去处理
//如果ViewGroup很想处理这个事件怎么办 onInterceptTouchEvent 返回true
//requestDisallowedInterceptTouchEvent(boolean disallowed) 请求自己的父布局不要拦截该事件
private BasePullToRefreshManager pullToRefreshManager;
private View viewPullToRefresh;
int downY;
private int minHeadViewHeight;
//头部布局最小高度
private int mHeadViewHeight;
//头部布局最大高度
private int maxHeadViewHeight;
//初始化状态默认是静止状态
private PullState mCurrentState = PullState.IDDLE;
private OnRefreshListener onRefreshListener;
private int downInterceptX;
private int downInterceptY;
private ScrollView mScrollView;
private boolean isScrollToTop = true;
/**
* 刷新完毕
*/
public void refreshComplate() {
pullToRefreshManager.refreshComplate();
mCurrentState = PullState.REFRESH_COMPLATE;
this.postDelayed(new Runnable() {
@Override
public void run() {
overRefresh();
}
}, 500);
}
public void overRefresh() {
final LinearLayout.LayoutParams params = (LayoutParams) viewPullToRefresh.getLayoutParams();
ValueAnimator animator = ValueAnimator.ofInt(params.topMargin, minHeadViewHeight);
animator.setDuration(500);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int values = (int) animation.getAnimatedValue();
params.topMargin = values;
viewPullToRefresh.setLayoutParams(params);
}
});
animator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
mCurrentState = PullState.IDDLE;
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
animator.start();
}
public interface OnRefreshListener {
void onRefreshing();
}
public void setOnRefreshListener(OnRefreshListener onRefreshListener) {
this.onRefreshListener = onRefreshListener;
}
public PullToRefresh(Context context) {
super(context);
}
public PullToRefresh(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PullToRefresh(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setPullToRefreshManager(BasePullToRefreshManager pullToRefreshManager) {
setOrientation(VERTICAL);
this.pullToRefreshManager = pullToRefreshManager;
initData();
}
private void initData() {
viewPullToRefresh = pullToRefreshManager.initRefreshView();
viewPullToRefresh.measure(0, 0);
LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, viewPullToRefresh.getMeasuredHeight());
addView(viewPullToRefresh, 0, params);
mHeadViewHeight = viewPullToRefresh.getMeasuredHeight();
minHeadViewHeight = -mHeadViewHeight;
maxHeadViewHeight = (int) (mHeadViewHeight * 0.3f);
params.topMargin = -mHeadViewHeight;
viewPullToRefresh.setLayoutParams(params);
}
public LinearLayout.LayoutParams getPullToFreshViewParams() {
return (LayoutParams) viewPullToRefresh.getLayoutParams();
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onFinishInflate() {
super.onFinishInflate();
View childAt = this.getChildAt(0);
if (childAt instanceof ScrollView) {
mScrollView = (ScrollView) childAt;
mScrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if (mScrollView.getScrollY() == 0) {
//顶部
isScrollToTop = true;
} else {
isScrollToTop = false;
}
View contentView = mScrollView.getChildAt(0);
if (contentView != null && contentView.getMeasuredHeight() == (mScrollView.getScrollY() + mScrollView.getHeight())) {
//底部
isScrollToTop = false;
}
}
});
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (mCurrentState == PullState.IDDLE) {
downY = (int) event.getY();
return true;
}
case MotionEvent.ACTION_MOVE:
if (mCurrentState == PullState.REFRESHING || mCurrentState == PullState.REFRESH_COMPLATE) {
return false;
}
int moveY = (int) event.getY();
int dy = moveY - downY;
if (dy > 0) {
//向下滑动
LinearLayout.LayoutParams params = (LayoutParams) viewPullToRefresh.getLayoutParams();
int topMargin = (int) Math.min(minHeadViewHeight + dy / 1.8f, maxHeadViewHeight);
params.topMargin = topMargin;
if (topMargin < 0) {
//headView没有完全显示出来之前
if (mCurrentState != PullState.DOWN_REFRESH) {
//这里改变状态只执行一遍,提高不必要的回调,提升程序性能。
mCurrentState = PullState.DOWN_REFRESH;
pullToRefreshManager.downRefresh();
}
} else {
//headView完整的显示出来。
if (mCurrentState != PullState.RELEASE_REFRESH) {
mCurrentState = PullState.RELEASE_REFRESH;
pullToRefreshManager.releaseRefresh();
}
}
viewPullToRefresh.setLayoutParams(params);
}
return true;
case MotionEvent.ACTION_UP:
if (handleEventUp()) {
return true;
}
break;
default:
break;
}
return super.onTouchEvent(event);
}
private boolean handleEventUp() {
final LinearLayout.LayoutParams params = (LayoutParams) viewPullToRefresh.getLayoutParams();
if (mCurrentState == PullState.DOWN_REFRESH) {
//当在下拉刷新状态的时候执行了up事件的话,就让刷新状态变为静止状态。
overRefresh();
} else if (mCurrentState == PullState.RELEASE_REFRESH) {
params.topMargin = 0;
viewPullToRefresh.setLayoutParams(params);
mCurrentState = PullState.REFRESHING;
pullToRefreshManager.refreshing();
onRefreshListener.onRefreshing();
}
return params.topMargin > minHeadViewHeight;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
downInterceptX = (int) ev.getX();
downInterceptY = (int) ev.getY();
downY = downInterceptY;
break;
case MotionEvent.ACTION_MOVE:
int dx = (int) (ev.getX() - downInterceptX);
int dy = (int) (ev.getY() - downInterceptY);
if (Math.abs(dy) > Math.abs(dx) && dy > 0 && isScrollToTop) {
return true;
}
break;
case MotionEvent.ACTION_UP:
break;
default:
break;
}
return super.onInterceptTouchEvent(ev);
}
enum PullState {
/**
* 静止
*/
IDDLE,
/**
* 下拉刷新
*/
DOWN_REFRESH,
/**
* 释放刷新
*/
RELEASE_REFRESH,
/**
* 正在刷新
*/
REFRESHING,
/**
* 刷新完毕
*/
REFRESH_COMPLATE;
}
}
| true
|
9d9a3b1b319e92a1bcc752d75e34375eaad35b09
|
Java
|
NationalSecurityAgency/ghidra
|
/Ghidra/Framework/Generic/src/main/java/ghidra/util/graph/AddableLongIntHashtable.java
|
UTF-8
| 1,471
| 2.453125
| 2
|
[
"GPL-1.0-or-later",
"GPL-3.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LGPL-2.1-only",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/* ###
* IP: GHIDRA
* REVIEWED: YES
*
* 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 ghidra.util.graph;
import ghidra.util.datastruct.LongIntHashtable;
import ghidra.util.exception.NoValueException;
/**
*
* This class modifies the behavior of LongIntHashtable. May add
* to the value stored with the key rather than replacing the value.
*
*/
public class AddableLongIntHashtable extends LongIntHashtable {
/**
*
*/
private static final long serialVersionUID = 1L;
public AddableLongIntHashtable(int capacity) {
super(capacity);
}
public AddableLongIntHashtable() {
super();
}
/** Adds value associated with the stored key */
public void add(long key, int value) {
try {
if (this.contains(key)) {
int oldValue = this.get(key);
int newValue = oldValue + value;
this.put(key, newValue);
}
else {
this.put(key, value);
}
}
catch (NoValueException e) {
//can't happen do nothing
}
}
}
| true
|
86c2b4f854d90da9a3042716905960cc941252c4
|
Java
|
CPIJ/DrawingApp
|
/src/DrawingApp/Models/DrawingItems/Image.java
|
UTF-8
| 85
| 1.710938
| 2
|
[] |
no_license
|
package DrawingApp.Models.DrawingItems;
public class Image extends DrawingItem {
}
| true
|
08d44533dc85d41b9a72f42e88f3d1ad441ff84c
|
Java
|
afescobar92/ShareMovies
|
/app/src/main/java/movies/com/co/myapplication/model/GenreMovie.java
|
UTF-8
| 554
| 2.34375
| 2
|
[] |
no_license
|
package movies.com.co.myapplication.model;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import java.io.Serializable;
import java.util.List;
@Root(strict = false)
public class GenreMovie implements Serializable {
@ElementList(entry = "name", inline = true, required = false)
private List<String> name;
public List<String> getGenreList() {
return name;
}
public void setGenreList(List<String> genreList) {
this.name = genreList;
}
}
| true
|
759b43c377b0a4638c45ef7eedefe7d9965ad7f6
|
Java
|
laggleton/ecl
|
/ExpectedCreditLoss/src/test/referenceobjects/CountryTest.java
|
UTF-8
| 5,775
| 2.53125
| 3
|
[] |
no_license
|
package test.referenceobjects;
import static org.junit.Assert.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import referenceobjects.BusinessDate;
import referenceobjects.Country;
import referenceobjects.DateFormat;
import referenceobjects.GrossDomesticProduct;
import utilities.Logger;
public class CountryTest {
private Logger l = Logger.getInstance();
@Test
public void evaluateStandardDeviation() {
Country ctry = setUpCountry();
Double stdDev = ctry.getStandardDeviationForGDPs(2017);
Double expectedResult = 0.040264d;
assertEquals(expectedResult, stdDev, 0.01);
}
@Test
public void evaluateRMSE() {
Country ctry = setUpCountry();
Double rmse = ctry.getRootMeanSquaredErrorForGDPs();
Double expectedResult = 0.0308609988d;
assertEquals(expectedResult, rmse, 0.01);
}
@Test
public void evaluateCurrentGrowth() {
Country ctry = setUpCountry();
Double growth = ctry.getCurrentGrowth();
Double expectedResult = 0.02675d;
assertEquals(expectedResult, growth, 0.01d);
}
@Test
public void evaluateProbRecessionFromRMSE() {
Country ctry = setUpCountry();
Double growth = ctry.getCurrentGrowth();
Double rmse = ctry.getRootMeanSquaredErrorForGDPs();
ctry.setProbabilityOfRecessionAndGrowthFromVariables(growth, rmse);
Double rmseRec = ctry.getProbabilityOfRecession();
Double expectedResult = 0.20330d;
assertEquals(expectedResult, rmseRec, 0.01d);
}
@Test
public void evaluateProbRecessionFromVariables() {
Country ctry = setUpCountry();
Double growth = ctry.getCurrentGrowth();
Double shape = new Double(0.033333161d);
ctry.setProbabilityOfRecessionAndGrowthFromVariables(growth, shape);
Double rec = ctry.getProbabilityOfRecession();
Double expectedResult = 0.211d;
assertEquals(expectedResult, rec, 0.01);
}
@Test
public void evaluateProbRecessionFromStdDev() {
Country ctry = setUpCountry();
Double growth = ctry.getCurrentGrowth();
Double stdDev = ctry.getStandardDeviationForGDPs(2017);
ctry.setProbabilityOfRecessionAndGrowthFromVariables(growth, stdDev);
Double stdRec = ctry.getProbabilityOfRecession();
Double expectedResult = 0.25322d;
assertEquals(expectedResult, stdRec, 0.01d);
}
private void setBusinessDate() {
BusinessDate.getInstance().initialise("2017-05-31");
}
private Country setUpCountry() {
setBusinessDate();
Country ctry = new Country("BG");
List<GrossDomesticProduct> gdps = new ArrayList<>();
GrossDomesticProduct gdp = new GrossDomesticProduct(1995); gdp.setActualGrowth(-0.016); gdps.add(gdp);
gdp = new GrossDomesticProduct(1996); gdp.setActualGrowth(-0.08); gdp.setOneYearPredictedGrowth(0d); gdps.add(gdp);
gdp = new GrossDomesticProduct(1997); gdp.setActualGrowth(-0.016); gdp.setOneYearPredictedGrowth(0.025); gdps.add(gdp);
gdp = new GrossDomesticProduct(1998); gdp.setActualGrowth(0.049); gdp.setOneYearPredictedGrowth(0.025); gdps.add(gdp);
gdp = new GrossDomesticProduct(1999); gdp.setActualGrowth(-0.005); gdp.setOneYearPredictedGrowth(0.0597); gdps.add(gdp);
gdp = new GrossDomesticProduct(2000); gdp.setActualGrowth(0.05); gdp.setOneYearPredictedGrowth(0.041); gdps.add(gdp);
gdp = new GrossDomesticProduct(2001); gdp.setActualGrowth(0.042); gdp.setOneYearPredictedGrowth(0.04); gdps.add(gdp);
gdp = new GrossDomesticProduct(2002); gdp.setActualGrowth(0.06); gdp.setOneYearPredictedGrowth(0.05d); gdps.add(gdp);
gdp = new GrossDomesticProduct(2003); gdp.setActualGrowth(0.051); gdp.setOneYearPredictedGrowth(0.05d); gdps.add(gdp);
gdp = new GrossDomesticProduct(2004); gdp.setActualGrowth(0.066); gdp.setOneYearPredictedGrowth(0.055); gdps.add(gdp);
gdp = new GrossDomesticProduct(2005); gdp.setActualGrowth(0.072); gdp.setOneYearPredictedGrowth(0.052); gdps.add(gdp);
gdp = new GrossDomesticProduct(2006); gdp.setActualGrowth(0.068); gdp.setOneYearPredictedGrowth(0.055); gdps.add(gdp);
gdp = new GrossDomesticProduct(2007); gdp.setActualGrowth(0.077); gdp.setOneYearPredictedGrowth(0.06d); gdps.add(gdp);
gdp = new GrossDomesticProduct(2008); gdp.setActualGrowth(0.056); gdp.setOneYearPredictedGrowth(0.0587); gdps.add(gdp);
gdp = new GrossDomesticProduct(2009); gdp.setActualGrowth(-0.042); gdp.setOneYearPredictedGrowth(0.0425); gdps.add(gdp);
gdp = new GrossDomesticProduct(2010); gdp.setActualGrowth(0.001); gdp.setOneYearPredictedGrowth(-0.025); gdps.add(gdp);
gdp = new GrossDomesticProduct(2011); gdp.setActualGrowth(0.016); gdp.setOneYearPredictedGrowth(0.02d); gdps.add(gdp);
gdp = new GrossDomesticProduct(2012); gdp.setActualGrowth(0.002); gdp.setOneYearPredictedGrowth(0.03d); gdps.add(gdp);
gdp = new GrossDomesticProduct(2013); gdp.setActualGrowth(0.013); gdp.setOneYearPredictedGrowth(0.015); gdps.add(gdp);
gdp = new GrossDomesticProduct(2014); gdp.setActualGrowth(0.015); gdp.setOneYearPredictedGrowth(0.016); gdps.add(gdp);
gdp = new GrossDomesticProduct(2015); gdp.setActualGrowth(0.03); gdp.setOneYearPredictedGrowth(0.02d); gdps.add(gdp);
gdp = new GrossDomesticProduct(2016); gdp.setActualGrowth(0.03); gdp.setOneYearPredictedGrowth(0.019); gdps.add(gdp);
gdp = new GrossDomesticProduct(2017); gdp.setActualGrowth(0.028); gdp.setOneYearPredictedGrowth(0.028); gdps.add(gdp);
gdp = new GrossDomesticProduct(2018); gdp.setOneYearPredictedGrowth(0.025); gdps.add(gdp);
Collections.sort(gdps);
try {
ctry.setGdps(gdps, DateFormat.ISO_FORMAT.parse("2017-05-31"));
}
catch (ParseException pe) {
l.error(pe);
l.error("Failed to parse date");
}
return ctry;
}
}
| true
|
e21fcb6914f611fd32a32016b3645b9c91258a07
|
Java
|
yohanjo/YUtils
|
/src/topicmodel/SLDA/SLDA.java
|
UTF-8
| 31,755
| 2.046875
| 2
|
[] |
no_license
|
/**
* Sentence LDA in the WSDM11 paper.
*
* @author Yohan Jo
* @version June 22, 2017
*/
package topicmodel.SLDA;
import java.io.File;
import java.io.FileReader;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import edu.stanford.nlp.ling.HasWord;
import edu.stanford.nlp.process.DocumentPreprocessor;
import util.container.Counter;
import util.io.BufferedFileReader;
import util.io.PrintFileWriter;
import util.matrix.DoubleMatrix;
import util.matrix.IntegerMatrix;
import util.matrix.MatrixView;
public class SLDA implements Callable<Void> {
static boolean updateParams; // Update parameters?
static boolean tokenization;
static double alpha, sumAlpha;
static double beta, sumBeta;
static double gamma; // p(word=FG) (Bernoulli parameter)
static int numProbWords = 100; // Number of top words to be displayed in the ProbWords file
static int numFTopics;
static final int numBTopics = 1;
static int numWords;
static int numDocs;
static int numThreads;
static int numIters;
static int numLogIters; // Num of iterations for computing log-likelihood
static int numTmpIters; // Period of generating temporary output files
static DoubleMatrix N_TW; // Foreground topic x word count
static DoubleMatrix N_BW; // Background topic x word count (only one background topic)
static DoubleMatrix N_DT; // Doc x topic count
static String inDir = null; // Input data directory
static String outDir = null; // Output directory
static String dataFileName = null; // Data file name (e.g., data.csv)
static String modelPathPrefix = null; // Trained model
static String outPrefix = null;
static Counter<String> wordCnt = new Counter<>(); // Vocab counts
static TreeMap<String,Integer> wordIndex = new TreeMap<>(); // Vocab index
static Vector<String> wordList = new Vector<>(); // Vocab list
static TreeMap<Integer,Double> logL = new TreeMap<>(); // Log-likelihood of the data
static TreeMap<String, RawDocument> rawDocs = new TreeMap<>();
static TreeMap<String,Document> docs = new TreeMap<>(); // Data
static TreeSet<String> stopwords = new TreeSet<String>();
static int minNumWords = 1; // Minimum number of occurrences for a word to be included
// Thread-specific variables
int threadId;
List<String> docIds;
// Matrix views used by each thread. Keep track of within-thread changes.
static MatrixView V_TW;
static MatrixView V_BW;
/**
* Command arguments
*/
public static class Parameters {
@Parameter(names = "-t", description = "Number of topics", required=true)
public int numTopics = -1;
@Parameter(names = "-i", description = "Number of iterations", required=true)
public int numIters = -1;
@Parameter(names = "-to", description = "Number of iterations for temporary output files.")
public int numTmpIters = -1;
@Parameter(names = "-log", description = "Number of iterations for calculating "
+ " log-likelihood.")
public int numLogIters = -1;
@Parameter(names = "-th", description = "Number of threads.")
public int numThreads = 1;
@Parameter(names = "-a", description = "Alpha.", required=true)
public double alpha = -1;
@Parameter(names = "-b", description = "Beta.", required=true)
public double beta = -1;
@Parameter(names = "-g", description = "Gamma. 1 means no background topic.")
public double gamma = 1;
@Parameter(names = "-d", description = "Input directory.", required=true)
public String inDir = null;
@Parameter(names = "-o", description = "Output directory.")
public String outDir = null;
@Parameter(names = "-data", description = "Data file name.", required=true)
public String dataFileName = null;
@Parameter(names = "-model", description = "Trained model to fit (no parameter update).")
public String model = null;
@Parameter(names = "-tok", description = "Do tokenization/pattern replacement.")
public boolean tokenize;
@Parameter(names = "-sw", description = "Stopwords file name.")
public String stopwordsFileName = null;
@Parameter(names = "-help", description = "Command description.", help=true)
public boolean help;
}
public static void main (String [] args) throws Exception {
// Load command arguments
Parameters inParams = new Parameters();
JCommander cmd = new JCommander(inParams, args);
if (inParams.help) {
cmd.usage();
System.exit(0);
}
if (inParams.model != null) {
updateParams = false;
modelPathPrefix = inParams.model;
} else {
updateParams = true;
}
tokenization = inParams.tokenize;
numFTopics = inParams.numTopics;
numIters = inParams.numIters;
numThreads = inParams.numThreads;
alpha = inParams.alpha;
beta = inParams.beta;
gamma = inParams.gamma;
inDir = inParams.inDir;
outDir = inParams.outDir;
dataFileName = inParams.dataFileName;
numTmpIters = inParams.numTmpIters;
numLogIters = inParams.numLogIters;
// Validity
if (!new File(inDir).exists())
throw new Exception("There's no such an input directory as " + inDir);
if (alpha <= 0)
throw new Exception("Alpha should be specified as a positive real number.");
if (beta <= 0)
throw new Exception("Beta should be specified as a positive real number.");
if (gamma < 0)
throw new Exception("Gamma should be specified as a nonnegative real number.");
// Training
if (updateParams) {
loadStopwords(inParams.stopwordsFileName);
loadInstances();
indexizeWords();
indexizeInstances();
setUpOutputEnvironment();
saveWords();
printConfiguration();
runSampling();
// Fitting (no parameter update)
} else {
loadWords();
loadInstances();
indexizeInstances();
setUpOutputEnvironment();
saveWords();
printConfiguration();
runSampling();
}
}
/**
* Prints the model configuration.
*/
public static void printConfiguration() {
System.out.println("Data: "+dataFileName);
System.out.println("Documents: "+docs.size());
System.out.println("Unique Words: "+wordList.size());
System.out.println("Topics: "+numFTopics);
System.out.println("Alpha: "+alpha);
System.out.println("Beta: "+beta);
System.out.println("Gamma: "+gamma);
System.out.println("Iterations: "+numIters);
System.out.println("Tmp Output Iterations: "+numTmpIters);
System.out.println("Threads: "+numThreads);
System.out.println("Input Dir: "+inDir);
System.out.println("Output Dir: "+outDir);
}
/**
* Runs Gibbs sampling. For each iteration, this method shuffles the order
* of the sequences, splits and assigns the sequences into threads,
* and invokes and joins the threads.
*/
public static void runSampling() throws Exception {
initialize();
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
Vector<String> docIds = new Vector<String>(docs.keySet());
for (int iter = 0; iter < numIters; iter++) {
System.out.print("Iteration "+iter);
LocalDateTime startTime = LocalDateTime.now();
// Randomize the order of sequences.
// Make sure previous threads have been finished before calling this.
Collections.shuffle(docIds);
List<Callable<Void>> tasks = new Vector<Callable<Void>>();
for (int tid = 0; tid < numThreads; tid++) {
tasks.add(new SLDA(tid, docIds));
}
executor.invokeAll(tasks);
Duration runTime = Duration.between(startTime, LocalDateTime.now());
Duration remainTime = runTime.multipliedBy(numIters - iter - 1);
System.out.println(String.format(" took %.3fs. (Remain: %dH %2dM %2dS)",
runTime.toMillis()/1000.0, remainTime.toHours(),
remainTime.toMinutes()%60, remainTime.getSeconds()%60));
if (numLogIters > 0 && (iter+1) % numLogIters == 0) {
double ll = logLikelihood();
System.out.println(" - logP: "+ll);
logL.put(iter+1, ll);
}
if (iter+1 == numIters || (numTmpIters > 0 && (iter+1) % numTmpIters == 0)) {
System.out.println(" - Generating output files...");
genOutFiles(iter+1);
}
}
executor.shutdownNow();
}
/**
* Constructs an instance of this class for running a thread.
*/
public SLDA(int threadId, List<String> docIds) {
this.threadId = threadId;
this.docIds = docIds;
V_TW = new MatrixView(N_TW, true);
V_BW = new MatrixView(N_BW, true);
}
/**
* Samples the parameters for one iteration and
* updates the within-thread counters to the global counters.
*/
@Override
public Void call() throws Exception {
int beginThread = threadId * docIds.size() / numThreads;
int endThread = (threadId+1) * docIds.size() / numThreads;
List<String> subDocIds = docIds.subList(beginThread, endThread);
try {
sampleTopic(subDocIds);
sampleLevel(subDocIds);
// Commit within-thread changes and update the global matrix.
V_TW.commit();
V_BW.commit();
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
return null;
}
/**
* Generates the output file name prefix and necessary output directories.
*/
public static void setUpOutputEnvironment() throws Exception {
outPrefix = "SLDA-"
+ dataFileName.replace(".csv","")
+ "-T" + numFTopics
+ "-A" + alpha
+ "-B" + beta
+ "-G" + gamma;
if (outDir == null) outDir = inDir+"/"+outPrefix;
Files.createDirectories(Paths.get(outDir));
}
/**
* Loads stop words from the given file.
*
* @param stopwordsFileName the name of the stop words file.
*/
public static void loadStopwords(String stopwordsFileName) throws Exception {
if (stopwordsFileName != null) {
BufferedFileReader stopwordsFile = new BufferedFileReader(inDir+"/"+stopwordsFileName);
while (stopwordsFile.nextLine()) {
stopwords.add(stopwordsFile.readLine().trim());
}
stopwordsFile.close();
}
}
/**
* Loads instances from the data file. The loaded data is stored in
* temporary data structure {@link #rawDocs}, which is later indexized
* in {@link #indexizeInstances()}.
*/
public static void loadInstances() throws Exception {
System.out.println("Loading data...");
CSVParser inData = new CSVParser(
new FileReader(inDir+"/"+dataFileName), CSVFormat.DEFAULT.withHeader());
for (CSVRecord record : inData) {
String docId = record.get("DocId");
RawDocument doc = new RawDocument();
doc.text = record.get("Text");
if (tokenization) {
DocumentPreprocessor dp = new DocumentPreprocessor(new StringReader(doc.text));
for (List<HasWord> sentence : dp) {
Vector<String> words = new Vector<String>();
for (HasWord word : sentence) {
if (word.word().length()==0) continue;
String w = word.word().toLowerCase();
if (w.matches("^[\\d]+$")) w = "##NUMBER##";
if (stopwords.contains(w)) continue;
words.add(w);
if (updateParams) wordCnt.increase(w);
}
if (!words.isEmpty()) doc.sentences.add(words);
}
} else {
Vector<String> words = new Vector<String>();
for (String w : doc.text.split(" ")) {
if (w.length()==0) continue;
if (stopwords.contains(w)) continue;
words.add(w);
if (updateParams) wordCnt.increase(w);
}
if (!words.isEmpty()) doc.sentences.add(words);
}
if (!doc.sentences.isEmpty()) {
rawDocs.put(docId, doc);
}
}
inData.close();
}
/**
* Indexizes the words loaded from the data file and generates
* {@link #wordIndex} and {@link #wordList}.
*/
public static void indexizeWords() {
wordIndex = new TreeMap<String,Integer>();
wordList = new Vector<String>();
for (String word : wordCnt.keySet()) {
if (minNumWords > 0 && wordCnt.get(word) < minNumWords) continue;
wordIndex.put(word, wordIndex.size());
wordList.add(word);
}
numWords = wordIndex.size();
}
/**
* Indexizes the loaded instances by changing the words and authors with
* the corresponding indices. This methods generates {@link #seqs}.
*/
public static void indexizeInstances() {
for (String docId : rawDocs.keySet()) {
RawDocument rawDoc= rawDocs.get(docId);
Document doc = new Document();
for (Vector<String> rawSentence : rawDoc.sentences) {
Sentence sentence = new Sentence();
for (String word : rawSentence) {
Integer index = wordIndex.get(word);
if (index != null) sentence.words.add(new Word(index));
}
if (!sentence.words.isEmpty()) doc.sentences.add(sentence);
}
if (!doc.sentences.isEmpty()) {
doc.idx = docs.size();
docs.put(docId, doc);
}
}
numDocs = docs.size();
}
/**
* Initializes all parameters and variables.
*/
public static void initialize() throws Exception {
N_DT = new DoubleMatrix(numDocs, numFTopics);
if (updateParams) {
N_TW = new DoubleMatrix(numFTopics, numWords);
N_BW = new DoubleMatrix(numBTopics, numWords);
} else {
restoreModel();
}
sumAlpha = alpha * numFTopics;
sumBeta = beta * numWords;
// Randomly assign topics to sentences
Random random = new Random();
for (String docId : docs.keySet()) {
Document doc = docs.get(docId);
for (Sentence sentence : doc.sentences) {
int newTopic = random.nextInt(numFTopics);
sentence.fTopic = newTopic;
N_DT.incValue(doc.idx, newTopic);
for (Word word : sentence.words) {
// Choose between foreground & background
int level = (random.nextDouble() <= gamma ? 1 : 0);
word.level = level;
if (updateParams) {
if (level==1) { // Foreground
N_TW.incValue(newTopic, word.idx);
} else { // Background
N_BW.incValue(0, word.idx);
}
}
}
}
}
}
/**
* Saves {@link #wordCnt} to a file.
*/
public static void saveWords() throws Exception {
CSVPrinter outWordCount = new CSVPrinter(
new PrintFileWriter(outDir+"/"+outPrefix+"-WordCount.csv"), CSVFormat.EXCEL);
outWordCount.printRecord("Word","Count");
for (String word : wordList)
outWordCount.printRecord(word, wordCnt.get(word));
outWordCount.flush();
outWordCount.close();
}
/**
* Saves the current counter matrices to files.
*/
public static void saveModel(String dir, String prefix) throws Exception {
String outPrefix = dir+"/"+prefix;
N_TW.saveToCsvFile(outPrefix+"-N_FW.csv");
N_BW.saveToCsvFile(outPrefix+"-N_BW.csv");
}
/**
* Samples the foreground topics of the given documents.
*
* @param docIds the documents whose foreground topics are sampled.
*/
private static void sampleTopic(List<String> docIds) throws Exception {
for (String docId : docIds) {
Document doc = docs.get(docId);
for (Sentence sentence : doc.sentences) {
int oldTopic = sentence.fTopic;
// Remove old topic assignment for this sentence
N_DT.decValue(doc.idx, oldTopic);
if (updateParams) {
for (Word word : sentence.words) {
if (word.level == 0) continue;
V_TW.decValue(oldTopic, word.idx);
}
}
// Calculate the conditional probability of topic assignment
double [] probs = new double[numFTopics];
for (int t = 0; t < numFTopics; t++) {
probs[t] += Math.log(N_DT.getValue(doc.idx, t) + alpha);
for (Word word : sentence.words) {
if (word.level == 0) continue; // Ignore a background word
probs[t] += Math.log((V_TW.getValue(t, word.idx) + beta) / (V_TW.getRowSum(t) + sumBeta));
if (updateParams) V_TW.incValue(t, word.idx);
}
// Revert the counter
if (updateParams) {
for (Word word : sentence.words) {
if (word.level == 0) continue; // Ignore a background word
V_TW.decValue(t, word.idx);
}
}
}
// Randomly choose a new topic for the sentence
double maxLogP = max(probs);
for (int t = 0; t < numFTopics; t++)
probs[t] = Math.exp(probs[t] - maxLogP);
int newTopic = sampleIndex(probs);
sentence.fTopic = newTopic;
// Update the new topic assignment
N_DT.incValue(doc.idx, newTopic);
if (updateParams) {
for (Word word : sentence.words) {
if (word.level == 0) continue;
V_TW.incValue(newTopic, word.idx);
}
}
}
}
}
/**
* Samples the level ("foreground" or "background") of each word
* in the given documents.
*
* @param docIds the documents for which the level of each word is sampled.
*/
private static void sampleLevel(List<String> docIds) throws Exception {
for (String docId : docIds) {
Document doc = docs.get(docId);
for (Sentence sentence : doc.sentences) {
int fTopic = sentence.fTopic;
for (Word word : sentence.words) {
int wordIdx = word.idx;
int oldLevel = word.level;
// Remove the old level assignment for the words
if (updateParams) {
if (oldLevel == 1) {
V_TW.decValue(fTopic, wordIdx);
} else {
V_BW.decValue(0, wordIdx);
}
}
// Calculate the probability of FG & BG for this word
double [] probs = new double[2];
probs[0] = (V_BW.getValue(0, wordIdx) + beta) / (V_BW.getRowSum(0) + sumBeta) * (1-gamma);
probs[1] = (V_TW.getValue(fTopic, wordIdx) + beta) / (V_TW.getRowSum(fTopic) + sumBeta) * gamma;
int newLevel = sampleIndex(probs);
word.level = newLevel;
if (updateParams) {
if (newLevel == 1) {
word.level = 1;
V_TW.incValue(fTopic, wordIdx);
} else {
word.level = 0;
V_BW.incValue(0, wordIdx);
}
}
}
}
}
}
/**
* Returns the max value of the given array.
*
* @param v the double array from which the max value is returned.
* @return the max value of the given array.
* @throws Exception if the array is empty.
*/
public static double max(double[] v) throws Exception {
return Arrays.stream(v).max().orElseThrow(
() -> new RuntimeException("Array is empty"));
}
/**
* Returns a value drawn from the categorical distribution with
* the given array as its parameter.
*
* @param probs the parameter of the categorical distribution.
* @return the sampled index.
*/
public static int sampleIndex(double[] probs) throws Exception {
double[] cumulProbs = probs.clone();
Arrays.parallelPrefix(cumulProbs, (x,y) -> x+y);
double rand = Math.random() * cumulProbs[cumulProbs.length-1];
return IntStream.range(0, cumulProbs.length)
.filter(i -> cumulProbs[i] >= rand)
.findFirst()
.orElseThrow(() -> new Exception("Sampling failed"));
}
/**
* Restores pre-trained counter matrices from files.
*/
public static void restoreModel() throws Exception {
N_TW = DoubleMatrix.loadFromCsvFile(modelPathPrefix+"-N_FW.csv");
N_BW = DoubleMatrix.loadFromCsvFile(modelPathPrefix+"-N_BW.csv");
}
/**
* Loads indexed words {@link #wordCnt}, {@link #wordIndex},
* and {@link #wordList} from files.
*/
public static void loadWords() throws Exception {
// Load wordCount, wordIndex, and wordList
CSVParser csvWordCount = new CSVParser(
new BufferedFileReader(modelPathPrefix.replaceAll("-I\\d+$","")+"-WordCount.csv"),
CSVFormat.EXCEL.withHeader());
for (CSVRecord record : csvWordCount) {
String word = record.get("Word");
double cnt = Double.valueOf(record.get("Count"));
wordCnt.increase(word, cnt);
wordIndex.put(word, wordIndex.size());
wordList.add(word);
}
csvWordCount.close();
numWords = wordIndex.size();
}
/**
* Calculates and returns the log-likelihood of the data.
*
* @return the log-likelihood of the data.
*/
public static double logLikelihood() {
DoubleMatrix P_TW = N_TW.copy();
for (int r = 0; r < P_TW.getNumRows(); r++) {
double denom = P_TW.getRowSum(r) + sumBeta;
for (int c = 0; c < P_TW.getNumColumns(); c++)
P_TW.setValue(r,c, (P_TW.getValue(r,c)+beta) / denom);
}
DoubleMatrix P_BW = N_BW.copy();
for (int r = 0; r < P_BW.getNumRows(); r++) {
double denom = P_BW.getRowSum(r) + sumBeta;
for (int c = 0; c < P_BW.getNumColumns(); c++)
P_BW.setValue(r,c, (P_BW.getValue(r,c)+beta) / denom);
}
DoubleMatrix P_DT = N_DT.copy();
for (int r = 0; r < P_DT.getNumRows(); r++) {
double denom = P_DT.getRowSum(r) + sumAlpha;
for (int c = 0; c < P_DT.getNumColumns(); c++)
P_DT.setValue(r,c, (P_DT.getValue(r,c)+alpha) / denom);
}
double logP = 0;
for (String docId : docs.keySet()) {
Document doc = docs.get(docId);
DoubleMatrix N_T = new DoubleMatrix(1, numFTopics);
for (Sentence sentence : doc.sentences) {
int fTopic = sentence.fTopic;
// p(fTopic | doc)
logP += Math.log((N_T.getValue(0, fTopic) + alpha) / (N_T.getRowSum(0) + sumAlpha));
N_T.incValue(0, fTopic);
for (Word word : sentence.words) {
if (word.level == 1) {
logP += Math.log(gamma * P_TW.getValue(fTopic, word.idx));
} else {
logP += Math.log((1-gamma) * P_BW.getValue(0, word.idx));
}
}
}
}
return logP;
}
/**
* Generates output files.
*
* @param iter the iteration number of the results to be output.
*/
public static void genOutFiles(int iter) throws Exception {
saveModel(outDir, outPrefix+"-I"+iter);
// Theta
CSVPrinter outTheta = new CSVPrinter(new PrintFileWriter(outDir+"/"+outPrefix+"-I"+iter+"-Theta.csv"), CSVFormat.EXCEL);
outTheta.print("");
for (int t = 0; t < numFTopics; t++) outTheta.print("T"+t);
outTheta.println();
for (String docId : docs.keySet()) {
Document doc = docs.get(docId);
outTheta.print(docId);
for (int t = 0; t < numFTopics; t++)
outTheta.print((N_DT.getValue(doc.idx, t) + alpha) / (N_DT.getRowSum(doc.idx) + sumAlpha));
outTheta.println();
}
outTheta.flush();
outTheta.close();
// PhiF
CSVPrinter outPhiF = new CSVPrinter(new PrintFileWriter(outDir+"/"+outPrefix+"-I"+iter+"-PhiF.csv"), CSVFormat.EXCEL);
outPhiF.print("");
for (int t = 0; t < numFTopics; t++) outPhiF.print("T"+t);
outPhiF.println();
for (int w = 0; w < numWords; w++) {
outPhiF.print(wordList.get(w));
for (int t = 0; t < numFTopics; t++)
outPhiF.print((N_TW.getValue(t,w) + beta) / (N_TW.getRowSum(t) + sumBeta));
outPhiF.println();
}
outPhiF.flush();
outPhiF.close();
// PhiB
if (gamma > 0) {
CSVPrinter outPhiB = new CSVPrinter(new PrintFileWriter(outDir+"/"+outPrefix+"-I"+iter+"-PhiB.csv"), CSVFormat.EXCEL);
outPhiB.print("");
for (int t = 0; t < numBTopics; t++) outPhiB.print("BT"+t);
outPhiB.println();
for (int w = 0; w < numWords; w++) {
outPhiB.print(wordList.get(w));
for (int t = 0; t < numBTopics; t++)
outPhiB.print((N_BW.getValue(t, w) + beta) / (N_BW.getRowSum(t) + sumBeta));
outPhiB.println();
}
outPhiB.flush();
outPhiB.close();
}
// Top words for each FG topic
CSVPrinter outProbWordsF = new CSVPrinter(new PrintFileWriter(outDir+"/"+outPrefix+"-I"+iter+"-ProbWordsF.csv"), CSVFormat.EXCEL);
for (int t = 0; t < numFTopics; t++) outProbWordsF.print("T"+t);
outProbWordsF.println();
IntegerMatrix P_TW = N_TW.getSortedIndexMatrix(1, Math.min(numProbWords, numWords));
for (int p = 0; p < Math.min(numProbWords, numWords); p++) {
for (int t = 0; t < numFTopics; t++) {
int w = P_TW.getValue(t,p);
outProbWordsF.print(String.format("%s (%.3f)", wordList.get(w), (N_TW.getValue(t, w) + beta) / (N_TW.getRowSum(t) + sumBeta)));
}
outProbWordsF.println();
}
outProbWordsF.flush();
outProbWordsF.close();
// Top words for each BG topic
if (gamma > 0) {
CSVPrinter outProbWordsB = new CSVPrinter(new PrintFileWriter(outDir+"/"+outPrefix+"-I"+iter+"-ProbWordsB.csv"), CSVFormat.EXCEL);
for (int t = 0; t < numBTopics; t++) outProbWordsB.print("BT"+t);
outProbWordsB.println();
IntegerMatrix P_BW = N_BW.getSortedIndexMatrix(1, Math.min(numProbWords, numWords));
for (int p = 0; p < Math.min(numProbWords, numWords); p++) {
for (int t = 0; t < numBTopics; t++) {
int w = P_BW.getValue(t,p);
outProbWordsB.print(String.format("%s (%.3f)", wordList.get(w), (N_BW.getValue(t,w) + beta) / (N_BW.getRowSum(t) + sumBeta)));
}
outProbWordsB.println();
}
outProbWordsB.flush();
outProbWordsB.close();
}
// Sentence-topic assignment
CSVPrinter outInstAssign = new CSVPrinter(new PrintFileWriter(
outDir+"/"+outPrefix+"-I"+iter+"-InstAssign.csv"), CSVFormat.EXCEL);
outInstAssign.printRecord("DocId", "Sentence", "Text", "TaggedText", "Topic");
for (String docId : rawDocs.keySet()) {
Document doc = docs.get(docId);
if (doc == null) continue;
for (int s = 0; s < doc.sentences.size(); s++) {
Sentence sentence = doc.sentences.get(s);
String taggedText =
sentence.words.stream().map(w -> (
w.level == 1 ? "F"+sentence.fTopic+":"+wordList.get(w.idx)
: "B:"+wordList.get(w.idx)))
.collect(Collectors.joining(" "));
String rawSentence =
rawDocs.get(docId).sentences.get(s).stream()
.collect(Collectors.joining(" "));
outInstAssign.printRecord(docId, s, rawSentence, taggedText, sentence.fTopic);
}
}
outInstAssign.flush();
outInstAssign.close();
// Log-likelihood
if (logL.size() > 0) {
CSVPrinter outLogL = new CSVPrinter(new PrintFileWriter(
outDir+"/"+outPrefix+"-I"+iter+"-LogL.csv"), CSVFormat.EXCEL);
outLogL.printRecord("Iter","LogL");
for (Map.Entry<Integer,Double> entry : logL.entrySet()) {
outLogL.printRecord(entry.getKey(), entry.getValue());
}
outLogL.flush();
outLogL.close();
}
}
/**
* A raw document before being indexed.
*/
private static class RawDocument {
String text = null;
Vector<Vector<String>> sentences = new Vector<>();
}
/**
* A document.
*/
private static class Document {
int idx = -1;
Vector<Sentence> sentences = new Vector<>();
}
/**
* A sentence.
*/
private static class Sentence {
int fTopic = -1;
Vector<Word> words = new Vector<>();
}
/**
* A word.
*/
private static class Word {
int idx = -1;
int level = -1;
public Word(int id) {
this.idx = id;
}
}
}
| true
|
76ab39c2a301a54a80ddf7fa46fec437a1213128
|
Java
|
cenggel/thymeleaf-layout-dialect
|
/Source/nz/net/ultraq/thymeleaf/decorator/TitlePatternProcessor.java
|
UTF-8
| 4,878
| 2.28125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2012, Emanuel Rabina (http://www.ultraq.net.nz/)
*
* 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 nz.net.ultraq.thymeleaf.decorator;
import static nz.net.ultraq.thymeleaf.LayoutUtilities.HTML_ELEMENT_TITLE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.Arguments;
import org.thymeleaf.Configuration;
import org.thymeleaf.dom.Element;
import org.thymeleaf.dom.Text;
import org.thymeleaf.exceptions.TemplateProcessingException;
import org.thymeleaf.processor.ProcessorResult;
import org.thymeleaf.processor.attr.AbstractAttrProcessor;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.thymeleaf.util.StringUtils;
/**
* Allows for greater control of the resulting <title> element by
* specifying a pattern with some special tokens. This can be used to extend
* the decorator's title with the content's one, instead of simply overriding
* it.
*
* @author Emanuel Rabina
*/
public class TitlePatternProcessor extends AbstractAttrProcessor {
private static final Logger logger = LoggerFactory.getLogger(TitlePatternProcessor.class);
private static final String PARAM_TITLE_DECORATOR = "$DECORATOR_TITLE";
private static final String PARAM_TITLE_CONTENT = "$CONTENT_TITLE";
public static final String PROCESSOR_NAME_TITLEPATTERN = "title-pattern";
public static final String DECORATOR_TITLE = "title-pattern::decorator-title";
public static final String CONTENT_TITLE = "title-pattern::content-title";
/**
* Constructor, sets this processor to work on the 'title-pattern' attribute.
*/
public TitlePatternProcessor() {
super(PROCESSOR_NAME_TITLEPATTERN);
}
/**
* {@inheritDoc}
*/
@Override
public int getPrecedence() {
return 1;
}
/**
* {@inheritDoc}
*/
@Override
protected ProcessorResult processAttribute(Arguments arguments, Element element, String attributeName) {
// Ensure this attribute is only on the <title> element
if (!element.getNormalizedName().equals(HTML_ELEMENT_TITLE)) {
logger.error("layout:title-pattern attribute should only appear in a <title> element");
throw new IllegalArgumentException("layout:title-pattern attribute should only appear in a <title> element");
}
Configuration configuration = arguments.getConfiguration();
IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration);
// Process the decorator and content title parts
String decoratortitle = processTitle((String)element.getNodeProperty(DECORATOR_TITLE),
arguments, configuration, parser);
String contenttitle = processTitle((String)element.getNodeProperty(CONTENT_TITLE),
arguments, configuration, parser);
// Replace the <title> text with an expanded title pattern expression,
// only using the pattern if both the decorator and content have a title.
String titlepattern = element.getAttributeValue(attributeName);
String title =
decoratortitle != null ? contenttitle != null ?
titlepattern
.replace(PARAM_TITLE_DECORATOR, decoratortitle)
.replace(PARAM_TITLE_CONTENT, contenttitle) :
decoratortitle :
contenttitle != null ? contenttitle : "";
element.clearChildren();
element.addChild(new Text(title));
element.removeAttribute(attributeName);
return ProcessorResult.OK;
}
/**
* Process a title part, executing expressions if it contains any.
*
* @param title
* @param arguments
* @param configuration
* @param parser
* @return The result of executing <tt>title</tt> if it contained any
* expressions, or <tt>null</tt> if the title resolved to an empty
* string or whitespace.
*/
private static String processTitle(String title, Arguments arguments,
Configuration configuration, IStandardExpressionParser parser) {
String titlevalue;
try {
titlevalue = title == null ? null :
parser.parseExpression(configuration, arguments, title)
.execute(configuration, arguments)
.toString();
}
catch (TemplateProcessingException ex) {
titlevalue = title;
}
titlevalue = StringUtils.isEmptyOrWhitespace(titlevalue) ? null : titlevalue.trim();
return titlevalue;
}
}
| true
|
5b31ae4fc47a838efb3d103eb0a50141775baa3e
|
Java
|
screenhunter/High-School
|
/High School/CodingBat_Java/src/Array2/Array2_withoutTen.java
|
UTF-8
| 558
| 3.140625
| 3
|
[] |
no_license
|
package Array2;
import java.io.IOException;
public class Array2_withoutTen {
public static int[] withoutTen(int[] nums) {
int[] result = new int[nums.length];
int j = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 10) {
} else {
result[j] = nums[i];
j++;
}
}
for (int i = j; i < nums.length; i++) {
result[i] = 0;
}
return result;
}
public static void main (String[] args) throws IOException {
int[] nums = {};
System.out.println(withoutTen(nums));
}
}
| true
|
00515fb32acb250d2dab030fcb2e3fb3b5b00006
|
Java
|
agnjeszka/ProjGr
|
/ProjGr/src/pg/is/projgr/graphs/BarGraph.java
|
WINDOWS-1250
| 1,958
| 2.453125
| 2
|
[] |
no_license
|
package pg.is.projgr.graphs;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import pg.is.projgr.actions.StatisticDataGenerator;
import android.content.Context;
import android.graphics.Color;
public class BarGraph {
private float[] _expenses;
private String _title;
public BarGraph(float[] array, String title){
_expenses=array;
_title=title;
}
public GraphicalView getView(Context context)
{
float[] x=_expenses;
CategorySeries series = new CategorySeries("Wydatki");
for (int i=0;i<x.length;i++)
{
series.add("Bar "+(i+1),x[i]);
}
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(series.toXYSeries());
XYSeriesRenderer renderer = new XYSeriesRenderer();
renderer.setDisplayChartValues(true);
renderer.setChartValuesSpacing((float)0.45);
renderer.setColor(Color.rgb(33, 99, 99));
XYMultipleSeriesRenderer mrenderer = new XYMultipleSeriesRenderer();
mrenderer.addSeriesRenderer(renderer);
mrenderer.setBackgroundColor(Color.BLACK);
mrenderer.setApplyBackgroundColor(true);
mrenderer.setChartTitle(_title);
mrenderer.setYTitle("Kwota");
mrenderer.setXTitle("Miesice");
mrenderer.setBarSpacing((float)1);
mrenderer.setGridColor(Color.DKGRAY);
mrenderer.setShowGrid(true);
mrenderer.setZoomButtonsVisible(false);
mrenderer.setZoomEnabled(true);
mrenderer.setYAxisMin(0);
mrenderer.setYAxisMax(StatisticDataGenerator.GetMax(_expenses));
mrenderer.setXAxisMin(0);
mrenderer.setXAxisMax(x.length+1);
return ChartFactory.getBarChartView(context, dataset, mrenderer, Type.DEFAULT);
}
}
| true
|
932af522e9905bafd88fc6b15ec782b8dfb9151b
|
Java
|
InnovateUKGitHub/innovation-funding-service
|
/common/ifs-rest-api-service/src/test/java/org/innovateuk/ifs/user/service/RoleProfileStatusRestServiceTest.java
|
UTF-8
| 2,057
| 2.15625
| 2
|
[
"MIT"
] |
permissive
|
package org.innovateuk.ifs.user.service;
import org.innovateuk.ifs.BaseRestServiceUnitTest;
import org.innovateuk.ifs.user.resource.ProfileRole;
import org.innovateuk.ifs.user.resource.RoleProfileStatusResource;
import org.junit.Test;
import org.springframework.core.ParameterizedTypeReference;
import java.util.List;
import static java.lang.String.format;
import static org.innovateuk.ifs.user.builder.RoleProfileStatusResourceBuilder.newRoleProfileStatusResource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class RoleProfileStatusRestServiceTest extends BaseRestServiceUnitTest<RoleProfileStatusRestServiceImpl> {
private String restUrl = "/user/%d/role-profile-status";
@Override
protected RoleProfileStatusRestServiceImpl registerRestServiceUnderTest() {
return new RoleProfileStatusRestServiceImpl();
}
@Test
public void updateUserStatus() {
long userId = 1L;
RoleProfileStatusResource resource = new RoleProfileStatusResource();
setupPutWithRestResultExpectations(format(restUrl, userId), resource);
assertTrue(service.updateUserStatus(userId, resource).isSuccess());
}
@Test
public void findByUserId() {
long userId = 1L;
List<RoleProfileStatusResource> resources = newRoleProfileStatusResource().build(1);
setupGetWithRestResultExpectations(format(restUrl, userId), new ParameterizedTypeReference<List<RoleProfileStatusResource>>() {}, resources);
assertEquals(resources, service.findByUserId(userId).getSuccess());
}
@Test
public void findByUserIdAndProfileRole() {
long userId = 1L;
ProfileRole role = ProfileRole.ASSESSOR;
RoleProfileStatusResource resource = newRoleProfileStatusResource().build();
setupGetWithRestResultExpectations(format(restUrl, userId) + "/" + role.name(), RoleProfileStatusResource.class, resource);
assertEquals(resource, service.findByUserIdAndProfileRole(userId, role).getSuccess());
}
}
| true
|
1ef5acbdc024aee79c294a8721bbf592bf8a9b32
|
Java
|
Katinuta/My_tasks
|
/src/Account/DepositAccount.java
|
UTF-8
| 1,087
| 3.515625
| 4
|
[] |
no_license
|
package Account;
/**
* Class DepositAccount contains constructors for create objects implements
* methods interface Depositable, override method toString
*/
public class DepositAccount extends Account implements Depositable {
DepositAccount() {
}
DepositAccount(int numberOfAccount, TypeOfCurrency currencyOfAccount, double balance) {
this.currencyOfAccount = currencyOfAccount;
this.numberOfAccount = numberOfAccount;
this.typeOfAccount = "deposit";
this.status = true;
this.balance = balance;
}
@Override
public double getIncome(double percantageInCome) {
double income = balance * percantageInCome / 100;
return income;
}
@Override
public void excludeDeposit(double sum) {
balance -= sum;
}
@Override
public String toString() {
return "Номер договора: " + numberOfAccount + ", тип валюты: " + currencyOfAccount.toString() + ", тип счета: "
+ typeOfAccount + ", остаток: " + balance;
}
@Override
public void addBalance(double sum) {
balance += sum;
}
}
| true
|
c136d86962625c0f37e529ac1d598b605de5379b
|
Java
|
cooligc/OtherRepo
|
/MyGoogleApi/src/main/java/com/skc/api/google/app/GmailAPIDemo.java
|
UTF-8
| 4,073
| 2.25
| 2
|
[] |
no_license
|
package com.skc.api.google.app;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.springframework.stereotype.Component;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleOAuthConstants;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.ListThreadsResponse;
@Component("gmailService")
@Path("/gmail")
public class GmailAPIDemo {
// Check https://developers.google.com/gmail/api/auth/scopes for all available scopes
private static final String SCOPE = "https://www.googleapis.com/auth/gmail.readonly";
private static final String APP_NAME = "Gmail API Quickstart";
// Email address of the user, or "me" can be used to represent the currently authorized user.
private static final String USER = "me";
// Path to the client_secret.json file downloaded from the Developer Console
private String clientCertPath;//"client_secret.json";
private static GoogleClientSecrets clientSecrets;
@GET
public Response getResponse() throws IOException {
GmailAPIDemo apiDemo = new GmailAPIDemo();
System.out.println(apiDemo.getClientCertPath());
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(apiDemo.getClientCertPath()));
// Allow user to authorize via url.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, clientSecrets, Arrays.asList(SCOPE))
.setAccessType("online")
.setApprovalPrompt("auto").build();
String url = flow.newAuthorizationUrl().setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI)
.build();
System.out.println("Please open the following URL in your browser then type"
+ " the authorization code:\n" + url);
// Read code entered by user.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = br.readLine();
// Generate Credential using retrieved code.
GoogleTokenResponse response = flow.newTokenRequest(code)
.setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).execute();
GoogleCredential credential = new GoogleCredential()
.setFromTokenResponse(response);
// Create a new authorized Gmail API client
Gmail service = new Gmail.Builder(httpTransport, jsonFactory, credential)
.setApplicationName(APP_NAME).build();
// Retrieve a page of Threads; max of 100 by default.
ListThreadsResponse threadsResponse = service.users().threads().list(USER).execute();
List<com.google.api.services.gmail.model.Thread> threads = threadsResponse.getThreads();
// Print ID of each Thread.
for (com.google.api.services.gmail.model.Thread thread : threads) {
System.out.println("Thread ID: " + thread.getId());
}
return Response.status(Status.OK).build();
}
/**
* @return the clientCertPath
*/
public String getClientCertPath() {
return clientCertPath;
}
/**
* @param clientCertPath the clientCertPath to set
*/
public void setClientCertPath(String clientCertPath) {
this.clientCertPath = this.getClass().getClassLoader().getResource("client_secret.json").getPath();;
}
}
| true
|
fd0a660ff07aecb3c69bbbf895f7b14ca702e462
|
Java
|
okzhu/OKTools
|
/oktools-toolkit/src/main/java/com/github/okzhu/toolkit/base/type/EnumUtil.java
|
UTF-8
| 1,431
| 3.078125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.github.okzhu.toolkit.base.type;
import org.apache.commons.lang3.EnumUtils;
import java.util.Set;
/**
* @author Administrator
*/
public class EnumUtil {
private EnumUtil() {
}
/**
* 将若干个枚举值转换为long(按bits 1,2,4,8...的方式叠加),用于使用long保存多个选项的情况.
*/
public static <E extends Enum<E>> long generateBits(final Class<E> enumClass, final Iterable<? extends E> values) {
return EnumUtils.generateBitVector(enumClass, values);
}
/**
* 将若干个枚举值转换为long(按bits 1,2,4,8...的方式叠加),用于使用long保存多个选项的情况.
*/
public static <E extends Enum<E>> long generateBits(final Class<E> enumClass, final E... values) {
return EnumUtils.generateBitVector(enumClass, values);
}
/**
* long重新解析为若干个枚举值,用于使用long保存多个选项的情况.
*/
public static <E extends Enum<E>> Set<E> processBits(final Class<E> enumClass, final long value) {
return EnumUtils.processBitVector(enumClass, value);
}
/**
* Enum转换为String
*/
public static String toString(Enum<?> e) {
return e.name();
}
/**
* String转换为Enum
*/
public static <T extends Enum<T>> T fromString(Class<T> enumClass, String value) {
return Enum.valueOf(enumClass, value);
}
}
| true
|
deb8504d4a172ec2068e969fa64149af778574dd
|
Java
|
HoangAnhPTIT/Student-Manager
|
/src/main/java/com/hoanganh/service/impl/UserService.java
|
UTF-8
| 3,686
| 2.375
| 2
|
[] |
no_license
|
package com.hoanganh.service.impl;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.hoanganh.DTO.StudentDTO;
import com.hoanganh.DTO.TeacherDTO;
import com.hoanganh.DTO.UserDTO;
import com.hoanganh.entity.StudentEntity;
import com.hoanganh.entity.TeacherEntity;
import com.hoanganh.entity.UserEntity;
import com.hoanganh.repository.StudentRepository;
import com.hoanganh.repository.TeacherRepository;
import com.hoanganh.repository.UserRepository;
import com.hoanganh.service.IUserService;
@Service
@Transactional
public class UserService implements IUserService {
@Autowired
private StudentRepository studentRepository;
@Autowired
private TeacherRepository teacherRepository;
@Autowired
private UserRepository userRepository;
private ModelMapper modelMapper = new ModelMapper();
@PersistenceContext
EntityManager entityManager;
@Override
public List<UserDTO> findAll() {
List<UserEntity> userEntity = userRepository.findAll();
List<UserDTO> users = new ArrayList<>();
for (UserEntity item : userEntity) {
users.add(modelMapper.map(item, UserDTO.class));
}
return users;
}
@Override
public List<TeacherDTO> findTeacherByCodeLike(String code, Pageable pageable) {
List<UserEntity> userEntity = userRepository.findBycodeLike(code, pageable);
List<TeacherDTO> teachers = new ArrayList<>();
for (UserEntity item : userEntity) {
TeacherEntity teacherEntity = teacherRepository.findByuser(item);
TeacherDTO teacher = modelMapper.map(item, TeacherDTO.class);
teacher.setExperience(teacherEntity.getExperience());
teacher.setSalary(teacherEntity.getSalary());
teacher.setSubject(teacherEntity.getSubject());
teachers.add(teacher);
}
return teachers;
}
@Override
public List<StudentDTO> findStudentByCodeLike(String code, Pageable pageable) {
List<UserEntity> userEntity = userRepository.findBycodeLike(code, pageable);
List<StudentDTO> students = new ArrayList<>();
for (UserEntity item : userEntity) {
students.add(modelMapper.map(item, StudentDTO.class));
}
return students;
}
@Override
public void save(UserDTO user) {
UserEntity userEntity = new UserEntity();
StudentEntity studentEntity = new StudentEntity();
userEntity.addStudent(studentEntity);
if (user.getId() == null) {
entityManager.persist(userEntity);
} else {
entityManager.merge(userEntity);
}
}
@Override
public UserDTO findById(Long id) {
UserEntity userEntity = userRepository.findByid(id);
return modelMapper.map(userEntity, UserDTO.class);
}
@Override
public TeacherDTO findTeacherById(Long id) {
UserEntity userEntity = userRepository.findByid(id);
TeacherEntity teacherEntity = teacherRepository.findByuser(userEntity);
TeacherDTO teacher = modelMapper.map(userEntity, TeacherDTO.class);
teacher.setExperience(teacherEntity.getExperience());
teacher.setSalary(teacherEntity.getSalary());
teacher.setSubject(teacherEntity.getSubject());
return teacher;
}
@Override
public StudentDTO findStudentById(Long id) {
UserEntity userEntity = userRepository.findByid(id);
StudentEntity studentEntity = studentRepository.findByuser(userEntity); // Them sau
StudentDTO student = modelMapper.map(userEntity, StudentDTO.class);
return student;
}
@Override
public int countByCodeLike(String code) {
return userRepository.countBycodeLike(code);
}
}
| true
|
893427b48a99375ebb1acfae4e27864c7a9352ca
|
Java
|
BrunoEberhard/minimal-j
|
/src/main/java/org/minimalj/frontend/form/Form.java
|
UTF-8
| 26,058
| 1.585938
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.minimalj.frontend.form;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.minimalj.application.Configuration;
import org.minimalj.frontend.Frontend;
import org.minimalj.frontend.Frontend.FormContent;
import org.minimalj.frontend.Frontend.IComponent;
import org.minimalj.frontend.form.element.BigDecimalFormElement;
import org.minimalj.frontend.form.element.CheckBoxFormElement;
import org.minimalj.frontend.form.element.CodeFormElement;
import org.minimalj.frontend.form.element.Enable;
import org.minimalj.frontend.form.element.EnumFormElement;
import org.minimalj.frontend.form.element.EnumSetFormElement;
import org.minimalj.frontend.form.element.FormElement;
import org.minimalj.frontend.form.element.Indication;
import org.minimalj.frontend.form.element.IntegerFormElement;
import org.minimalj.frontend.form.element.LocalDateFormElement;
import org.minimalj.frontend.form.element.LocalDateTimeFormElement;
import org.minimalj.frontend.form.element.LocalTimeFormElement;
import org.minimalj.frontend.form.element.LongFormElement;
import org.minimalj.frontend.form.element.PasswordFormElement;
import org.minimalj.frontend.form.element.SelectionFormElement;
import org.minimalj.frontend.form.element.SmallCodeListFormElement;
import org.minimalj.frontend.form.element.StringFormElement;
import org.minimalj.frontend.form.element.TableFormElement;
import org.minimalj.frontend.form.element.TextFormElement;
import org.minimalj.frontend.form.element.UnknownFormElement;
import org.minimalj.model.Code;
import org.minimalj.model.Keys;
import org.minimalj.model.Selection;
import org.minimalj.model.annotation.Enabled;
import org.minimalj.model.annotation.NotEmpty;
import org.minimalj.model.annotation.Visible;
import org.minimalj.model.properties.ChainedProperty;
import org.minimalj.model.properties.PropertyInterface;
import org.minimalj.model.validation.ValidationMessage;
import org.minimalj.security.model.Password;
import org.minimalj.util.ChangeListener;
import org.minimalj.util.CloneHelper;
import org.minimalj.util.Codes;
import org.minimalj.util.EqualsHelper;
import org.minimalj.util.ExceptionUtils;
import org.minimalj.util.FieldUtils;
import org.minimalj.util.mock.Mocking;
public class Form<T> {
private static Logger logger = Logger.getLogger(Form.class.getSimpleName());
public static final boolean EDITABLE = true;
public static final boolean READ_ONLY = false;
public static final int DEFAULT_COLUMN_WIDTH = 100;
public static final Object GROW_FIRST_ELEMENT = new Object();
protected final boolean editable;
private final int columns;
private final FormContent formContent;
private boolean ignoreCaption;
private final LinkedHashMap<PropertyInterface, FormElement<?>> elements = new LinkedHashMap<>();
private final FormChangeListener formChangeListener = new FormChangeListener();
private ChangeListener<Form<?>> changeListener;
private boolean changeFromOutside;
private final LinkedHashMap<String, List<PropertyInterface>> dependencies = new LinkedHashMap<>();
@SuppressWarnings("rawtypes")
private final LinkedHashMap<PropertyInterface, LinkedHashMap<PropertyInterface, PropertyUpdater>> propertyUpdater = new LinkedHashMap<>();
private final Map<IComponent, Object[]> keysForTitle = new HashMap<>();
private T object;
public Form() {
this(EDITABLE);
}
public Form(boolean editable) {
this(editable, 1);
}
public Form(int columns) {
this(EDITABLE, columns);
}
public Form(boolean editable, int columns) {
this(editable, columns, DEFAULT_COLUMN_WIDTH);
}
public Form(boolean editable, int columns, int columnWidth) {
this.editable = editable;
this.columns = columns;
this.formContent = Frontend.getInstance().createFormContent(columns, columnWidth);
}
public Form(boolean editable, List<Integer> columnWidths) {
this.editable = editable;
this.columns = columnWidths.size();
this.formContent = Frontend.getInstance().createFormContent(columnWidths);
}
// Methods to create the form
public FormContent getContent() {
return formContent;
}
protected FormElement<?> createElement(Object key) {
FormElement<?> element = null;
PropertyInterface property;
boolean forcedReadonly = false;
if (key instanceof ReadOnlyWrapper) {
forcedReadonly = true;
key = ((ReadOnlyWrapper) key).key;
}
if (key == null) {
throw new NullPointerException("Key must not be null");
} else if (key instanceof Function) {
return createElement(((Function) key).apply(this.editable && !forcedReadonly));
} else if (key instanceof FormElement) {
element = (FormElement<?>) key;
property = element.getProperty();
if (property == null)
throw new IllegalArgumentException(IComponent.class.getSimpleName() + " has no key");
} else {
property = Keys.getProperty(key);
if (property != null) {
boolean editable = !forcedReadonly && this.editable && !(FieldUtils.isAllowedPrimitive(property.getClazz()) && property.isFinal());
element = createElement(property, editable);
}
}
return element;
}
@SuppressWarnings("rawtypes")
protected FormElement<?> createElement(PropertyInterface property, boolean editable) {
Class<?> fieldClass = property.getClazz();
if (fieldClass == String.class) {
return editable ? new StringFormElement(property) : new TextFormElement(property);
} else if (fieldClass == Boolean.class) {
return new CheckBoxFormElement(property, editable);
} else if (fieldClass == Integer.class) {
return new IntegerFormElement(property, editable);
} else if (fieldClass == Long.class) {
return new LongFormElement(property, editable);
} else if (fieldClass == BigDecimal.class) {
return new BigDecimalFormElement(property, editable);
} else if (fieldClass == LocalDate.class) {
return new LocalDateFormElement(property, editable);
} else if (fieldClass == LocalTime.class) {
return new LocalTimeFormElement(property, editable);
} else if (fieldClass == LocalDateTime.class) {
return new LocalDateTimeFormElement(property, editable);
} else if (Code.class.isAssignableFrom(fieldClass)) {
return editable ? new CodeFormElement(property) : new TextFormElement(property);
} else if (Enum.class.isAssignableFrom(fieldClass)) {
return editable ? new EnumFormElement(property) : new TextFormElement(property);
} else if (fieldClass == Set.class) {
return new EnumSetFormElement(property, editable);
} else if (fieldClass == List.class && Codes.isCode(property.getGenericClass())) {
return new SmallCodeListFormElement(property, editable);
} else if (fieldClass == Password.class) {
return new PasswordFormElement(new ChainedProperty(property, Keys.getProperty(Password.$.getPassword())));
} else if (fieldClass == Selection.class) {
return new SelectionFormElement(property);
}
logger.severe("No FormElement could be created for: " + property.getName() + " of class " + fieldClass.getName());
return new UnknownFormElement(property);
}
public void setIgnoreCaption(boolean ignoreCaption) {
this.ignoreCaption = ignoreCaption;
}
//
public void line(Object... keys) {
if (keys[0] == GROW_FIRST_ELEMENT) {
assertColumnCount(keys.length - 1);
for (int i = 1; i < keys.length; i++) {
int elementSpan = i == 1 ? columns - keys.length + 2 : 1;
add(keys[i], elementSpan);
}
} else {
assertColumnCount(keys.length);
int span = columns / keys.length;
int rest = columns;
for (int i = 0; i < keys.length; i++) {
int elementSpan = span;
while (i < keys.length - 1 && keys[i + 1] == keys[i]) {
elementSpan += span;
i++;
}
if (i == keys.length - 1) {
elementSpan = rest;
}
add(keys[i], elementSpan);
rest = rest - elementSpan;
}
}
}
private void assertColumnCount(int elementCount) {
if (elementCount > columns) {
logger.severe("This form was constructed for " + columns + " column(s) but should be filled with " + elementCount + " form elements");
logger.fine("The solution is most probably to add/set the correct number of columns when calling the Form constructor");
throw new IllegalArgumentException("Not enough columns (" + columns + ") for form elements (" + elementCount + ")");
}
}
private void add(Object key, int elementSpan) {
boolean forcedNotEmpty = false;
if (key instanceof NotEmptyWrapper) {
forcedNotEmpty = true;
key = ((NotEmptyWrapper) key).key;
}
FormElement<?> element = createElement(key);
if (element != null) {
add(element, elementSpan, forcedNotEmpty);
} else {
formContent.add(null, false, Frontend.getInstance().createText("" + key), null, elementSpan);
}
}
private void add(FormElement<?> element, int span, boolean forcedNotEmpty) {
boolean required = forcedNotEmpty || element.getProperty().getAnnotation(NotEmpty.class) != null && element.getProperty().getClazz() != Boolean.class && !(element instanceof TextFormElement);
formContent.add(ignoreCaption ? null : element.getCaption(), required, element.getComponent(), element.getConstraint(), span);
registerNamedElement(element);
addDependencies(element);
}
//
public static Object readonly(Object key) {
ReadOnlyWrapper wrapper = new ReadOnlyWrapper();
wrapper.key = key;
return wrapper;
}
private static class ReadOnlyWrapper {
private Object key;
}
public static Object notEmpty(Object key, boolean notEmpty) {
return notEmpty ? notEmpty(key) : key;
}
public static Object notEmpty(Object key) {
NotEmptyWrapper wrapper = new NotEmptyWrapper();
wrapper.key = key;
return wrapper;
}
private static class NotEmptyWrapper {
private Object key;
}
public void addTitle(String text, Object... keys) {
IComponent label = Frontend.getInstance().createTitle(text);
formContent.add(null, false, label, null, -1);
if (keys.length > 0) {
keysForTitle.put(label, keys);
}
}
//
/**
* Declares that if the <i>from</i> property changes all the properties with
* <i>to</i> could change. This is normally used if the to <i>to</i> property is
* a getter that calculates something that depends on the <i>from</i> in some
* way.
*
* @param from the key or property of the field triggering the update
* @param to the field possible changed its value implicitly
*/
public void addDependecy(Object from, Object... to) {
PropertyInterface fromProperty = Keys.getProperty(from);
List<PropertyInterface> list = dependencies.computeIfAbsent(fromProperty.getPath(), p -> new ArrayList<>());
for (Object key : to) {
list.add(Objects.requireNonNull(Keys.getProperty(key)));
}
}
private void addDependecy(PropertyInterface fromProperty, PropertyInterface to) {
addDependecy(fromProperty.getPath(), to);
}
private void addDependecy(String fromPropertyPath, PropertyInterface to) {
List<PropertyInterface> list = dependencies.computeIfAbsent(fromPropertyPath, p -> new ArrayList<>());
list.add(to);
}
/**
* Declares that if the key or property <i>from</i> changes the specified
* updater should be called and after its return the <i>to</i> key or property
* could have changed.
* <p>
*
* This is used if there is a more complex relation between two fields.
*
* @param <FROM> the type (class) of the fromKey / field
* @param <TO> the type (class) of the toKey / field
* @param from the field triggering the update
* @param updater the updater doing the change of the to field
* @param to the changed field by the updater
*/
public <FROM, TO> void addDependecy(FROM from, PropertyUpdater<FROM, TO, T> updater, TO to) {
PropertyInterface fromProperty = Keys.getProperty(from);
PropertyInterface toProperty = Keys.getProperty(to);
propertyUpdater.computeIfAbsent(fromProperty, p -> new LinkedHashMap<>()).put(toProperty, updater);
addDependecy(from, to);
}
@FunctionalInterface
public interface PropertyUpdater<FROM, TO, EDIT_OBJECT> {
/**
*
* @param input The new value of the property that has changed
* @param copyOfEditObject The current object of the This reference should
* <b>not</b> be changed. It should be treated as a read
* only version or a copy of the object. It's probably
* not a real copy as it is to expensive to copy the
* object for every call.
* @return The new value the updater wants to set to the toKey property
*/
public TO update(FROM input, EDIT_OBJECT copyOfEditObject);
}
//
private void registerNamedElement(FormElement<?> field) {
elements.put(field.getProperty(), field);
field.setChangeListener(formChangeListener);
}
private void addDependencies(FormElement<?> field) {
PropertyInterface property = field.getProperty();
List<PropertyInterface> dependencies = Keys.getDependencies(property);
for (PropertyInterface dependency : dependencies) {
addDependecy(dependency, field.getProperty());
}
// a.b.c
String path = property.getPath();
while (path != null && path.contains(".")) {
int pos = path.lastIndexOf('.');
addDependecy(path.substring(0, pos), property);
path = path.substring(0, pos);
}
}
public final void mock() {
changeFromOutside = true;
try {
fillWithDemoData(object);
} catch (Exception x) {
logger.log(Level.SEVERE, "Fill with demo data failed", x);
} finally {
readValueFromObject();
changeFromOutside = false;
}
}
protected void fillWithDemoData(T object) {
for (FormElement<?> field : elements.values()) {
PropertyInterface property = field.getProperty();
if (field instanceof Mocking) {
Mocking demoEnabledElement = (Mocking) field;
demoEnabledElement.mock();
property.setValue(object, field.getValue());
}
}
}
//
/**
*
* @return Collection provided by a LinkedHashMap so it will be a ordered set
*/
public Collection<PropertyInterface> getProperties() {
return elements.keySet();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void set(PropertyInterface property, Object value) {
FormElement element = elements.get(property);
try {
element.setValue(value);
} catch (Exception x) {
ExceptionUtils.logReducedStackTrace(logger, x);
}
}
private void setValidationMessage(PropertyInterface property, List<ValidationMessage> validationMessages) {
FormElement<?> formElement = elements.get(property);
if (formElement instanceof TableFormElement) {
// TODO make tableFormElement to Indication
TableFormElement<?> tableFormElement = (TableFormElement<?>) formElement;
tableFormElement.setValidationMessages(validationMessages);
} else if (formElement instanceof Indication) {
Indication indication = (Indication) formElement;
List<ValidationMessage> localValidationMessages = new ArrayList<>(validationMessages.size());
int prefixSize = ChainedProperty.getChain(property).size();
for (ValidationMessage message : validationMessages) {
List<PropertyInterface> chain = ChainedProperty.getChain(message.getProperty());
chain = chain.subList(prefixSize, chain.size());
ValidationMessage localValidationMessage = new ValidationMessage(chain.size() > 0 ? ChainedProperty.buildChain(chain) : null, message.getFormattedText());
localValidationMessages.add(localValidationMessage);
}
indication.setValidationMessages(localValidationMessages, formContent);
} else {
formContent.setValidationMessages(formElement.getComponent(), validationMessages.stream().map(ValidationMessage::getFormattedText).collect(Collectors.toList()));
}
}
public void setObject(T object) {
if (editable && changeListener == null)
throw new IllegalStateException("Listener has to be set on a editable Form");
if (logger.isLoggable(Level.FINE)) {
logDependencies();
}
changeFromOutside = true;
this.object = object;
readValueFromObject();
changeFromOutside = false;
}
private void readValueFromObject() {
for (PropertyInterface property : getProperties()) {
Object propertyValue = property.getValue(object);
set(property, propertyValue);
}
updateEnable();
updateVisible();
}
private void logDependencies() {
logger.fine("Dependencies in " + this.getClass().getSimpleName());
for (Map.Entry<String, List<PropertyInterface>> entry : dependencies.entrySet()) {
logger.fine(entry.getKey() + " -> " + entry.getValue().stream().map(PropertyInterface::getPath).collect(Collectors.joining(", ")));
}
}
private String getName(FormElement<?> field) {
PropertyInterface property = field.getProperty();
return property.getName();
}
public void setChangeListener(ChangeListener<Form<?>> changeListener) {
this.changeListener = Objects.requireNonNull(changeListener);
}
private class FormChangeListener implements ChangeListener<FormElement<?>> {
@Override
public void changed(FormElement<?> changedField) {
if (changeFromOutside)
return;
if (changeListener == null) {
if (editable)
logger.severe("Editable Form must have a listener");
return;
}
PropertyInterface property = changedField.getProperty();
Object newValue = changedField.getValue();
logger.finer(() -> "ChangeEvent from element: " + getName(changedField) + ", property: " + property.getPath() + ", value: " + newValue);
HashSet<PropertyInterface> changedProperties = new HashSet<>();
setValue(property, newValue, changedProperties);
logger.finer(() -> "Changed properties: " + changedProperties.stream().map(PropertyInterface::getPath).collect(Collectors.joining(", ")));
if (!changedProperties.isEmpty()) {
// propagate all possible changed values to the form elements
updateDependingFormElements(changedField, changedProperties);
// update enable/disable status of the form elements
updateEnable();
updateVisible();
changeListener.changed(Form.this);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void updateDependingFormElements(FormElement<?> changedFormElement, HashSet<PropertyInterface> changedProperties) {
for (PropertyInterface changedProperty : changedProperties) {
for (FormElement formElement : elements.values()) {
if (formElement == changedFormElement) {
// don't need to update the FormElement where the change comes from
continue;
}
PropertyInterface formElementProperty = formElement.getProperty();
String formElementPath = formElementProperty.getPath();
String changedPropertyPath = changedProperty.getPath();
if (formElementPath.equals(changedPropertyPath) || formElementPath.startsWith(changedPropertyPath) && formElementPath.charAt(changedPropertyPath.length()) == '.') {
Object newValue = formElementProperty.getValue(object);
formElement.setValue(newValue);
}
}
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void executeUpdater(PropertyInterface property, Object updaterInput, Object clonedObject, HashSet<PropertyInterface> changedProperties) {
if (propertyUpdater.containsKey(property)) {
Map<PropertyInterface, PropertyUpdater> updaters = propertyUpdater.get(property);
for (Map.Entry<PropertyInterface, PropertyUpdater> entry : updaters.entrySet()) {
logger.finer(() -> "Update from " + property.getPath() + " to " + entry.getKey().getPath());
Object updaterOutput = entry.getValue().update(updaterInput, clonedObject);
setValue(entry.getKey(), updaterOutput, changedProperties);
}
}
}
private void setValue(PropertyInterface property, Object newValue, HashSet<PropertyInterface> changedProperties) {
Object oldValue = property.getValue(object);
logger.finest(() -> "Set " + property.getPath() + " to " + newValue + " (previous: " + oldValue + ")");
if (!EqualsHelper.equals(oldValue, newValue) || newValue instanceof Collection) {
Object clonedObject = CloneHelper.clone(object); // clone before change!
property.setValue(object, newValue);
executeUpdater(property, newValue, clonedObject, changedProperties);
addChangedPropertyRecursive(property, changedProperties);
} else if (newValue instanceof Collection) {
// same instance of Collection can have changed content always assume a change.
// But not need of setValue .
Object clonedObject = CloneHelper.clone(object);
executeUpdater(property, newValue, clonedObject, changedProperties);
addChangedPropertyRecursive(property, changedProperties);
}
}
private void addChangedPropertyRecursive(PropertyInterface property, HashSet<PropertyInterface> changedProperties) {
changedProperties.add(property);
HashSet<PropertyInterface> changedRoots = new HashSet<>(changedProperties);
changedRoots.forEach(root -> changedProperties.addAll(collectDependencies(root)));
}
private HashSet<PropertyInterface> collectDependencies(PropertyInterface property) {
HashSet<PropertyInterface> collection = new HashSet<>();
collectDependencies(property, collection);
return collection;
}
private void collectDependencies(PropertyInterface property, HashSet<PropertyInterface> collection) {
if (!collection.contains(property)) {
collection.add(property);
if (dependencies.containsKey(property.getPath())) {
for (PropertyInterface dependingProperty : dependencies.get(property.getPath())) {
collectDependencies(dependingProperty, collection);
}
}
}
}
}
private void updateEnable() {
for (Map.Entry<PropertyInterface, FormElement<?>> element : elements.entrySet()) {
PropertyInterface property = element.getKey();
boolean enabled = !(property.isFinal() && FieldUtils.isAllowedPrimitive(property.getClazz())) && evaluate(object, property, Enabled.class);
if (element.getValue() instanceof Enable) {
((Enable) element.getValue()).setEnabled(enabled);
} else if (!enabled && !property.isFinal()) {
if (editable) {
logger.severe("element " + property.getPath() + " should implement Enable");
} else {
logger.fine("element " + property.getPath() + " should maybe implement Enable");
}
}
}
}
private void updateVisible() {
for (Map.Entry<PropertyInterface, FormElement<?>> element : elements.entrySet()) {
PropertyInterface property = element.getKey();
boolean visible = evaluate(object, property, Visible.class);
formContent.setVisible(element.getValue().getComponent(), visible);
}
for (Map.Entry<IComponent, Object[]> element : keysForTitle.entrySet()) {
boolean visible = false;
for (Object key : element.getValue()) {
if (evaluate(object, Keys.getProperty(key), Visible.class)) {
visible = true;
break;
}
}
formContent.setVisible(element.getKey(), visible);
}
}
// TODO move to properties package, write tests
static boolean evaluate(Object object, PropertyInterface property, Class<? extends Annotation> annotationClass) {
for (PropertyInterface p2 : ChainedProperty.getChain(property)) {
Annotation annotation = p2.getAnnotation(annotationClass);
if (annotation != null) {
// No common class between Enabled and Visible
String condition = annotation instanceof Enabled ? ((Enabled) annotation).value() : ((Visible) annotation).value();
if (!evaluateCondition(object, p2, condition)) {
return false;
}
}
object = p2.getValue(object);
if (object == null) {
return true;
}
}
return true;
}
static boolean evaluateCondition(Object object, PropertyInterface property, String methodName) {
boolean invert = methodName.startsWith("!");
if (invert)
methodName = methodName.substring(1);
try {
Class<?> clazz = object.getClass();
Method method = clazz.getMethod(methodName);
if (!((Boolean) method.invoke(object) ^ invert)) {
return false;
}
} catch (Exception x) {
String fieldName = property.getName();
if (!fieldName.equals(property.getPath())) {
fieldName += " (" + property.getPath() + ")";
}
logger.log(Level.SEVERE, "Update enable of " + fieldName + " failed", x);
}
return true;
}
public boolean indicate(List<ValidationMessage> validationMessages) {
List<ValidationMessage> unused = new ArrayList<>(validationMessages);
boolean relevantValidationMessage = false;
for (PropertyInterface property : getProperties()) {
List<ValidationMessage> filteredValidationMessages = ValidationMessage.filterValidationMessage(validationMessages, property);
setValidationMessage(property, filteredValidationMessages);
relevantValidationMessage |= !filteredValidationMessages.isEmpty();
unused.removeAll(filteredValidationMessages);
}
if (!unused.isEmpty()) {
for (ValidationMessage unusedMessage : unused) {
logger.log(Configuration.isDevModeActive() ? Level.WARNING : Level.FINER, "Unused validation message for: " + unusedMessage.getProperty().getPath());
}
}
return relevantValidationMessage;
}
}
| true
|
b7a14d0d28a71f8d6b4eacd78e301ba5befd36b2
|
Java
|
ObstinateCloud/design-patterns
|
/adapter-pattern/src/com/lengedyun/adapter/Target.java
|
UTF-8
| 233
| 1.945313
| 2
|
[] |
no_license
|
package com.lengedyun.adapter;
/**
* @author zjy
* @title: Target
* @projectName design-patterns
* @description: 目标类
* @date 2019/7/28 17:07
*/
public abstract class Target {
public abstract void normalRequest();
}
| true
|
b24dc4feea3db4980976605a02222f4dda701213
|
Java
|
zxypw/Hospital-by-java
|
/src/phar/UpdateMed.java
|
GB18030
| 4,738
| 2.328125
| 2
|
[] |
no_license
|
package phar;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import mySQL.MySQLConnect;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class UpdateMed extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
private String Me_id=null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UpdateMed frame = new UpdateMed();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public UpdateMed() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 502, 438);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("ҩƷ");
lblNewLabel.setBounds(44, 33, 90, 18);
contentPane.add(lblNewLabel);
textField = new JTextField();
textField.setBounds(161, 30, 99, 24);
contentPane.add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
search();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(291, 29, 82, 27);
contentPane.add(btnNewButton);
JLabel lblNewLabel_1 = new JLabel("ҩƷ");
lblNewLabel_1.setBounds(80, 112, 45, 18);
contentPane.add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel("ҩƷ");
lblNewLabel_2.setBounds(80, 144, 45, 18);
contentPane.add(lblNewLabel_2);
JLabel lblNewLabel_3 = new JLabel("");
lblNewLabel_3.setBounds(80, 175, 30, 18);
contentPane.add(lblNewLabel_3);
JLabel lblNewLabel_4 = new JLabel("");
lblNewLabel_4.setBounds(80, 206, 30, 18);
contentPane.add(lblNewLabel_4);
textField_1 = new JTextField();
textField_1.setBounds(271, 172, 86, 24);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(271, 203, 86, 24);
contentPane.add(textField_2);
textField_2.setColumns(10);
JLabel lblNewLabel_9 = new JLabel("ֵ");
lblNewLabel_9.setBounds(285, 80, 72, 18);
contentPane.add(lblNewLabel_9);
JButton btnNewButton_1 = new JButton("ȷ");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textField_1.getText()!=null && textField_2.getText()!=null)
update();
close();
}
});
btnNewButton_1.setBounds(260, 255, 113, 27);
contentPane.add(btnNewButton_1);
textField_3 = new JTextField();
textField_3.setBounds(155, 109, 86, 24);
contentPane.add(textField_3);
textField_3.setColumns(10);
textField_4 = new JTextField();
textField_4.setBounds(155, 141, 86, 24);
contentPane.add(textField_4);
textField_4.setColumns(10);
textField_5 = new JTextField();
textField_5.setBounds(155, 172, 86, 24);
contentPane.add(textField_5);
textField_5.setColumns(10);
textField_6 = new JTextField();
textField_6.setBounds(155, 203, 86, 24);
contentPane.add(textField_6);
textField_6.setColumns(10);
}
public void search() throws SQLException {
String name=textField.getText();
String sql="SELECT * FROM Medicine WHERE Me_name='"+name+"';";
MySQLConnect conn=new MySQLConnect(sql);
ResultSet re=conn.pst.executeQuery();
if(re.next())
{
textField_3.setText(re.getString(2));
textField_4.setText(re.getString(1));
textField_5.setText(re.getString(3));
textField_6.setText(re.getString(4));
Me_id=re.getString(1);
}
conn.close();
}
public void update(){
String new_price =textField_1.getText();
String new_count=textField_2.getText();
String sql="UPDATE Medicine SET Me_price="+new_price+",Me_inventory="+new_count+" WHERE Me_id='"+Me_id+"';";
MySQLConnect conn=new MySQLConnect(sql);
try {
conn.pst.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn.close();
}
public void close(){
this.dispose();
}
}
| true
|
904c8e046f35e290ce40986590a7be127c9bbffa
|
Java
|
ahmedhammad97/Bus-Station-Ticket-System
|
/Ticket.java
|
UTF-8
| 358
| 2.890625
| 3
|
[] |
no_license
|
package busstation;
public class Ticket implements java.io.Serializable{
private int number;
private int sold;
public Ticket(int number){
this.number = number;
this.sold = 0;
}
public int getLeft(){
return number-sold;
}
public void setSold(int num){
this.sold+=num;
}
}
| true
|
17faf06988029b47849dc7100cae8337bb90458c
|
Java
|
AndaP94/fristStepsSpring
|
/src/main/java/com/pichlera/pos1/test/firststeps/repository/ArticleMemRepository.java
|
UTF-8
| 1,250
| 2.171875
| 2
|
[] |
no_license
|
package com.pichlera.pos1.test.firststeps.repository;
import com.pichlera.pos1.test.firststeps.model.Article;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
public class ArticleMemRepository implements ArticleRepository {
@Override
public <S extends Article> S save(S s) {
return null;
}
@Override
public <S extends Article> Iterable<S> saveAll(Iterable<S> iterable) {
return null;
}
@Override
public Optional<Article> findById(Long aLong) {
return Optional.empty();
}
@Override
public boolean existsById(Long aLong) {
return false;
}
@Override
public Iterable<Article> findAll() {
return null;
}
@Override
public Iterable<Article> findAllById(Iterable<Long> iterable) {
return null;
}
@Override
public long count() {
return 0;
}
@Override
public void deleteById(Long aLong) {
}
@Override
public void delete(Article article) {
}
@Override
public void deleteAll(Iterable<? extends Article> iterable) {
}
@Override
public void deleteAll() {
}
}
| true
|
e6548b5a6fe08b492a62b777fe509310a05a085d
|
Java
|
Arif-un/Meal-Management
|
/src/View/Dlt_Confirm.java
|
UTF-8
| 3,006
| 2.359375
| 2
|
[
"MIT"
] |
permissive
|
package View;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.Color;
import javax.swing.border.LineBorder;
import Model.Mem_info;
import Model.Reports;
import java.awt.Font;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.io.File;
import java.awt.event.ActionEvent;
import java.awt.Cursor;
public class Dlt_Confirm extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Dlt_Confirm frame = new Dlt_Confirm(null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* @param idd
*/
public Dlt_Confirm(String idd) {
setTitle("Confirm");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 348, 213);
contentPane = new JPanel();
contentPane.setBackground(new Color(221,222,236));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnOk = new JButton("Yes");
btnOk.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnOk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Reports.reset();
}
});
btnOk.setForeground(Color.BLACK);
btnOk.setFont(new Font("BERTHOLD", Font.PLAIN, 13));
btnOk.setFocusPainted(false);
btnOk.setBorderPainted(false);
btnOk.setBorder(new LineBorder(new Color(0, 191, 255), 5, true));
btnOk.setBackground(Color.LIGHT_GRAY);
btnOk.setBounds(52, 127, 95, 23);
contentPane.add(btnOk);
JButton btnCancel = new JButton("Cancel");
btnCancel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Dlt_Confirm.this.dispose();
}
});
btnCancel.setForeground(Color.BLACK);
btnCancel.setFont(new Font("BERTHOLD", Font.PLAIN, 13));
btnCancel.setFocusPainted(false);
btnCancel.setBorderPainted(false);
btnCancel.setBorder(new LineBorder(new Color(0, 191, 255), 5, true));
btnCancel.setBackground(Color.LIGHT_GRAY);
btnCancel.setBounds(170, 128, 95, 23);
contentPane.add(btnCancel);
JLabel lblAreYouSure = new JLabel("Are You Sure !!!! ");
lblAreYouSure.setForeground(new Color(0, 153, 255));
lblAreYouSure.setFont(new Font("Proxima Nova Rg", Font.PLAIN, 16));
lblAreYouSure.setBounds(100, 78, 178, 14);
contentPane.add(lblAreYouSure);
JLabel lblItWillDelete = new JLabel("IT Will Delete All of Records in Database !!!");
lblItWillDelete.setForeground(new Color(255, 0, 0));
lblItWillDelete.setFont(new Font("Proxima Nova Rg", Font.PLAIN, 17));
lblItWillDelete.setBounds(10, 34, 312, 33);
contentPane.add(lblItWillDelete);
}
}
| true
|
d3e66b858ebb2fea2a0882772c1b1a3e469d679b
|
Java
|
DeepakBalyan23/Objects101-Practice-Exercise
|
/Exercise2/src/test/java/com/stackroute/exercise2/ChessBoardPrinterTest.java
|
UTF-8
| 787
| 2.4375
| 2
|
[] |
no_license
|
package com.stackroute.exercise2;
import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/* Unit test for EvenNumTest
*/
public class ChessBoardPrinterTest
{
private static ChessBoardPrinter chessBoardPrinter;
@BeforeClass
public static void setup() {
// This methods runs, before running any one of the test case
// This method is used to initialize the required variables
chessBoardPrinter = new ChessBoardPrinter();
}
@AfterClass
public static void teardown() {
// This method runs, after running all the test cases
// This method is used to clear the initialized variables
chessBoardPrinter = null;
}
@Test
public void testPrintChessBoard() {
chessBoardPrinter.printChessBoard();
}
}
| true
|
69012352a2786b22e369533514cfd60a88b25ac5
|
Java
|
GitUserAnkit/SpringMVC100p
|
/src/main/java/com/ankit/service/UserService.java
|
UTF-8
| 136
| 1.617188
| 2
|
[] |
no_license
|
package com.ankit.service;
import com.ankit.dto.UserDTO;
public interface UserService {
public String authenticate(UserDTO dto);
}
| true
|
eebb71bec03fd2bc56c8bded0f77a0ddcd724e2f
|
Java
|
mahyuddin/pharostesbed
|
/PharosMiddleware/src/pharoslabut/missions/DTT_FT1.java
|
UTF-8
| 6,732
| 2.65625
| 3
|
[] |
no_license
|
package pharoslabut.missions;
import pharoslabut.sensors.*;
import pharoslabut.tasks.Priority;
import pharoslabut.tasks.MotionTask;
import pharoslabut.logger.*;
import pharoslabut.navigate.MotionArbiter;
import playerclient3.*;
import playerclient3.structures.*;
import playerclient3.structures.position2d.PlayerPosition2dData;
/**
* This is the code we used during Distributed Traction Control Field Test 1 (DTT-FT1)
*
* @author Chien-Liang Fok
*/
public class DTT_FT1 implements Position2DListener {
private PlayerClient client = null;
private FileLogger flogger = null;
/**
* The constructor.
*
* @param serverIP The IP address of the robot.
* @param serverPort The port on which the robot is listening.
* @param logFileName The log file in which to save results.
* @param mobilityPlane The type of mobility plane being used.
* @param testStartDelay The number of seconds to wait before starting the test.
*/
public DTT_FT1(String serverIP, int serverPort, String logFileName,
MotionArbiter.MotionType mobilityPlane, int testStartDelay)
{
if (logFileName != null) {
flogger = new FileLogger(logFileName);
Logger.setFileLogger(flogger);
}
try {
Logger.log("Connecting to server " + serverIP + ":" + serverPort);
client = new PlayerClient(serverIP, serverPort);
} catch(PlayerException e) {
Logger.logErr("ERROR: Could not connect to player server: ");
Logger.logErr(" [ " + e.toString() + " ]");
System.exit (1);
}
Logger.log("Subscribing to motor interface and creating motion arbiter");
Position2DInterface motors = client.requestInterfacePosition2D(0, PlayerConstants.PLAYER_OPEN_MODE);
if (motors == null) {
Logger.logErr("ERROR: motors is null");
System.exit(1);
} else {
// subscribe to MCU debug messages
Position2DBuffer p2db = new Position2DBuffer(motors);
p2db.addPos2DListener(this);
p2db.start();
}
MotionArbiter motionArbiter = new MotionArbiter(mobilityPlane, motors);
Logger.log("Starting motor stress test in " + testStartDelay + " seconds ...");
while (testStartDelay-- > 0) {
synchronized(this) {
try {
wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (testStartDelay > 0) Logger.log(testStartDelay + "...");
}
MotionTask currTask;
double speed = 2.0;
double heading = 0.0;
currTask = new MotionTask(Priority.SECOND, speed, heading);
Logger.log("Submitting motion task: " + currTask);
motionArbiter.submitTask(currTask);
pause(5000);
speed = 2.0;
heading = -20.0;
currTask = new MotionTask(Priority.SECOND, speed, heading);
Logger.log("Submitting motion task: " + currTask);
motionArbiter.submitTask(currTask);
pause(1000);
speed = 2.0;
heading = 0.0;
currTask = new MotionTask(Priority.SECOND, speed, heading);
Logger.log("Submitting motion task: " + currTask);
motionArbiter.submitTask(currTask);
pause(2000);
speed = 2.0;
heading = 20.0;
currTask = new MotionTask(Priority.SECOND, speed, heading);
Logger.log("Submitting motion task: " + currTask);
motionArbiter.submitTask(currTask);
pause(1000);
speed = 2.0;
heading = 0.0;
currTask = new MotionTask(Priority.SECOND, speed, heading);
Logger.log("Submitting motion task: " + currTask);
motionArbiter.submitTask(currTask);
pause(5000);
currTask = new MotionTask(Priority.FIRST, MotionTask.STOP_SPEED, MotionTask.STOP_STEERING_ANGLE);
Logger.log("Submitting motion task: " + currTask);
motionArbiter.submitTask(currTask);
Logger.log("Test complete!");
System.exit(0);
}
@Override
public void newPlayerPosition2dData(PlayerPosition2dData data) {
PlayerPose2d pp = data.getPos();
Logger.log("Odometry Data: x=" + pp.getPx() + ", y=" + pp.getPy() + ", a=" + pp.getPa() + ", vel=" + data.getVel() + ", stall=" + data.getStall());
}
private void pause(int duration) {
synchronized(this) {
try {
wait(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// private void logErr(String msg) {
// String result = "DTT_FT1: " + msg;
// System.err.println(result);
// if (flogger != null)
// flogger.log(result);
// }
//
// private void log(String msg) {
// String result = "MotorStressTest: " + msg;
// System.out.println(result);
// if (flogger != null)
// flogger.log(result);
// }
private static void usage() {
System.err.println("Usage: pharoslabut.missions.DTT_FT1 <options>\n");
System.err.println("Where <options> include:");
System.err.println("\t-server <ip address>: The IP address of the Player Server (default localhost)");
System.err.println("\t-port <port number>: The Player Server's port number (default 6665)");
System.err.println("\t-log <file name>: name of file in which to save results (default null)");
System.err.println("\t-mobilityPlane <traxxas|segway|create>: The type of mobility plane being used (default traxxas)");
System.err.println("\t-testStartDelay <delay in seconds>: The number of seconds to wait before starting the test (default 4)");
}
public static void main(String[] args) {
String logFileName = null;
String serverIP = "localhost";
int serverPort = 6665;
int testStartDelay = 4;
MotionArbiter.MotionType mobilityPlane = MotionArbiter.MotionType.MOTION_TRAXXAS;
try {
for (int i=0; i < args.length; i++) {
if (args[i].equals("-server")) {
serverIP = args[++i];
}
else if (args[i].equals("-port")) {
serverPort = Integer.valueOf(args[++i]);
}
else if (args[i].equals("-log")) {
logFileName = args[++i];
}
else if (args[i].equals("-testStartDelay")) {
testStartDelay = Integer.valueOf(args[++i]);
}
else if (args[i].equals("-mobilityPlane")) {
String mp = args[++i].toLowerCase();
if (mp.equals("traxxas"))
mobilityPlane = MotionArbiter.MotionType.MOTION_TRAXXAS;
else if (mp.equals("segway"))
mobilityPlane = MotionArbiter.MotionType.MOTION_SEGWAY_RMP50;
else if (mp.equals("create"))
mobilityPlane = MotionArbiter.MotionType.MOTION_IROBOT_CREATE;
else {
System.err.println("Unknown mobility plane " + mp);
usage();
System.exit(1);
}
}
else {
usage();
System.exit(1);
}
}
} catch(Exception e) {
e.printStackTrace();
usage();
System.exit(1);
}
System.out.println("Server IP: " + serverIP);
System.out.println("Server port: " + serverPort);
System.out.println("Log: " + logFileName);
System.out.println("Mobility Plane: " + mobilityPlane);
System.out.println("Test start delay: " + testStartDelay);
new DTT_FT1(serverIP, serverPort, logFileName, mobilityPlane, testStartDelay);
}
}
| true
|
b0773c4cdc3db0a4353ac4c3a1f05d4cc37a4de6
|
Java
|
TParaschiv/RepTeme
|
/Colectii/endava/training/collections/CustomComparator.java
|
UTF-8
| 1,059
| 3.4375
| 3
|
[] |
no_license
|
package endava.training.collections;
import java.util.Comparator;
import java.util.List;
public class CustomComparator implements Comparator<Penguin>{
/**
* Get average of penguins age
* @param penguins mates to average
* @param age main penguin age
* @return average of the mates + main penguin age
*/
private double getAvg(List<Penguin> penguins, double age) {
for (Penguin penguin : penguins)
age += penguin.getAge();
return age / (penguins.size() + 1);
}
@Override
public int compare(Penguin p1, Penguin p2) {
double res = p1.getMatingPartners().size() - p2.getMatingPartners().size();
if (res == 0) {
res = getAvg(p1.getMatingPartners(), p1.getAge()) - getAvg(p2.getMatingPartners(), p2.getAge());
if (res == 0)
return p1.getName().compareTo(p2.getName());
else if (res < 0)
return -1;
return 1;
}
else if (res < 0)
return -1;
return 1;
}
}
| true
|
2f022d953572983503c011d9717025e38fe45e8d
|
Java
|
cristobajobremote/Nissum
|
/bff-user/src/main/java/cl/nisum/bffuser/data/datasource/impl/database/mapper/UserFindDataSourceMapper.java
|
UTF-8
| 2,203
| 2.0625
| 2
|
[] |
no_license
|
package cl.nisum.bffuser.data.datasource.impl.database.mapper;
import cl.nisum.bffuser.data.datasource.impl.database.model.PhoneDataBaseModel;
import cl.nisum.bffuser.data.datasource.impl.database.model.UserDataBaseModel;
import cl.nisum.bffuser.domain.entity.PhoneEntity;
import cl.nisum.bffuser.domain.entity.UserEntity;
import org.mapstruct.InjectionStrategy;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.UUID;
@Mapper(componentModel = "spring", imports = {OffsetDateTime.class, ZoneId.class, Instant.class, UUID.class}, injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public interface UserFindDataSourceMapper {
@Mapping(target = "id", expression="java(UUID.fromString(userDataBaseModel.getId()))")
@Mapping(target = "name", source ="name" )
@Mapping(target = "email", source ="email" )
@Mapping(target = "password", source ="password" )
@Mapping(target = "token", source ="token" )
@Mapping(target = "created", expression ="java( userDataBaseModel.getCreated()!=null ? OffsetDateTime.ofInstant(Instant.ofEpochMilli(userDataBaseModel.getCreated().getTime()), ZoneId.systemDefault()): null)" )
@Mapping(target = "modified", expression ="java(userDataBaseModel.getModified()!=null ? OffsetDateTime.ofInstant(Instant.ofEpochMilli(userDataBaseModel.getModified().getTime()), ZoneId.systemDefault()): null)" )
@Mapping(target = "lastLogin", expression ="java(userDataBaseModel.getLastLogin()!=null ? OffsetDateTime.ofInstant(Instant.ofEpochMilli(userDataBaseModel.getLastLogin().getTime()), ZoneId.systemDefault()): null)" )
@Mapping(target = "isUserActive", source ="active" )
@Mapping(target = "phones", source ="phones" )
UserEntity mapDataSourceModelToDomainEntity(UserDataBaseModel userDataBaseModel);
@Mapping(target = "id", expression ="java(UUID.fromString(phone.getId()))" )
@Mapping(target = "number", source ="number" )
@Mapping(target = "cityCode", source ="cityCode" )
@Mapping(target = "countryCode", source ="countryCode" )
PhoneEntity mapDomainEntityToDataSourceModel(PhoneDataBaseModel phone);
}
| true
|
278fdf2f6f271ab096af87dab80fa15b8474e9c5
|
Java
|
laim0nas100/CallerFramework
|
/src/main/java/lt/lb/caller/util/sync/CompletablePromise.java
|
UTF-8
| 1,155
| 2.75
| 3
|
[] |
no_license
|
package lt.lb.caller.util.sync;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
*
* @author laim0nas100
*/
public class CompletablePromise<T> implements RunnableFuture<T> {
public final CompletableFuture<T> future;
public CompletablePromise(CompletableFuture<T> future) {
this.future = future;
}
@Override
public void run() {
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return future.cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return future.isCancelled();
}
@Override
public boolean isDone() {
return future.isDone();
}
@Override
public T get() throws InterruptedException, ExecutionException {
return future.get();
}
@Override
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return future.get(timeout, unit);
}
}
| true
|
76699808cc20abd025dcfb734aeb4860021565ba
|
Java
|
Damonzh/FTInfo
|
/app/src/main/java/io/github/damon/ftinfo/ui/adapter/MovieAdapter.java
|
UTF-8
| 4,737
| 2.28125
| 2
|
[] |
no_license
|
package io.github.damon.ftinfo.ui.adapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
import io.github.damon.ftinfo.R;
import io.github.damon.ftinfo.widget.MetaballView;
import io.github.damonzh.ftinfo.API;
import io.github.damonzh.ftinfo.bean.Movies;
/**
* Author: ZhangYan
* Date: 15/12/25
* Description:
*/
public class MovieAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Movies> mMovieList;
private Context mContext;
private OnItemClickListener mOnItemClickListener;
private static final int VIEW_TYPE_CONTENT = 1;
private static final int VIEW_TYPE_PROGRESS = 2;
public MovieAdapter(Context context,List<Movies> mMovieList) {
this.mMovieList = mMovieList;
this.mContext = context;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (VIEW_TYPE_CONTENT == viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_movie, parent, false);
return new MovieHolder(view);
}else{
View view = LayoutInflater.from(mContext).inflate(R.layout.load_more_footer,parent,false);
return new ProgressHolder(view);
}
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof MovieHolder) {
final MovieHolder movieHolder = (MovieHolder) holder;
final Movies movies = mMovieList.get(position);
movieHolder.mMovieName.setText(movies.getTitle());
Picasso.with(mContext).load(API.IMAGE_BASE_URL + movies.getBackdrop_path()).into(movieHolder.mMoviePoster);
movieHolder.mMoviePoster.setOnClickListener(new View.OnClickListener() {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onClick(View v) {
if (null != mOnItemClickListener) {
movieHolder.mMoviePoster.setTransitionName(movies.getTitle());
mOnItemClickListener.onItemClick(v, position);
}
}
});
}else if (holder instanceof ProgressHolder){
ProgressHolder progressHolder = (ProgressHolder) holder;
}
}
@Override
public int getItemCount() {
return mMovieList == null ? 0 : mMovieList.size();
}
@Override
public int getItemViewType(int position) {
return mMovieList.get(position) != null ? VIEW_TYPE_CONTENT : VIEW_TYPE_PROGRESS;
}
public void addMoreMovies(List<Movies> moreMovies) {
if (mMovieList != null) {
mMovieList.addAll(moreMovies);
notifyDataSetChanged();
}
}
public void addMovie(Movies movie){
if (mMovieList != null){
mMovieList.add(movie);
notifyItemInserted(mMovieList.size() - 1);
}
}
public void removeMovie(int position){
if (mMovieList != null){
mMovieList.remove(position);
notifyItemRemoved(position);
}
}
public void setOnItemClickListener(OnItemClickListener listener){
this.mOnItemClickListener = listener;
}
public List<Movies> getAllMovies() {
return mMovieList;
}
public Movies getItemAtPosition(int position) {
if (null != mMovieList) {
return mMovieList.get(position);
}
return null;
}
static class MovieHolder extends RecyclerView.ViewHolder {
public ImageView mMoviePoster;
public TextView mMovieName;
public MovieHolder(View itemView) {
super(itemView);
mMoviePoster = (ImageView) itemView.findViewById(R.id.iv_movie_poster);
mMovieName = (TextView) itemView.findViewById(R.id.tv_movie_name);
}
}
static class ProgressHolder extends RecyclerView.ViewHolder{
public MetaballView mProgressView;
public TextView mHintText;
public ProgressHolder(View itemView) {
super(itemView);
mProgressView = (MetaballView) itemView.findViewById(R.id.mv_progress_bar);
mHintText = (TextView) itemView.findViewById(R.id.tv_hint_text);
}
}
public interface OnItemClickListener{
void onItemClick(View view, int position);
}
}
| true
|
4bb30c156bfd934f08f47942d6e32d539055c004
|
Java
|
saugata-git/GeeksForGeeks
|
/07.Heap/000.Heap_Sort.java
|
UTF-8
| 1,179
| 3.578125
| 4
|
[] |
no_license
|
class HeapSort{
static void swap(int a,int b){
int temp=a;
a=b;
b=temp;
}
static void heapify(int arr[],int n,int i){
int largest=i;
int l=2*i+1;
int r=2*i+2;
if(l<n && arr[l]>arr[largest])
largest=l;
if(r<n && arr[r]>arr[largest])
largest=r;
if(largest!=i){
swap(arr[i],arr[largest]);
heapify(arr,n,largest);
}
}
public static void sort(int arr[]){
int n=arr.length;
//Build heap
for(int i=n/2 -1;i>=0;i--)
heapify(arr,n,i);
// One by one extract an element from heap
for (int i=n-1; i>=0; i--){
swap(arr[0],arr[i]);
heapify(arr,i,0);
}
}
static void printArray(int arr[]){
int n=arr.length;
for(int i=0;i<n;i++){
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static void main(String args[]){
int arr[]={12, 11, 13, 5, 6, 7};
int n= arr.length;
HeapSort ob =new HeapSort();
ob.sort(arr);
System.out.println("Sorted array is ");
printArray(arr);
}
}
| true
|
77aed21f2a4e9fcbeb8e356b50bc8ade9e49cfad
|
Java
|
sumit-mishra/N26-Code-Challenge
|
/src/test/java/com/n26/StatisticsServiceTest.java
|
UTF-8
| 2,194
| 2.40625
| 2
|
[] |
no_license
|
package com.n26;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.stream.IntStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.n26.exception.OutOfScopeTransaction;
import com.n26.exception.UnparsableData;
import com.n26.model.Transaction;
import com.n26.model.TransactionStatistics;
import com.n26.service.StatisticsService;
import com.n26.service.TransactionService;
import com.n26.service.repository.TransactionRepository;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class StatisticsServiceTest {
@Autowired
private TransactionService transactionService;
@Autowired
private StatisticsService statisticsService;
@Test
public void countAndSumMustBeZeroWhenRepoIsEmpty() {
TransactionRepository.getInstance().clear();
TransactionStatistics statistics = TransactionStatistics.getInstance();
assertTrue(statistics.getSum() == BigDecimal.ZERO);
assertTrue(statistics.getCount() == 0);
}
@Test
public void serviceShouldPrepareStatistics() {
TransactionRepository.getInstance().clear();
String timestamp = String.valueOf(Instant.now());
int[] sum = new int[] {0};
IntStream.range(1, 100).forEach(i -> {
Transaction transaction = new Transaction(String.valueOf(i), timestamp);
sum[0] += i;
try {
transactionService.createTransaction(transaction);
} catch (UnparsableData | OutOfScopeTransaction e) {
}
});
TransactionStatistics statistics = statisticsService.prepare();
assertTrue(statistics.getSum().compareTo(BigDecimal.valueOf(sum[0])) == 0);
assertTrue(statistics.getCount() == 99);
assertTrue(statistics.getMin().compareTo(BigDecimal.ONE) == 0);
assertTrue(statistics.getMax().compareTo(BigDecimal.valueOf(99)) == 0);
}
}
| true
|
3c74f7a62bfac7ceb68477aaeccc77a5bc9801ea
|
Java
|
mikhelvin/cuesheetmaker
|
/src/csm/CueTotal.java
|
UTF-8
| 472
| 2.46875
| 2
|
[] |
no_license
|
package csm;
import java.awt.Cursor;
import java.awt.Rectangle;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class CueTotal extends JPanel {
// COMPONENTS
private JLabel durationTotal;
public CueTotal() {
initialize();
}
public void initialize() {
durationTotal = new JLabel("THIS IS THE TOTAL DURATION");
durationTotal.setHorizontalAlignment(SwingConstants.CENTER);
add(durationTotal);
}
}
| true
|
0b4d86e17cc60aa7c3e4672073020dbfaf0f86b9
|
Java
|
tonyta/CS106A
|
/Chapter5/PrimeFinderBrute.java
|
UTF-8
| 777
| 4.1875
| 4
|
[] |
no_license
|
/*
* File: PrimeFinderBrute.java
* --------------------
* This program finds and displays prime numbers from 1 to N
* using a brute-force algorithm.
*/
import acm.program.*;
public class PrimeFinderBrute extends ConsoleProgram {
// Checks each number from 1 to N to see if it is prime.
// Prints out the number if it is prime.
public void run() {
println("This program displays all prime numbers up to N.");
int N = readInt("N: ");
for (int i = 1; i <= N; i++) {
if (isPrime(i)) println(i);
}
}
// Determines if given number is prime.
private boolean isPrime(int n) {
boolean divisorFound = false;
for (int i = 2; i < n; i++) {
if (n % i == 0) {
divisorFound = true;
}
}
return !divisorFound;
}
}
| true
|
cf1c975c6818d809e0bb224bc7b787e00f00ea61
|
Java
|
daiqingsong2021/ord_project
|
/acm-module-dc2/src/main/java/com/wisdom/acm/dc2/po/TrainDailyPassageMilePo.java
|
UTF-8
| 2,244
| 2.015625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.wisdom.acm.dc2.po;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.wisdom.base.common.po.BasePo;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Table;
import java.util.Date;
@Table(name = "odr_train_daily_mile")
@Data
public class TrainDailyPassageMilePo extends BasePo
{
/**
*线路
*/
@Column(name = "LINE")
private String line;
/**
* 记录日期
*/
@Column(name = "RECORD_TIME")
private Date recordTime;
/**
*行车日况id
*/
@Column(name = "TRAIN_DAILY_ID")
private String trainDailyId;
/**
*列次数
*/
@Column(name = "TRAIN_LIST_NUMBER")
private String trainListNumber;
/**
*载客里程
*/
@Column(name = "PASSENGER_MILES")
private String passengerMiles;
/**
*空驶里程
*/
@Column(name = "EMPTY_MILES")
private String emptyMiles;
/**
*既有线载客里程
*/
@Column(name = "ALL_LINE_PASSENAGE_MILES")
private String allLinePassenageMiles;
/**
*既有线空驶里程
*/
@Column(name = "ALL_LINE_EMPTY_MILES")
private String allLineEmptyMiles;
/**
*新线线载客里程
*/
@Column(name = "NEW_LINE_PASSENAGE_MILES")
private String newLinePassenageMiles;
/**
*新线空驶里程
*/
@Column(name = "NEW_LINE_EMPTY_MILES")
private String newLineEmptyMiles;
/**
*载客里程
*/
@Column(name = "ABNORMAL_PASSENGER_MILES")
private String abnormalPassengerMiles;
/**
*空驶里程
*/
@Column(name = "ABNORMAL_EMPTY_MILES")
private String abnormalEmptyMiles;
/**
*既有线载客里程
*/
@Column(name = "ABNORMAL_ALL_PASSENAGE_MILES")
private String abnormalAllPassenageMiles;
/**
*既有线空驶里程
*/
@Column(name = "ABNORMAL_ALL_EMPTY_MILES")
private String abnormalAllEmptyMiles;
/**
*新线线载客里程
*/
@Column(name = "ABNORMAL_NEW_PASSENAGE_MILES")
private String abnormalNewPassenageMiles;
/**
*新线空驶里程
*/
@Column(name = "ABNORMAL_NEW_EMPTY_MILES")
private String abnormalNewEmptyMiles;
}
| true
|
0767011802172d77e2a7285166c13acd26174a80
|
Java
|
jackchenji/WISDOMWATERAPP
|
/app/src/main/java/com/cdww/app/bean/ResponModel.java
|
UTF-8
| 1,050
| 2.375
| 2
|
[] |
no_license
|
package com.cdww.app.bean;
import java.io.Serializable;
/**
* ================================================
* 描述:
* 来源: Android Studio.
* 作者: chenji
* 项目名: Android-wisdomwaterapp;
* 包名: com.cdww.app.bean
* 创建时间: 2020-09-09
* <p>
* ================================================
*/
public class ResponModel<T> implements Serializable {
public static final int RESULT_SUCCESS = 0;
private T data;
private int errorCode;
private String errorMsg;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public boolean isSuccess(){
return RESULT_SUCCESS == errorCode;
}
}
| true
|
a093b0315a4e8dbbac9c1e378c02785206e4aa38
|
Java
|
atcharatip/platform_frameworks_base
|
/core/java/android/net/RecommendationResult.java
|
UTF-8
| 2,403
| 2.03125
| 2
|
[
"LicenseRef-scancode-unicode",
"Apache-2.0"
] |
permissive
|
/*
* Copyright (C) 2016 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 android.net;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.net.wifi.WifiConfiguration;
import android.os.Parcel;
import android.os.Parcelable;
import com.android.internal.annotations.VisibleForTesting;
/**
* The result of a network recommendation.
*
* @see {@link NetworkScoreManager#requestRecommendation(RecommendationRequest)}.
* @hide
*/
@SystemApi
public final class RecommendationResult implements Parcelable {
private final WifiConfiguration mWifiConfiguration;
public RecommendationResult(@Nullable WifiConfiguration wifiConfiguration) {
mWifiConfiguration = wifiConfiguration;
}
private RecommendationResult(Parcel in) {
mWifiConfiguration = in.readParcelable(WifiConfiguration.class.getClassLoader());
}
/**
* @return The recommended {@link WifiConfiguration} to connect to. A {@code null} value
* indicates that no WiFi connection should be attempted at this time.
*/
public WifiConfiguration getWifiConfiguration() {
return mWifiConfiguration;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeParcelable(mWifiConfiguration, flags);
}
public static final Creator<RecommendationResult> CREATOR =
new Creator<RecommendationResult>() {
@Override
public RecommendationResult createFromParcel(Parcel in) {
return new RecommendationResult(in);
}
@Override
public RecommendationResult[] newArray(int size) {
return new RecommendationResult[size];
}
};
}
| true
|
c715ba91d63737c4740a455a32d4dd1a86febfb7
|
Java
|
dreadiscool/YikYak-Decompiled
|
/src/com/parse/ParsePinningEventuallyQueue$13.java
|
UTF-8
| 1,118
| 1.835938
| 2
|
[] |
no_license
|
package com.parse;
import l;
import m;
class ParsePinningEventuallyQueue$13
implements l<Void, m<Object>>
{
ParsePinningEventuallyQueue$13(ParsePinningEventuallyQueue paramParsePinningEventuallyQueue, EventuallyPin paramEventuallyPin, ParseOperationSet paramParseOperationSet) {}
public m<Object> then(m<Void> paramm)
{
int i = this.val$eventuallyPin.getType();
ParseObject localParseObject = this.val$eventuallyPin.getObject();
String str = this.val$eventuallyPin.getSessionToken();
m localm;
if (i == 1) {
localm = localParseObject.saveAsync(this.val$operationSet, str);
}
for (;;)
{
return localm.b(new ParsePinningEventuallyQueue.13.1(this, i, localParseObject));
if (i == 2) {
localm = localParseObject.deleteAsync(str);
} else {
localm = this.val$eventuallyPin.getCommand().executeAsync();
}
}
}
}
/* Location: C:\Users\dreadiscool\Desktop\tools\classes-dex2jar.jar
* Qualified Name: com.parse.ParsePinningEventuallyQueue.13
* JD-Core Version: 0.7.0.1
*/
| true
|
4a462f925b62b24ed0e833b61357317902436bab
|
Java
|
cha63506/CompSecurity
|
/Shopping/flipp_source/src/com/google/analytics/tracking/android/an.java
|
UTF-8
| 1,315
| 1.851563
| 2
|
[] |
no_license
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.google.analytics.tracking.android;
// Referenced classes of package com.google.analytics.tracking.android:
// ao, ap, ak
public final class an
{
private static ak a;
public static void a(String s)
{
ao ao1 = b();
if (ao1 != null)
{
ao1.d(s);
}
}
public static boolean a()
{
if (b() != null)
{
return ap.a.equals(b().a());
} else
{
return false;
}
}
private static ao b()
{
if (a == null)
{
a = ak.a();
}
if (a != null)
{
return a.b;
} else
{
return null;
}
}
public static void b(String s)
{
ao ao1 = b();
if (ao1 != null)
{
ao1.b(s);
}
}
public static void c(String s)
{
ao ao1 = b();
if (ao1 != null)
{
ao1.a(s);
}
}
public static void d(String s)
{
ao ao1 = b();
if (ao1 != null)
{
ao1.c(s);
}
}
}
| true
|
1a3667e8cea23240d17266ec0a2594e848df5839
|
Java
|
Maokei/project-Battleship
|
/src/battleship/screen/ChallengePanel.java
|
UTF-8
| 4,941
| 2.640625
| 3
|
[] |
no_license
|
/**
* @file ChallangePanel.java
* @authors rickard, lars
* @date 2015-05-25
* */
package battleship.screen;
import static battleship.game.Constants.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Map.Entry;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import battleship.game.LoginDialog;
import battleship.game.Message;
import battleship.game.Player;
/**
* @class ChallangePanel
* @extends JPanel
* @brief Class describes a challange panel.
* */
public class ChallengePanel extends JPanel {
private static final long serialVersionUID = 2283968572833866258L;
private Player player;
private JList<String> players;
private JButton invite, refresh;;
private JPanel centerPanel, buttonPanel;
private JScrollPane pane;
private Font font;
private String opponent;
private final String noPlayers = "No available players.";
/**
* @constructor ChallangePanel
* @param Takes a Player pointer.
* */
public ChallengePanel(Player player) {
this.player = player;
setLayout(new BorderLayout());
font = new Font("Monospaced", Font.BOLD, 12);
centerPanel = new JPanel();
buttonPanel = new JPanel();
invite = new JButton("Invite");
invite.setBorderPainted(false);
invite.setBackground(new Color(62, 60, 250));
invite.setForeground(new Color(255, 255, 255));
invite.setFont(font);
invite.addActionListener(new ChallengeListener());
refresh = new JButton("Refresh");
refresh.setBorderPainted(false);
refresh.setBackground(new Color(90, 191, 7));
refresh.setForeground(new Color(255, 255, 255));
refresh.setFont(font);
refresh.addActionListener(ae -> { updateNames(); });
buttonPanel.add(invite);
buttonPanel.add(refresh);
buttonPanel.setBackground(new Color(80, 80, 80));
centerPanel.setBackground(new Color(80, 80, 80));
setupPlayersList();
centerPanel.add(players);
add(centerPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
setSize(100, 140);
setVisible(true);
}
/**
* setInviteEnabled
* @name setInviteEnabled
* @param Boolean to set enabled state.
* */
public void setInviteEnabled(boolean enabled) {
invite.setEnabled(enabled);
}
/**
* updateNames
*
* @name updateNames
* @brief Set new names into list from names.
* */
public void updateNames() {
players.clearSelection();
String[] names = player.getConnectedPlayers().keySet().toArray(
new String[player.getConnectedPlayers().size()]);
String[] available = player.getConnectedPlayers().values().toArray(
new String[player.getConnectedPlayers().size()]);
ArrayList<String> availableNames = new ArrayList<String>();
for(Entry<String, String> entry : player.getConnectedPlayers().entrySet()) {
availableNames.add(entry.getKey() + " " + entry.getValue());
}
String[] display = availableNames.toArray(new String[player.getConnectedPlayers().size()]);
players.setListData(display);
}
/**
* setupPlayersList
*
* @name setupPlayersList
* @brief to setup the players JList
* */
private void setupPlayersList() {
players = new JList<String>(player.getConnectedPlayers().keySet().toArray(
new String[player.getConnectedPlayers().size()]));
players.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
players.setLayoutOrientation(JList.VERTICAL);
players.setBackground(new Color(30, 30, 30));
players.setForeground(new Color(255, 255, 255));
players.setFont(font);
players.setSelectionBackground(new Color(116, 255, 150));
players.setPreferredSize(new Dimension(120, 140));
pane = new JScrollPane(players);
}
/**
* @class ChallangeListener
* @implements ActionListener
* @brief Class describes a button listener for the Challenge panel.
* */
private class ChallengeListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if(!players.isSelectionEmpty()) {
String sel = (String)players.getSelectedValue();
String[] values = sel.split(" ");
String name = values[0];
String available = values[1];
//Don't allow player to match himself
if(name.equals(player.getName()))
return;
if(available.trim().equalsIgnoreCase("Playing")) {
players.setSelectionBackground(new Color(212, 97, 93));
} else {
player.sendMessage(new Message(Message.CHALLENGE, player.getName(),
name, Challenge_Request));
}
//JOptionPane.showMessageDialog(new JFrame(), "Sending battle challange to opponent, " + sel);
}
}
}
}
| true
|
fdcaef1d2fa65f9babeb0e491035b02d69351a75
|
Java
|
aakashParticulate/zero-votes
|
/ZVotes-ejb/src/main/java/com/zero/votes/persistence/RecipientFacade.java
|
UTF-8
| 1,789
| 2.421875
| 2
|
[] |
no_license
|
package com.zero.votes.persistence;
import com.zero.votes.persistence.entities.Recipient;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
@Stateless
public class RecipientFacade extends AbstractFacade<Recipient> {
@PersistenceContext(unitName = "com.zero.votes.ZVotesPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public RecipientFacade() {
super(Recipient.class);
}
/**
* Returns all entities of type Recipient from range[0] to range[1]
* with an attribute fieldName:=value, ordered ascending by email.
* @param fieldName
* @param value
* @param range
* @return
*/
public List<Recipient> findRangeByOrderByEmail(String fieldName, Object value, int[] range) {
getEntityManager().getEntityManagerFactory().getCache().evictAll();
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery<Recipient> cq = cb.createQuery(Recipient.class);
Root<Recipient> rt = cq.from(Recipient.class);
cq.select(rt).where(cb.equal(rt.get(fieldName), value));
cq.orderBy(cb.asc(rt.get("email")));
TypedQuery<Recipient> q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0]);
q.setFirstResult(range[0]);
try {
return q.getResultList();
} catch (NoResultException e) {
return null;
}
}
}
| true
|
1d7cd6d95b9231d4b4ea2eec8bcd63dfb216a5e8
|
Java
|
virginv/rest_mongo_jwt
|
/src/main/java/com/base/mongo/models/User.java
|
UTF-8
| 1,379
| 2.328125
| 2
|
[] |
no_license
|
package com.base.mongo.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "usuarios")
public class User {
@Id
@JsonIgnore
private ObjectId _id;
private String name;
@Indexed(unique = true)
private String username;
private String email;
@JsonIgnore
private String password;
public User() {
super();
}
public User(ObjectId _id, String name, String username, String email, String password) {
super();
this._id = _id;
this.name = name;
this.username = username;
this.email = email;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String get_id() {
return _id.toHexString();
}
public void set_id(ObjectId _id) {
this._id = _id;
}
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;
}
}
| true
|
b86823ec09e3d0865c67048240a1ee66f8d25000
|
Java
|
adminfieldService/PDFReportProject
|
/src/main/java/com/digisign/pdf/service/PDFGenerationItemService.java
|
UTF-8
| 1,680
| 1.835938
| 2
|
[] |
no_license
|
/*
* 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 com.digisign.pdf.service;
import com.digisign.pdf.entity.PDFGenerationItem;
import com.digisign.pdf.repo.PDFGenerationDao;
import com.digisign.pdf.repo.PDFGenerationItemDao;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
/**
*
* @author newbiecihuy
*/
@Service("pdfGenerationItemService")
public class PDFGenerationItemService {
@Autowired
@Qualifier("pdfGenerationItemDao")
private PDFGenerationItemDao pdfGenerationItemDao;
@Transactional
public Long generatePDFItem(PDFGenerationItem pdfGenerate) {
return pdfGenerationItemDao.generatePDFItem(pdfGenerate);
}
@Transactional
public void updatePDFGenertateItem(PDFGenerationItem pdfGenerateItem) {
pdfGenerationItemDao.updatePDFGenertateItem(pdfGenerateItem);
}
@Transactional
public PDFGenerationItem findById(Long idpdfGenerateItem) {
return pdfGenerationItemDao.findById(idpdfGenerateItem);
}
@Transactional
public List<PDFGenerationItem> findByFormatItem(Long idFormatItem) {
return pdfGenerationItemDao.findByFormatItem(idFormatItem);
}
@Transactional
public int setIdPdfGnerate(Long idPdfGenerate) {
return pdfGenerationItemDao.setIdPdfGnerate(idPdfGenerate);
}
}
| true
|
2201245776ef2df606c63cd6d70386a080ad200c
|
Java
|
iv0id/REST-API-STARTER
|
/rest-api-commons-core/src/main/java/com/sqli/commons/core/exception/FunctionalException.java
|
UTF-8
| 1,152
| 2.609375
| 3
|
[] |
no_license
|
package com.sqli.commons.core.exception;
/**
* The Class FunctionalException.
*/
public class FunctionalException extends RuntimeException {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 6751810024555728387L;
/** The code. */
private final Long code;
/** The message. */
private final String message;
/**
* Gets the code.
*
* @return the code
*/
public Long getCode() {
return code;
}
/*
* (non-Javadoc)
*
* @see java.lang.Throwable#getMessage()
*/
public String getMessage() {
return message;
}
/**
* Instantiates a new functional exception.
*
* @param code
* the code
* @param message
* the message
* @param e
* the e
*/
public FunctionalException(Long code, String message, Throwable e) {
super(e);
this.code = code;
this.message = message;
}
/**
* Instantiates a new functional exception.
*
* @param code
* the code
* @param message
* the message
*/
public FunctionalException(Long code, String message) {
super();
this.code = code;
this.message = message;
}
}
| true
|
c5c8545e41a091f7773f92d7909db19b5d040033
|
Java
|
loorola/SolidityStaticAnalyzer
|
/src/main/java/utils/Content/ContractNodeType/Statement/SingleStatement.java
|
UTF-8
| 336
| 2.171875
| 2
|
[] |
no_license
|
package utils.Content.ContractNodeType.Statement;
import parser.Base.SolidityParser;
import utils.Content.ContractNodeType.BasicContractDefinition.Statement;
public class SingleStatement extends Statement {
public SingleStatement(SolidityParser.StatementContext ctx) {
super(ctx, 3);
singleStatement=this;
}
}
| true
|
243265e95d6ec1043e8b6e978981cdedd74fb5ef
|
Java
|
code-Adrian/ResourceAllocationSystem
|
/src/Project/Facility.java
|
UTF-8
| 1,014
| 2.859375
| 3
|
[] |
no_license
|
package Project;
public class Facility {
public Facility(int facilityId, String facilityName, int user_id) {
this.facilityId = facilityId;
this.facilityName = facilityName;
this.user_id = user_id;
}
private int facilityId;
private String facilityName;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
private int user_id;
public int getFacilityId() {
return facilityId;
}
public void setFacilityId(int facilityId) {
this.facilityId = facilityId;
}
public String getFacilityName() {
return facilityName;
}
public void setFacilityName(String facilityName) {
this.facilityName = facilityName;
}
@Override
public String toString() {
return "Facility{" +
"facilityId=" + facilityId +
", facilityName='" + facilityName + '\'' +
'}';
}
}
| true
|
4b5f8812c3df9a2e9c577bd13f96ef987fd1f3de
|
Java
|
nikelin/SMSi
|
/console/src/main/java/ru/nikita/platform/sms/console/components/plugins/registry/windows/RegisterWindow.java
|
UTF-8
| 3,638
| 2.21875
| 2
|
[] |
no_license
|
package ru.nikita.platform.sms.console.components.plugins.registry.windows;
import com.redshape.ui.application.UIException;
import com.redshape.ui.application.UnhandledUIException;
import com.redshape.ui.application.events.AppEvent;
import com.redshape.ui.application.events.IEventHandler;
import com.redshape.ui.application.events.handlers.WindowCloseHandler;
import com.redshape.ui.components.InteractionAction;
import com.redshape.ui.data.bindings.render.ISwingRenderer;
import com.redshape.ui.data.bindings.render.components.ObjectUI;
import com.redshape.ui.utils.UIRegistry;
import com.redshape.ui.views.IView;
import ru.nikita.platform.sms.console.components.plugins.registry.RegistryController;
import ru.nikita.platform.sms.console.data.records.PluginsRegistry;
import ru.nikita.platform.sms.console.data.stores.PluginsRegistryStore;
import javax.swing.*;
import java.awt.*;
/**
* Created by IntelliJ IDEA.
* User: cyril
* Date: 12/12/11
* Time: 12:14 PM
* To change this template use File | Settings | File Templates.
*/
public class RegisterWindow extends JFrame {
private ObjectUI ui;
public RegisterWindow() {
super();
this.configUI();
this.buildUI();
}
protected void configUI() {
this.setTitle("New plugins registry details");
this.setSize(300,200);
}
protected void buildUI() {
try {
JPanel panel = new JPanel();
panel.setLayout( new BoxLayout(panel, BoxLayout.Y_AXIS ) );
panel.setMinimumSize(new Dimension(500, 400));
ISwingRenderer renderer = UIRegistry.<ISwingRenderer>getViewRendererFacade()
.createRenderer( PluginsRegistry.class );
this.ui = renderer.render(panel, PluginsRegistry.class);
this.ui.setMinimumSize( new Dimension(400, 500) );
this.ui.invalidate();
this.ui.repaint();
Box buttonsBox = Box.createHorizontalBox();
buttonsBox.add( new JButton( new InteractionAction("Save", new IEventHandler() {
@Override
public void handle(AppEvent event) {
RegisterWindow.this.onSave();
RegisterWindow.this.setVisible(false);
try {
UIRegistry.getViewsManager().activate(RegistryController.LIST_VIEW);
} catch ( Throwable e ) {
UIRegistry.getNotificationsManager().error( e.getMessage() );
throw new UnhandledUIException( e.getMessage(), e );
}
}
})));
buttonsBox.add( new JButton( new InteractionAction("Cancel", new IEventHandler() {
@Override
public void handle(AppEvent event) {
RegisterWindow.this.setVisible(false);
}
}) ) );
panel.add( buttonsBox );
this.add(panel);
} catch ( InstantiationException e ) {
throw new UnhandledUIException( e.getMessage(), e );
} catch ( UIException e ) {
throw new UnhandledUIException( e.getMessage(), e );
}
}
protected void onSave() {
try {
UIRegistry.getStoresManager().getStore(PluginsRegistryStore.class)
.add(RegisterWindow.this.ui.<PluginsRegistry>createInstance());
} catch ( Throwable e ) {
UIRegistry.getNotificationsManager().error( e.getMessage() );
throw new UnhandledUIException( e.getMessage(), e );
}
}
}
| true
|
94c2fc800fefa221ea8cd265025e2750492fb4a0
|
Java
|
ayscoder/core-java
|
/src/main/java/corejava/dp/behavioural/cor/ITicketHandler.java
|
UTF-8
| 1,591
| 3.484375
| 3
|
[] |
no_license
|
package corejava.dp.behavioural.cor;
/**
* The chain of responsibility pattern is a behavioral object design pattern. In
* the chain of responsibility pattern, a series of handler objects are chained
* together to handle a request made by a client object. If the first handler
* can't handle the request, the request is forwarded to the next handler, and
* it is passed down the chain until the request reaches a handler that can
* handle the request or the chain ends. In this pattern, the client is
* decoupled from the actual handling of the request, since it does not know
* what class will actually handle the request.
*
* In this pattern, a Handler is an interface for handling a request and
* accessing a handler's successor. A Handler is implemented by a Concrete
* Handler. The Concrete Handler will handle the request or pass it on to the
* next Concrete Handler. A Client makes the request to the start of the handler
* chain.
*
* Now, let's look at an example of the chain of responsibility pattern. Rather
* than an interface, I'll use an abstract base class as the handler so that
* subclasses can utilize the implemented setSuccessor() method. This abstract
* class is called PlanetHandler. Concrete handlers that subclass PlanetHandler
* need to implement the handleRequest() method.
*
* @author ayush
*
*/
public abstract class ITicketHandler {
protected ITicketHandler tickerHandler;
public void setHandler(ITicketHandler tickerHandler) {
this.tickerHandler = tickerHandler;
}
public abstract void handleTicket(TicketType ticketType);
}
| true
|
e7d73843f5f5f68a9b5d4e93154e72492e6db7b5
|
Java
|
shxr/NJG
|
/easrc/pm/invite/examRecord.java
|
GB18030
| 1,726
| 2.390625
| 2
|
[] |
no_license
|
/**
* output package name
*/
package com.kingdee.eas.port.pm.invite;
import java.util.Map;
import java.util.List;
import java.util.Iterator;
import com.kingdee.util.enums.StringEnum;
/**
* output class name
*/
public class examRecord extends StringEnum
{
public static final String HAVE_VALUE = "1";//alias=
public static final String NONE_VALUE = "2";//alias=
public static final String NOTFOUND_VALUE = "3";//alias=δ
public static final String CONFIRM_VALUE = "4";//alias=ʵ
public static final examRecord have = new examRecord("have", HAVE_VALUE);
public static final examRecord none = new examRecord("none", NONE_VALUE);
public static final examRecord notFound = new examRecord("notFound", NOTFOUND_VALUE);
public static final examRecord confirm = new examRecord("confirm", CONFIRM_VALUE);
/**
* construct function
* @param String examRecord
*/
private examRecord(String name, String examRecord)
{
super(name, examRecord);
}
/**
* getEnum function
* @param String arguments
*/
public static examRecord getEnum(String examRecord)
{
return (examRecord)getEnum(examRecord.class, examRecord);
}
/**
* getEnumMap function
*/
public static Map getEnumMap()
{
return getEnumMap(examRecord.class);
}
/**
* getEnumList function
*/
public static List getEnumList()
{
return getEnumList(examRecord.class);
}
/**
* getIterator function
*/
public static Iterator iterator()
{
return iterator(examRecord.class);
}
}
| true
|
8041124501de89f6ed2f58deb7ecfaede1b1be1a
|
Java
|
jakobkennerberg/Hangman
|
/src/client/ViewerSelectCategory.java
|
UTF-8
| 6,599
| 3.046875
| 3
|
[] |
no_license
|
package client;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
import javax.swing.border.BevelBorder;
/**
* This class contains the frame for selecting the category of word
* being guessed in the game
* @author Jakob Kennerberg
*/
public class ViewerSelectCategory extends JPanel {
private JButton btnRandom = new JButton("Random");
private JButton btnCities = new JButton("Cities");
private JButton btnAnimals = new JButton("Animals");
private JButton btnBrands = new JButton("Brands");
private JButton btnBack = new JButton("<-- BACK");
private JLabel lblCategory = new JLabel("CATEGORY ", SwingConstants.CENTER);
private ButtonListener listener = new ButtonListener();
private BackListener bListener = new BackListener();
private ContinueListener continueListener;
private Controller controller;
/**
* Constructor
*/
public ViewerSelectCategory() {
setPreferredSize(new Dimension(1200,800));
setLayout(new BorderLayout());
add(pnlNorth(), BorderLayout.NORTH);
add(pnlButtons(), BorderLayout.CENTER);
btnRandom.addActionListener(listener);
btnCities.addActionListener(listener);
btnAnimals.addActionListener(listener);
btnBrands.addActionListener(listener);
btnBack.addActionListener(listener);
btnBack.addMouseListener(bListener);
btnRandom.addMouseListener(bListener);
btnCities.addMouseListener(bListener);
btnAnimals.addMouseListener(bListener);
btnBrands.addMouseListener(bListener);
}
/**
* Method which creates the panel containing all the category buttons
* @return A JPanel with category-buttons
*/
private JPanel pnlButtons() {
JPanel panel = new JPanel(null);
Font btnFont = new Font("SansSerif", Font.BOLD, 30);
btnRandom.setBounds(450, 50, 300, 100);
btnCities.setBounds(450, 200, 300, 100);
btnAnimals.setBounds(450, 350, 300, 100);
btnBrands.setBounds(450, 500, 300, 100);
btnRandom.setFont(btnFont);
btnCities.setFont(btnFont);
btnAnimals.setFont(btnFont);
btnBrands.setFont(btnFont);
btnRandom.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.black, Color.black));
btnRandom.setBackground(Color.white);
btnRandom.setOpaque(true);
btnCities.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.black, Color.black));
btnCities.setBackground(Color.white);
btnCities.setOpaque(true);
btnAnimals.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.black, Color.black));
btnAnimals.setBackground(Color.white);
btnAnimals.setOpaque(true);
btnBrands.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.black, Color.black));
btnBrands.setBackground(Color.white);
btnBrands.setOpaque(true);
panel.setBackground(Color.DARK_GRAY);
panel.add(btnRandom);
panel.add(btnCities);
panel.add(btnAnimals);
panel.add(btnBrands);
return panel;
}
/**
* Method which creates the upper panel, containing the title and
* back button
* @return A JPanel With a header and back-button
*/
private JPanel pnlNorth() {
JPanel panel = new JPanel();
Font btnFont = new Font("SansSerif", Font.BOLD, 30);
panel.setBackground(Color.DARK_GRAY);
panel.setLayout(new BorderLayout());
panel.add(lblCategory, BorderLayout.CENTER);
panel.add(btnBack, BorderLayout.WEST);
btnBack.setFont(btnFont);
btnBack.setPreferredSize(new Dimension(200,100));
btnBack.setForeground(Color.WHITE);
btnBack.setContentAreaFilled(false);
btnBack.setBorderPainted(false);
lblCategory.setFont(new Font("SansSerif", Font.PLAIN, 125));
lblCategory.setForeground(Color.WHITE);
return panel;
}
/**
* Method which sets the listener(interface) to the frame
* @param listener The continueListener to control the flow from/to this frame
*/
public void setListener(ContinueListener listener) {
continueListener = listener;
}
/**
* Method which sets the controller to the frame
* @param controller The controller this frame will use
*/
public void setController(Controller controller) {
this.controller = controller;
}
/**
* An inner class which listens to the input made by clicking on the buttons
* and performs actions according to this.
* @author Jakob Kennerberg
*
*/
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnRandom) {
continueListener.nextPanel();
controller.setCategoryWord("files/Random.txt", "RANDOM");
} else if (e.getSource() == btnCities) {
continueListener.nextPanel();
controller.setCategoryWord("files/Cities.txt", "CITIES");
} else if (e.getSource() == btnAnimals) {
continueListener.nextPanel();
controller.setCategoryWord("files/Animals.txt", "ANIMALS");
} else if (e.getSource() == btnBrands) {
continueListener.nextPanel();
controller.setCategoryWord("files/Brands.txt", "BRANDS");
} else if (e.getSource() == btnBack) {
continueListener.goBack();
}
}
}
/**
* An inner class which listens to the input made by hovering over buttons
* and stopping to do this.
* @author Jakob Kennerberg
*
*/
private class BackListener implements MouseListener {
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {
if(e.getSource()==btnBack) {
btnBack.setForeground(Color.RED);
}
if(e.getSource()==btnRandom) {
btnRandom.setForeground(Color.RED);
}
if(e.getSource()==btnAnimals) {
btnAnimals.setForeground(Color.RED);
}
if(e.getSource()==btnBrands) {
btnBrands.setForeground(Color.RED);
}
if(e.getSource()==btnCities) {
btnCities.setForeground(Color.RED);
}
}
public void mouseExited(MouseEvent e) {
if(e.getSource()==btnBack) {
btnBack.setForeground(Color.WHITE);
}
if(e.getSource()==btnRandom) {
btnRandom.setForeground(Color.BLACK);
}
if(e.getSource()==btnCities) {
btnCities.setForeground(Color.BLACK);
}
if(e.getSource()==btnAnimals) {
btnAnimals.setForeground(Color.BLACK);
}
if(e.getSource()==btnBrands) {
btnBrands.setForeground(Color.BLACK);
}
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
}
| true
|
5401d8874d242e032cfc99e9db0afa4f2cda77d8
|
Java
|
dominikafudala/currency-calculator
|
/src/main/java/com/nbp/Calculator.java
|
UTF-8
| 267
| 1.890625
| 2
|
[] |
no_license
|
package com.nbp;
public class Calculator {
private static Calculator instance;
private static String url = "https://www.nbp.pl/kursy/xml/lasta.xml";
private Calculator() {
}
public static Calculator getInstance(){
return null;
}
}
| true
|
2997d20b2c4d144a1339073831d94ef69da01b32
|
Java
|
nymann/portfolio_assignment_part_one
|
/src/main/java/dev/nymann/sensor/CO2SensorAdapter.java
|
UTF-8
| 603
| 2.5
| 2
|
[] |
no_license
|
package dev.nymann.sensor;
import dk.sdu.mmmi.st4.scfs.sensors.CO2Sensor;
public class CO2SensorAdapter extends Sensor {
private final CO2Sensor co2Sensor;
public CO2SensorAdapter(String id) {
co2Sensor = new CO2Sensor(id);
}
@Override
public String getName() {
return co2Sensor.getId();
}
@Override
public Double getValue() {
int val = co2Sensor.getValue();
return (double) val;
}
@Override
public void start() {
co2Sensor.start();
}
@Override
public void stop() {
co2Sensor.stop();
}
}
| true
|
9f0a330fe5f7e61a3a44d37551ee13a665f9c4fb
|
Java
|
XuJiaoJie/P2PChat
|
/app/src/main/java/com/xjhaobang/p2pchat/adapter/ChatMessageAdapter.java
|
UTF-8
| 2,881
| 2.34375
| 2
|
[] |
no_license
|
package com.xjhaobang.p2pchat.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.xjhaobang.p2pchat.R;
import com.xjhaobang.p2pchat.bean.SocketBeen;
import com.xjhaobang.p2pchat.constant.Constant;
import java.util.List;
/**
* Created by PC on 2017/6/5.
*/
public class ChatMessageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<SocketBeen> mList;
public ChatMessageAdapter(Context context, List<SocketBeen> list) {
mInflater = LayoutInflater.from(context);
mList = list;
}
@Override
public int getCount() {
return mList.size();
}
@Override
public Object getItem(int position) {
return mList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
SocketBeen socketBeen = mList.get(position);
return socketBeen.getUserIP().equals(Constant.userIP) ? 1 : 0;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
SocketBeen socketBeen = mList.get(position);
ViewHolder viewHolder;
if (convertView == null){
viewHolder = new ViewHolder();
if (!socketBeen.getUserIP().equals(Constant.userIP)){
convertView = mInflater.inflate(R.layout.main_chat_from_msg, parent, false);
viewHolder.createDate = (TextView) convertView.findViewById(R.id.chat_from_createDate);
viewHolder.content = (TextView) convertView.findViewById(R.id.chat_from_content);
viewHolder.name = (TextView)convertView.findViewById(R.id.chat_from_name);
convertView.setTag(viewHolder);
}else {
convertView = mInflater.inflate(R.layout.main_chat_send_msg, null);
viewHolder.createDate = (TextView) convertView.findViewById(R.id.chat_send_createDate);
viewHolder.content = (TextView) convertView.findViewById(R.id.chat_send_content);
viewHolder.name = (TextView)convertView.findViewById(R.id.chat_send_name);
convertView.setTag(viewHolder);
}
}else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.content.setText(socketBeen.getMsg());
viewHolder.createDate.setText(socketBeen.getTime());
viewHolder.name.setText(socketBeen.getUserName());
return convertView;
}
private class ViewHolder{
public TextView createDate;
public TextView name;
public TextView content;
}
}
| true
|
f8ecaf52310f5d61ea49bbc23bd671eec7f94c89
|
Java
|
ZackPouget/Advent-of-Code-2020
|
/Dec 7th/Q2.java
|
UTF-8
| 1,416
| 3.109375
| 3
|
[] |
no_license
|
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Q2 {
public static void specifyContents(String line) {
Pattern pattern = Pattern.compile("\\d*\\s?\\w+\\s\\w+\\sbag");
Matcher matcher = pattern.matcher(line);
matcher.find();
String container = matcher.group();
Contents.contentsOfBag.put(container, new Contents());
while (matcher.find()) {
if (matcher.group().equals(" no other bag")) {
Contents.contentsOfBag.get(container).isEmpty = true;
} else {
int split = matcher.group().indexOf(" ");
Contents.contentsOfBag.get(container).counts.add(Integer.parseInt(matcher.group().substring(0, split)));
Contents.contentsOfBag.get(container).bags.add(matcher.group().substring(split + 1));
}
}
}
public static void main(String[] args) {
try {
Scanner in = new Scanner(new File("input.txt"));
while (in.hasNextLine())
specifyContents(in.nextLine());
System.out.println(Contents.contentsOfBag.get("shiny gold bag").getContents());
} catch (FileNotFoundException e) {
System.out.println("Input not found");
e.printStackTrace();
}
}
}
| true
|
35d6e36ce63c495d4a84f78e3d277eab52e7f76e
|
Java
|
codebaker/TryRestAPI1121
|
/app/src/main/java/com/codebakery/joan/tryrestapi1121/OpenWeatherAPITask.java
|
UTF-8
| 1,664
| 2.34375
| 2
|
[] |
no_license
|
package com.codebakery.joan.tryrestapi1121;
import android.os.AsyncTask;
import android.util.JsonReader;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class OpenWeatherAPITask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String id = params[0];
String apiKey = "90ea006486e913a15ddf36187febc4ec";
HttpURLConnection urlConnection=null;
InputStream inputStream=null;
JSONObject weather = null;
try {
URL url = new URL("http://api.openweathermap.org/data/2.5/weather?q=" + id + "&appid=" +apiKey);
urlConnection = (HttpURLConnection)url.openConnection();
inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1000];
inputStream.read(buffer);
weather = new JSONObject(new String(buffer));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}finally{
if(urlConnection !=null) urlConnection.disconnect();
if(inputStream !=null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return weather.toString();
}
}
| true
|
709fff93ecab71df99b144101b0703391934fb6a
|
Java
|
spoorthi9095/TestProject
|
/app/src/main/java/com/example/appiness/sampleapp/realm/RealmSetup.java
|
UTF-8
| 559
| 2.171875
| 2
|
[] |
no_license
|
package com.example.appiness.sampleapp.realm;
import android.app.Application;
import io.realm.Realm;
import io.realm.RealmConfiguration;
public class RealmSetup extends Application
{
@Override
public void onCreate() {
super.onCreate();
// The default Realm file is "default.realm" in Context.getFilesDir();
// we'll change it to "sample.realm"
Realm.init(this);
RealmConfiguration config = new RealmConfiguration.Builder().name("sample.realm").build();
Realm.setDefaultConfiguration(config);
}
}
| true
|
aeeb5b82697435854ffccc90bb1095e0a97c8ce9
|
Java
|
amtech/big-data-research
|
/Samples/spark/spark-examples/src/main/java/net/slisenko/sql/HelloSparkSQL.java
|
UTF-8
| 2,150
| 2.578125
| 3
|
[] |
no_license
|
package net.slisenko.sql;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.sql.api.java.JavaSQLContext;
import org.apache.spark.sql.api.java.JavaSchemaRDD;
import scala.Tuple2;
import java.util.Arrays;
import java.util.List;
public class HelloSparkSQL {
public static void main(String... args) {
String logFilePath = "/home/kslisenko/IdeaProjects/big-data-research/Samples/spark/spark-examples/src/main/resources/links.json";
SparkConf conf = new SparkConf().setAppName("Hello spark").setMaster("local[2]");
// Context tells Spark how to access cluster
JavaSparkContext context = new JavaSparkContext(conf);
JavaSQLContext sqlContext = new JavaSQLContext(context);
JavaRDD<Friendship> friendshipRdd = context.textFile(logFilePath).map(new Function<String, Friendship>() {
@Override
public Friendship call(String s) throws Exception {
String clean = s.replace("[", "").replace("]", "").replace("\"", "");
String[] pair = clean.split(", ");
Friendship fr = new Friendship();
fr.setFriend1(pair[0]);
fr.setFriend2(pair[1]);
return fr;
}
});
JavaSchemaRDD schemaFriendship = sqlContext.applySchema(friendshipRdd, Friendship.class);
schemaFriendship.registerTempTable("friends");
// SQL
// JavaSchemaRDD tomFriendships = sqlContext.sql("SELECT * FROM friends WHERE friend1='Tom' or friend2='Tom'");
// System.out.println(tomFriendships.collect());
JavaSchemaRDD friendship = sqlContext.sql("SELECT DISTINCT t1.friend1, t1.friend2 FROM friends t1 INNER JOIN friends t2 ON (t1.friend1 = t2.friend2 AND t1.friend2 = t2.friend1)");
System.out.println(friendship.collect());
}
}
| true
|
421400f68ec850f1ad88d56873454f040bbbed04
|
Java
|
Cypher121/kettle
|
/src/main/java/coffee/cypher/kettle/mixins/BlockEntitySchedulerMixin.java
|
UTF-8
| 1,406
| 1.859375
| 2
|
[
"MIT"
] |
permissive
|
package coffee.cypher.kettle.mixins;
import coffee.cypher.kettle.scheduler.TickingScheduler;
import coffee.cypher.kettle.tickers.mixinaccessors.BlockEntitySchedulerAccessor;
import coffee.cypher.kettle.tickers.task.TaskTicker;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.block.entity.BlockEntityType;
import net.minecraft.util.math.BlockPos;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.WeakHashMap;
@Mixin(BlockEntity.class)
abstract class BlockEntitySchedulerMixin implements BlockEntitySchedulerAccessor {
@Unique
private WeakHashMap<TaskTicker<?>, TickingScheduler<?>> kettle$TaskTickerSchedulerMap;
@Inject(
method = "<init>",
at = @At("RETURN")
)
public void kettle$constructorInitMap(BlockEntityType<?> blockEntityType, BlockPos blockPos, BlockState blockState, CallbackInfo ci) {
this.kettle$TaskTickerSchedulerMap = new WeakHashMap<>();
}
@Override
public @NotNull WeakHashMap<TaskTicker<?>, TickingScheduler<?>> kettle$getTaskTickerSchedulerMap() {
return kettle$TaskTickerSchedulerMap;
}
}
| true
|
6861855945eb0536ad68ae7573fcd8f4d03f509a
|
Java
|
chakroulant/OpenClassroomsGame
|
/src/com/ocr/chak/Character.java
|
UTF-8
| 2,823
| 3.4375
| 3
|
[] |
no_license
|
package com.ocr.chak;
import java.util.InputMismatchException;
import java.util.Scanner;
public abstract class Character {
protected int playerNumber, characterClass, level, life, strenght, agility, intelligence;
protected boolean alive ;
protected int action, damage;
String attackName;
Scanner scann = new Scanner(System.in);
protected boolean goodAnswer;
public Character(int playerNumber, int characterClass, int level, int life, int strenght, int agility, int intelligence) {
}
/**
* Partie commune de l'attaque de tous les champions, soit la prise du type d'attaque.
*/
public void Attacks(Character victim){
do {
try {
System.out.println("Joueur " + playerNumber + " (" + life + " Vitalité) veuillez choisir votre action (1 : Attaque basique, 2 : Attaque Spéciale)");
action = scann.nextInt();
scann.nextLine();
goodAnswer = (action == 1 || action == 2);
} catch (InputMismatchException e) {
goodAnswer = false;
}
}while(!goodAnswer);
}
public abstract void Presentation();
/**
* Permet simplement de definir si le champion est encore en vie.
*/
public void Alive() {
if (life > 0)
alive = (true);
else {
alive = (false);
System.out.println("Joueur " + playerNumber + " est mort");
}
}
public int getPlayerNumber() {
return playerNumber;
}
public void setPlayerNumber(int playerNumber) {
this.playerNumber = playerNumber;
}
public int getCharacterClass() {
return characterClass;
}
public void setCharacterClass(int characterClass) {
this.characterClass = characterClass;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getLife() {
return life;
}
public void setLife(int life) {
this.life = life;
}
public int getStrenght() {
return strenght;
}
public void setStrenght(int strengh) {
this.strenght = strengh;
}
public int getAgility() {
return agility;
}
public void setAgility(int agility) {
this.agility = agility;
}
public int getIntelligence() {
return intelligence;
}
public void setIntelligence(int intelligence) {
this.intelligence = intelligence;
}
public boolean isAlive() {
return alive;
}
public void setAlive(boolean alive) {
this.alive = alive;
}
public int getAction() {
return action;
}
public void setAction(int action) {
this.action = action;
}
}
| true
|
68c8416aab1fe02fe98cb01a3efb3b21c750463c
|
Java
|
TADG500/MoodTracker
|
/app/src/main/java/m/tadg500/moodtrackerv5/MainActivity.java
|
UTF-8
| 2,699
| 2.078125
| 2
|
[] |
no_license
|
package m.tadg500.moodtrackerv5;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
////////////////////// variable : start //////////////////////
private ImageView mSmiley;
private Button mCommentaryButton;
private Button mHistoricalButton;
private TextView mDebugText;
private ToastMessage myToast = new ToastMessage();
private String message = "";
////////////////////// variable : end //////////////////////
////////////////////// debug variable : start //////////////////////
public static int incre = 0;
////////////////////// debug variable : end //////////////////////
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
////////////////////// layout connection : start //////////////////////
mCommentaryButton = (Button) findViewById(R.id.activity_main_comm_btn);
mHistoricalButton = (Button) findViewById(R.id.activity_main_histo_btn);
mDebugText = (TextView) findViewById(R.id.activity_main_mood_debugText);
////////////////////// layout connection : end //////////////////////
////////////////////// mCommentaryButton setOnClickListener redefinition : start //////////////////////
mCommentaryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
message = ("display commentary pop up");
myToast.ToastDisplay(message, getApplicationContext());
mDebugText.setText("Affichage popup Commentaire");
}
});
////////////////////// mCommentaryButton setOnClickListener redefinition : stop //////////////////////
////////////////////// mHistoricalButton setOnClickListener redefinition : start //////////////////////
mHistoricalButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
message = ("display history pop up");
myToast.ToastDisplay(message, getApplicationContext());
mDebugText.setText("Affichage popup Historique");
}
});
////////////////////// mHistoricalButton setOnClickListener redefinition : start //////////////////////
}
}
| true
|
b9c1c6ab371049daa62395ad6a671621f3c55ca2
|
Java
|
AHahalinski/JavaIntroOnline
|
/src/by/bemn/java_intro_online/lesson04_programming_with_classes/aggregation_composition/task2/Engine.java
|
UTF-8
| 631
| 3.328125
| 3
|
[] |
no_license
|
package by.bemn.java_intro_online.lesson04_programming_with_classes.aggregation_composition.task2;
public class Engine {
private static int id;
private boolean isWorking;
public Engine() {
isWorking = false;
id++;
}
public boolean isWorking() {
return isWorking;
}
public void setWorking(boolean working) {
isWorking = working;
}
public void startEngine(){
isWorking = true;
System.out.println("Engine is working");
}
public void stoppingEngine(){
isWorking = false;
System.out.println("Engine is stopping");
}
}
| true
|
ed71832d300c6ddda9b860c97d5d78ccb985bca6
|
Java
|
bfok123/Discord-Bot
|
/src/main/java/DiscordBot/SirBot/commands/BlackjackCommand.java
|
UTF-8
| 3,068
| 2.84375
| 3
|
[] |
no_license
|
package DiscordBot.SirBot.commands;
import java.awt.Color;
import DiscordBot.SirBot.App;
import DiscordBot.SirBot.blackjack.BlackjackManager;
import DiscordBot.SirBot.commands.subcommands.BlackjackDealSubCommand;
import DiscordBot.SirBot.commands.subcommands.BlackjackHitSubCommand;
import DiscordBot.SirBot.commands.subcommands.BlackjackJoinSubCommand;
import DiscordBot.SirBot.commands.subcommands.BlackjackLeaveSubCommand;
import DiscordBot.SirBot.commands.subcommands.BlackjackStandSubCommand;
import DiscordBot.SirBot.commands.subcommands.SubCommand;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.MessageEmbed;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
public class BlackjackCommand extends Command {
private SubCommand[] subCommands;
private BlackjackManager blackjackManager;
public BlackjackCommand() {
blackjackManager = new BlackjackManager();
subCommands = new SubCommand[5]; // hit, double down, split, stand, join, leave?
subCommands[0] = new BlackjackHitSubCommand(this, blackjackManager);
subCommands[1] = new BlackjackJoinSubCommand(this, blackjackManager);
subCommands[2] = new BlackjackStandSubCommand(this, blackjackManager);
subCommands[3] = new BlackjackDealSubCommand(this, blackjackManager);
subCommands[4] = new BlackjackLeaveSubCommand(this, blackjackManager);
}
@Override
public String getName() {
return "blackjack";
}
@Override
public String getDescription() {
return "play blackjack";
}
@Override
public void onCommand(MessageReceivedEvent e, String[] msgArgs) {
String mention = "<@" + e.getAuthor().getId() + ">";
if(msgArgs.length == 1) {
sendHelpMessage();
} else {
// sub commands get msgArgs that start with their name
String[] subCommandMsgArgs = new String[msgArgs.length - 1];
for(int i = 0; i < subCommandMsgArgs.length; i++) {
subCommandMsgArgs[i] = msgArgs[i + 1];
}
for(SubCommand subCommand : subCommands) {
if(msgArgs[1].equals(subCommand.getName())) {
subCommand.onCommand(e, subCommandMsgArgs);
return;
}
}
sendErrorEmbed(new EmbedBuilder().setDescription(mention + ", that is not a valid command.").build());
}
}
@Override
public Message sendEmbed(MessageEmbed embed) {
embed = new EmbedBuilder(embed).setColor(Color.ORANGE).build();
return App.getBotTextChannel().sendMessage(embed).complete();
}
@Override
public Message sendUsageEmbed(MessageEmbed embed) {
embed = new EmbedBuilder(embed).setTitle("Usage - Blackjack").setColor(Color.YELLOW).build();
return App.getBotTextChannel().sendMessage(embed).complete();
}
@Override
public void sendHelpMessage() {
EmbedBuilder builder = new EmbedBuilder();
for(SubCommand subCommand : subCommands) {
builder.appendDescription("- " + subCommand.getName() + " : " + subCommand.getDescription() + "\n");
}
sendUsageEmbed(builder.build());
}
}
| true
|
a9a9a2de65599aee7059d610cbda8e5426f8e5cf
|
Java
|
julpfc/TeachOnSnap
|
/src/test/java/com/julvez/pfc/teachonsnap/ut/usergroup/UserGroupServiceFactoryTest.java
|
UTF-8
| 459
| 1.796875
| 2
|
[] |
no_license
|
package com.julvez.pfc.teachonsnap.ut.usergroup;
import com.julvez.pfc.teachonsnap.usergroup.UserGroupService;
import com.julvez.pfc.teachonsnap.usergroup.UserGroupServiceFactory;
import com.julvez.pfc.teachonsnap.ut.service.ServiceFactoryTest;
public class UserGroupServiceFactoryTest extends ServiceFactoryTest<UserGroupService> {
@Override
protected UserGroupService getTestService() {
return UserGroupServiceFactory.getService();
}
}
| true
|
fa976c38aeb120697be446b749a32b49c2cbf980
|
Java
|
JamesJi9277/Algorithm
|
/medium/450. Delete Node in a BST .java
|
UTF-8
| 2,460
| 3.640625
| 4
|
[] |
no_license
|
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) {
return null;
}
if (root.val > key) {
root.left = deleteNode(root.left, key);
} else if (root.val < key) {
root.right = deleteNode(root.right, key);
} else {
if (root.left == null) {
return root.right;
} else if (root.right == null) {
return root.left;
}
TreeNode min = findMin(root.right);
root.val = min.val;
root.right = deleteNode(root.right, min.val);
}
return root;
}
private TreeNode findMin(TreeNode root) {
TreeNode runner = root;
while (runner.left != null) {
runner = runner.left;
}
return runner;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) {
return null;
}
if (root.val == key) {
return helper(root);
}
TreeNode dummy = root;
while (root != null) {
if (root.val > key) {
if (root.left != null && root.left.val == key) {
root.left = helper(root.left);
break;
} else {
root = root.left;
}
} else {
if (root.right != null && root.right.val == key) {
root.right = helper(root.right);
break;
} else {
root = root.right;
}
}
}
return dummy;
}
public TreeNode helper(TreeNode root) {
if (root.left == null) {
return root.right;
} else if (root.right == null){
return root.left;
} else {
TreeNode rightChild = root.right;
TreeNode lastRight = findLastRight(root.left);
lastRight.right = rightChild;
return root.left;
}
}
public TreeNode findLastRight(TreeNode root) {
if (root.right == null) {
return root;
}
return findLastRight(root.right);
}
}
| true
|
6cd32b627c42c7b2d785a8fde34fda2f744af8e5
|
Java
|
zy990307/test-rabbitmq-consumer
|
/src/main/java/com/xuecheng/test/rabbitmq/consumer/TestConsumer02_Publish.java
|
UTF-8
| 2,483
| 2.59375
| 3
|
[] |
no_license
|
package com.xuecheng.test.rabbitmq.consumer;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class TestConsumer02_Publish {
private final static String EXCHANGE_FANOUT_INFORM="EXCHANGE_FANOUT_INFORM";
private final static String QUEUE_INFORM_SMS="QUEUE_INFORM_SMS";
private final static String QUEUE_INFORM_EMAIL="QUEUE_INFORM_EMAIL";
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("guest");
factory.setPassword("guest");
factory.setHost("106.12.211.16");
factory.setPort(5672);
factory.setVirtualHost("/");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
//创建交换机
channel.exchangeDeclare(EXCHANGE_FANOUT_INFORM,BuiltinExchangeType.FANOUT);
channel.queueDeclare(QUEUE_INFORM_EMAIL,true,false,false,null);
channel.queueDeclare(QUEUE_INFORM_SMS,true,false,false,null);
channel.queueBind(QUEUE_INFORM_SMS,EXCHANGE_FANOUT_INFORM,QUEUE_INFORM_SMS,null);
channel.queueBind(QUEUE_INFORM_EMAIL,EXCHANGE_FANOUT_INFORM,QUEUE_INFORM_EMAIL,null);
DefaultConsumer smsConsumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("sms消费者:--------------------");
String routingKey = envelope.getRoutingKey();
System.out.println("RoutingKey:"+routingKey);
System.out.println(new String(body,"utf-8"));
}
};
DefaultConsumer emailConsumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("email消费者:--------------------");
String routingKey = envelope.getRoutingKey();
System.out.println("RoutingKey:"+routingKey);
System.out.println(new String(body,"utf-8"));
}
};
channel.basicConsume(QUEUE_INFORM_EMAIL,true,emailConsumer);
channel.basicConsume(QUEUE_INFORM_SMS,true,smsConsumer);
}
}
| true
|
a231402494d8e14515ebe52b1ee8cd26ae387215
|
Java
|
MinsuCracy/imgsearch
|
/imgsearch/src/main/java/org/imgsearch/vo/StoreMenuVO.java
|
UTF-8
| 820
| 2.265625
| 2
|
[] |
no_license
|
package org.imgsearch.vo;
public class StoreMenuVO {
private int sm_no;
private int s_no;
private String sm_menu;
private int sm_price;
public int getSm_no() {
return sm_no;
}
public void setSm_no(int sm_no) {
this.sm_no = sm_no;
}
public int getS_no() {
return s_no;
}
public void setS_no(int s_no) {
this.s_no = s_no;
}
public String getSm_menu() {
return sm_menu;
}
public void setSm_menu(String sm_menu) {
this.sm_menu = sm_menu;
}
public int getSm_price() {
return sm_price;
}
public void setSm_price(int sm_price) {
this.sm_price = sm_price;
}
@Override
public String toString() {
return "StoreMenuVO [sm_no=" + sm_no + ", s_no=" + s_no + ", sm_menu="
+ sm_menu + ", sm_price=" + sm_price + "]";
}
}
| true
|
7eebd3e37d33e606d0b8188a129507e716bf26b9
|
Java
|
couchbase/couchbase-jvm-clients
|
/java-client/src/test/java/com/couchbase/client/java/codec/JsonSerializerTestBase.java
|
UTF-8
| 5,291
| 2.046875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2019 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.couchbase.client.java.codec;
import com.couchbase.client.core.error.DecodingFailureException;
import com.couchbase.client.java.json.JsonArray;
import com.couchbase.client.java.json.JsonObject;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.couchbase.client.core.util.CbCollections.listOf;
import static com.couchbase.client.core.util.CbCollections.setOf;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Verifies the basic functionality of the default {@link DefaultJsonSerializer}.
*/
abstract class JsonSerializerTestBase {
protected abstract JsonSerializer serializer();
@Test
void encodesJsonObject() {
JsonObject input = JsonObject.create().put("foo", "bar");
byte[] output = serializer().serialize(input);
assertEquals("{\"foo\":\"bar\"}", new String(output, UTF_8));
}
@Test
void decodesJsonObject() {
byte[] input = "{\"foo\":\"bar\"}".getBytes(UTF_8);
JsonObject decoded = serializer().deserialize(JsonObject.class, input);
assertEquals(JsonObject.fromJson(input), decoded);
JsonObject decodedWithTypeRef = serializer().deserialize(new TypeRef<JsonObject>() {
}, input);
assertEquals(decoded, decodedWithTypeRef);
}
@Test
void encodesJsonArray() {
JsonArray input = JsonArray.from("1", true, 2);
byte[] output = serializer().serialize(input);
assertEquals("[\"1\",true,2]", new String(output, UTF_8));
}
@Test
void decodesJsonArray() {
byte[] input = "[\"1\",true,2]".getBytes(UTF_8);
JsonArray decoded = serializer().deserialize(JsonArray.class, input);
assertEquals(JsonArray.fromJson(input), decoded);
JsonArray decodedWithTypeRef = serializer().deserialize(new TypeRef<JsonArray>() {
}, input);
assertEquals(decoded, decodedWithTypeRef);
}
@Test
void encodesMap() {
Map<String, Object> input = Collections.singletonMap("foo", "bar");
byte[] output = serializer().serialize(input);
assertEquals("{\"foo\":\"bar\"}", new String(output, UTF_8));
}
@Test
void decodesMap() {
Map<String, String> expected = Collections.singletonMap("foo", "bar");
byte[] input = "{\"foo\":\"bar\"}".getBytes(UTF_8);
Map decoded = serializer().deserialize(Map.class, input);
assertEquals(expected, decoded);
Map<String, String> decodedWithTypeRef = serializer().deserialize(new TypeRef<Map<String, String>>() {
}, input);
assertEquals(decoded, decodedWithTypeRef);
}
@Test
void encodesList() {
List<Object> input = Arrays.asList("1", true, 2);
byte[] output = serializer().serialize(input);
assertEquals("[\"1\",true,2]", new String(output, UTF_8));
}
@Test
void decodesList() {
List<Object> expected = Arrays.asList("1", true, 2);
byte[] input = "[\"1\",true,2]".getBytes(UTF_8);
List decoded = serializer().deserialize(List.class, input);
assertEquals(expected, decoded);
List<Object> decodedWithTypeRef = serializer().deserialize(new TypeRef<List<Object>>() {
}, input);
assertEquals(decoded, decodedWithTypeRef);
}
@Test
void encodesSet() {
Set<String> input = new LinkedHashSet<>(listOf("foo", "bar"));
byte[] output = serializer().serialize(input);
assertEquals("[\"foo\",\"bar\"]", new String(output, UTF_8));
}
@Test
void decodesSet() {
Set<String> expected = setOf("foo", "bar");
byte[] input = "[\"foo\",\"bar\"]".getBytes(UTF_8);
Set decoded = serializer().deserialize(Set.class, input);
assertEquals(expected, decoded);
Set<String> decodedWithTypeRef = serializer().deserialize(new TypeRef<Set<String>>() {
}, input);
assertEquals(decoded, decodedWithTypeRef);
}
@Test
void decodesObject() {
assertEquals(
listOf("a", 1, true),
serializer().deserialize(Object.class, "[\"a\",1,true]".getBytes(UTF_8)));
}
@Test
void handlesBytesOnEncode() {
byte[] result = serializer().serialize("foobar".getBytes(UTF_8));
assertEquals("foobar", new String(result, UTF_8));
}
@Test
void handlesBytesOnDecode() {
byte[] input = "foobar".getBytes(UTF_8);
byte[] result = serializer().deserialize(byte[].class, input);
assertArrayEquals(input, result);
assertThrows(DecodingFailureException.class, () -> {
serializer().deserialize(new TypeRef<byte[]>() {
}, input);
});
}
}
| true
|
dfd65e84a7533eda9f0e9a30f2eb3ea9565fc0ee
|
Java
|
zxcwindy/AlgorithmComplete
|
/src/main/java/org/yousharp/designpattern/singleton/PerfectSingleton.java
|
UTF-8
| 1,433
| 3.53125
| 4
|
[] |
no_license
|
package org.yousharp.designpattern.singleton;
import java.io.Serializable;
/**
* 增加序列化的支持,因为反序列化时,总是会产生新的实例。
* readResolve函数表示,当反序列化时,该函数返回的对象(当前可用的对象)作为流的返回值,即不会创建新的
* 实例;
* 增加serialVersionUID,因为序列化和反序列化时,serialVersionUID不一致,类的结构的变化会导致JVM抛异常。
* User: Daniel
* Date: 13-12-5
* Time: 下午10:23
*/
public class PerfectSingleton implements Serializable {
// serial version id
private static final long serialVersionUID = 1L;
// private constructor
private PerfectSingleton() {}
// readResolve
protected Object readResolve() {
return getInstance();
}
// inner class
private static class PerfectHolder {
private static final PerfectSingleton instance = new PerfectSingleton();
}
public static PerfectSingleton getInstance() {
return PerfectHolder.instance;
}
}
/**
* 总之,我们可以发现,一共6中单例模式,可以分为三类:饿汉式、懒汉式和内部类;
* 饿汉式:EagerSingleton(使用构造函数)和StaticBlockSingleton(使用静态初始化块)
* 懒汉式:LazySingleton(不能用于多线程)和DoubleCheckSingleton(可以用于多线程)
* 内部类:InnerClassSingleton(不支持序列化)和PerfectSingleton支持序列化
*/
| true
|
494565f829cb06312ecaa0516ab10ed4552647ac
|
Java
|
shmilyshirley/xhfjq
|
/src/main/java/com/hlframe/xhjq/controller/xhfjqData/HotelPriceController.java
|
UTF-8
| 5,251
| 2.53125
| 3
|
[] |
no_license
|
package com.hlframe.xhjq.controller.xhfjqData;
import com.google.common.collect.Lists;
import com.google.gson.internal.LinkedHashTreeMap;
import com.hlframe.xhjq.domain.xhfjqData.HotelPrice;
import com.hlframe.xhjq.service.HotelCommentService;
import com.hlframe.xhjq.service.HotelPriceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
/**
* @company:华量软件
* @author:Fan Junhan
* @email:fjh@hleast.com
* @date:2019-01-11 11:03
*/
@RestController
@RequestMapping(value = "hotelPrice")
public class HotelPriceController {
@Autowired
private HotelPriceService hotelPriceService;
/**
* 计算酒5个类别酒店最低价(1-12月)
*
* @return
*/
@RequestMapping(value = "countLowestPriceByType")
public List countHotel() {
List<HotelPrice> hotelPriceList = null;
hotelPriceList = hotelPriceService.countLowestPriceByType();
List<Map<String, String>> resultList = Lists.newArrayList();
if (hotelPriceList == null)
return null;
for (HotelPrice hotelPrice : hotelPriceList) {
Map map = new HashMap<String, String>();
map.put("hotelType", hotelPrice.getHotel_type());
List list = new ArrayList<>();
list.add(hotelPrice.getJan() != null ? hotelPrice.getJan() : 0);
list.add(hotelPrice.getFeb() != null ? hotelPrice.getFeb() : 0);
list.add(hotelPrice.getMar() != null ? hotelPrice.getMar() : 0);
list.add(hotelPrice.getApr() != null ? hotelPrice.getApr() : 0);
list.add(hotelPrice.getMar() != null ? hotelPrice.getMar() : 0);
list.add(hotelPrice.getJun() != null ? hotelPrice.getJun() : 0);
list.add(hotelPrice.getJul() != null ? hotelPrice.getJul() : 0);
list.add(hotelPrice.getAug() != null ? hotelPrice.getAug() : 0);
list.add(hotelPrice.getSept() != null ? hotelPrice.getSept() : 0);
list.add(hotelPrice.getOct() != null ? hotelPrice.getOct() : 0);
list.add(hotelPrice.getNov() != null ? hotelPrice.getNov() : 0);
list.add(hotelPrice.getDec() != null ? hotelPrice.getDec() : 0);
// 将list放入map
map.put("value", list);
// 将map存入list并返回
resultList.add(map);
}
// 获取当前月份
Calendar calendar = Calendar.getInstance();
//获得当前时间的月份,月份从0开始所以结果要加1
int month = calendar.get(Calendar.MONTH) + 1;
System.out.println("month = " + month);
return resultList;
}
/*// 近12个月各类酒店最低价格
@RequestMapping(value = "test")
public List test (){
List<Map<String,Object>> testList = hotelPriceService.test();
List<Map<String,Object>> resultList = new ArrayList<>();
for (Map<String, Object> ele : testList) {
Map<String,Object> tempMap1 = new LinkedHashTreeMap<>();
int count = 0;
// 当前月份
int currMonth = new Date().getMonth() + 1;
for (int i = currMonth; i <=12 ; i++) {
// 判断是否当前年份
if (i >= currMonth) {
tempMap1.put(String.valueOf(i), ele.get(String.valueOf(i)));
}
}
for (int j = 1; j < currMonth;j++){
tempMap1.put(String.valueOf(j), ele.get(String.valueOf(j)));
}
tempMap1.put("hotelType",ele.get("hotel_type"));
resultList.add(tempMap1);
// count++;
}
return resultList;
}*/
// 近12个月各类酒店最低价格
@RequestMapping(value = "test")
public List test() {
List<Map<String, Object>> testList = hotelPriceService.test();
List<Map<String, Object>> resultList = new ArrayList<>();
for (Map<String, Object> ele : testList) {
Map<String, Object> tempMap1 = new LinkedHashTreeMap<>();
// 存储value的list
List<Integer> valueList = new ArrayList<>();
// 存储month的list
List<String> monthList = new ArrayList<>();
int count = 0;
// 当前月份
int currMonth = new Date().getMonth() + 1;
for (int i = currMonth; i <= 12; i++) {
// 判断是否当前年份
if (i >= currMonth) {
monthList.add(String.valueOf(i));
valueList.add((Integer) ele.get(String.valueOf(i)));
}
}
for (int j = 1; j < currMonth; j++) {
monthList.add(String.valueOf(j));
valueList.add((Integer) ele.get(String.valueOf(j)));
}
// 设置酒店类别
tempMap1.put("hotelType", ele.get("hotel_type"));
// 设置月份
tempMap1.put("month", monthList);
// 设置值
tempMap1.put("value", valueList);
resultList.add(tempMap1);
}
return resultList;
}
}
| true
|
30ce7d849ac38799fc7db9e54ae749a02778d183
|
Java
|
Siddhartha123/Eclipse-workspace
|
/ObjectPoolNew/src/main/java/com/mkyong/rest/ThreadPool.java
|
UTF-8
| 1,574
| 2.59375
| 3
|
[] |
no_license
|
package com.mkyong.rest;
import java.sql.*;
import java.util.Stack;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Logger;
import java.sql.*;
import java.util.concurrent.Semaphore;
public class ThreadPool {
final static Logger logger=Logger.getLogger(ThreadPool.class);
public static AtomicInteger count=new AtomicInteger(0);
public static int maxSize = 10;
public static int baseSize=5;
public static final Semaphore available = new Semaphore(baseSize, true);
public static Stack<Object> ObjectPool = new Stack<Object>();
public static boolean manage=false;
public static Object getObject() throws InterruptedException {
available.acquire();
return getAvailableItem();
}
public static void putObject(Object x) {
ObjectPool.push(x);
available.release();
logger.info("Object returned to pool by:"+Thread.currentThread().getName());
}
private static synchronized Object getAvailableItem() {
while(ObjectPool.empty());
logger.info("Object removed from pool by:"+Thread.currentThread().getName());
Object ob=ObjectPool.pop();
return ob;
}
public static void increasePoolSize() throws ClassNotFoundException, SQLException{
jdbc_con db=new jdbc_con("com.mysql.jdbc.Driver","jdbc:mysql://localhost/cyborg","root","");
Object x=(Object)db.getConnection();
ThreadPool.putObject(x);
ThreadPool.count.incrementAndGet();
}
}
| true
|
a0bae89ad66fc709bab560446b6fa1820ef8e1f0
|
Java
|
zfy0098/salesman-service
|
/src/main/java/com/rhjf/salesman/service/service/SalesManBulletinServiceImpl.java
|
UTF-8
| 2,016
| 2.015625
| 2
|
[] |
no_license
|
package com.rhjf.salesman.service.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.rhjf.account.modle.domain.salesman.LoginUser;
import com.rhjf.account.modle.domain.salesman.ParamterData;
import com.rhjf.account.modle.domain.salesman.SalesManBulletin;
import com.rhjf.salesman.core.service.SalesManBulletinService;
import com.rhjf.salesman.service.mapper.SalesManBulletinMapper;
import net.sf.json.JSONObject;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by hadoop on 2017/8/4.
*/
@Transactional
public class SalesManBulletinServiceImpl implements SalesManBulletinService {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private SalesManBulletinMapper salesManBulletinMapper;
/**
* 显示公告列表
*
* @param user
* @param paramter
* @return
*/
public ParamterData salesmanBulletinList(LoginUser user, ParamterData paramter) {
Map<String, String> map = new HashMap<>();
map.put("agentID", user.getAgentID());
map.put("salesmanID", user.getSalesManID());
List<SalesManBulletin> list = salesManBulletinMapper.salesManBulletinList(map);
Integer count = salesManBulletinMapper.unreadCount(user.getSalesManID());
paramter.setCount(String.valueOf(count));
paramter.setList(JSONObject.fromObject(list).toString());
return paramter;
}
/**
* 显示公告详细
*
* @param user
* @param paramter
* @return
*/
public ParamterData salesmanBulletinDetail(LoginUser user, ParamterData paramter) {
SalesManBulletin salesManBulletin = salesManBulletinMapper.getSalesmanBulletinDetail(paramter.getID());
paramter.setList(JSONObject.fromObject(salesManBulletin).toString());
return paramter;
}
}
| true
|
0558b62ab228ede3cf02e2117ee04efe1c7488c2
|
Java
|
igecommerce/RestAPIServices
|
/src/main/java/com/gaia/web/rest/CountriesManyController.java
|
UTF-8
| 2,085
| 2.09375
| 2
|
[] |
no_license
|
package com.gaia.web.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.PagedResources;
import org.springframework.hateoas.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.gaia.common.ErrorCodes;
import com.gaia.common.GaiaException;
import com.gaia.domain.CountriesManyEntity;
import com.gaia.service.CountriesManyService;
@RestController
@RequestMapping(path = "/api/v1.0", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public class CountriesManyController {
@Autowired
private CountriesManyService countriesManyServ;
@GetMapping("countriesMany/{id}")
public ResponseEntity<CountriesManyEntity> getCountriesMany(@PathVariable long id) throws GaiaException {
return new ResponseEntity<CountriesManyEntity>(countriesManyServ.getCountriesMany(id), HttpStatus.OK);
}
@GetMapping("countriesMany")
public ResponseEntity<PagedResources<Resource<CountriesManyEntity>>> getCountriesMany(
PagedResourcesAssembler<CountriesManyEntity> assembler,@RequestParam(name = "id", required = false) Long id,
@RequestParam(name = "name", required = false) String name,
Pageable pageable) throws GaiaException {
Page<CountriesManyEntity> response = countriesManyServ.getCountriesMany(id, name, pageable);
if (response.getContent().isEmpty()) {
throw new GaiaException(ErrorCodes.CODE_NO_DATA, ErrorCodes.MSG_NO_DATA);
}
return new ResponseEntity<>(assembler.toResource(response), HttpStatus.OK);
}
}
| true
|
0e1ed53305843a97b0be4d5ed337c758904b43b1
|
Java
|
liuzhiyong14/gitVersionTest
|
/src/main/java/com/service/QRCodeEvents.java
|
UTF-8
| 1,699
| 2.390625
| 2
|
[] |
no_license
|
package com.service;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.UUID;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
public class QRCodeEvents {
public static void main(String[] args) throws WriterException {
String qrcodeFilePath = "";
try {
int qrcodeWidth = 500;
int qrcodeHeight = 500;
String qrcodeFormat = "png";
HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode("www.baidu.com", BarcodeFormat.QR_CODE, qrcodeWidth, qrcodeHeight, hints);
BufferedImage image = new BufferedImage(qrcodeWidth, qrcodeHeight, BufferedImage.TYPE_INT_RGB);
File QrcodeFile = new File("D:\\qrcode\\" + UUID.randomUUID().toString() + "." + qrcodeFormat);
Path QrcodePath = QrcodeFile.toPath();
ImageIO.write(image, qrcodeFormat, QrcodeFile);
MatrixToImageWriter.writeToPath(bitMatrix, qrcodeFormat, QrcodePath);
qrcodeFilePath = QrcodeFile.getAbsolutePath();
System.out.println("qrcodeFilePath==" + qrcodeFilePath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true
|
7f41ba15d2836e1b11b5e0a803834b8c1c8787fa
|
Java
|
kcsl/lsap-frontend
|
/JavaWorkspace/patchGeneration/src/test/java/edu/iastate/sdmay1809/ParameterTest.java
|
UTF-8
| 2,271
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
package edu.iastate.sdmay1809;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.Before;
public class ParameterTest {
private Parameter p1;
private Parameter p2;
private Parameter p3;
private Parameter p4;
private Parameter p5;
private Parameter p6;
private Parameter p7;
private Parameter p8;
@Before
public void setUp() throws Exception
{
p1 = new Parameter("void *name");
p2 = new Parameter("void* name");
p3 = new Parameter("void * name");
p4 = new Parameter("struct mutex *name");
p5 = new Parameter("struct mutex* name");
p6 = new Parameter("struct mutex * name");
p7 = new Parameter("int name");
p8 = new Parameter("struct mutex otherName");
}
@Test
public void parameterConstructor()
{
assertThat(p1, instanceOf(Parameter.class));
assertThat(p2, instanceOf(Parameter.class));
assertThat(p3, instanceOf(Parameter.class));
assertThat(p4, instanceOf(Parameter.class));
assertThat(p5, instanceOf(Parameter.class));
assertThat(p6, instanceOf(Parameter.class));
assertThat(p7, instanceOf(Parameter.class));
assertThat(p8, instanceOf(Parameter.class));
}
@Test
public void parameterGetName()
{
assertEquals(p1.getName(), "name");
assertEquals(p2.getName(), "name");
assertEquals(p3.getName(), "name");
assertEquals(p4.getName(), "name");
assertEquals(p5.getName(), "name");
assertEquals(p6.getName(), "name");
assertEquals(p7.getName(), "name");
assertEquals(p8.getName(), "otherName");
}
@Test
public void parameterGetType()
{
assertEquals(p1.getType(), "void*");
assertEquals(p2.getType(), "void*");
assertEquals(p3.getType(), "void*");
assertEquals(p4.getType(), "struct mutex*");
assertEquals(p5.getType(), "struct mutex*");
assertEquals(p6.getType(), "struct mutex*");
assertEquals(p7.getType(), "int");
assertEquals(p8.getType(), "struct mutex");
}
@Test
public void parameterImproperConstructor()
{
String[] thingsToTry = { "notParam", "struct mutex *", null };
for (String thing : thingsToTry)
{
try
{
new Parameter(thing);
fail("No exception was thrown on improper input \"" + thing + "\"!");
}
catch (Exception e)
{
continue;
}
}
}
}
| true
|
d6d869209368dab0f50d3c9e6dacf8a8c60676c7
|
Java
|
ArekYuan/Mobile_OA
|
/app/src/main/java/com/sewz/mobile_oa/utils/CommonUtils.java
|
UTF-8
| 12,434
| 2.078125
| 2
|
[] |
no_license
|
package com.sewz.mobile_oa.utils;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
*
*
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class CommonUtils {
public static int dip(Context context, int pxValue) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, pxValue,
context.getResources().getDisplayMetrics());
}
public static int px(Context context, int dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
public static ValueAnimator createHeightAnimator(final View view, int start, int end) {
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
int value = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
layoutParams.height = value;
view.setLayoutParams(layoutParams);
}
});
// animator.setDuration(DURATION);
return animator;
}
/**
* 收缩动画
*/
@SuppressLint("NewApi")
public static void animateCollapsing(final View view) {
int origHeight = view.getHeight();
ValueAnimator animator = createHeightAnimator(view, origHeight, 0);
animator.addListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation) {
view.setVisibility(View.GONE);
}
});
animator.start();
}
public static ValueAnimator createTopMarginAnimatorForLl(final View view, int start, int end) {
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
int value = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
((LinearLayout.LayoutParams) layoutParams).setMargins(0, value, 0, 0);
// layoutParams.height = value;
view.setLayoutParams(layoutParams);
}
});
// animator.setDuration(500000);
animator.setDuration(500);
return animator;
}
public static boolean animateExpandingWidth(final View view, int width) {
if (view.getVisibility() == View.VISIBLE) {
return false;
}
view.setVisibility(View.VISIBLE);
final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(widthSpec, heightSpec);
ValueAnimator animator = createWidthAnimator(view, 0, width);
animator.start();
return true;
}
public static void animateCollapsingWidth(final View view, int width) {
int origHeight = view.getWidth();
ValueAnimator animator = createWidthAnimator(view, width, 0);
animator.addListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation) {
view.setVisibility(View.GONE);
}
;
});
animator.start();
}
public static ValueAnimator createWidthAnimator(final View view, int start, int end) {
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
int value = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
layoutParams.width = value;
view.setLayoutParams(layoutParams);
}
});
// animator.setDuration(DURATION);
return animator;
}
/**
* 扩展动画
*/
public static boolean animateExpanding(final View view) {
if (view.getVisibility() == View.VISIBLE) {
return false;
}
view.setVisibility(View.VISIBLE);
final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(widthSpec, heightSpec);
ValueAnimator animator = createHeightAnimator(view, 0, view.getMeasuredHeight());
animator.start();
return true;
}
public static boolean animateExpanding(final View view, Handler handler) {
if (view.getVisibility() == View.VISIBLE) {
return false;
}
view.setVisibility(View.VISIBLE);
final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(widthSpec, heightSpec);
ValueAnimator animator = createHeightAnimator(view, 0, view.getMeasuredHeight());
animator.start();
handler.sendMessageDelayed(new Message(), animator.getDuration() + 80);
return true;
}
public static float getTextWidth(Context Context, String text, int textSize, TextPaint paint) {
float scaledDensity = Context.getResources().getDisplayMetrics().scaledDensity;
paint.setTextSize(scaledDensity * textSize);
return paint.measureText(text);
}
/**
* 隐藏 软键盘
*
* @param event touch event
* @param mActivity who's pager
*/
public static void hideSoft(MotionEvent event, Activity mActivity) {
InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mActivity.getCurrentFocus() != null) {
if (mActivity.getCurrentFocus().getWindowToken() != null) {
imm.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
}
/**
* 隐藏 软键盘
*
* @param mActivity who's pager
*/
public static void hideSoft(Activity mActivity) {
InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (mActivity.getCurrentFocus() != null) {
if (mActivity.getCurrentFocus().getWindowToken() != null) {
imm.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
public static void showImm(Activity mActivity, View view) {
InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
/**
* 获取屏幕宽度
*
* @param mContext
*/
public static int getWidth(Context mContext) {
Resources resources = mContext.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
float density = dm.density;
int width = dm.widthPixels;
int height = dm.heightPixels;
return width;
}
public static int getheight(Context mContext) {
Resources resources = mContext.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
float density = dm.density;
int width = dm.widthPixels;
int height = dm.heightPixels;
return height;
}
/**
* saveImageForShare(保存分享的图片)
* (这里描述这个方法适用条件 – 可选)
* void
*
* @throws
* @since 1.0.0
*/
public static void saveImageForShare(final String imageUrl, final Handler mShareHandler) {
new Thread() {
public void run() {
boolean isSend = false;
InputStream is = null;
URL url = null;
HttpURLConnection urlConnection = null;
Looper.prepare();
try {
url = new URL(imageUrl);
urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
is = urlConnection.getInputStream();
} else {
mShareHandler.sendEmptyMessage(1);
isSend = true;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mShareHandler.sendEmptyMessage(1);
isSend = true;
}
Bitmap bm = BitmapFactory.decodeStream(is);
// Bitmap mShareImage=changeColor(bm);
CommonUtils.saveBitmapFile(bm, "/sdcard/wjl/share.jpg");
if (!isSend) {
mShareHandler.sendEmptyMessage(0);
}
}
;
}.start();
}
public static void saveBitmapFile(Bitmap bitmap, String path) {
File file = new File(path);// 将要保存图片的路径
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 添加遮罩阴影
*
* @param t 透明度
*/
public static void setWindow(float t, Activity activity) {
WindowManager.LayoutParams wl = activity.getWindow().getAttributes();
wl.alpha = t;
activity.getWindow().setAttributes(wl);
}
/**
* 真是路径转 文件路径
*
* @param context
* @param uri
* @return
*/
public static String filePath(final Context context, final Uri uri) {
if (null == uri) return null;
final String scheme = uri.getScheme();
String filePath = null;
if (scheme == null)
filePath = uri.getPath();
else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
filePath = uri.getPath();
} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
if (null != cursor) {
if (cursor.moveToFirst()) {
int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
if (index > -1) {
filePath = cursor.getString(index);
}
}
cursor.close();
}
}
return filePath;
}
}
| true
|
8380ec2ac58053f605efc14f73b7d77a8d992672
|
Java
|
manbusky/java-sort-algorithm
|
/src/main/java/manbu/demo/impl/BubbleSort.java
|
UTF-8
| 613
| 2.9375
| 3
|
[] |
no_license
|
package manbu.demo.impl;
import manbu.demo.Person;
import manbu.demo.Sort;
/**
* 冒泡排序
* Created by manbu on 12/12/16.
*/
public class BubbleSort implements Sort {
public Person[] sort(Person[] array) {
for (int j = 0; j < array.length - 1; j++) {
for (int i = 0; i < array.length - 1 - j; i++) {
if(array[i].getClassId() > array[i + 1].getClassId()) {
Person temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
return array;
}
}
| true
|
802aae2a5aad6394029490462f3de6732cda6f89
|
Java
|
rodolfoand/Fincol
|
/app/src/main/java/com/fatec/fincol/ui/statement/StatementViewModel.java
|
UTF-8
| 459
| 2.21875
| 2
|
[] |
no_license
|
package com.fatec.fincol.ui.statement;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class StatementViewModel extends ViewModel {
private MutableLiveData<String> mText;
public StatementViewModel() {
mText = new MutableLiveData<>();
mText.setValue("This is statement fragment");
}
public LiveData<String> getText() {
return mText;
}
}
| true
|
e594ee1d36c05aed95ea4d9790e35d8d263e094e
|
Java
|
ibtisamasif/lastingsales_android
|
/app/src/main/java/com/example/muzafarimran/lastingsales/viewholders/ViewHolderTaskCard.java
|
UTF-8
| 8,246
| 1.867188
| 2
|
[] |
no_license
|
package com.example.muzafarimran.lastingsales.viewholders;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.muzafarimran.lastingsales.R;
import com.example.muzafarimran.lastingsales.SessionManager;
import com.example.muzafarimran.lastingsales.app.MyURLs;
import com.example.muzafarimran.lastingsales.events.TaskAddedEventModel;
import com.example.muzafarimran.lastingsales.providers.models.LSContact;
import com.example.muzafarimran.lastingsales.providers.models.LSTask;
import de.halfbit.tinybus.TinyBus;
/**
* Created by ibtisam on 2/1/2018.
*/
public class ViewHolderTaskCard extends RecyclerView.ViewHolder {
private static final String TAG = "ViewHolderTaskCard";
private final TextView tvContactName;
private final TextView tvContactNumber;
private final TextView tvTaskName;
private final TextView tvTaskDescription;
private final ImageView ivTick;
public ViewHolderTaskCard(View v) {
super(v);
tvContactName = v.findViewById(R.id.tvContactName);
tvContactNumber = v.findViewById(R.id.tvNumber);
tvTaskName = v.findViewById(R.id.tvTaskName);
tvTaskDescription = v.findViewById(R.id.tvTaskDescription);
ivTick = v.findViewById(R.id.ivTick);
}
public void bind(Object item, int position, Context mContext) {
LSTask lsTask = (LSTask) item;
LSContact lsContact = LSContact.getContactFromServerId(lsTask.getLeadId());
if (lsContact != null) {
// Log.i(TAG, "bind: lscontact: " + lsContact.toString());
if (lsContact.getContactName() != null)
tvContactName.setText(lsContact.getContactName());
if (lsContact.getPhoneOne() != null) {
tvContactNumber.setText(lsContact.getPhoneOne());
}
} else {
Log.i(TAG, "bind: lscontact: is NULL");
}
if (lsTask.getName() != null) {
tvTaskName.setText(lsTask.getName());
}
if (lsTask.getName() != null) {
tvTaskDescription.setText(lsTask.getDescription());
}
ivTick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(mContext);
View mView = layoutInflaterAndroid.inflate(R.layout.user_input_dialog_box, null);
AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(mContext);
alertDialogBuilderUserInput.setView(mView);
final EditText userInputDialogEditText = (EditText) mView.findViewById(R.id.userInputDialog);
alertDialogBuilderUserInput
.setCancelable(false)
.setPositiveButton("Send", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
lsTask.setStatus("Done");
String remarksText = userInputDialogEditText.getText().toString();
if (remarksText != null && !remarksText.equalsIgnoreCase(""))
lsTask.setRemarks(remarksText);
editTaskToServer(mContext, lsTask);
Toast.makeText(mContext, "Syncing task", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
dialogBox.cancel();
}
});
AlertDialog alertDialogAndroid = alertDialogBuilderUserInput.create();
alertDialogAndroid.show();
}
});
}
private void editTaskToServer(final Context mContext, final LSTask lsTask) {
SessionManager sessionManager = new SessionManager(mContext);
RequestQueue queue = Volley.newRequestQueue(mContext);
final int MY_SOCKET_TIMEOUT_MS = 60000;
final String BASE_URL = MyURLs.UPDATE_TASK;
Uri builtUri;
builtUri = Uri.parse(BASE_URL)
.buildUpon()
.appendPath("" + lsTask.getLeadId())
.appendPath("task")
.appendPath("" + lsTask.getServerId())
// .appendQueryParameter("status", "done")
.appendQueryParameter("status", lsTask.getStatus())
.appendQueryParameter("remarks", "" + lsTask.getRemarks())
.appendQueryParameter("api_token", "" + sessionManager.getLoginToken())
.build();
final String myUrl = builtUri.toString();
Log.d(TAG, "editTaskToServer: URL: " + myUrl);
StringRequest sr = new StringRequest(Request.Method.PUT, myUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Log.d(TAG, "onResponse() editTaskToServer: response = [" + response + "]");
// try {
// JSONObject jObj = new JSONObject(response);
// int responseCode = jObj.getInt("responseCode");
// if (responseCode == 200) {
// JSONObject responseObject = jObj.getJSONObject("response");
// Log.d(TAG, "onResponse : LastSeenInLocal : " + sessionManager.getLastAppVisit());
// Log.d(TAG, "onResponse : LastSeenFromServer : " + responseObject.getString("last_seen"));
lsTask.delete();
// }
// } catch (JSONException e) {
// FirebaseCrash.report(e);
// }
TaskAddedEventModel mCallEvent = new TaskAddedEventModel();
TinyBus bus = TinyBus.from(mContext.getApplicationContext());
bus.post(mCallEvent);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse:editTaskToServer CouldNotUpdateTaskToServer");
try {
if (error.networkResponse != null) {
Log.e(TAG, "onErrorResponse: statusCode: " + error.networkResponse.statusCode);
if (error.networkResponse.statusCode == 410) {
Log.e(TAG, "onErrorResponse: alreadyUpdatedTaskToServer");
lsTask.delete();
}
if (error.networkResponse.statusCode == 412) {
Log.e(TAG, "onErrorResponse: NoFurtherSteps");
lsTask.delete();
}
TaskAddedEventModel mCallEvent = new TaskAddedEventModel();
TinyBus bus = TinyBus.from(mContext.getApplicationContext());
bus.post(mCallEvent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}) {
};
sr.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(sr);
}
}
| true
|
827d4137c103c1f3349da2ac88a58f77efd48cc6
|
Java
|
chenjyr/Cars_Android_Jackie_Chen
|
/AxiomZenCars/src/com/example/axiomzencars/activities/DetailedCarActivity.java
|
UTF-8
| 6,732
| 2.453125
| 2
|
[] |
no_license
|
package com.example.axiomzencars.activities;
import com.example.axiomzencars.R;
import com.example.axiomzencars.data.ImageDownloader;
import com.example.axiomzencars.data.api.ApiRequest;
import com.example.axiomzencars.data.api.ApiRequest.OnTaskCompletedListener;
import com.example.axiomzencars.data.api.ApiResponse;
import com.example.axiomzencars.data.car.Car;
import com.example.axiomzencars.data.car.MakeModel;
import com.example.axiomzencars.data.car.Price;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class DetailedCarActivity extends Activity {
private static final String TAG = DetailedCarActivity.class.getSimpleName();
private Car car;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_car);
car = getIntent().getParcelableExtra(AvailableCarsActivity.CAR_EXTRA);
if (car == null) {
Toast.makeText(this, "Error loading car details", Toast.LENGTH_SHORT).show();
finish();
}
Log.d(TAG, car.toString());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setTitle(String.format("%s %s", car.getModelMake().getMake(), car.getModelMake().getModel()));
TextView carMakeTextView = (TextView) findViewById(R.id.car_make_text_view);
TextView carModelTextView = (TextView) findViewById(R.id.car_model_text_view);
TextView carYearTextView = (TextView) findViewById(R.id.car_year_text_view);
TextView carPriceTextView = (TextView) findViewById(R.id.car_price_text_view);
TextView carDescriptionTextView = (TextView) findViewById(R.id.car_description_text_view);
carMakeTextView.setText(car.getModelMake().getMake());
carModelTextView.setText(car.getModelMake().getModel());
carYearTextView.setText(String.valueOf(car.getYear().value()));
carPriceTextView.setText(String.valueOf(car.getPrice().value()));
carDescriptionTextView.setText(car.getDescription().getDescriptionText());
downloadCarImage(findViewById(R.id.car_image_progress_indicator), (ImageView) findViewById(R.id.car_image_view));
downloadStandardPrice(findViewById(R.id.car_standard_price_progress_indicator),
(TextView) findViewById(R.id.car_standard_price_text_view), (TextView) findViewById(R.id.car_price_difference_text_view));
downloadBestAndWorstOfYear(findViewById(R.id.car_best_or_worst_of_year_progress_indicator),
(TextView) findViewById(R.id.car_best_or_worst_of_year_text_view));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return false;
}
private void downloadCarImage(final View progressIndicator, final ImageView imageView) {
new ImageDownloader(car.getImage().getUrl(), new ImageDownloader.OnImageDownloadedListener() {
@Override
public void onImageDownloaded(Bitmap bitmap) {
progressIndicator.setVisibility(View.GONE);
imageView.setImageBitmap(bitmap);
}
}).execute();
}
private void downloadStandardPrice(final View progressIndicator, final TextView standardPriceTextView,
final TextView priceDifferenceTextView) {
ApiRequest.requestStandardPrice(this, car, new OnTaskCompletedListener() {
@Override
public void onTaskCompleted(ApiResponse response) {
Price standardPrice = response.getStandardPrice();
if (standardPrice != null) {
progressIndicator.setVisibility(View.GONE);
standardPriceTextView.setText(String.valueOf(standardPrice.value()));
int priceDifference = car.getPrice().value() - standardPrice.value();
if (priceDifference < 0) {
priceDifferenceTextView.setTextColor(Color.rgb(0, 150, 0));
priceDifferenceTextView.setText(String.format("%d", priceDifference));
} else if (priceDifference > 0) {
priceDifferenceTextView.setTextColor(Color.rgb(180, 0, 0));
priceDifferenceTextView.setText(String.format("+%d", priceDifference));
}
standardPriceTextView.setVisibility(View.VISIBLE);
}
}
});
}
private void downloadBestAndWorstOfYear(final View progressIndicator, final TextView textView) {
ApiRequest.requestBestCarsForYear(this, car.getYear().value(), new OnTaskCompletedListener() {
@Override
public void onTaskCompleted(ApiResponse response) {
if (response.getBestCarsForYear() != null) {
for (MakeModel modelMake : response.getBestCarsForYear()) {
if (car.isModelMake(modelMake)) {
textView.setText(String.format("Best of %d", car.getYear().value()));
textView.setTextColor(Color.rgb(0, 150, 0));
textView.setVisibility(View.VISIBLE);
progressIndicator.setVisibility(View.GONE);
return;
}
}
}
ApiRequest.requestWorstCarsForYear(DetailedCarActivity.this, car.getYear().value(), new OnTaskCompletedListener() {
@Override
public void onTaskCompleted(ApiResponse response) {
if (response.getWorstCarsForYear() != null) {
for (MakeModel modelMake : response.getWorstCarsForYear()) {
if (car.isModelMake(modelMake)) {
textView.setText(String.format("Worst of %d", car.getYear().value()));
textView.setTextColor(Color.rgb(180, 0, 0));
textView.setVisibility(View.VISIBLE);
break;
}
}
}
progressIndicator.setVisibility(View.GONE);
}
});
}
});
}
}
| true
|
bc7174c581b1f6a6ae545c592cf8b566355ea4d2
|
Java
|
ER2-1017/Homework_03
|
/src/Hw03.java
|
UTF-8
| 1,410
| 3.671875
| 4
|
[] |
no_license
|
import java.util.Scanner;
public class Hw03 {
public static void main(String[] args){
int play=1;
do {
int guess=(int) Math.round(9*Math.random());
System.out.println("Угадайте c трёх раз число от 0 до 9.");
int tryCount=2;
while (tryCount >=0) {
Scanner scan = (new Scanner(System.in));
int userAnswer = scan.nextInt();
if (userAnswer == guess) {
System.out.println("Вы угадали!");
break;
} else if (userAnswer > guess) {
System.out.println("Вы ввели слишком большое число! Осталось попыток: " + (tryCount));
tryCount--;
} else if (tryCount==0 && userAnswer!=guess){
System.out.println("Вы проиграли!");
break;
} else {
System.out.println("Вы ввели слишком маленькое число! Осталось попыток: " + (tryCount));
tryCount--;
}
}
System.out.println("Сыграть ещё? 1 - да, 0 - нет.");
Scanner scan = (new Scanner(System.in));
play = scan.nextInt();
} while (play==1);
}
}
| true
|
244899b86950ae97e0b5e84bc402f3c3e6e6337c
|
Java
|
plssts/Java2020
|
/src/main/java/com/j2020/model/deutsche/DeutscheSepaPaymentRequestData.java
|
UTF-8
| 1,805
| 2.46875
| 2
|
[] |
no_license
|
/**
* @author Paulius Staisiunas
*/
package com.j2020.model.deutsche;
import com.j2020.Constants;
public class DeutscheSepaPaymentRequestData {
private String type = Constants.DEUTSCHE_SEPA_PAYMENT_REQUEST_DATA_TYPE;
private String targetIban;
private String amountCurrency;
private String amountValue;
public DeutscheSepaPaymentRequestData() {
}
public DeutscheSepaPaymentRequestData(String targetIban, String amountCurrency, String amountValue) {
this.targetIban = targetIban;
this.amountCurrency = amountCurrency;
this.amountValue = formatValue(amountValue);
}
public static String formatValue(String value) {
StringBuilder builder = new StringBuilder(value);
if (builder.indexOf(".") > 0) {
while (builder.substring(builder.length() - 1).equals("0")) {
builder = builder.deleteCharAt(builder.length() - 1);
}
if (builder.substring(builder.length() - 1).equals(".")) {
builder = builder.deleteCharAt(builder.length() - 1);
}
}
return builder.toString();
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTargetIban() {
return targetIban;
}
public void setTargetIban(String targetIban) {
this.targetIban = targetIban;
}
public String getAmountCurrency() {
return amountCurrency;
}
public void setAmountCurrency(String amountCurrency) {
this.amountCurrency = amountCurrency;
}
public String getAmountValue() {
return amountValue;
}
public void setAmountValue(String amountValue) {
this.amountValue = formatValue(amountValue);
}
}
| true
|
84105fa4082c36f12c09919193dc30a3ba4875e9
|
Java
|
fjh658/bindiff
|
/src_procyon/y/a/V_1.java
|
UTF-8
| 765
| 2.1875
| 2
|
[] |
no_license
|
package y.a;
import y.c.*;
class V extends S
{
private V() {
}
double a(final d[] array, final c c, final int n) {
final boolean a = h.a;
if (array.length == 0) {
return 0.0;
}
final i e = array[0].c().e();
final double a2 = S.b().a(array, c, n);
final int[] a3 = S.a(e, c, n);
int n2 = 0;
int i = 0;
while (i < a3.length) {
if (a3[i] > 0) {
n2 += a3[i] * (a3[i] - 1);
}
++i;
if (a) {
break;
}
}
return 1.0 - 2.0 / (e.e() * (e.e() - 1)) * ((1.0 - 2.0 * a2 / array.length) * array.length + 0.5 * n2);
}
V(final T t) {
this();
}
}
| true
|
f230132773ed354f64e3cf5560b3c0d1940b8303
|
Java
|
kuryaki/cs-fpp
|
/lab3/src/prob1/Util.java
|
UTF-8
| 226
| 2.328125
| 2
|
[
"MIT"
] |
permissive
|
package prob1;
import java.text.DateFormat;
import java.util.Date;
public class Util {
public static String dateAsString(Date d) {
DateFormat f = DateFormat.getDateInstance(DateFormat.SHORT);
return f.format(d);
}
}
| true
|
7c063f1e69d4ebf5406bce8e1c9fece431a52949
|
Java
|
shuaike123/test
|
/20200312_JavaWebAjax5/src/com/zking/dao/JDBCUtils.java
|
UTF-8
| 2,713
| 2.75
| 3
|
[] |
no_license
|
package com.zking.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
public class JDBCUtils {
//数据库操作类
private QueryRunner runner = new QueryRunner(DBPool.getInstance().getDataSource());
/**
* 更新数据--返回更新的数据条数
*/
public int updateObject(String sql, Object...params) {
Connection conn = null;
PreparedStatement pst = null;
int n = 0;
try {
conn = DBPool.getInstance().getConnection();
pst = conn.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
pst.setObject(i + 1, params[i]);
}
}
n = pst.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
close(conn, pst);
}
return n;
}
/**
* 增加数据--返回更新的数据的自增主键值
* @param sql 增加sql
* @param params 参数
* @return 这个增加语句产生的主键值
*/
public Long addObject(String sql, Object...params) {
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
Long n = new Long(0);
try {
conn = DBPool.getInstance().getConnection();
//autoGeneratedKeys:自动生成主键
//RETURN_GENERATED_KEYS:返回生成的主键
pst = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
if (params != null) {
for (int i = 0; i < params.length; i++) {
pst.setObject(i + 1, params[i]);
}
}
pst.executeUpdate();
//获取返回的主键
rs = pst.getGeneratedKeys();
//获取结果集中的返回的主键
n = rs.next()?rs.getLong(1):-1;
} catch (Exception e) {
e.printStackTrace();
} finally {
close(conn, pst);
}
return n;
}
/**
* 查询所有数据条数
*/
public int getTotalCount(String sql) {
try {
return Integer.parseInt(runner.query(sql, new ScalarHandler<Object>()).toString());
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
//释放资源
public void close(Connection conn, Statement st, ResultSet rs) {
try {
if (conn != null) {
conn.close();
}
if (st != null) {
st.close();
}
if (rs != null) {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void close(Connection conn, Statement st) {
try {
if (conn != null) {
conn.close();
}
if (st != null) {
st.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true
|
efad01844635af63fdccc1586d997a37df132e40
|
Java
|
puongdv/ums-api
|
/src/vn/ghn/warehouse/ActionOneWarehouse.java
|
UTF-8
| 4,231
| 2.421875
| 2
|
[] |
no_license
|
/*
* 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 vn.ghn.warehouse;
import com.google.gson.Gson;
import common.api.APIRequest;
import common.api.APIResource;
import common.api.APIResponder;
import common.api.APIResponse;
import common.api.APIStatus;
import common.api.annotation.APIMethod;
import org.apache.log4j.Logger;
import vn.ghn.utils.Utility;
/**
*
* @author Bee
*/
public class ActionOneWarehouse extends APIResource{
private static final Logger LOGGER = Logger.getLogger(ActionOneWarehouse.class);
private static final Gson GSON = new Gson();
public ActionOneWarehouse(String path) {
super(path);
}
@APIMethod(name = "GET")
public void onGet(APIRequest req, APIResponder resp) {
try {
String id = req.getVar("id");
if (id == null || id.isEmpty()) {
resp.respond(new APIResponse(APIStatus.INVALID, "Invalid id."));
return;
}
APIResponse<Warehouse> apiResult = WarehouseClient.getInstance()
.get(Utility.stringArrToIntArr(id.split(",")));
if(apiResult == null){
resp.respond(
new APIResponse(
APIStatus.ERROR,
"Management system is busy, please try again later."
)
);
return;
}
resp.respond(apiResult);
} catch (Exception ex) {
LOGGER.error(ex.getMessage(), ex);
resp.respond(new APIResponse(APIStatus.ERROR, "An error occurred, please try again later."));
}
}
@APIMethod(name = "PUT")
public void onPut(APIRequest req, APIResponder resp) {
try {
String id = req.getVar("id");
if (id == null || id.isEmpty()) {
resp.respond(new APIResponse(APIStatus.INVALID, "Invalid id."));
return;
}
String content = req.getContent();
Warehouse warehouse = null;
if (content != null) {
try {
warehouse = GSON.fromJson(content, Warehouse.class);
} catch (Exception ex) {
LOGGER.error(ex.getMessage(), ex);
}
}
if (warehouse == null){
resp.respond(new APIResponse(APIStatus.INVALID, "Invalid data. Please put in JSON format."));
return;
}
APIResponse<Warehouse> result = WarehouseClient.getInstance().update(Utility.parseInt(id), warehouse);
if(result == null){
resp.respond(new APIResponse(APIStatus.ERROR, "Management system is busy, please try again later."));
return;
}
resp.respond(result);
} catch (Exception ex) {
LOGGER.error(ex.getMessage(), ex);
resp.respond(new APIResponse(APIStatus.ERROR, "An error occurred, please try again later."));
}
}
@APIMethod(name = "DELETE")
public void onDelete(APIRequest req, APIResponder resp) {
try {
String id = req.getVar("id");
if (id == null || id.isEmpty()) {
resp.respond(new APIResponse(APIStatus.INVALID, "Invalid id."));
return;
}
APIResponse<Warehouse> result = WarehouseClient.getInstance().delete(Utility.parseInt(id));
if(result == null){
resp.respond(new APIResponse(APIStatus.ERROR, "Management system is busy, please try again later."));
return;
}
resp.respond(result);
} catch (Exception ex) {
LOGGER.error(ex.getMessage(), ex);
resp.respond(new APIResponse(APIStatus.ERROR, "An error occurred, please try again later."));
}
}
}
| true
|
09bf2ae12d652fe1b898a3fdaf66df113bf94385
|
Java
|
HarshitaInani/salespersonApp
|
/Mp Salesperson 2/AmitLibs/src/com/Amitlibs/utils/Commons.java
|
UTF-8
| 3,021
| 2.640625
| 3
|
[] |
no_license
|
package com.Amitlibs.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.List;
import org.apache.http.NameValuePair;
import android.content.Context;
import android.text.format.DateFormat;
import android.widget.Toast;
public class Commons {
public static String serialize(Serializable obj) {
if (obj == null)
return "";
try {
ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
objStream.writeObject(obj);
objStream.close();
return encodeBytes(serialObj.toByteArray());
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error in Serialization");
}
return "";
}
public static Object deserialize(String str) {
if (str == null || str.length() == 0)
return null;
try {
ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
ObjectInputStream objStream = new ObjectInputStream(serialObj);
return objStream.readObject();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error in Deserialization");
}
return null;
}
public static String encodeBytes(byte[] bytes) {
StringBuffer strBuf = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
}
return strBuf.toString();
}
public static byte[] decodeBytes(String str) {
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length(); i += 2) {
char c = str.charAt(i);
bytes[i / 2] = (byte) ((c - 'a') << 4);
c = str.charAt(i + 1);
bytes[i / 2] += (c - 'a');
}
return bytes;
}
public static void toastMessage(Context context, String msg) {
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
}
public static String formatDecimal(double d) {
DecimalFormat format = new DecimalFormat("#.##");
return format.format(d);
// return String.format("%.2f", d);
}
public static String getStringMonth(int m) {
return new String[] { "JAN", "FAB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" }[m];
}
public static String date(final String format) {
return DateFormat.format(format, System.currentTimeMillis()).toString();
}
public static String getUrlEncodedString(List<NameValuePair> nvp) {
String encodedString = "";
for (NameValuePair n : nvp) {
try {
String name = URLEncoder.encode(n.getName(), "ISO-8859-1");
String value = URLEncoder.encode(n.getValue(), "ISO-8859-1");
encodedString += name + "=" + value + "&";
} catch (UnsupportedEncodingException e) {
System.out.println("Encoding Error from AppUtils");
e.printStackTrace();
}
}
return encodedString;
}
}
| true
|
6b58472dbaa523021b10e09c07b981bfd9765c60
|
Java
|
Kostyshina/Boilerplate
|
/app/src/main/java/com/andersenlab/boilerplate/activity/MainActivity.java
|
UTF-8
| 659
| 2.03125
| 2
|
[] |
no_license
|
package com.andersenlab.boilerplate.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.andersenlab.boilerplate.R;
import butterknife.ButterKnife;
import butterknife.OnClick;
import timber.log.Timber;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@OnClick(R.id.btn_main_add_item)
public void addItem(View view) {
Timber.i("Tap on add item button");
}
}
| true
|
f27bed73828a1402b7bb567f363d15a86bcb4aec
|
Java
|
gbumgard/js4ms
|
/js4ms-jsdk/common/src/main/java/org/js4ms/common/util/buffer/BufferBackedObject.java
|
UTF-8
| 3,957
| 2.609375
| 3
|
[
"Apache-2.0"
] |
permissive
|
package org.js4ms.common.util.buffer;
/*
* #%L
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* BufferBackedObject.java [org.js4ms.jsdk:common]
* %%
* Copyright (C) 2009 - 2014 Cisco Systems, 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.
* #L%
*/
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.js4ms.common.util.logging.LoggableBase;
/**
* @author Gregory Bumgardner
*/
public abstract class BufferBackedObject
extends LoggableBase {
final ByteBuffer buffer;
/**
* Creates a slice of the remaining bytes within the buffer, sets the
* limit in the slice to the value specified for the size argument,
* and advances the input buffer position by the same amount.
*/
public static ByteBuffer consume(final ByteBuffer buffer, final int size) {
ByteBuffer slice = buffer.slice();
buffer.position(buffer.position() + size);
slice.limit(size);
return slice;
}
/**
* Creates a buffer containing bytes read from an InputStream.
*
* @throws IOException
*/
public static ByteBuffer consume(final InputStream is, final int size) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(size);
is.read(buffer.array(), 0, size);
return buffer;
}
/**
* @param size
*/
public BufferBackedObject(final int size) {
this.buffer = ByteBuffer.allocate(size);
}
/**
* @param buffer
*/
public BufferBackedObject(final ByteBuffer buffer) {
this.buffer = buffer.slice();
}
/**
* @param buffer
* @param size
*/
public BufferBackedObject(final ByteBuffer buffer, final int size) {
this.buffer = consume(buffer, size);
}
/**
* @param buffer
* @param size
* @throws IOException
*/
public BufferBackedObject(final InputStream is, final int size) throws IOException {
this.buffer = consume(is, size);
}
/**
* Returns a duplicate of the ByteBuffer instance referenced by this object.
*
* @return
*/
public final ByteBuffer getBuffer() {
return this.buffer.duplicate();
}
/**
* Returns the actual ByteBuffer instance referenced by this object.
*
* @return
*/
protected final ByteBuffer getBufferInternal() {
return this.buffer;
}
/**
* @param buffer
*/
public void writeTo(final ByteBuffer buffer) {
this.buffer.rewind();
buffer.put(this.buffer);
this.buffer.rewind();
}
@Override
public void log(final Logger logger, final Level level) {
super.log(logger, level);
logState(logger, level);
}
/**
* Logs member variables declared or maintained by this class.
*
* @param logger
*/
private void logState(final Logger logger, final Level level) {
logger.log(level,this.log.msg(": buffer array-offset=" + this.buffer.arrayOffset() +
", position=" + this.buffer.position() +
", remaining=" + this.buffer.remaining() +
", limit=" + this.buffer.limit() +
", capacity=" + this.buffer.capacity()));
}
}
| true
|
7b4fed6dbbabdcc1132d17bd7011ecad5a62126c
|
Java
|
MaheshInfogird/HrGirdAdminNew
|
/app/src/main/java/com/hrgirdowner/BaseActivityExp.java
|
UTF-8
| 27,543
| 1.585938
| 2
|
[] |
no_license
|
package com.hrgirdowner;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
@SuppressWarnings("deprecation")
public class BaseActivityExp extends ActionBarActivity {
private CharSequence mDrawerTitle;
private CharSequence mTitle;
SharedPreferences pref;
UserSessionManager session;
private ActionBarDrawerToggle mDrawerToggle;
public static final String MyPREFERENCES_notify = "MyPrefs_notify" ;
SharedPreferences pref1;
SharedPreferences.Editor editor, editor2;
private static final String PREFER_NAME = "MyPref";
public static final String MyPREFERENCES_url = "MyPrefs_url" ;
public static final String MyPREFERENCES = "MyPrefs" ;
int PRIVATE_MODE = 0;
SharedPreferences shared_pref, pref_rm;
SharedPreferences.Editor editor1;
private DrawerLayout mDrawerLayout;
private android.app.Fragment fragment = null;
private ExpandableListView expListView;
private HashMap<String, List<String>> listDataChild;
private ExpandableListAdapter listAdapter;
ImageView Headerimage;
View view_Group;
String Url, logo;
String firstName, LastName, Email;
static String reportingManager;
int lastExpandedPosition = -1;
Toolbar toolbar;
private List<String> listDataHeader;
static int[] icon_rm = { R.drawable.dashboard_icon,
//R.drawable.approved_leave,
//R.drawable.pending_approvals,
R.drawable.need_to_review_icon,
R.drawable.attendance_icon,
R.drawable.events_icon,
R.drawable.settings_icon
/* R.drawable.logout_icon*/};
static int[] icon = { R.drawable.dashboard_icon,
R.drawable.leave_menu_icon,
R.drawable.events_icon,
//R.drawable.approved_leave,
//R.drawable.pending_approvals,
//R.drawable.leave_menu_icon,
R.drawable.attendance_listing_icon,
R.drawable.settings_icon/*,
R.drawable.logout_icon*/};
static int[] sub_icon = { R.drawable.birthday_icon_new,
R.drawable.work_anni_icon,
R.drawable.marriage_anni_icon};
static int[] sub_icon_att = { R.drawable.daily_attendance_icon,
R.drawable.absent_attendance_icon,
R.drawable.on_leave_attendance_icon,
R.drawable.holiday_icon};
static int[] sub_icon_review = { R.drawable.review_icon,
R.drawable.reviewed_icon};
static int[] sub_icon_settings = { R.drawable.reset_password_icon,
R.drawable.logout_icon,R.drawable.logout_icon};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.base_activity_exp);
session = new UserSessionManager(getApplicationContext());
toolbar = (Toolbar)findViewById(R.id.toolbar_inner);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mTitle = mDrawerTitle = getTitle();
shared_pref = getSharedPreferences(MyPREFERENCES_url, MODE_PRIVATE);
Url = (shared_pref.getString("url", ""));
logo = (shared_pref.getString("logo", ""));
pref = getApplicationContext().getSharedPreferences(PREFER_NAME, this.MODE_PRIVATE);
firstName = pref.getString("Tag_firstname", "");
LastName = pref.getString("Tag_lastname", "");
Email = pref.getString("Tag_email", "");
pref_rm = getApplicationContext().getSharedPreferences(MyPREFERENCES, this.MODE_PRIVATE);
reportingManager = pref_rm.getString("reportingManager","");
setUpDrawer();
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
@Override
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
@Override
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
makeActionOverflowMenuShown();
}
// actionbar over flow icon
public void makeActionOverflowMenuShown()
{
try
{
final ViewConfiguration config = ViewConfiguration.get(this);
final Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if (menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
}
catch (final Exception e) {
Log.e("", e.getLocalizedMessage());
}
}
public void setUpDrawer()
{
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerListener(mDrawerListener);
expListView = (ExpandableListView) findViewById(R.id.list_slidermenu);
prepareListData();
LayoutInflater inflater = getLayoutInflater();
View listHeaderView = inflater.inflate(R.layout.side_menu_header, null, false);
Headerimage = (ImageView)listHeaderView.findViewById(R.id.header_logo);
Picasso.with(this).load(logo).into(Headerimage);
expListView.addHeaderView(listHeaderView);
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
expListView.setAdapter(listAdapter);
expListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
@Override
public void onGroupExpand(int groupPosition) {
Log.i("expand","last="+lastExpandedPosition);
Log.i("expand","group="+groupPosition);
if (lastExpandedPosition!=-1 && groupPosition!=lastExpandedPosition){
expListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
Log.i("expand","last_after="+lastExpandedPosition);
}
});
expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener()
{
@Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id)
{
v.setSelected(true);
switch (groupPosition)
{
case 0:
Intent intent1 = new Intent(getApplicationContext(), DashBoard.class);
startActivity(intent1);
finish();
break;
/* case 1:
Intent intent2 = new Intent(getApplicationContext(), HolidayActivity.class);
startActivity(intent2);
finish();
break;*/
case 1:
if (!reportingManager.equals("1"))
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(BaseActivityExp.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
alertDialog.setTitle("Not Authorised");
alertDialog.setMessage("Your not authorized for Review");
alertDialog.setCancelable(true);
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
alertDialog.show();
}
break;
case 2:
/*Intent intent4 = new Intent(getApplicationContext(), Approvals.class);
startActivity(intent4);
finish();*/
/* if (!reportingManager.equals("1"))
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(BaseActivityExp.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
alertDialog.setTitle("Not Authorised");
alertDialog.setMessage("Your not authorized for Review");
alertDialog.setCancelable(true);
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
alertDialog.show();
}
break;*/
break;
case 3:
/* Intent intent5 = new Intent(getApplicationContext(), PendingApprovals.class);
startActivity(intent5);
finish();*/
/* Intent intent6 = new Intent(getApplicationContext(), AttendanceListing.class);
startActivity(intent6);
finish();*/
break;
case 4:
/*Intent intent6 = new Intent(getApplicationContext(), AttendanceListing.class);
startActivity(intent6);
finish();*/
/* Intent intent8 = new Intent(getApplicationContext(), Settings.class);
startActivity(intent8);
finish();*/
break;
// case 6:
/*Intent intent8 = new Intent(getApplicationContext(), Settings.class);
startActivity(intent8);
finish();*/
/* AlertDialog.Builder alertDialog = new AlertDialog.Builder(BaseActivityExp.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
alertDialog.setTitle("Logout");
alertDialog.setMessage("Do you want to logout from Application?");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
session.logoutUser();
NavDrawerListAdapter.setSelectedPosition(0);
Intent intent = new Intent(BaseActivityExp.this, LogInActivity.class);
startActivity(intent);
finish();
pref1 = getApplicationContext().getSharedPreferences(MyPREFERENCES_notify, PRIVATE_MODE);
editor2 = pref.edit();
editor2.clear();
editor2.putBoolean("notification", false);
editor2.commit();
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
}
});
alertDialog.show();
break;*/
/*case 7:
*//*AlertDialog.Builder alertDialog = new AlertDialog.Builder(BaseActivityExp.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
alertDialog.setTitle("Logout");
alertDialog.setMessage("Do you want to logout from Application?");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
session.logoutUser();
NavDrawerListAdapter.setSelectedPosition(0);
Intent intent = new Intent(BaseActivityExp.this, LogInActivity.class);
startActivity(intent);
finish();
pref1 = getApplicationContext().getSharedPreferences(MyPREFERENCES_notify, PRIVATE_MODE);
editor2 = pref.edit();
editor2.clear();
editor2.putBoolean("notification", false);
editor2.commit();
}
// });
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
}
});
alertDialog.show();*//*
break;
case 8:
*//*Intent intent9 = new Intent(getApplicationContext(), Settings.class);
startActivity(intent9);
finish();*//*
break;*/
default:
break;
}
return false;
}
});
expListView.setOnChildClickListener(new OnChildClickListener()
{
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
{
v.setSelected(true);
if (view_Group != null) {
}
view_Group = v;
switch (groupPosition)
{
case 0:
break;
/* case 1:
break;*/
case 1:
if (reportingManager.equals("1")) {
switch (childPosition) {
case 0:
Intent intent4 = new Intent(getApplicationContext(), ReviewActivity.class);
startActivity(intent4);
finish();
break;
case 1:
Intent intent5 = new Intent(getApplicationContext(), ReviewedActivity.class);
startActivity(intent5);
finish();
break;
default:
break;
}
}
break;
case 2:
Intent intent8 = new Intent(getApplicationContext(), AttendanceListing.class);
startActivity(intent8);
finish();
switch (childPosition)
{
case 0:
Intent intent2 = new Intent(getApplicationContext(), AttendanceListing.class);
startActivity(intent2);
finish();
break;
case 1:
Intent intent4 = new Intent(getApplicationContext(), AttendanceListingAbsent.class);
startActivity(intent4);
finish();
break;
case 2:
Intent intent5 = new Intent(getApplicationContext(), AttendanceListingOnLeave.class);
startActivity(intent5);
finish();
break;
case 3:
Intent intent6 = new Intent(getApplicationContext(), HolidayActivity.class);
startActivity(intent6);
finish();
break;
default:
break;
}
break;
case 3:
switch (childPosition)
{
case 0:
Intent intent2 = new Intent(getApplicationContext(), BirthdayActivity.class);
startActivity(intent2);
finish();
break;
case 1:
Intent intent4 = new Intent(getApplicationContext(), WorkAnnActivity.class);
startActivity(intent4);
finish();
break;
case 2:
Intent intent5 = new Intent(getApplicationContext(), MarriageAnnActivity.class);
startActivity(intent5);
finish();
break;
default:
break;
}
break;
case 4:
switch (childPosition) {
case 0:
Intent intent6 = new Intent(getApplicationContext(), Settings.class);
startActivity(intent6);
finish();
break;
case 1:
Intent intent7 = new Intent(getApplicationContext(), PostActivity.class);
startActivity(intent7);
finish();
break;
case 2:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(BaseActivityExp.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
alertDialog.setTitle("Logout");
alertDialog.setMessage("Do you want to logout from Application?");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
session.logoutUser();
NavDrawerListAdapter.setSelectedPosition(0);
Intent intent = new Intent(BaseActivityExp.this, LogInActivity.class);
startActivity(intent);
finish();
/* pref1 = getApplicationContext().getSharedPreferences(MyPREFERENCES_notify, PRIVATE_MODE);
editor2 = pref.edit();
editor2.clear();
editor2.putBoolean("notification", false);
editor2.commit();*/
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
}
});
alertDialog.show();
break;
default:
break;
}
/* case 6:
break;*/
/* case 7:
break;
case 8:
*//*Intent intent9 = new Intent(getApplicationContext(), Approvals.class);
startActivity(intent9);
finish();*/
default:
break;
}
expListView.setItemChecked(childPosition, true);
expListView.setSelection(groupPosition);
mDrawerLayout.closeDrawer(expListView);
return false;
}
});
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
// Pass any configuration //change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == android.R.id.home)
{
if (mDrawerLayout.isDrawerOpen(expListView))
{
mDrawerLayout.closeDrawer(expListView);
}
else
{
mDrawerLayout.openDrawer(expListView);
}
}
return super.onOptionsItemSelected(item);
}
private DrawerListener mDrawerListener = new DrawerListener() {
@Override
public void onDrawerStateChanged(int status) {
}
@Override
public void onDrawerSlide(View view, float slideArg) {
}
@Override
public void onDrawerOpened(View view) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
supportInvalidateOptionsMenu();
}
@Override
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
supportInvalidateOptionsMenu();
}
};
private void prepareListData()
{
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
String[] array = getResources().getStringArray(R.array.nav_drawer_items_rm);
listDataHeader = Arrays.asList(array);
List<String> dashboard = new ArrayList<String>();
//String[] dash = getResources().getStringArray(R.array.dashboard);
//dashboard = Arrays.asList(dash);
// List<String> leaves = new ArrayList<String>();
//String[] sub_leaves = getResources().getStringArray(R.array.leaves);
//leaves = Arrays.asList(sub_leaves);
List<String> events = new ArrayList<String>();
String[] sub_events = getResources().getStringArray(R.array.events);
events = Arrays.asList(sub_events);
List<String> settings = new ArrayList<String>();
String[] sub_settings = getResources().getStringArray(R.array.settings);
settings = Arrays.asList(sub_settings);
List<String> approved = new ArrayList<String>();
//String[] myproe = getResources().getStringArray(R.array.approved);
//approved = Arrays.asList(myproe);
List<String> pending = new ArrayList<String>();
//String[] inco = getResources().getStringArray(R.array.pending);
//pending = Arrays.asList(inco);
List<String> attListing = new ArrayList<String>();
String[] sub_att = getResources().getStringArray(R.array.attListing);
attListing = Arrays.asList(sub_att);
//String[] listing = getResources().getStringArray(R.array.attListing);
//attListing = Arrays.asList(listing);
/* List<String> settings = new ArrayList<String>();*/
List<String> logout = new ArrayList<String>();
List<String> review = new ArrayList<String>();
if (reportingManager.equals("1")) {
String[] sub_review = getResources().getStringArray(R.array.need_review);
review = Arrays.asList(sub_review);
}
listDataChild.put(listDataHeader.get(0), dashboard); // Header, Child data
/* listDataChild.put(listDataHeader.get(1), leaves);*/
listDataChild.put(listDataHeader.get(1), review);
listDataChild.put(listDataHeader.get(2), attListing);
listDataChild.put(listDataHeader.get(3), events);
//listDataChild.put(listDataHeader.get(3), approved);
//listDataChild.put(listDataHeader.get(4), pending);
listDataChild.put(listDataHeader.get(4), settings);
// listDataChild.put(listDataHeader.get(6), logout);
// assigning values to menu and submenu
}
}
| true
|
f04aeaabb94af6a64475d50a546fce6572541515
|
Java
|
y3ton/rdb
|
/rdbback/db/src/main/java/ru/rdb/db/repositories/LinkRepository.java
|
UTF-8
| 714
| 2.125
| 2
|
[] |
no_license
|
package ru.rdb.db.repositories;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import ru.rdb.models.DbId;
import ru.rdb.models.Link;
public interface LinkRepository extends CrudRepository<Link, DbId> {
@Query(
nativeQuery = true,
value =
"SELECT id, grp, url, create_date, read_date " +
"FROM public.links " +
"where grp = :group and (read_date is null or read_date < :maxDate) " +
"order by random() " +
"limit 1")
Link getRandom(@Param("group") String group, @Param("maxDate") Long maxDate);
}
| true
|
ed8e17bc5d5839a0937e0c1baa62668da1fb962f
|
Java
|
4102Discord/4102Week13
|
/tweet.java
|
UTF-8
| 3,456
| 2.953125
| 3
|
[
"Unlicense",
"MIT"
] |
permissive
|
import java.lang.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Collections;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.*;
/**
*
*/
public class tweet
{
private String tweetContent;
private int retweet;
HashMap <String, tweet> tweetList = new HashMap<String, tweet>();
List<String> txt= new ArrayList<String>();
/**
* Constructor for objects of class tweet
*/
public tweet(List<String> text)
{
txt = text;
this.retweet = retweet;
}
public int getRetweet (){
return this.retweet;
}
public void setRetweet (String c){
this.retweet = Integer.parseInt(c);
}
public void setTweetContent (String c){
this.tweetContent = c;
}
public String getTweetContent (){
return this.tweetContent;
}
public void getTweetData()
{
String date = "";
String tweetContent = "";
String rt= "";
String patternString1 = ".*\\[.*\\]\\s.*\\s\\d{0,}\\s\\d{0,}.*";
Pattern pattern = Pattern.compile(patternString1);
String arr = "";
for (int j = 0; j < txt.size(); j++){
Matcher matcher = pattern.matcher(txt.get(j));
if(matcher.find()) {
tweet t = new tweet(txt);
arr = matcher.group().split("\\]\\s")[1].trim();
arr.replace("]"," ");
String [] arr1 = arr.split(" ");
tweetContent = arr.replace(arr1[arr1.length-2]+" "+arr1[arr1.length-1]," ").trim();
rt = arr1[arr1.length-1];
t.setRetweet(rt);
tweetList.put(tweetContent,t);
}
}
}
public void maxRetweet(int n){
try {
FileWriter writer = new FileWriter("maxRetweet.txt", true);
List<Integer> retweetCount = new ArrayList<Integer>();
for (String key: tweetList.keySet()){
retweetCount.add(tweetList.get(key).getRetweet());
Collections.sort(retweetCount,Collections.reverseOrder());
}
List<String> list = new ArrayList<String>();
writer.write("Top"+ n+" tweets have the most retweet\r\n");
for (int i=0; i<n; i++){
for (String key : tweetList.keySet()) {
if ((tweetList.get(key)).getRetweet()== retweetCount.get(i)){
if (list.size()>n-1)
break;
if (!list.contains(key))
list.add(key);
}
}
}
for (int i = 0; i < list.size(); i++) {
writer.write(list.get(i)+" Retweeted " +retweetCount.get(i)+" times\r\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true
|
03f8ecd317926dd57c760f95f5f901144d1a5723
|
Java
|
amanda-plotnik/EmployeeDatabase
|
/EMS-master/src/hashtables/MyHashTable.java
|
UTF-8
| 6,591
| 3.59375
| 4
|
[] |
no_license
|
package hashtables;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import java.io.File;
import java.util.*;
public class MyHashTable {
public ArrayList<EmployeeInfo>[] buckets;
private int k;
public MyHashTable(int numBuckets) {
k = numBuckets;
buckets = new ArrayList[k];
for (int i = 0; i < k; i++) {
buckets[i] = new ArrayList<EmployeeInfo>();
}
}
//Main methods (add, remove, search)
public void addEmployee(EmployeeInfo toAdd) {
int buck = toAdd.getEmpNumber() % k;
buckets[buck].add(toAdd);
}
public boolean removeEmployee(EmployeeInfo toSack) {
int buck = toSack.getEmpNumber() % k;
for (int i = 0; i < buckets[buck].size(); i++) {
if (buckets[buck].get(i).getEmpNumber() == toSack.getEmpNumber()) {
buckets[buck].remove(i);
}
}
return true;
}
public EmployeeInfo search(int toFind) {
int buck = toFind % k;
EmployeeInfo found = null;
int position = -1;
for (int i = 0; i < buckets[buck].size(); i++) {
if (buckets[buck].get(i).getEmpNumber() == toFind) {
position = i;
found = buckets[buck].get(i);
}
}
System.out.println("Employee Number " + toFind + " can be found in bucket " + buck + ", position " + position);
return found;
}
//Other methods (display, read/write from file)
public void displayContents() {
// Print the employee numbers for the employees stored in each bucket's ArrayList, starting with bucket 0, then bucket 1, and so on.
for (int i = 0; i < buckets.length; i++) {
// For the current bucket, print out the employee number for each item in its ArrayList.
System.out.println("\nExamining the ArrayList for bucket " + i);
int listSize = buckets[i].size();
if (listSize == 0) {
System.out.println(" Nothing in its ArrayList!");
} else {
for (int j = 0; j < listSize; j++) {
int theEmpNum = buckets[i].get(j).getEmpNumber();
System.out.println(" Employee " + theEmpNum);
}
}
}
}
public void readFromFile() {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("dataTextFile.txt"));
String line;
while ((line = reader.readLine()) != null) {
if (line.equals("Part Time Employee")) {
line = reader.readLine(); // reads employee number
int empNum = Integer.parseInt(line);
line = reader.readLine(); // reads first name
String firstName = line;
line = reader.readLine(); // reads last name
String lastName = line;
line = reader.readLine(); // reads deduct rate
Double deductRate = Double.parseDouble(line);
line = reader.readLine(); // reads gender
Gender gender = Gender.valueOf(line);
line = reader.readLine(); // reads location
Location location = Location.valueOf(line);
line = reader.readLine(); // reads hourly wage
Double hourlyWage = Double.parseDouble(line);
line = reader.readLine(); // reads hours worked per week
Double hoursPerWeek = Double.parseDouble(line);
line = reader.readLine(); // reads weeks worked per year
Double weeksPerYear = Double.parseDouble(line);
EmployeeInfo theEmployee = new PartTimeEmployee(empNum, firstName, lastName, gender, location,
deductRate, hourlyWage, hoursPerWeek, weeksPerYear);
addEmployee(theEmployee);
} else if (line.equals("Full Time Employee")) {
line = reader.readLine(); // reads employee number
int empnum = Integer.parseInt(line);
line = reader.readLine(); // reads first name
String firstname = line;
line = reader.readLine(); // reads last name
String lastname = line;
line = reader.readLine(); // reads deduct rate
double deductrate = Double.parseDouble(line);
line = reader.readLine(); // reads gender
Gender gender = Gender.valueOf(line); // converts the string value gender into the Gender enum
line = reader.readLine(); // reads location
Location location = Location.valueOf(line); // converts the string value location into the Location enum
line = reader.readLine();
double yearlySalary = Double.parseDouble(line);
EmployeeInfo theEmployee = new FullTimeEmployee(empnum, firstname, lastname, gender, location,
deductrate, yearlySalary);
addEmployee(theEmployee);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeToFile() {
try {
PrintWriter writer = new PrintWriter("dataTextFile.txt");
for (int i = 0; i < buckets.length; i++) {
int listSize = buckets[i].size();
if (listSize == 0) {
System.out.println(" Nothing in its ArrayList!");
} else if (listSize != 0) {
for (int j = 0; j < listSize; j++) {
EmployeeInfo someEmployee = buckets[i].get(j); // Gets employee
if (someEmployee instanceof PartTimeEmployee) {
writer.println("Part Time Employee"); // write PART TIME EMPLOYEE
} else if (someEmployee instanceof FullTimeEmployee) {
writer.println("Full Time Employee");
}
writer.println(someEmployee.getEmpNumber()); // Write EMPLOYEE NUMBER
writer.println(someEmployee.getFirstName()); // Writes FIRST NAME
writer.println(someEmployee.getLastName()); // Writes LAST NAME
writer.println(someEmployee.getDeductRate()); // Writes DEDUCT RATE
writer.println(someEmployee.getGender()); // Writes GENDER
writer.println(someEmployee.getLocation()); // Writes LOCATION
if (someEmployee instanceof PartTimeEmployee) {
writer.println(((PartTimeEmployee) someEmployee).getHourlyWage()); // Writes HOURLY WAGE
writer.println(((PartTimeEmployee) someEmployee).getHoursPerWeek()); // Writes HOURS WORKED PER WEEK
writer.println(((PartTimeEmployee) someEmployee).getWeeksPerYear()); // Writes WEEKS WORKED PER WEEK
} else if (someEmployee instanceof FullTimeEmployee) {
writer.println(((FullTimeEmployee) someEmployee).getYearlySalary()); // Writes YEARLY SALARY
}
}
}
}
writer.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "File Not Found");
}
}
public void displayToTable(ArrayList<EmployeeInfo> b) {
for (int i = 0; i < buckets.length; i++) {
int listSize = buckets[i].size();
if (listSize == 0) {
System.out.println(" Nothing in its ArrayList!");
} else {
for (int j = 0; j < listSize; j++) {
EmployeeInfo someEmployee = buckets[i].get(j);
System.out.println(someEmployee.getEmpNumber());
b.add(someEmployee); // f
}
}
}
}
}
| true
|
657115e9cfaaac72d930ed345e2491d197367c02
|
Java
|
grapeqin/spring-data-book
|
/mongodb/src/test/java/grape/springdata/mongodb/AbstractSpringbootMongoApplicationTests.java
|
UTF-8
| 3,251
| 2.25
| 2
|
[] |
no_license
|
package grape.springdata.mongodb;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.sound.sampled.Line;
import com.mongodb.MongoClient;
import grape.springdata.mongodb.core.Address;
import grape.springdata.mongodb.core.Customer;
import grape.springdata.mongodb.core.EmailAddress;
import grape.springdata.mongodb.core.Product;
import grape.springdata.mongodb.dao.CustomerRepository;
import grape.springdata.mongodb.dao.OrderRepository;
import grape.springdata.mongodb.dao.ProductRepository;
import grape.springdata.mongodb.order.LineItem;
import grape.springdata.mongodb.order.Order;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
*
* @author grape
* @date 2019-05-17
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public abstract class AbstractSpringbootMongoApplicationTests {
@Autowired
protected MongoClient mongoClient;
@Autowired
protected MongoTemplate mongoTemplate;
@Autowired
protected CustomerRepository customerRepository;
@Autowired
protected ProductRepository productRepository;
@Autowired
protected OrderRepository orderRepository;
@Before
public void setUp(){
//customers
customerRepository.deleteAll();
EmailAddress emailAddress = new EmailAddress("dave@dmband.com");
Address address = new Address("Broadway","New York","United States");
Customer dave = new Customer("Dave","Matthews");
dave.setEmailAddress(emailAddress);
dave.addAddress(address);
customerRepository.save(dave);
emailAddress = new EmailAddress("alicia@keys.com");
address = new Address("27 Broadway","New York","United States");
Customer alicia = new Customer("Alicia","Keys");
alicia.setEmailAddress(emailAddress);
alicia.addAddress(address);
customerRepository.save(alicia);
//products
productRepository.deleteAll();
List<Product> productList = new ArrayList<>();
Product ipad = new Product("iPad", BigDecimal.valueOf(499.0),"Apple tablet device");
ipad.setAttribute("connector","plus");
productList.add(ipad);
Product macBook = new Product("MacBook Pro",BigDecimal.valueOf(1299.0),"Apple notebook");
productList.add(macBook);
Product dock = new Product("dock",BigDecimal.valueOf(49.0),"Dock for iPhone/iPad");
dock.setAttribute("connector","plus");
productList.add(dock);
productRepository.saveAll(productList);
//orders
Order order = new Order(dave,address);
LineItem ipadLineItem = new LineItem(ipad,2);
order.addLineItem(ipadLineItem);
LineItem macBookLineItem = new LineItem(macBook);
order.addLineItem(macBookLineItem);
orderRepository.save(order);
}
@After
public void destroy(){
}
@Test
public void testComponents(){
assertThat(mongoClient, is(notNullValue()));
assertThat(mongoTemplate,is(notNullValue()));
assertThat(customerRepository,is(notNullValue()));
}
}
| true
|
dd4ba63a5e41c141f099ea86ccccaf90c0de13d1
|
Java
|
soleilvi/JavaTutoring
|
/Tutoring/src/BasicCalculator/SimpleCalculator.java
|
UTF-8
| 1,574
| 4.375
| 4
|
[] |
no_license
|
package BasicCalculator;
// BasicCalculator.SimpleCalculator.java
/*
A calculator that asks the user which operation they want to do (addition, subtraction, multiplication, division,
modulo) and which two numbers they want to use. Once it has that, it performs the operation of those two numbers
and prints the result.
By Soleil Vivero
*/
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args){
String operator;
float num1, num2, result = 0.0f;
Scanner input = new Scanner(System.in);
System.out.println("What operator do you want to use? (options: +, -, *, /, %)");
operator = input.nextLine();
System.out.println("What is the first number of the operation?");
num1 = input.nextInt();
System.out.println("What is the second number of the operation?");
num2 = input.nextInt();
// TODO: incorporate a for-loop for checking whether the inputs for each question are valid
// Removes all the spaces from the input string. "\\s" is a single space in unicode.
operator = operator.replaceAll("\\s", "");
switch (operator) {
case "+" -> result = num1 + num2;
case "-" -> result = num1 - num2;
case "*" -> result = num1 * num2;
case "/" -> result = num1 / num2;
case "%" -> result = num1 % num2;
default -> System.out.println("Invalid operator, please try again.");
}
System.out.println("Your result is: " + String.format("%.3f", result));
}
}
| true
|
df5952cf10ca870063855cf0ba2766dacf30f92e
|
Java
|
danielwikstrom/trabajoFinalSoftware
|
/src/Personajes/Personaje.java
|
UTF-8
| 584
| 2.75
| 3
|
[] |
no_license
|
package Personajes;
import State.*;
public class Personaje extends Avatar{
//Clase del jugador, hereda de Avatar
public Personaje (int vida,int fuerza, int defensa, int poder, int resistencia,String clase){
this.vida=vida;
this.fuerza=fuerza;
this.defensa=defensa;
this.poder=poder;
this.resistencia=resistencia;
this.clase=clase;
dormido= new Dormido(this);
quemado= new Quemado(this);
evasivo = new Evasivo(this);
normal= new Normal(this);
state= normal;
isNormal=true;
isQuemado=false;
isDormido=false;
isEvasivo=false;
}
}
| true
|
184ebd1e7d02eba7c4111786691e662176d83db0
|
Java
|
lhf87/spring-cloud-extends
|
/feign-extends/feign-extends-hystrix-stream-support/src/main/java/com/lhf/feign/hystrix/stream/FeignHystrixStreamInitializer.java
|
UTF-8
| 4,697
| 2.109375
| 2
|
[] |
no_license
|
package com.lhf.feign.hystrix.stream;
import feign.Target;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cloud.stream.converter.CompositeMessageConverterFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.integration.handler.AbstractMessageHandler;
import org.springframework.messaging.Message;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.messaging.converter.MessageConversionException;
import org.springframework.util.Assert;
/**
* Created on 2018/1/6.
*/
public class FeignHystrixStreamInitializer implements ApplicationContextAware, InitializingBean {
private String serviceName;
private CompositeMessageConverterFactory converterFactory;
private FeignHystrixStreamChannelFactory channelFactory;
private FallbackMessageProcessor messageProcessor;
private ApplicationContext context;
public FeignHystrixStreamInitializer(CompositeMessageConverterFactory converterFactory,
FeignHystrixStreamChannelFactory channelFactory,
FallbackMessageProcessor messageProcessor,
String serviceName) {
Assert.notNull(converterFactory, "converter factory cannot be null");
Assert.notNull(channelFactory, "channel factory cannot be null");
Assert.notNull(messageProcessor, "messageProcessor cannot be null");
Assert.hasText(serviceName, "ServiceName cannot be empty");
this.converterFactory = converterFactory;
this.channelFactory = channelFactory;
this.messageProcessor = messageProcessor;
this.serviceName = serviceName;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
@Override
public void afterPropertiesSet() throws Exception {
// 监听当前服务的fallback channel
subscribeChannelMessage();
// 初始化其他服务的fallback channel
// 用到时再初始化
/*Arrays.stream(context.getBeanNamesForAnnotation(FeignClient.class)).forEach(beanName -> {
String sName = checkServiceName(beanName);
if(!serviceName.equals(sName)) {
channelFactory.getOutputChannel(sName);
}
});*/
}
private void subscribeChannelMessage() {
SubscribableChannel channel = (SubscribableChannel)channelFactory.getInputChannel(serviceName);
StreamListenerMessageHandler listenerMessageHandler =
new StreamListenerMessageHandler(converterFactory, messageProcessor);
channel.subscribe(listenerMessageHandler);
}
private String checkServiceName(String name) {
/**
* controller继承自FeignClient的是cglib代理, hystrix的fallback继承自FeignClient的是jdk代理
* {@link }
*/
Object beanInstance = context.getBean(name);
Target target = ProxyUtils.getFeignTarget(beanInstance);
if(null != target) {
return target.name();
}
return serviceName;
}
private final class StreamListenerMessageHandler extends AbstractMessageHandler {
private CompositeMessageConverterFactory converterFactory;
private FallbackMessageProcessor messageProcessor;
public StreamListenerMessageHandler(CompositeMessageConverterFactory converterFactory,
FallbackMessageProcessor messageProcessor) {
this.converterFactory = converterFactory;
this.messageProcessor = messageProcessor;
}
@Override
protected void handleMessageInternal(Message<?> message) throws Exception {
FallbackMessageProcessor.FallbackMessage fallbackMessage =
(FallbackMessageProcessor.FallbackMessage) converterFactory.getMessageConverterForAllRegistered()
.fromMessage(message, FallbackMessageProcessor.FallbackMessage.class);
if(null != fallbackMessage) {
messageProcessor.receiveMessage(fallbackMessage);
} else {
throw new MessageConversionException(message, "Cannot convert from [" +
message.getPayload().getClass().getName() + "] to [" +
FallbackMessageProcessor.FallbackMessage.class.getName() + "] for " + message);
}
}
}
}
| true
|
2d85e00537f5ba04de8f6a95fb6dd6b278df6388
|
Java
|
motinsa/inteligencia_artificial
|
/tp6-parte1/758267/tarea3/nqueens.csp/AvailableCells.java
|
UTF-8
| 764
| 2.921875
| 3
|
[] |
no_license
|
package aima.gui.nqueens.csp;
/**
* AvailableCells crea el juego del sudoku con un número de celdas dadas.
* Cada celda juega el papel de una variable en el problema CSP.
*/
import java.util.ArrayList;
import java.util.List;
import aima.core.search.csp.Variable;
public class AvailableCells {
private int numOfAvailable;
private List<Variable> list;
public AvailableCells(int num) {
this.numOfAvailable = num;
list = new ArrayList<Variable>(numOfAvailable);
}
public void insert(int i) {
NQueensVariable variable = new NQueensVariable("Reina en columna[" + i + "]", i);
//variable.setValue(value);
list.add(variable);
}
public int getNumOfAvailable() {
return numOfAvailable;
}
public List<Variable> getList() {
return list;
}
}
| true
|
5272ff499c9199c30d2d8717e22edac983088903
|
Java
|
lapd87/SoftUniJavaOOPAdvanced
|
/04Reflection/src/_04BarracksWarsTheCommandsStrikeBack/core/commands/RetireCommand.java
|
UTF-8
| 791
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
package _04BarracksWarsTheCommandsStrikeBack.core.commands;
import _04BarracksWarsTheCommandsStrikeBack.contracts.Repository;
import _04BarracksWarsTheCommandsStrikeBack.contracts.UnitFactory;
/**
* Created by IntelliJ IDEA.
* User: LAPD
* Date: 26.7.2018 г.
* Time: 16:55 ч.
*/
public class RetireCommand extends BaseCommand {
protected RetireCommand(String[] data, Repository repository, UnitFactory unitFactory) {
super(data, repository, unitFactory);
}
@Override
public String execute() {
try {
String unitType = super.getData()[1];
super.getRepository().removeUnit(unitType);
return unitType + " retired!";
} catch (IllegalArgumentException e) {
return e.getMessage();
}
}
}
| true
|
12fa901c8743cf8850f056c201b4c7ab3e83a002
|
Java
|
HaniLucky/example
|
/ERP-APP/erp/src/main/java/com/hanilucky/core/controller/RoleMenuController.java
|
UTF-8
| 2,186
| 2.203125
| 2
|
[] |
no_license
|
package com.hanilucky.core.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.hanilucky.common.Result;
import com.hanilucky.core.service.RoleMenuService;
import com.hanilucky.core.service.RoleService;
import com.hanilucky.core.vo.RoleMenu;
import com.hanilucky.core.vo.Tree;
@RestController
@RequestMapping(value = "/role/menu")
public class RoleMenuController {
@Autowired
private RoleService roleService;
@Autowired
private RoleMenuService roleMenuService;
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public List<Tree> readRoleMenus(@PathVariable String id) {
return roleService.readRoleMenus(id);
}
@RequestMapping(value = "/",method = RequestMethod.POST)
public Result updateRoleMenu(String id,String checkedStr){
try {
// 获取权限数据
// 清空角色菜单中间表数据 根据角色id
int num =roleMenuService.deleteById(Integer.valueOf(id));
// 新增角色菜单中间表数据
if(!StringUtils.isEmpty(checkedStr)){ // 传递的菜单项不是""时才插入 要不会分割一个串 插入一个roleId有值 menuid没有值得记录
String[] split = checkedStr.split(",");
for (String menuuuid : split) {
RoleMenu roleMenu = new RoleMenu(Integer.valueOf(id),menuuuid);
roleMenuService.save(roleMenu);
}
}
}catch (Exception e){
e.printStackTrace();
return new Result(true,"更新角色权限失败",null);
}
// 删除redis用户菜单缓存
// 拥有该角色的用户
// 循环删除
// jedis.del("menuTree"+id);
// 更新数据
return new Result(true,"更新角色权限成功",null);
}
}
| true
|
6f9fce6813156333e94b00e234af68fae1905788
|
Java
|
r-paredes-bernal/Java_Academy_Core
|
/src/academy/core/session4/collections/ComputerStoreMap.java
|
UTF-8
| 1,080
| 3.6875
| 4
|
[] |
no_license
|
package academy.core.session4.collections;
import java.util.HashMap;
import java.util.Map;
import academy.core.session4.generics.computers.Computer;
import academy.core.session4.generics.computers.Printable;
// Create and use ArrayList, TreeSet, TreeMap, and ArrayDeque objects
public class ComputerStoreMap implements Printable{
Map<Integer, String> inventory;
ComputerStoreMap(Map<Integer, String> inventory){
this.inventory = inventory;
}
@Override
public void printInventory() {
// lambda operator -> body
this.inventory.forEach((key, value) -> System.out.println(key + " " + value));
}
public static void main(String[] args) {
Map<Integer, String> computers = new HashMap<>();
Computer c1 = new Computer(2009, "white");
Computer c2 = new Computer(2009, "black");
Computer c3 = new Computer(2014, "grey");
computers.put(c1.getId(), c1.getDesc());
computers.put(c2.getId(), c2.getDesc());
computers.put(c3.getId(), c3.getDesc());
ComputerStoreMap store = new ComputerStoreMap(computers);
store.printInventory();
}
}
| true
|
de533d38edc81efe04284220fcccfe7d632e5a9f
|
Java
|
qzhou0305/zhangqin-framework
|
/zhangqin-framework-common/src/main/java/com/zhangqin/framework/common/entity/ResponseData.java
|
UTF-8
| 4,024
| 2.59375
| 3
|
[] |
no_license
|
package com.zhangqin.framework.common.entity;
import java.io.Serializable;
import com.zhangqin.framework.common.enums.BaseEnum;
import com.zhangqin.framework.common.enums.ResponseCodeEnum;
import com.zhangqin.framework.common.utils.BeanMapper;
/**
*
* ClassName: ResponseData
* @Description: 客户端响应对象
* @author zhangqin
* @date 2018年1月13日
*
* =================================================================================================
* Task ID Date Author Description
* ----------------+----------------+-------------------+-------------------------------------------
*
*/
public class ResponseData<T> implements Serializable {
/**
* @Fields serialVersionUID : serialVersionUID
*/
private static final long serialVersionUID = 5084805328527653848L;
/**
* 数据
*/
private T data;
/**
* 消息
*/
private String message;
/**
* 状态码
*/
private Integer code;
/**
* <p>Title: 构造方法1</p>
* <p>Description:</p>
*/
public ResponseData() {
this(ResponseCodeEnum.SUCCESS);
}
/**
*
* <p>Title: 构造方法2</p>
* <p>Description: </p>
* @param result
*/
public ResponseData(BaseEnum<?, Integer> result) {
this.code = result.getValue();
this.message = result.getDesc();
}
/**
*
* <p>Title: 构造方法3</p>
* <p>Description: </p>
* @param result
* @param data
*/
public ResponseData(BaseEnum<?, Integer> result, T data) {
this.code = result.getValue();
this.message = result.getDesc();
this.data = data;
}
/**
*
* <p>Title: 构造方法4</p>
* <p>Description: </p>
* @param code
* @param message
* @param data
*/
public ResponseData(Integer code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
/**
* 创建ResponseData
* @param data
* @param result
* @return
*/
public static <E> ResponseData<E> builder(E data, BaseEnum<?, Integer> result) {
return new ResponseData<E>(result, data);
}
/**
* @Description: ResponseData中Data对象转换
* @param destinationClass
* @return
* @author guocp
* @date 2017年11月8日
*/
public <E> ResponseData<E> map(Class<E> destinationClass) {
ResponseData<E> response = new ResponseData<E>();
response.setCode(code);
response.setMessage(message);
response.setData(BeanMapper.map(this.data, destinationClass));
return response;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
/**
* ClassName: Builder
* @Description: ResponseData构造器
* @author zhangqin
* @date 2017年12月5日
*
* =================================================================================================
* Task ID Date Author Description
* ----------------+----------------+-------------------+-------------------------------------------
*
*/
public static class Builder<T> {
/**
* 数据
*/
private T data;
/**
* 消息
*/
private String message;
/**
* 状态码
*/
private Integer code;
public Builder<T> code(Integer code) {
this.code = code;
return this;
}
public Builder<T> message(String message) {
this.message = message;
return this;
}
public Builder<T> data(T data) {
this.data = data;
return this;
}
public Builder<T> result(BaseEnum<?, Integer> result) {
this.code = result.getValue();
this.message = result.getDesc();
return this;
}
public ResponseData<T> build() {
return new ResponseData<T>(this.code, this.message, this.data);
}
}
}
| true
|
51fdae4a10680b2d1f546579f53ce9a204a120dc
|
Java
|
dnosauro/singcie
|
/base_source_from_JADX/sources/com/google/android/gms/internal/ads/zzuj.java
|
UTF-8
| 294
| 1.554688
| 2
|
[] |
no_license
|
package com.google.android.gms.internal.ads;
import com.google.android.gms.internal.ads.zzue;
final class zzuj implements zzekl {
static final zzekl zzer = new zzuj();
private zzuj() {
}
public final boolean zzi(int i) {
return zzue.zzc.zza.zzcb(i) != null;
}
}
| true
|
23e489f7bdc49eba57eaf944754c0f4665454ca6
|
Java
|
xukh630/jcs
|
/base/src/main/java/com/jcs/base/enums/BussiEnum.java
|
UTF-8
| 873
| 2.6875
| 3
|
[] |
no_license
|
package com.jcs.base.enums;
/**
* @auther xukh
* @date 2019/8/13 20:29
*/
public enum BussiEnum {
SCUESS(200, "成功"),
ERROR(500, "失败");
private Integer code;
private String msg;
private BussiEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return this.code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return this.msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public static BussiEnum getEnumIndex(Integer code) {
BussiEnum[] bussiEnums = BussiEnum.values();
for (BussiEnum bussiEnum : bussiEnums) {
if (bussiEnum.code.equals(code)){
return bussiEnum;
}
}
return null;
}
}
| true
|