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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0f4b4df100305392b2788531e5b23512e21474ba
|
Java
|
danwinkler/jstrategymass
|
/core/src/com/danwink/strategymass/gamestats/TeamStats.java
|
UTF-8
| 623
| 2.796875
| 3
|
[] |
no_license
|
package com.danwink.strategymass.gamestats;
import java.util.ArrayList;
import com.danwink.strategymass.game.GameState;
import com.danwink.strategymass.game.objects.Team;
public class TeamStats
{
public Team t;
public ArrayList<Integer> units = new ArrayList<>();
public ArrayList<Integer> points = new ArrayList<>();
public TeamStats() {}
public TeamStats( Team t )
{
this.t = t;
}
public void update( GameState state )
{
units.add( (int)state.units.stream().filter( u -> u.getUnit().team == t.id ).count() );
points.add( (int)state.map.points.stream().filter( p -> p.team == t.id ).count() );
}
}
| true
|
8a9e5ac559859bd4e51a87572dc2e399baa4f3de
|
Java
|
Kneesnap/FrogLord
|
/src/net/highwayfrogs/editor/file/map/poly/polygon/MAPPolyF3.java
|
UTF-8
| 241
| 1.914063
| 2
|
[] |
no_license
|
package net.highwayfrogs.editor.file.map.poly.polygon;
/**
* Shaded flat triangle.
* Created by Kneesnap on 8/25/2018.
*/
public class MAPPolyF3 extends MAPPolyFlat {
public MAPPolyF3() {
super(MAPPolygonType.F3, 3);
}
}
| true
|
c6e8b0419c9836f60438ec963789284444971e9e
|
Java
|
ss-d49/refrigerator_java
|
/refrigerator/SQLiteTest.java
|
UTF-8
| 1,547
| 2.8125
| 3
|
[] |
no_license
|
package refrigerator;
import java.sql.*;
public class SQLiteTest {
private static Connection con;
private static boolean hasData = false;
public ResultSet displayUsers() throws ClassNotFoundException, SQLException {
if (con == null) {
getConnection();
}
Statement state = con.createStatement();
ResultSet res = state.executeQuery("SELECT fItemName, fExpiryDate FROM user");
return res;
}
private static void getConnection() throws ClassNotFoundException, SQLException {
con = DriverManager.getConnection("jdbc:sqlite:SQLiteTest1.db");
initialize();
}
private static void initialize() throws SQLException {
if (!hasData) {
hasData = true;
Statement state = con.createStatement();
ResultSet res = state.executeQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='user'");
if (!res.next()) {
System.out.println("Building the User table with prepopulated values.");
// need to build the table
Statement state2 = con.createStatement();
state2.execute("CREATE TABLE user(id integer,"
+ "fItemName varchar(60)," + "fExpiryDate date,"
+ "primary key(id));");
}
}
}
public static void addUser(String foodItemName, Date foodExpiryDate) throws ClassNotFoundException, SQLException {
if (con == null) {
getConnection();
}
PreparedStatement prep = con.prepareStatement("INSERT INTO user values(?,?,?);");
prep.setString(2, foodItemName);
prep.setDate(3, foodExpiryDate);
prep.execute();
}
}
| true
|
07df83b517882b99ee242d9f6ae8f0071aaa7021
|
Java
|
maocurai/UA-Training
|
/Homework 2/NumberGame/src/main/java/View.java
|
UTF-8
| 1,903
| 3.359375
| 3
|
[
"MIT"
] |
permissive
|
public class View {
public static final String START_MESSAGE = "Hello user, try to guess the number\n";
public static final String GREATER_NUMBER = "\nYour number is greater";
public static final String LESS_NUMBER = "\nYour number is less";
public static final String GAME_OVER = "\nCongratulations! You won, game over!\n";
public static final String NUMBER_RANGE = "\nNumber in range: ";
public static final String ATTEMPTS = "Your attempts: ";
public void printMessage(String message){
System.out.print(message);
}
public void printMessageAndPhrase(String message, String phrase){
System.out.println(message + phrase);
}
public void show(Integer result) {
if(result != null) {
switch (result) {
case 1:
printMessage(GREATER_NUMBER);
break;
case -1:
printMessage(LESS_NUMBER);
break;
case 0:
printMessage(GAME_OVER);
showTotalStatistics();
return;
}
}
printMessageAndPhrase(NUMBER_RANGE, Repository.getModel().rangeToString());
showAttempts();
}
public void showTotalStatistics() {
System.out.println("Your statistics");
showAttempts();
System.out.println("Total attempts: " + Repository.get_statistics().getUserNumberStatisticsSet().size());
}
public void showAttempts() {
if(!Repository.get_statistics().getUserNumberStatisticsSet().isEmpty()) {
printMessage(ATTEMPTS);
for(Integer userNum : Repository.get_statistics().getUserNumberStatisticsSet()) {
System.out.print(userNum + " ");
}
System.out.println();
}
}
}
| true
|
33b2fcaf0a594b76b908a97611358c9f3792c74e
|
Java
|
hyb1234hi/reverse-wechat
|
/weixin6519android1140/src/sourcecode/com/tencent/mm/plugin/webview/fts/ui/FtsWebDotPercentIndicator.java
|
UTF-8
| 2,334
| 1.734375
| 2
|
[] |
no_license
|
package com.tencent.mm.plugin.webview.fts.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.tencent.gmtrace.GMTrace;
import com.tencent.mm.R.g;
import com.tencent.mm.sdk.platformtools.w;
public class FtsWebDotPercentIndicator
extends LinearLayout
{
LayoutInflater CJ;
int ilo;
public FtsWebDotPercentIndicator(Context paramContext, AttributeSet paramAttributeSet)
{
super(paramContext, paramAttributeSet);
GMTrace.i(20484980736000L, 152625);
init(paramContext);
GMTrace.o(20484980736000L, 152625);
}
public FtsWebDotPercentIndicator(Context paramContext, AttributeSet paramAttributeSet, int paramInt)
{
super(paramContext, paramAttributeSet, paramInt);
GMTrace.i(20485114953728L, 152626);
init(paramContext);
GMTrace.o(20485114953728L, 152626);
}
private void init(Context paramContext)
{
GMTrace.i(20485249171456L, 152627);
this.CJ = LayoutInflater.from(paramContext);
GMTrace.o(20485249171456L, 152627);
}
public final void Q(float paramFloat)
{
float f1 = 1.0F;
float f2 = 0.0F;
GMTrace.i(20485383389184L, 152628);
if (paramFloat < 0.0F)
{
paramFloat = f2;
if (paramFloat <= 1.0F) {
break label122;
}
paramFloat = f1;
}
int j;
label122:
for (;;)
{
int k = (int)Math.rint(this.ilo * paramFloat);
w.v("MicroMsg.AppBrandDotPercentIndicator", "setPercent percent:%s dotsOnNum:%d", new Object[] { Float.valueOf(paramFloat), Integer.valueOf(k) });
int i = 0;
for (;;)
{
j = i;
if (i >= k) {
break;
}
j = i;
if (i >= getChildCount()) {
break;
}
((ImageView)getChildAt(i)).setImageResource(R.g.aWP);
i += 1;
}
break;
}
while (j < getChildCount())
{
((ImageView)getChildAt(j)).setImageResource(R.g.aWO);
j += 1;
}
GMTrace.o(20485383389184L, 152628);
}
}
/* Location: D:\tools\apktool\weixin6519android1140\jar\classes2-dex2jar.jar!\com\tencent\mm\plugin\webview\fts\ui\FtsWebDotPercentIndicator.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| true
|
670c02824fdf1d90d8ecabb0788834aa52e4ed11
|
Java
|
itdevline/spring-ws-client
|
/src/main/java/com/springws/client/SpringWsClientApplication.java
|
UTF-8
| 751
| 1.867188
| 2
|
[] |
no_license
|
package com.springws.client;
import com.genwebservice.Webservicerequest;
import com.genwebservice.Webservicereresponse;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
@SpringBootApplication
public class SpringWsClientApplication {
public static void main(String[] args) {
SpringApplication.run(SpringWsClientApplication.class, args);
}
@Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller.setClassesToBeBound(Webservicerequest.class, Webservicereresponse.class);
return jaxb2Marshaller;
}
}
| true
|
9c0ab86a1faff8fb01d6eced1f08b8b7d8b0bde0
|
Java
|
JetBrains/intellij-community
|
/platform/platform-impl/src/com/intellij/internal/cachedValueProfiler/TurnOnOffCachedValueProfilerAction.java
|
UTF-8
| 1,239
| 1.9375
| 2
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.cachedValueProfiler;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.psi.util.CachedValueProfiler;
import org.jetbrains.annotations.NotNull;
final class TurnOnOffCachedValueProfilerAction extends DumbAwareAction {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
Project project = e.getProject();
if (project == null) return;
CachedValueProfilerDumpHelper.toggleProfiling(project);
}
@Override
public @NotNull ActionUpdateThread getActionUpdateThread() {
return ActionUpdateThread.BGT;
}
@Override
public void update(@NotNull AnActionEvent e) {
Project project = e.getProject();
boolean enabled = project != null;
boolean running = CachedValueProfiler.isProfiling();
e.getPresentation().setEnabledAndVisible(enabled);
e.getPresentation().setText(running ? "Stop Cached Value Profiling" : "Start Cached Value Profiling");
}
}
| true
|
c6d4c17fe3076d22352fced1f2533523b70f1dd6
|
Java
|
ImmediateActionGroup/issues
|
/src/main/java/com/immediateactiongroup/issues/model/User.java
|
UTF-8
| 552
| 1.648438
| 2
|
[] |
no_license
|
package com.immediateactiongroup.issues.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String username;
private String password;
private String phone;
private String email;
private String nickname;
private Date lastLoginTime;
private Integer deleteFlag;
private Date lastModifyTime;
private Date createTime;
}
| true
|
ba65703bf21cceab8175a50efe10fbec2e870f61
|
Java
|
christian-p-anderson/LC_Sessions
|
/src/main/java/Others/DecodeWays.java
|
UTF-8
| 1,933
| 4.25
| 4
|
[] |
no_license
|
package Others;
public class DecodeWays {
public int numWaysToDecode(String s) {
//uses bottoms-up processing
int[] ways = new int[s.length() + 1];
//this is a dynamic programming array
//we're saying plus one because we want to account for the number 0 if we have no string, and we also want to
//return really the number of ways to decode a string if it's of the length s
ways[0] = 1; //base case - number of ways to decode a string of length 0 is 1
ways[1] = s.charAt(0) == '0' ? 0 : 1; //base case - number of ways to decode a string of length 1 is going to
//depend on whether it's a zero or not
//now that we have the base cases we can iterate all the way to s' length and solve our sub-problems
//we're going to look and evaluate the digit we're on
for (int i = 2; i <= s.length(); i++) {
int oneDigit = Integer.valueOf(s.substring(i - 1, i)); //getting the character we're on and turning it to an
// Integer
int twoDigits = Integer.valueOf(s.substring(i - 2, i)); //getting the character we're on and turning it to
//an Integer
//now we want to know if there is a mapping using oneDigit and twoDigits
if (oneDigit >= 1 && oneDigit <= 9) {
ways[i] += ways[i - 1];
}
if (twoDigits >= 10 && twoDigits <= 26) {
ways[i] += ways[i - 2];
}
}
return ways[s.length()];
//our dp array stores the maximum number of ways to decode our string up till that index and our index
//represents the number of characters we have
}
}
/*
Dynamic programming is the idea to simply store the results of sub-problems, so that we do not have to re-compute
them when needed later. This simple optimization reduces time complexities from exponential to polynomial.
*/
| true
|
7e12846326d3a6c953d3c623177de6981464f25e
|
Java
|
latant/tablut-android
|
/app/src/main/java/hu/bme/aut/tablut/game/Tablut.java
|
UTF-8
| 2,920
| 3.03125
| 3
|
[] |
no_license
|
package hu.bme.aut.tablut.game;
import java.io.Serializable;
import hu.bme.aut.tablut.game.field.Ground;
import hu.bme.aut.tablut.game.field.Throne;
import hu.bme.aut.tablut.game.piece.King;
import hu.bme.aut.tablut.game.field.Field;
import hu.bme.aut.tablut.game.piece.Soldier;
public class Tablut implements Serializable {
public static Player player1Arg, player2Arg;
public static final int SIZE = 9;
private static final int HALF_SIZE = SIZE / 2;
private Player defender, attacker, actual;
private Field[][] fields;
private King king;
public Tablut(Player defender, Player attacker) {
this.defender = defender;
this.attacker = attacker;
actual = defender;
fields = new Field[SIZE][];
for (int i = 0; i < SIZE; i++) fields[i] = new Field[SIZE];
createKing(defender);
createSoldiers(1, HALF_SIZE, defender);
createSoldiers(2, HALF_SIZE, defender);
createSoldiers(3, HALF_SIZE, this.attacker);
createSoldierRows(4, HALF_SIZE - 1, HALF_SIZE + 1, this.attacker);
fillWithGrounds();
Field.bindFields(fields);
}
private void createKing(Player player) {
Throne throne = new Throne();
king = new King(player, throne, this);
fields[HALF_SIZE][HALF_SIZE] = throne;
}
private void createSoldierAt(int i, int j, Player player) {
Ground ground = new Ground();
new Soldier(player, ground, this);
fields[i][j] = ground;
}
private void createSoldiers(int cylinder, int at, Player player) {
createSoldierAt(HALF_SIZE - cylinder, at, player);
createSoldierAt(HALF_SIZE + cylinder, at, player);
createSoldierAt(at, HALF_SIZE - cylinder, player);
createSoldierAt(at, HALF_SIZE + cylinder, player);
}
private void createSoldierRows(int cylinder, int start, int end, Player player) {
for (int i = start; i <= end; i++) {
createSoldiers(cylinder, i, player);
}
}
private void fillWithGrounds() {
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++)
if (fields[i][j] == null)
fields[i][j] = new Ground();
}
public Field[][] getFields() {
return fields;
}
public Player getActualPlayer() {
return actual;
}
public void nextPlayer() {
actual = actual == defender ? attacker : defender;
}
public Player getDefender() { return defender; }
public Player getAttacker() { return attacker; }
public Player getWinner() {
if (king.isDied())
return attacker;
int minimumSide = actual == king.getOwner() ? 1 : 2;
if (king.getVisitableSides().size() >= minimumSide || king.getField().isSide()) {
return defender;
}
return null;
}
public King getKing() { return king; }
}
| true
|
4330658e408a9ef709547a16b8b1457ce1fd8396
|
Java
|
ustadho/haris
|
/src/com/klinik/model/Reservasi.java
|
UTF-8
| 2,233
| 2.203125
| 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.klinik.model;
import java.util.Date;
/**
*
* @author faheem
*/
public class Reservasi {
private Integer id;
Pasien pasien;
private String userIns;
private Date timeIns;
private Boolean batal;
private String userBatal;
private Date timeBatal;
private String status; //'F --> Finised, W -> Waiting, C --> Cancel';
private String kodeDokter;
private Date tanggal;
private String title;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Pasien getPasien() {
return pasien;
}
public void setPasien(Pasien px) {
this.pasien = px;
}
public String getUserIns() {
return userIns;
}
public void setUserIns(String userIns) {
this.userIns = userIns;
}
public Date getTimeIns() {
return timeIns;
}
public void setTimeIns(Date timeIns) {
this.timeIns = timeIns;
}
public Boolean isBatal() {
return batal;
}
public void setBatal(Boolean batal) {
this.batal = batal;
}
public String getUserBatal() {
return userBatal;
}
public void setUserBatal(String userBatal) {
this.userBatal = userBatal;
}
public Date getTimeBatal() {
return timeBatal;
}
public void setTimeBatal(Date timeBatal) {
this.timeBatal = timeBatal;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getKodeDokter() {
return kodeDokter;
}
public void setKodeDokter(String kodeDokter) {
this.kodeDokter = kodeDokter;
}
public Date getTanggal() {
return tanggal;
}
public void setTanggal(Date tanggal) {
this.tanggal = tanggal;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
| true
|
5702ccd397f8226c763f03e75e31b1a91d384240
|
Java
|
lolose21/fundamentosjava
|
/src/fundamentos/Comandos.java
|
UTF-8
| 774
| 2.734375
| 3
|
[] |
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 fundamentos;
/**
*
* @author Usuario
*/
public class Comandos {
//comentarios con dos barras
/* varias lineas de comentarios
de comentarios
*/
// como generar comentarios dinamicamente
// control +shift es la tecla encima de control + C
// generar metodo de arranque o ejecucion
// se utilizan las siglas del metodo : psvm + tabulador las dos flechitas
public static void main(String[] args) {
// mensaje en la consola out: sout + tab = tabulador
System.out.println("mensaje entre comillas dobles");
//shif + f6 (mestra el mensaje)
}
}
| true
|
a412e251a5d900eb3b30b9707a6f3c4f8b3aa2df
|
Java
|
goddenis/olekstra-test
|
/src/main/java/ru/olekstra/services/HibernateLetterService.java
|
UTF-8
| 1,066
| 2.359375
| 2
|
[] |
no_license
|
package ru.olekstra.services;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import ru.olekstra.domains.Letter;
import java.util.List;
@Repository
@Transactional
public class HibernateLetterService implements LetterService {
@Autowired
@Qualifier("sessionFactory")
private SessionFactory sessionFactory;
public HibernateLetterService() {
}
/*@Inject
public HibernateLetterService(SessionFactory sf){
this.sessionFactory = sf;
}
*/
private Session currentSesion() {
return sessionFactory.getCurrentSession();
}
@Override
public List<Letter> getLetters() {
return currentSesion().createCriteria(Letter.class).list();
}
@Override
public void addLetter(Letter letter) {
currentSesion().save(letter);
}
}
| true
|
0f97ae20e831f1b7fe59b427269f884bbe44b149
|
Java
|
CapRobin/LjngProject
|
/NxLjngMeter/src/main/java/com/zfg/org/myexample/model/ClockModel.java
|
UTF-8
| 585
| 2.40625
| 2
|
[] |
no_license
|
package com.zfg.org.myexample.model;
public class ClockModel {
private int week;
private int type;
private int enable;
private boolean isLabel;
public int getWeek() {
return week;
}
public void setWeek(int week) {
this.week = week;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getEnable() {
return enable;
}
public void setEnable(int enable) {
this.enable = enable;
}
public boolean isLabel() {
return isLabel;
}
public void setLabel(boolean isLabel) {
this.isLabel = isLabel;
}
}
| true
|
e63c27f49685652e0ee4cc6ab9a1540b6a251714
|
Java
|
eishub/Starcraft
|
/eisbw/src/main/java/eisbw/actions/StartNewManager.java
|
UTF-8
| 938
| 2.328125
| 2
|
[] |
no_license
|
package eisbw.actions;
import java.util.List;
import eis.iilang.Action;
import eis.iilang.Parameter;
import eisbw.Game;
import jnibwapi.JNIBWAPI;
import jnibwapi.Unit;
import jnibwapi.types.UnitType;
public class StartNewManager extends StarcraftAction {
private final Game game;
/**
* The StartManager constructor.
*
* @param api The BWAPI
*/
public StartNewManager(final JNIBWAPI api, final Game game) {
super(api);
this.game = game;
}
@Override
public boolean isValid(final Action action) {
final List<Parameter> parameters = action.getParameters();
return parameters.isEmpty();
}
@Override
public boolean canExecute(final UnitType type, final Action action) {
return true;
}
@Override
public void execute(final Unit unit, final Action action) {
this.game.startNewManager();
}
@Override
public String toString() {
return "startNewManager";
}
}
| true
|
d1ce44838992e3d5772e95eee7eec7300e02423c
|
Java
|
ms930602/TJRJ
|
/warehouse-role-permission/warehouse-role-permission-entity/src/main/java/com/ms/warehouse/permission/entity/TsysModuleEntity.java
|
UTF-8
| 3,947
| 2.125
| 2
|
[] |
no_license
|
/**
* All rights reserved by XinGuoDu Inc.
*/
package com.ms.warehouse.permission.entity;
import com.ms.warehouse.common.entity.BaseEntity;
import com.ms.warehouse.common.vo.field;
/**
* <p>
* @author lansongtao
* @Date 2017-04-06 15:35:28
* @since 1.0
*/
public class TsysModuleEntity extends BaseEntity {
/** serialVersionUID */
private static final long serialVersionUID = 1L;
/** . */
@field("")
private Long id;
/** 名称. */
@field("名称")
private String name;
/** 图标. */
@field("图标")
private String iconCls;
/** 名称. */
@field("名称")
private String caption;
/** 父节点. */
@field("父节点")
private Long parentid;
/** 排序. */
@field("排序")
private Long sort;
/** 创建时间. */
@field("创建时间")
private java.util.Date createtime;
private Long sysId;
/** . */
@field("")
private String indexT;
/** 系统id. */
public Long getSysId() {
return sysId;
}
public void setSysId(Long sysId) {
this.sysId = sysId;
}
/** set . */
public void setId(Long id) {
this.id = id;
}
/** get . */
public Long getId() {
return this.id;
}
/** set . */
public void setName(String name) {
this.name = name;
}
/** get . */
public String getName() {
return this.name;
}
/** set . */
public void setIconCls(String iconCls) {
this.iconCls = iconCls;
}
/** get . */
public String getIconCls() {
return this.iconCls;
}
/** set . */
public void setCaption(String caption) {
this.caption = caption;
}
/** get . */
public String getCaption() {
return this.caption;
}
/** set . */
public void setParentid(Long parentid) {
this.parentid = parentid;
}
/** get . */
public Long getParentid() {
return this.parentid;
}
/** set . */
public void setSort(Long sort) {
this.sort = sort;
}
/** get . */
public Long getSort() {
return this.sort;
}
/** set . */
public void setCreatetime(java.util.Date createtime) {
this.createtime = createtime;
}
/** get . */
public java.util.Date getCreatetime() {
return this.createtime;
}
/** set . */
public void setIndexT(String indexT) {
this.indexT = indexT;
}
/** get . */
public String getIndexT() {
return this.indexT;
}
/** constructor */
public TsysModuleEntity() {
super();
}
/**
* constructor.<p>
* @param name
* @param iconCls
* @param caption
* @param parentid
* @param sort
* @param createtime
* @param indexT
*/
public TsysModuleEntity(String name,String iconCls,String caption,Long parentid,Long sort,java.util.Date createtime,String indexT){
this();
this.name = name;
this.iconCls = iconCls;
this.caption = caption;
this.parentid = parentid;
this.sort = sort;
this.createtime = createtime;
this.indexT = indexT;
}
@Override
public String toString() {
return new StringBuilder().append("TsysModuleEntity[")
.append("Id=").append(getId()).append(", ")
.append("Name=").append(getName()).append(", ")
.append("IconCls=").append(getIconCls()).append(", ")
.append("Caption=").append(getCaption()).append(", ")
.append("Parentid=").append(getParentid()).append(", ")
.append("Sort=").append(getSort()).append(", ")
.append("Createtime=").append(getCreatetime()).append(", ")
.append("IndexT=").append(getIndexT())
.append("]").toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof TsysModuleEntity == false) return false;
if(this == obj) return true;
TsysModuleEntity other = (TsysModuleEntity)obj;
if (getId() == null) {
if (other.getId() != null)
return false;
} else if (!getId().equals(other.getId()))
return false;
return false;
}
}
| true
|
bc66a8fb91574c6d67fae5b7d1ddf6965d684928
|
Java
|
Devapatel/SpringClassses
|
/IOC-proj56-LMI-problem1/src/main/java/com/nt/test/LMIProblemTest.java
|
UTF-8
| 960
| 2.171875
| 2
|
[] |
no_license
|
package com.nt.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.nt.beans.WebContainer;
public class LMIProblemTest {
public static void main(String[] args) {
ApplicationContext ctx=null;
WebContainer webCon=null;
//create IOC container
System.out.println("============= IOC Container Creation (main) ===========");
ctx=new ClassPathXmlApplicationContext("com/nt/cfgs/applicationContext.xml");
webCon=ctx.getBean("webCon",WebContainer.class);
System.out.println("============================");
webCon.webRequest("First ");
System.out.println("-------------------");
webCon.webRequest("second ");
System.out.println("--------------------");
webCon.webRequest("Third ");
((AbstractApplicationContext) ctx).close();
}
}
| true
|
04bbbf178eacd939652f69d4f9957f7449b84f4d
|
Java
|
cyyeungaj1/travelagentchatbotdup
|
/sample-spring-boot-kitchensink/src/test/java/com/example/bot/spring/interface/InterfaceTester.java
|
UTF-8
| 9,382
| 1.789063
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.example.bot.spring.userinterface;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonSyntaxException;
import com.google.gson.JsonParseException;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.linecorp.bot.model.event.message.TextMessageContent;
import com.example.bot.spring.ChatBotController;
import com.example.bot.spring.NLPParser;
import com.example.bot.spring.model.NLPChatRoom;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import ai.api.AIConfiguration;
import ai.api.AIDataService;
import ai.api.model.AIContext;
import ai.api.model.AIRequest;
import ai.api.model.AIResponse;
import ai.api.model.Entity;
import ai.api.model.Status;
import ai.api.model.Metadata;
import ai.api.model.Result;
@Slf4j
public class InterfaceTester{
ChatBotController controller = new ChatBotController();
// private final static Gson GSON = GsonFactory.getDefaultFactory().getGson();
private final Gson gson = new GsonBuilder().create();
@Test
public void testMenu() {
// String msg =
// controller.processInput("replyToken", "Ufc6e2d7119a764a7c5ebeca95a0d2914", new TextMessageContent("id", "hi"));
// controller.processInput("replyToken", "Ufc6e2d7119a764a7c5ebeca95a0d2914", new TextMessageContent("id", "-1"));
// controller.processInput("replyToken", "Ufc6e2d7119a764a7c5ebeca95a0d2914", new TextMessageContent("id", "1"));
// controller.processInput("replyToken", "Ufc6e2d7119a764a7c5ebeca95a0d2914", new TextMessageContent("id", "1"));
// controller.processInput("replyToken", "Ufc6e2d7119a764a7c5ebeca95a0d2914", new TextMessageContent("id", "-11"));
// controller.processInput("replyToken", "Ufc6e2d7119a764a7c5ebeca95a0d2914", new TextMessageContent("id", "2017/01/01 11:11:11"));
// controller.processInput("replyToken", "Ufc6e2d7119a764a7c5ebeca95a0d2914", new TextMessageContent("id", "2017/01/04 23:11:11"));
// controller.processInput("replyToken", "Ufc6e2d7119a764a7c5ebeca95a0d2914", new TextMessageContent("id", "2018/01/15 23:11:11"));
// controller.processInput("replyToken", "Ufc6e2d7119a764a7c5ebeca95a0d2914", new TextMessageContent("id", "Hello World!!!"));
// controller.processInput("replyToken", "Ufc6e2d7119a764a7c5ebeca95a0d2914", new TextMessageContent("id", "1"));
}
//
// @Test
// public void testNLP() {
// String error = null;
// try {
// AIConfiguration configuration = new AIConfiguration("25537dd6c15f44148cd489334c15293d");
// AIDataService dataService = new AIDataService(configuration);
// AIRequest request = new AIRequest("i want to announce");
// AIResponse response = dataService.request(request);
// if (response.getStatus().getCode() == 200) {
// log.info(response.getResult().getFulfillment().getSpeech());
// } else {
// log.info(response.getStatus().getErrorDetails());
// }
// } catch (Exception ex) {
// error = ex.toString();
// }
//
// if(error != null)
// log.info("testNLP::error::" + error);
// }
//
// @Test
// public void testNLP2() {
// String error = null;
// try {
// AIConfiguration configuration = new AIConfiguration("25537dd6c15f44148cd489334c15293d");
// AIDataService dataService = new AIDataService(configuration);
//
// query(dataService, "i want to announce");
// query(dataService, "hi");
// query(dataService, "2017/01/01 11:11:11");
// query(dataService, "sure");
//
//
//
// } catch (Exception ex) {
// error = ex.toString();
// }
//
// if(error != null)
// log.info("testNLP::error::" + error);
// }
//
// @Test
// public void testNLP3() {
// String error = null;
// try {
// AIConfiguration configuration = new AIConfiguration("25537dd6c15f44148cd489334c15293d");
// AIDataService dataService = new AIDataService(configuration);
//
// query(dataService, "i want to announce");
// query(dataService, "hi");
// query(dataService, "2017/01/01 11:11:11");
// query(dataService, "CONCONCON");
// NLPParser p = query(dataService, "sure");
// p.resetAll();
// query(dataService, "sure");
//
// } catch (Exception ex) {
// error = ex.toString();
// }
//
// if(error != null)
// log.info("testNLP::error::" + error);
// }
// @Test
// public void testNLP4() {
// NLPChatRoom nlpChatRoom = new NLPChatRoom("111");
// nlpChatRoom.resetAll();
// //1. i want to announce
// final String action1 = "announce.announce";
// final String context1 = "announce-followup";
// NLPParser n1 = nlpChatRoom.query("i want to announce");
// log.info("1. i want to announce");
// if(n1.getAction().equals(action1)){
// log.info("action: " + action1);
// }else{
// log.info("session 1 fail");
// }
// log.info("ans. " + n1.getReply());
//
// //2. 2018-01-06 10:10:10
// final String action2 = "announce.announce-save-datetime";
// final String context2 = "announce-ask-datetime-followup";
// NLPParser n2 = nlpChatRoom.query("2018-01-06 10:10:10");
// log.info("2. 2018-01-06 10:10:10");
// if(n2.getAction().equals(action2)){
// final String para1 = "date.original";
// final String para2 = "time.original";
// Map<String, JsonElement> parameters = n2.getParameter(context2);
// String date = parameters.get(para1).getAsString();
// String time = parameters.get(para2).getAsString();
// log.info("para1: " + date);
// log.info("para2: " + time);
// }else{
// log.info("session 2 fails");
// log.info("n2: " + n2.getAction());
// log.info("this: " + action2);
// }
// log.info("ans. " + n2.getReply());
//
// //3. content
// final String action3 = "announce.announce-save-content";
// final String context3 = "announce-ask-content-followup";
// NLPParser n3 = nlpChatRoom.query("content is content");
// log.info("3. content");
// if(n3.getAction().equals(action3)){
// final String para1 = "content.original";
// Map<String, JsonElement> parameters = n3.getParameter(context3);
// String content = parameters.get(para1).getAsString();
// log.info("para1: " + content);
// }else{
// log.info("session 3 fails");
// }
// log.info("ans. " + n3.getReply());
//
//
// }
@Test
public void testNLPMenu() {
// controller.processInput("replyToken", "Ufc6e2d7119a764a7c5ebeca95a0d2914", new TextMessageContent("id", "hi"));
// controller.processInput("replyToken", "Ufc6e2d7119a764a7c5ebeca95a0d2914", new TextMessageContent("id", "i want to announce"));
// controller.processInput("replyToken", "Ufc6e2d7119a764a7c5ebeca95a0d2914", new TextMessageContent("id", "2018/01/20 18:00:00"));
// controller.processInput("replyToken", "Ufc6e2d7119a764a7c5ebeca95a0d2914", new TextMessageContent("id", "this is the content kiki"));
// controller.processInput("replyToken", "Ufc6e2d7119a764a7c5ebeca95a0d2914", new TextMessageContent("id", "wtf"));
// controller.processInput("replyToken", "Ufc6e2d7119a764a7c5ebeca95a0d2914", new TextMessageContent("id", "sure"));
// controller.processInput("replyToken", "Ufc6e2d7119a764a7c5ebeca95a0d2914", new TextMessageContent("id", "hi"));
// NLPChatRoom cr = new NLPChatRoom("111");
// NLPParser p1 = cr.query("hi");
// p1.getAllContextInfo();
// log.info("1. " + p1.getReply());
//
// NLPParser p2 = cr.query("i want to announce");
// p2.getAllContextInfo();
// log.info("2. " + p2.getReply());
//
// cr.resetAll();
//
// NLPParser p3 = cr.query("hi");
// p3.getAllContextInfo();
// log.info("3. " + p3.getReply());
}
public void showMetadata(Result result){
final Metadata metadata = result.getMetadata();
if(metadata != null){
// log.info(metadata.toString());
log.info("get intent id: " + metadata.getIntentId());
log.info("get intent name: " + metadata.getIntentName());
}else{
log.info("metadata is null");
}
}
public NLPParser query(AIDataService dataService, String str){
String error = null;
NLPParser p = null;
log.info("\n\n");
try{
AIRequest request = new AIRequest(str);
request.setSessionId("111");
AIResponse response = dataService.request(request);
p = new NLPParser(response);
log.info("action: " + p.getAction());
log.info("reply: " + p.getReply());
p.getAllContextInfo();
// log.info("request::" + gson.toJson(request));
// log.info("response::" + gson.toJson(response));
// if (response.getStatus().getCode() == 200) {
// log.info(response.getResult().getFulfillment().getSpeech());
// } else {
// log.info(response.getStatus().getErrorDetails());
// }
// showMetadata(response.getResult());
}catch(Exception e){
error = e.toString();
}
if(error != null)
log.info("query::" + error);
log.info("\n\n");
return p;
}
}
| true
|
4a20d010acd391ec79e60b5c59f12f4f8b11eb32
|
Java
|
frc868/2016-robot-src
|
/src/com/techhounds/commands/angler/LimitCheckCommand.java
|
UTF-8
| 1,275
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
package com.techhounds.commands.angler;
import edu.wpi.first.wpilibj.command.Command;
import com.techhounds.RobotMap.Angler;
import com.techhounds.subsystems.AnglerSubsystem;
/**
*
*/
public class LimitCheckCommand extends Command {
private AnglerSubsystem angler;
public double forLim = Angler.ANGLER_FORWARD_LIMIT;
public double revLim = Angler.ANGLER_REVERSE_LIMIT;
public LimitCheckCommand() {
angler = AnglerSubsystem.getInstance();
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
if(angler.getPosition() < revLim){
angler.stopPower();
angler.setPosition(revLim);
}else if(angler.getPosition() > forLim){
angler.stopPower();
angler.setPosition(forLim);
}
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
end();
}
}
| true
|
8c2a1b52eb0e55a1f095299b197434da7175a05e
|
Java
|
CircuitSim2/simulator
|
/simulate/circuit/src/gui/Susiki.java
|
UTF-8
| 1,667
| 2.71875
| 3
|
[] |
no_license
|
package gui;
import circuit.Element;
import circuit.SeriesCircuit;
public class Susiki
{
private MainDispApp disp;
public Susiki (MainDispApp disp){
this.disp = disp;
}
public void showElement()
{
int resi=0,capa=0,indu=0;
if(disp.mainCircuit instanceof SeriesCircuit)
{
for(int z =0; z < disp.mainCircuit.getElem().length; z++)
{
Element elem = disp.mainCircuit.getElem(z);
switch(elem.getEt()){
case RESISTANCE:
resi++;
break;
case CAPACITANCE:
capa++;
break;
case INDUCTANCE:
indu++;
break;
case LINE:
break;
default:
break;
}
}
if((resi==1)&&(indu==1)&&(capa==0)){
disp.formula = "RL直列回路に流れる電流の一般解\n"
+ "i(t)=E/R-E/R・e^-(R/L)t \n\n"
+ "抵抗Rの電圧の一般解\n"
+ "eR(t)=E-E・e^-(R/L)t\n\n"
+ "コイルLの電圧の一般解\n"
+ "eL(t)=E・e^-(R/L)t";
}
else if((resi==1)&&(capa==1)&&(indu==0)){
disp.formula = "コンデンサCの電荷の一般解\n"
+ "q(t)=CE-CE・e^-(1/RC)t\n\n"
+ "RC直列回路に流れる電流の一般解\n"
+ "i(t)=(E/R)・e^-(1/RC)t\n\n"
+ "抵抗Rの電圧の一般解\n"
+ "eR(t)=E・e^-(1/RC)t\n\n"
+ "コンデンサCの電圧の一般解\n"
+ "eC(t)=E-E・e^-(1/RC)t";
}
else if((resi==1)&&(indu==1)&&(capa==1)){
disp.formula = "合成インピーダンスz\n"
+ "z=R+j(ωL-1/ωC)\n\n"
+ "合成インピーダンスzの大きさ\n"
+ "|z|=√(R^2+(ωL-1/ωC)^2)";
}
disp.textArea.setEditable(false);
disp.textArea.setText(disp.formula);
}
}
}
| true
|
57b57e584eb3e160715a8dda1d1f40af8111c07a
|
Java
|
ser6440/java
|
/Day0402_Loop/src/DoWhileEx2.java
|
UTF-8
| 1,251
| 4.1875
| 4
|
[] |
no_license
|
import java.util.Scanner;
public class DoWhileEx2 {
public static void main(String[] args) {
//사용자가 특정한 수를 맞추는 게임 프로그램 작성
//사용자에게 숫자를 입력받아서
//입력받은 수가 지정한 수보다 큰지 작은지 알려주다가
//사용자가 정답을 입력하면 정답! 이라고 알려주고 종료
//do-while로 작성
int answer = 67; //정답
int number; //사용자에게 입력받을 수를 저장하는 변수
Scanner input = new Scanner(System.in);
//해야할일
//사용자에게 숫자를 입력받아
//숫자가 정답보다 큰지 작은지, 또는 정답인지 출력
//정답과 입력받은 숫자가 같으면 종료
/*
while(answer != number) {
}
*/ //초기화가 되어 있지 않기 때문에 number를 사용할 수 없음
do {
System.out.println("숫자를 입력하세요");
number = input.nextInt();
if(number > answer) {
System.out.println("입력하신 수가 정답보다 큽니다.");
}else if(number < answer){
System.out.println("입력하신 수가 정답보다 작습니다.");
}else {
System.out.println("축하합니다! 정답입니다!");
}
}while(answer != number);
}
}
| true
|
da5c1d9e1a4a21eeddd94a465aeb3520267b6961
|
Java
|
Zzy2016/AndroidStudy
|
/app/src/main/java/com/example/androidstudy/http/data/HttpResponseInterface.java
|
UTF-8
| 222
| 1.914063
| 2
|
[] |
no_license
|
package com.example.androidstudy.http.data;
import com.google.gson.Gson;
public interface HttpResponseInterface {
/*获取处理掉code和msg之后的信息*/
String getResponseData(Gson gson,String response);
}
| true
|
b2691d331448d60467fbac3ffbf44d1f5de874cb
|
Java
|
claasahl/forex-sandbox
|
/fx-base/src/main/java/org/github/claasahl/forex/generator/Generator.java
|
UTF-8
| 1,123
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
package org.github.claasahl.forex.generator;
import java.time.*;
import java.util.function.*;
import io.reactivex.*;
import io.reactivex.schedulers.*;
public class Generator<V> {
private final Supplier<Duration> duration;
private final Predicate<OffsetDateTime> filter;
private final Function<OffsetDateTime, V> producer;
public Generator(Supplier<Duration> duration, Function<OffsetDateTime, V> producer) {
this(duration, dT -> true, producer);
}
public Generator(Supplier<Duration> duration, Predicate<OffsetDateTime> filter,
Function<OffsetDateTime, V> producer) {
this.duration = duration;
this.filter = filter;
this.producer = producer;
}
public Observable<V> generate(OffsetDateTime from) {
return Observable.generate(() -> from, this::increment)
.filter(filter::test)
.map(producer::apply)
.subscribeOn(Schedulers.computation())
.observeOn(Schedulers.trampoline());
}
private OffsetDateTime increment(OffsetDateTime dateTime, Emitter<OffsetDateTime> emitter) {
emitter.onNext(dateTime);
return dateTime.plus(duration.get());
}
}
| true
|
b87100ea9b77bfbb3bdf21a1d46ded7fb1aed5ad
|
Java
|
abought/cas-overlay
|
/cas-server-support-oauth/src/main/java/org/jasig/cas/support/oauth/OAuthTokenUtils.java
|
UTF-8
| 13,096
| 1.84375
| 2
|
[] |
no_license
|
/*
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.cas.support.oauth;
import org.apache.commons.collections4.Predicate;
import org.apache.commons.lang3.StringUtils;
import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.Authentication;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.authentication.principal.SimpleWebApplicationServiceImpl;
import org.jasig.cas.support.oauth.authentication.principal.OAuthCredential;
import org.jasig.cas.ticket.InvalidTicketException;
import org.jasig.cas.ticket.ServiceTicket;
import org.jasig.cas.ticket.Ticket;
import org.jasig.cas.ticket.TicketException;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.util.CipherExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
/**
* OAuth Access Token Utilities
*
* @author Michael Haselton
* @since 4.1.0
*/
public class OAuthTokenUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(OAuthTokenUtils.class);
public static OAuthToken getAccessToken(final HttpServletRequest request, final CipherExecutor cipherExecutor)
throws RuntimeException {
String accessToken = request.getParameter(OAuthConstants.ACCESS_TOKEN);
if (StringUtils.isBlank(accessToken)) {
final String authHeader = request.getHeader("Authorization");
if (StringUtils.isNotBlank(authHeader)
&& authHeader.toLowerCase().startsWith(OAuthConstants.BEARER_TOKEN.toLowerCase() + " ")) {
accessToken = authHeader.substring(OAuthConstants.BEARER_TOKEN.length() + 1);
} else {
LOGGER.debug("Missing access token");
throw new TokenInvalidException();
}
}
final OAuthToken token = readToken(cipherExecutor, accessToken);
if (token == null) {
LOGGER.debug("Could not read access token");
throw new TokenInvalidException();
}
return token;
}
public static OAuthToken getToken(final HttpServletRequest request, final CipherExecutor cipherExecutor, final String name)
throws RuntimeException {
final String jwtToken = request.getParameter(name);
final OAuthToken token = readToken(cipherExecutor, jwtToken);
if (token == null) {
LOGGER.debug("Could not read token [{}]", name);
throw new TokenInvalidException();
}
return token;
}
public static Ticket getTicket(final CentralAuthenticationService centralAuthenticationService, final OAuthToken token)
throws RuntimeException {
final String ticketId = token.serviceTicketId != null ? token.serviceTicketId : token.ticketGrantingTicketId;
try {
return centralAuthenticationService.getTicket(ticketId, Ticket.class);
} catch (InvalidTicketException e) {
LOGGER.debug("Invalid or expired ticket [{}]", token);
throw new TokenInvalidException();
}
}
public static ServiceTicket getServiceTicket(final CentralAuthenticationService centralAuthenticationService,
final OAuthToken token)
throws RuntimeException {
if (StringUtils.isBlank(token.serviceTicketId)) {
final Service service = new SimpleWebApplicationServiceImpl(token.serviceId);
try {
return centralAuthenticationService.grantServiceTicket(token.ticketGrantingTicketId, service);
} catch (TicketException e) {
LOGGER.debug("Invalid or expired ticket granting ticket [{}] for service [{}]", token.ticketGrantingTicketId, service);
throw new TokenUnauthorizedException();
}
} else {
try {
return centralAuthenticationService.getTicket(token.serviceTicketId, Ticket.class);
} catch (InvalidTicketException e) {
LOGGER.debug("Invalid or expired service ticket [{}]", token.serviceTicketId);
throw new TokenUnauthorizedException();
}
}
}
public static String getJsonWebToken(final CipherExecutor cipherExecutor, final Ticket ticket) {
return getJsonWebToken(cipherExecutor, ticket, null);
}
public static String getJsonWebToken(final CipherExecutor cipherExecutor, final Ticket ticket, final Service service) {
if (ticket instanceof TicketGrantingTicket) {
return cipherExecutor.encode(new OAuthToken(ticket.getId(), service == null ? null : service.getId()).toString());
}
return cipherExecutor.encode(new OAuthToken(ticket.getId()).toString());
}
public static Boolean hasPermission(final Ticket accessTicket, final Ticket ticket) {
final Authentication accessAuthentication = getAuthentication(accessTicket);
final Principal accessPrincipal = accessAuthentication.getPrincipal();
final Authentication ticketAuthentication = getAuthentication(ticket);
final Principal ticketPrincipal = ticketAuthentication.getPrincipal();
return accessPrincipal.getId().equals(ticketPrincipal.getId());
}
public static Authentication getAuthentication(final Ticket ticket) {
return ticket instanceof TicketGrantingTicket ?
((TicketGrantingTicket) ticket).getAuthentication() : ticket.getGrantingTicket().getAuthentication();
}
/**
* Fetch a new access ticket.
*
* @param centralAuthenticationService the central authentication service
* @param refreshTicket the refresh ticket
* @param service the service
* @return ServiceTicket, if successful
*/
public static ServiceTicket fetchAccessTicket(final CentralAuthenticationService centralAuthenticationService,
final TicketGrantingTicket refreshTicket, final Service service)
throws TokenUnauthorizedException {
try {
return centralAuthenticationService.grantServiceTicket(refreshTicket.getId(), service);
} catch (Exception e) {
throw new TokenUnauthorizedException();
}
}
/**
* Fetch a new refresh ticket.
*
* @param centralAuthenticationService the central authentication service
* @param clientId the client id
* @param principal the principal
* @return TicketGrantingTicket, if successful
*/
public static TicketGrantingTicket fetchRefreshTicket(final CentralAuthenticationService centralAuthenticationService,
final String clientId, final Principal principal)
throws TokenUnauthorizedException {
final OAuthCredential credential = new OAuthCredential(clientId, principal.getId(), principal.getAttributes());
try {
return centralAuthenticationService.createTicketGrantingTicket(credential);
} catch (final Exception e) {
throw new TokenUnauthorizedException();
}
}
/**
* Attempt to locate and return an existing refresh token.
*
* @param centralAuthenticationService the central authentication service
* @param clientId the client id
* @param principal the principal
* @return TicketGrantingTicket refresh token or null
*/
public static TicketGrantingTicket getRefreshToken(final CentralAuthenticationService centralAuthenticationService, final String clientId, final Principal principal) {
final Collection<Ticket> tickets = centralAuthenticationService.getTickets(new Predicate() {
@Override
public boolean evaluate(final Object currentTicket) {
if (currentTicket instanceof TicketGrantingTicket) {
final TicketGrantingTicket currentTicketGrantingTicket = (TicketGrantingTicket) currentTicket;
final Principal currentPrincipal = currentTicketGrantingTicket.getAuthentication().getPrincipal();
final Map<String, Object> currentAttributes = currentTicketGrantingTicket.getAuthentication().getAttributes();
if ((currentAttributes.containsKey(OAuthCredential.AUTHENTICATION_ATTRIBUTE_OAUTH) && (Boolean) currentAttributes.get(OAuthCredential.AUTHENTICATION_ATTRIBUTE_OAUTH))
&& (currentAttributes.containsKey(OAuthConstants.CLIENT_ID) && currentAttributes.get(OAuthConstants.CLIENT_ID).equals(clientId))
&& currentPrincipal.getId().equals(principal.getId())) {
return !currentTicketGrantingTicket.isExpired();
}
}
return false;
}
});
if (tickets.size() == 1) {
return (TicketGrantingTicket) tickets.iterator().next();
}
return null;
}
/**
* Return a list of refresh tokens associated with a specific client application.
*
* @param centralAuthenticationService the central authentication service
* @param clientId the client id
* @return Collection of refresh tokens for the application specified
*/
public static Collection<Ticket> getRefreshTokens(final CentralAuthenticationService centralAuthenticationService, final String clientId) {
return centralAuthenticationService.getTickets(new Predicate() {
@Override
public boolean evaluate(final Object currentTicket) {
if (currentTicket instanceof TicketGrantingTicket) {
final TicketGrantingTicket currentTicketGrantingTicket = (TicketGrantingTicket) currentTicket;
final Map<String, Object> currentAttributes = currentTicketGrantingTicket.getAuthentication().getAttributes();
if ((currentAttributes.containsKey(OAuthCredential.AUTHENTICATION_ATTRIBUTE_OAUTH) && (Boolean) currentAttributes.get(OAuthCredential.AUTHENTICATION_ATTRIBUTE_OAUTH))
&& (currentAttributes.containsKey(OAuthConstants.CLIENT_ID) && currentAttributes.get(OAuthConstants.CLIENT_ID).equals(clientId))) {
return !currentTicketGrantingTicket.isExpired();
}
}
return false;
}
});
}
/**
* Return a list of refresh tokens associated with the a principal.
*
* @param centralAuthenticationService the central authentication service
* @param principal the principal
* @return Collection of refresh tokens associated with the principal specified
*/
public static Collection<Ticket> getRefreshTokens(final CentralAuthenticationService centralAuthenticationService, final Principal principal) {
return centralAuthenticationService.getTickets(new Predicate() {
@Override
public boolean evaluate(final Object currentTicket) {
if (currentTicket instanceof TicketGrantingTicket) {
final TicketGrantingTicket currentTicketGrantingTicket = (TicketGrantingTicket) currentTicket;
final Principal currentPrincipal = currentTicketGrantingTicket.getAuthentication().getPrincipal();
final Map<String, Object> currentAttributes = currentTicketGrantingTicket.getAuthentication().getAttributes();
if ((currentAttributes.containsKey(OAuthCredential.AUTHENTICATION_ATTRIBUTE_OAUTH) && (Boolean) currentAttributes.get(OAuthCredential.AUTHENTICATION_ATTRIBUTE_OAUTH))
&& currentPrincipal.getId().equals(principal.getId())) {
return !currentTicketGrantingTicket.isExpired();
}
}
return false;
}
});
}
private static OAuthToken readToken(final CipherExecutor cipherExecutor, final String jwtToken) {
try {
return OAuthToken.read(cipherExecutor.decode(jwtToken));
} catch (IOException | NullPointerException e) {
return null;
}
}
}
| true
|
297271c65571c2e23bce327dff7aacd1b9a726c0
|
Java
|
petargenev/FinalProject
|
/src/main/java/com/eshop/dao/CamcorderDAO.java
|
UTF-8
| 3,522
| 2.453125
| 2
|
[] |
no_license
|
package com.eshop.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.activity.InvalidActivityException;
import com.eshop.connection.DBConnection;
import com.eshop.exceptions.ArticleException;
import com.eshop.exceptions.InvalidInputException;
import com.eshop.interfaces.DAO;
import com.eshop.models.Article;
import com.eshop.models.Camcorder;
import com.eshop.models.Computer;
public class CamcorderDAO implements DAO {
Connection connection = DBConnection.getInstance().getConnection();
@Override
public Collection<Article> showAll() throws SQLException, InvalidInputException, InvalidInputException {
List<Article> camcorders = new ArrayList<Article>();
String query = "SELECT c.*, l.* FROM camcorder c JOIN label l on(c.label_id = l.id);";
PreparedStatement ps = connection.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String label = rs.getString("label");
String model = rs.getString("model");
double price = rs.getDouble("price");
String image = rs.getString("image");
double resolution = rs.getDouble("resolution");
double displaySize = rs.getDouble("display_size");
int digitalZoom = rs.getInt("digital_zoom");
String cameraType = rs.getString("camera_type");
int id = rs.getInt("id");
try {
camcorders.add(new Camcorder(image, label, model, price, resolution, cameraType, displaySize, digitalZoom, id));
} catch (InvalidActivityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
connection.close();
return Collections.unmodifiableList(camcorders);
}
public void insertCamcorder(Camcorder camcorder) throws SQLException {
try {
String labelQuery = "SELECT label FROM label WHERE label LIKE '" + camcorder.getLabel() + "';";
PreparedStatement labelPs = connection.prepareStatement(labelQuery);
ResultSet labelRs = labelPs.executeQuery();
int labelId = 0;
if (labelRs.next()) {
labelId = labelRs.getInt("id");
} else {
labelId = new KeysDAO().insertLabel(camcorder.getLabel());
}
PreparedStatement camcorderPs = connection
.prepareStatement("INSERT INTO camcorder VALUES(null, ?, ?, ?, ?, ?, ?, ?, ?)");
camcorderPs.setDouble(1, camcorder.getResolution());
camcorderPs.setDouble(2, camcorder.getDisplaySize());
camcorderPs.setInt(3, camcorder.getDigitalZoom());
camcorderPs.setDouble(4, camcorder.getPrice());
camcorderPs.setString(5, camcorder.getModel());
camcorderPs.setString(6, camcorder.getImage());
camcorderPs.setString(7, camcorder.getCameraType());
camcorderPs.setInt(8, labelId);
camcorderPs.executeUpdate();
connection.close();
} catch (SQLException e) {
connection.close();
e.printStackTrace();
}
}
@Override
public Computer getArticleById(int articleId) throws SQLException, InvalidInputException {
// TODO Auto-generated method stub
return null;
}
@Override
public Collection<Article> getArticleByLabel(String articlelabel) throws SQLException, InvalidInputException {
// TODO Auto-generated method stub
return null;
}
@Override
public void deleteArticleById(int id) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void insertArticle(Article article) throws ArticleException {
// TODO Auto-generated method stub
}
}
| true
|
eef60c623a810491d665c586a74b5a473e1faaaa
|
Java
|
Gaya3Balasubramanian/OldMavenProject
|
/src/test/java/ArrayList_Demo/Practice3.java
|
UTF-8
| 957
| 3.6875
| 4
|
[] |
no_license
|
package ArrayList_Demo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class Practice3 {
public static void main(String[] args) {
ArrayList<String>places= new ArrayList<String>();
}
public static void PrintArraylist(ArrayList<String> places) {
Iterator i=places.iterator();
while(i.hasNext()) {
System.out.println("Now Visiting " + i.next());
}
}
public static boolean addinorder(ArrayList<String> places, String newplace) {
ListIterator<String> Stringlist= places.listIterator();
while(Stringlist.hasNext()) {
int comparison= Stringlist.next().compareTo(newplace);
if(comparison==0) {
System.out.println("New place is already in the destination place");
}
else if(comparison>0) {
Stringlist.previous();
Stringlist.add(newplace);
return true;
}
else if(comparison<0) {
}
}
Stringlist.add(newplace);
return true;
}
}
| true
|
6cd5c06f90d2f5fff090f169929ec47ece958b7e
|
Java
|
ViniciusArnhold/Android-Realm-CRUD
|
/app/src/main/java/br/unisinos/db2realm/AddAnuncio.java
|
UTF-8
| 2,872
| 2.328125
| 2
|
[] |
no_license
|
package br.unisinos.db2realm;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import br.unisinos.db2realm.model.Anunciante;
import br.unisinos.db2realm.model.Anuncio;
import io.realm.Realm;
import io.realm.RealmChangeListener;
public class AddAnuncio extends AppCompatActivity {
private EditText idAnuncianteText;
private Button addAnuncioBotao;
private EditText tituloText;
private EditText descText;
private EditText valorText;
private CheckBox disponivelRadio;
private String idAnunciante;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_anuncio);
idAnuncianteText = (EditText) findViewById(R.id.edit_text_anunciante_anuncio);
tituloText = (EditText) findViewById(R.id.edit_text_titulo);
descText = (EditText) findViewById(R.id.edit_text_desc);
valorText = (EditText) findViewById(R.id.edit_text_valor);
disponivelRadio = (CheckBox) findViewById(R.id.edit_radio_disponivel);
idAnunciante = getIntent().getStringExtra(AddUpdateUsuario.EXTRA_ANUNCIANTE_ID);
Realm.getDefaultInstance().where(Anunciante.class)
.equalTo("id", idAnunciante)
.findFirstAsync().addChangeListener(new RealmChangeListener<Anunciante>() {
@Override
public void onChange(Anunciante anunciante) {
idAnuncianteText.setText("Anunciante: " + anunciante.getNomeFantasia());
}
});
addAnuncioBotao = (Button) findViewById(R.id.button_add_update_anuncio);
addAnuncioBotao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Realm.getDefaultInstance().executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.copyToRealm(new Anuncio(idAnunciante,
tituloText.getText().toString(),
descText.getText().toString(),
Double.valueOf(valorText.getText().toString()),
disponivelRadio.isChecked()));
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
Toast t = Toast.makeText(AddAnuncio.this, "Anuncio criado com sucesso!", Toast.LENGTH_SHORT);
t.show();
finish();
}
});
}
});
}
}
| true
|
ec0b9ab96d2c42fed826cedd34cdc9a77e104a66
|
Java
|
xrealm/tiktok-src
|
/sources/com/p280ss/android/ugc/aweme/video/p1697a/C43180a.java
|
UTF-8
| 883
| 1.71875
| 2
|
[] |
no_license
|
package com.p280ss.android.ugc.aweme.video.p1697a;
import com.p280ss.android.ugc.playerkit.p1750a.C44910d;
/* renamed from: com.ss.android.ugc.aweme.video.a.a */
public interface C43180a {
/* renamed from: com.ss.android.ugc.aweme.video.a.a$a */
public static class C43181a {
/* renamed from: a */
public final C44910d<String> f111812a;
/* renamed from: b */
public final String f111813b;
/* renamed from: c */
private String f111814c;
/* renamed from: a */
public final String mo104813a() {
if (this.f111814c == null) {
this.f111814c = (String) this.f111812a.mo104814a();
}
return this.f111814c;
}
public C43181a(C44910d<String> dVar, String str) {
this.f111812a = dVar;
this.f111813b = str;
}
}
}
| true
|
49dd727d3cf9bfd294cea9b80048df1e50a2fd16
|
Java
|
zwoosks/SpamDetector
|
/src/me/zwoosks/spamDetector/listeners/notifiedWords/AlertAnvilListener.java
|
UTF-8
| 2,448
| 2.25
| 2
|
[] |
no_license
|
package me.zwoosks.spamDetector.listeners.notifiedWords;
import java.util.HashMap;
import java.util.List;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import me.zwoosks.spamDetector.Main;
import me.zwoosks.spamDetector.listeners.notifiedWords.utils.Cmd;
import me.zwoosks.spamDetector.listeners.notifiedWords.utils.Messages;
import me.zwoosks.spamDetector.utils.LogRegisterer;
import me.zwoosks.spamDetector.utils.Similarities;
import me.zwoosks.spamDetector.utils.Utils;
public class AlertAnvilListener implements Listener {
private Main plugin;
public AlertAnvilListener(Main plugin) {
this.plugin = plugin;
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onItemRenameAnvil(InventoryClickEvent e) {
try {
if(e.getSlotType() == InventoryType.SlotType.RESULT) {
if(!e.getWhoClicked().hasPermission("antispam.bypass.alert.anvil")) {
String written = Utils.raw(e.getCurrentItem().getItemMeta().getDisplayName());
List<String> blockedWords = plugin.getConfig().getStringList("anvil.alert.alertWords");
for(String word : blockedWords) {
HashMap<String, Object> map = Similarities.check(written, word);
if((boolean)map.get("found") == true) {
Player player = (Player) e.getWhoClicked();
e.setCancelled(plugin.getConfig().getBoolean("anvil.alert.cancelEventOnAlert"));
Cmd.runCommand("anvil", (String) map.get("word"), (String) map.get("text"), player.getName(), plugin.getConfig());
Messages.sendToPlayer("anvil", (String) map.get("word"), (String) map.get("text"), player, plugin.getConfig());
Messages.alertStaff("anvil", (String) map.get("word"), (String) map.get("text"), player, plugin.getConfig());
if(plugin.getConfig().getBoolean("anvil.alert.saveInLog")) {
LogRegisterer.registerLog(player.getName(), (String) map.get("word"), (String) map.get("text"), "anvil", plugin);
}
} else if((boolean)map.get("found") == false) {} else {
plugin.getLogger().info(Utils.chat("&c&lAn error occured while trying to check if a witten message is illegal."
+ " Please, report the error!"));
}
}
}
}
} catch(Exception ex) {}
}
}
| true
|
bfec61c248d0f9c3f9e545734793156e8bd5f8bf
|
Java
|
waynechou1204/VFEAP
|
/src/dataStructure/ProgramCalculation.java
|
UTF-8
| 1,107
| 2.4375
| 2
|
[] |
no_license
|
package dataStructure;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import dataStructure.entity.VFIFE_Bar;
import dataStructure.entity.VFIFE_CartesianPoint;
import dataStructure.entity.VFIFE_Load;
import dataStructure.entity.VFIFE_LoadNode;
import dataStructure.entity.VFIFE_Material;
import dataStructure.entity.VFIFE_Node;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ProgramCalculation {
public void LoadData(){
}
public void caculate(String input){
try {
System.out.println("start");
String cmd="python main.py "+input;
Process pr = Runtime.getRuntime().exec(cmd);
BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
pr.waitFor();
System.out.println("end");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
| true
|
a2ada0cbe1702725aedb8b10daaadd7d6f678490
|
Java
|
fouomene/spotify-streamer-two
|
/SpotifyStreamer/app/src/main/java/com/fouomene/spotifystreamer/data/SpotifyStreamerDbHelper.java
|
UTF-8
| 2,371
| 2.703125
| 3
|
[] |
no_license
|
/**
*
* Created by FOUOMENE
* EmailAuthor: fouomenedaniel@gmail.com .
*
**/
package com.fouomene.spotifystreamer.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.fouomene.spotifystreamer.data.SpotifyStreamerContract.TopTrackEntry;
/**
* Manages a local database for toptrack data.
*/
public class SpotifyStreamerDbHelper extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database version.
private static final int DATABASE_VERSION = 4;
public static final String DATABASE_NAME = "spotifystreamer.db";
public SpotifyStreamerDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Create a table to hold toptrack.
final String SQL_CREATE_TOPTRACK_TABLE = "CREATE TABLE " + TopTrackEntry.TABLE_NAME + " (" +
TopTrackEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
TopTrackEntry.COLUMN_ARTIST_ID + " TEXT NOT NULL, " +
TopTrackEntry.COLUMN_ARTIST_NAME + " TEXT NOT NULL, " +
TopTrackEntry.COLUMN_ALBUM_NAME + " TEXT NOT NULL, " +
TopTrackEntry.COLUMN_ALBUM_ARTWORK_URL + " TEXT NOT NULL, " +
TopTrackEntry.COLUMN_TRACK_NAME + " TEXT NOT NULL, " +
TopTrackEntry.COLUMN_TRACK_URL + " TEXT NOT NULL, " +
TopTrackEntry.COLUMN_TRACK_DURATION + " TEXT NOT NULL " + // in ms
" );";
sqLiteDatabase.execSQL(SQL_CREATE_TOPTRACK_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
// Note that this only fires if you change the version number for your database.
// It does NOT depend on the version number for your application.
// If you want to update the schema without wiping data, commenting out the next 2 lines
// should be your top priority before modifying this method.
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TopTrackEntry.TABLE_NAME);
onCreate(sqLiteDatabase);
}
}
| true
|
ad20fe8fc2992915f9a477a46146b68a2694b903
|
Java
|
alexanderFeltser/MultiThread-Sorter
|
/MultiThreadSorter/src/multiThreadSorter/Controller.java
|
UTF-8
| 6,655
| 2.703125
| 3
|
[] |
no_license
|
package multiThreadSorter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Controller implements QueueListener, Runnable {
final int MAX_X;
final int MAX_Y;
MessageQueue postBoxIn;
final private HashMap<QueueNo, MessageQueue> sortersPostBoxes;
final private HashMap<QueuePair, QueuePair> sendedNumbersPairs;
Thread thread;
HashSet<QueuePair> sortEndedPairsMmap;// contains number of Sorters that
// possibly ended sorting
public Controller(int mAX_X, int mAX_Y) {
MAX_X = mAX_X;
MAX_Y = mAX_Y;
postBoxIn = new MessageQueue(new QueueNo(-1, -1));
postBoxIn.addNewQueueListener(this);
sortersPostBoxes = new HashMap<>();
sortEndedPairsMmap = new HashSet<>();
sendedNumbersPairs = new HashMap<>();
}
public boolean haveSmallerSibling(QueueNo queueNo) {
return (queueNo.getX() > 1 || queueNo.getY() > 1);
}
public boolean haveRightSibling(QueueNo queueNo) {
return (queueNo.getX() < MAX_X || queueNo.getY() < MAX_Y);
}
public QueueNo getSmallerSiblingNo(QueueNo queueNo) {
if (queueNo.getX() > 1) {
return new QueueNo(queueNo.getX() - 1, queueNo.getY());
} else if (queueNo.getY() > 1) {
return new QueueNo(MAX_X, queueNo.getY() - 1);
} else {
throw new IndexOutOfBoundsException(
"Trying to get left sibling of (" + queueNo.getX() + "," + queueNo.getX() + ")");
}
}
public QueueNo getGraterSiblingNo(QueueNo queueNo) {
if (queueNo.getX() < MAX_X) {
return new QueueNo(queueNo.getX() + 1, queueNo.getY());
} else if (queueNo.getY() < MAX_Y) {
return new QueueNo(1, queueNo.getY() + 1);
} else {
throw new IndexOutOfBoundsException(
"Trying to get right sibling of (" + queueNo.getX() + "," + queueNo.getX() + ")");
}
}
public boolean isSortStopped() {
return postBoxIn.isEmpty();
}
void addSorterThreadMessageBox(QueueNo queueNo, MessageQueue queuePostBoxIn) {
sortersPostBoxes.put(queueNo, queuePostBoxIn);
}
public final Thread getThread() {
if (thread == null) {
thread = new Thread(this);
}
return thread;
}
private boolean isSortEnded() {
if (!postBoxIn.isEmpty()) {
return false;
}
if (sortEndedPairsMmap.size() != MAX_X * MAX_Y - 1) {
return false;
}
return true;
}
private void sendToAllThread(Message endMessege) {
Collection<MessageQueue> allQueues = sortersPostBoxes.values();
for (MessageQueue queue : allQueues) {
queue.sendNumber2Sorter(endMessege);
}
}
@Override
public void run() {
boolean isSortEnded = false;
int cnt = 0;
while (true) {
if (postBoxIn.isEmpty()) {
if (isSortEnded) {
System.out.println("Controller sends an end message...");
sendToAllThread(Message.getEndMessageFrom(postBoxIn.getQueueNo()));
break;
}
postBoxIn.wateForMessage();
}
if (cnt > 700) {
// printPairs(sendedNumbersPairs);
cnt++;
}
cnt++;
writeNumbersFromSorters();
isSortEnded = isSortEnded();
sendNumbersTosorters();
}
// sendToAllThread(Message.getEndMessage());
System.out.println("Controller exits... ");
}
private void printPairs(HashMap<QueuePair, QueuePair> sendedNumbersPairs2) {
Collection<QueuePair> qPairCollection = sendedNumbersPairs2.values();
if (qPairCollection.size() > 0) {
System.out.println("Pairs:");
}
for (QueuePair qPair : qPairCollection) {
System.out.println(qPair);
}
}
private void sendNumbersTosorters() {
Message message;
QueuePair qPairValue;
ArrayList<QueuePair> removePairArray = new ArrayList<>();
Set<QueuePair> qPairSet = sendedNumbersPairs.keySet();
for (QueuePair qPair : qPairSet) {
if (sendedNumbersPairs.get(qPair).havePair()) {
qPairValue = sendedNumbersPairs.get(qPair);
removePairArray.add(qPair);
if (qPairValue.needToSwitch()) {
sortEndedPairsMmap.add(qPair);
qPairValue.switchNumbers();
} else {
sortEndedPairsMmap.clear();// contains number of Sorters
// that
// possibly ended sorting
}
message = qPairValue.messageToLeftQueue();
sortersPostBoxes.get(message.getToo()).sendNumber2Sorter(message);
message = qPairValue.messageToRightQueue();
sortersPostBoxes.get(message.getToo()).sendNumber2Sorter(message);
}
}
for (QueuePair qPaiRmv : removePairArray) {
sendedNumbersPairs.remove(qPaiRmv);
}
}
private void writeNumbersFromSorters() {
Message message;
QueuePair qPairValue;
QueuePair qPair;
while (!postBoxIn.isEmpty()) { // || !allPairsRedyToProcess() ||
// sendedNumbersPairs.size() < MAX_X *
// MAX_Y - 1)
message = getMessageFromQueue();
// System.out.println("writeNumbersFromSorters");
// sortersPostBoxes.get(message.getToo()).sendNumber2Sorter(message);
qPair = QueuePair.getQueueParFromMessage(message);
if (sendedNumbersPairs.containsKey(qPair)) {
qPairValue = sendedNumbersPairs.remove(qPair);
} else {
qPairValue = qPair;
}
qPairValue.putMessage(message);
sendedNumbersPairs.put(qPair, qPairValue);
}
}
@Override
public Message getMessageFromQueue() {
return postBoxIn.removeFromSendedNumbersQueue();
}
private MessageQueue getControllerPostBox() {
return postBoxIn;
}
public static void main(String[] args) throws InterruptedException {
int x = 20;
int y = 10;
int numbersInThread = 20;
SorterThread sortThread;
Controller controller = new Controller(x, y);
QueueNo queueNo;
List<SorterThread> queueList = new ArrayList<SorterThread>();
System.out.format("Before Sort Matrix (%d,%d):", x, y);
System.out.println();
for (int j = 1; j <= y; j++) {
for (int i = 1; i <= x; i++) {
queueNo = new QueueNo(i, j);
sortThread = new SorterThread(numbersInThread, controller.getControllerPostBox(), queueNo, controller);
queueList.add(sortThread);
sortThread.fillNumbers();
controller.addSorterThreadMessageBox(queueNo, sortThread.getPostBoxIn());
sortThread.getThread().start();
}
}
controller.getThread().start();
Thread.sleep(10000);
System.out.println("==============================================================================");
System.out.println("Print Result:");
System.out.println("==============================================================================");
for (SorterThread q : queueList) {
q.printNumbers("Result:");
}
}
}
| true
|
7dcb75f2df2ae92aba6346bb6970323150cec80e
|
Java
|
jasobimDevelopers/jasobim
|
/src/com/my/spring/utils/MenuNodeUtil.java
|
UTF-8
| 4,582
| 2.765625
| 3
|
[] |
no_license
|
package com.my.spring.utils;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.gson.JsonArray;
import net.sf.json.JSONArray;
import java.util.Collections;
/**
* 多叉树类
*/
public class MenuNodeUtil {
public String getJasonStringOfMenu(List dataList) {
// 读取层次数据结果集列表
//List dataList = VirtualDataGenerator.getVirtualResult();
// 节点列表(散列表,用于临时存储节点对象)
HashMap nodeList = new HashMap();
// 根节点
NodeMenu root = null;
List<NodeMenu> pcList = new ArrayList<NodeMenu>();
// 根据结果集构造节点列表(存入散列表)
for (Iterator it = dataList.iterator(); it.hasNext();) {
Map dataRecord = (Map) it.next();
NodeMenu node = new NodeMenu();
node.id = (String) dataRecord.get("id");
node.name = (String) dataRecord.get("name");
node.menuPath = (String) dataRecord.get("menuPath");
node.pid = (String) dataRecord.get("pid");
node.createDate = (String) dataRecord.get("createDate");
node.createUser = (String) dataRecord.get("createUser");
nodeList.put(node.id, node);
}
// 构造无序的多叉树
Set entrySet = nodeList.entrySet();
for(Iterator it = entrySet.iterator(); it.hasNext();) {
NodeMenu node = (NodeMenu) ((Map.Entry) it.next()).getValue();
if (node.pid == null || node.pid.equals("")) {
// root = node;
pcList.add(node);
} else {
((NodeMenu) nodeList.get(node.pid)).addChild(node);
}
}
// 输出无序的树形菜单的JSON字符串
//System.out.println(pcList);
String results = pcList.toString();
return results;
}
/**
* 节点类
*/
class NodeMenu {
/**
* 节点编号
*/
public String id;
/**
* 节点内容
*/
public String name;
/**
* 父节点编号
*/
public String pid;
public String createUser;
public String createDate;
public String menuPath;
/**
* 孩子节点列表
*/
private MenuChildren children = new MenuChildren();
// 先序遍历,拼接JSON字符串
public String toString() {
String result = "{"
+ "\"id\" : \"" + id + "\""+", \"menuPath\" : \"" + menuPath + "\""
+ ", \"name\" : \"" + name + "\"" + ", \"createUser\" : \""
+ createUser + "\"" +", \"createDate\" : \"" + createDate + "\"";
if (children != null && children.getSize() != 0) {
result += ", \"children\" : " + children.toString();
} else {
result += ",\"leaf\" : \"true\"";
}
System.out.println(result);
return result + "}";
}
// 兄弟节点横向排序
public void sortChildren() {
if (children != null && children.getSize() != 0) {
children.sortChildren();
}
}
// 添加孩子节点
public void addChild(NodeMenu node) {
this.children.addChild(node);
}
}
/**
* 孩子列表类
*/
class MenuChildren {
private List list = new ArrayList();
public int getSize() {
return list.size();
}
public void addChild(NodeMenu node) {
list.add(node);
}
// 拼接孩子节点的JSON字符串
public String toString() {
String result = "[";
for (Iterator it = list.iterator(); it.hasNext();) {
result += ((NodeMenu) it.next()).toString();
result += ",";
}
result = result.substring(0, result.length() - 1);
result += "]";
return result;
}
// 孩子节点排序
public void sortChildren() {
// 对本层节点进行排序
// 可根据不同的排序属性,传入不同的比较器,这里传入ID比较器
Collections.sort(list, new NodeIDComparator());
// 对每个节点的下一层节点进行排序
for (Iterator it = list.iterator(); it.hasNext();) {
((NodeMenu) it.next()).sortChildren();
}
}
}
/**
* 节点比较器
*/
class NodeIDComparator implements Comparator {
// 按照节点编号比较
public int compare(Object o1, Object o2) {
int j1 = Integer.parseInt(((NodeMenu)o1).id);
int j2 = Integer.parseInt(((NodeMenu)o2).id);
return (j1 < j2 ? -1 : (j1 == j2 ? 0 : 1));
}
}
}
| true
|
ccbf5864ba04a32c3c7d416ada8537d0953ea9e6
|
Java
|
jacob-carlborg/descent
|
/descent.ui/src/descent/internal/debug/ui/jres/IAddVMDialogRequestor.java
|
UTF-8
| 644
| 2.203125
| 2
|
[] |
no_license
|
package descent.internal.debug.ui.jres;
import descent.launching.IVMInstall;
/**
* This interface is implemented by clients of the <code>AddVMDialog</code>.
*/
public interface IAddVMDialogRequestor {
/**
* Reply whether or not a new VM of the specified name would
* constitute a duplicate.
*
* @param name the name of a potential new VM
* @return whether a new VM with the specified name would be a duplicate VM
*/
public boolean isDuplicateName(String name);
/**
* Notification that a VM has been added from the <code>AddVMDialog</code>.
*
* @param vm the added vm
*/
public void vmAdded(IVMInstall vm);
}
| true
|
73ef05110ba5b317cf0fd63f6b9f4ea4e8f24685
|
Java
|
rahulmitt/kafka-demo
|
/kafka-producer/src/main/java/com/rahulmitt/interviewpedia/kafka/producer/config/KafkaProducerConfigs.java
|
UTF-8
| 1,649
| 1.960938
| 2
|
[] |
no_license
|
package com.rahulmitt.interviewpedia.kafka.producer.config;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.IntegerSerializer;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import org.springframework.kafka.support.serializer.JsonSerializer;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class KafkaProducerConfigs {
public static final String BOOTSTRAP_SERVERS = "interviewpedia:9092";
public static final String GROUP_ID = "app2";
@Bean
public ProducerFactory<String, ?> producerFactory() {
Map<String, Object> producerProperties = new HashMap<>();
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS);
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class.getName());
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class.getName());
return new DefaultKafkaProducerFactory<>(producerProperties);
}
@Bean
public KafkaTemplate<String, ?> kafkaTemplate() {
return new KafkaTemplate<>(producerFactory());
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
| true
|
1f4332c6a94ce7043031558385718c7693f2aea4
|
Java
|
dingqz/Java
|
/20160928/TestStatic.java
|
UTF-8
| 355
| 3.203125
| 3
|
[] |
no_license
|
public class TestStatic
{
//定义一个非静态的内部类,是一个空类
private class In{}
//外部类的静态方法
public static void main(String[] args)
{
//下面代码引发编译异常,因为静态成员(main方法)无法访问非静态成员(In类)
new In();
}
}
| true
|
0e1bc634df9087bd2d17ef2ed7a2dd9ad4df31c7
|
Java
|
netikras/StudentBuddy
|
/commons/src/main/java/com/netikras/studies/studentbuddy/commons/exception/StudBudUncheckedException.java
|
UTF-8
| 4,371
| 2.421875
| 2
|
[] |
no_license
|
package com.netikras.studies.studentbuddy.commons.exception;
import com.netikras.tools.common.exception.FriendlyUncheckedException;
import com.netikras.tools.common.remote.http.HttpStatus;
/**
* Normally should not get out to userspace...
*
* Created by netikras on 17.3.7.
*/
public class StudBudUncheckedException extends FriendlyUncheckedException {
private static final long serialVersionUID = -7777687824412011184L;
private int statusCode;
private int errorCode;
private String message1;
private String message2;
private String probableCause;
private String url;
private String developerMessage;
private Throwable wrappedException;
public StudBudUncheckedException(){}
public StudBudUncheckedException(String message){
setMessage1(message);
}
public StudBudUncheckedException(int statusCode){
setStatusCode(statusCode);
}
public StudBudUncheckedException(String message, int statusCode){
setMessage1(message);
setStatusCode(statusCode);
}
public StudBudUncheckedException(String message1, String message2, int statusCode, String probableCause){
setMessage1(message1);
setMessage2(message2);
setStatusCode(statusCode);
setProbableCause(probableCause);
}
public StudBudUncheckedException(String message1, String message2, int statusCode, String probableCause,
String url, String developerMessage, int errorCode){
setMessage1(message1);
setMessage2(message2);
setStatusCode(statusCode);
setProbableCause(probableCause);
setUrl(url);
setDeveloperMessage(developerMessage);
setErrorCode(errorCode);
}
public Throwable getWrappedException() {
return wrappedException;
}
public StudBudUncheckedException setWrappedException(Throwable wrappedException) {
this.wrappedException = wrappedException;
if (wrappedException != null) {
wrappedException.printStackTrace();
}
return this;
}
public StudBudUncheckedException setStatusCode(HttpStatus code) {
this.statusCode = code.getCode();
return this;
}
public StudBudUncheckedException setStatusCode(org.springframework.http.HttpStatus code) {
this.statusCode = code.value();
return this;
}
public StudBudUncheckedException setStatusCode(int code) {
this.statusCode = code;
return this;
}
public StudBudUncheckedException setMessage1(String message) {
this.message1 = message;
return this;
}
public StudBudUncheckedException setMessage2(String message) {
this.message2 = message;
return this;
}
public StudBudUncheckedException setProbableCause(String cause) {
this.probableCause = cause;
return this;
}
public StudBudUncheckedException setUrl(String url) {
this.url = url;
return this;
}
public StudBudUncheckedException setDeveloperMessage(String message) {
this.developerMessage = message;
return this;
}
public StudBudUncheckedException setErrorCode(int code){
this.errorCode = code;
return this;
}
public String getUrl() {
return url;
}
public int getStatusCode() {
return statusCode;
}
public String getMessage1() {
return message1;
}
public String getMessage2() {
return message2;
}
public String getProbableCause() {
return probableCause;
}
public String getDeveloperMessage() {
return developerMessage;
}
public int getErrorCode(){
return errorCode;
}
@Override
public String toString() {
return "StudBudUncheckedException{" +
"statusCode=" + statusCode +
", errorCode=" + errorCode +
", message1='" + message1 + '\'' +
", message2='" + message2 + '\'' +
", probableCause='" + probableCause + '\'' +
", url='" + url + '\'' +
", developerMessage='" + developerMessage + '\'' +
", wrappedException=" + wrappedException +
", errors=" + getErrors() +
'}';
}
}
| true
|
4193140f532a94ef1029c87a0c531559cfa6b80b
|
Java
|
deniace/crud_java_spring_rest_api
|
/src/main/java/com/deni/crudrest2/controller/PegawaiController.java
|
UTF-8
| 5,884
| 2.21875
| 2
|
[] |
no_license
|
package com.deni.crudrest2.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.catalina.connector.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.deni.crudrest2.dto.PageDto;
import com.deni.crudrest2.model.Pegawai;
import com.deni.crudrest2.service.PegawaiService;
import com.deni.crudrest2.util.ResponseUtil;
@RestController
@RequestMapping("pegawai")
public class PegawaiController {
@Autowired
PegawaiService service;
@GetMapping("")
public ResponseEntity<?> index() {
List<Pegawai> allData = service.getAll();
if (allData.isEmpty()) {
return new ResponseEntity<>(ResponseUtil.responseConstruct(false, null, "no data"), HttpStatus.OK);
} else {
return new ResponseEntity<>(ResponseUtil.responseConstruct(true, allData, "ok"), HttpStatus.OK);
}
}
@PostMapping("/paging")
public ResponseEntity<?> getPage(@RequestBody PageDto pageDto) {
Pageable pageable = PageRequest.of(pageDto.getPage(), pageDto.getPageSize());
List<Pegawai> all = service.getPage(pageable);
if (all.isEmpty()) {
return new ResponseEntity<>(ResponseUtil.responseConstruct(false, null, "nodata"), HttpStatus.OK);
} else {
return new ResponseEntity<>(ResponseUtil.responseConstruct(true, all, "ok"), HttpStatus.OK);
}
}
@PostMapping("/paging2")
public ResponseEntity<?> getPaging(@RequestBody PageDto pageDto) {
Pageable pageable = PageRequest.of(pageDto.getPage(), pageDto.getPageSize());
Page<Pegawai> allPage = service.getPaging(pageable);
if (allPage.isEmpty()) {
// page dimulai dari 0
List<Pegawai> list = allPage.getContent();
int currentPage = allPage.getNumber();
int totalPage = allPage.getTotalPages();
long totalElement = allPage.getTotalElements();
return new ResponseEntity<>(ResponseUtil.responseConstruct(false, null, "nodata"), HttpStatus.OK);
} else {
return new ResponseEntity<>(ResponseUtil.responseConstruct(true, allPage, "ok"), HttpStatus.OK);
}
}
@GetMapping("/{nip}")
public ResponseEntity<?> getByNip(@PathVariable("nip") String nip) {
Pegawai peg = service.getByNip(nip);
if (peg != null) {
return new ResponseEntity<>(ResponseUtil.responseConstruct(true, peg, "ok"), HttpStatus.OK);
} else {
return new ResponseEntity<>(ResponseUtil.responseConstruct(false, null, "nip not found"), HttpStatus.OK);
}
}
@PostMapping("")
public ResponseEntity<?> create(@RequestBody(required = false) Pegawai p) {
if (p != null) {
Map<String, String> req = new HashMap<String, String>();
if (p.getNip() == null) {
req.put("nip", "nip is required");
}
if (p.getNama() == null) {
req.put("nama", "nama is required");
}
if (p.getJabatan() == null) {
req.put("jabatan", "jabatan is required");
}
if (p.getNoHp() == null) {
req.put("noHp", "no hp is required");
}
if (req.isEmpty()) {
service.create(p);
return new ResponseEntity<>(ResponseUtil.responseConstruct(true, p, "saved"), HttpStatus.CREATED);
} else {
return new ResponseEntity<>(ResponseUtil.responseConstruct(false, req, "required data is missing"),
HttpStatus.OK);
}
} else {
return new ResponseEntity<>(ResponseUtil.responseConstruct(false, null, "no data"), HttpStatus.OK);
}
}
@PutMapping("/{nip}")
public ResponseEntity<?> update(@PathVariable("nip") String nip, @RequestBody Pegawai p) {
Map<String, String> req = new HashMap<String, String>();
if (nip == null) {
req.put("nip", "nip is required");
}
if (p.getNama() == null) {
req.put("nama", "nama is required");
}
if (p.getJabatan() == null) {
req.put("jabatan", "jabatan is required");
}
if (p.getNoHp() == null) {
req.put("noHp", "no hp is required");
}
if (p.getDepartemen() == null) {
req.put("departemen", "departemen is required");
}
if (req.isEmpty()) {
Pegawai peg = service.getByNip(nip);
if (peg != null) {
peg.setNama(p.getNama());
peg.setJabatan(p.getJabatan());
peg.setNoHp(p.getNoHp());
peg.setDepartemen(p.getDepartemen());
service.create(peg);
return new ResponseEntity<>(ResponseUtil.responseConstruct(true, peg, "data updated"),
HttpStatus.CREATED);
} else {
return new ResponseEntity<>(ResponseUtil.responseConstruct(true, null, "no data"), HttpStatus.OK);
}
} else {
return new ResponseEntity<>(ResponseUtil.responseConstruct(false, req, "required data is missing"),
HttpStatus.OK);
}
}
@DeleteMapping("/{nip}")
public ResponseEntity<?> delete(@PathVariable("nip") String nip) {
if (nip == null) {
Map<String, String> req = new HashMap<String, String>();
req.put("nip", "nip is required");
return new ResponseEntity<>(ResponseUtil.responseConstruct(false, req, "required data is missing"),
HttpStatus.OK);
} else {
Pegawai pgw = service.getByNip(nip);
if (pgw != null) {
service.delete(nip);
return new ResponseEntity<>(ResponseUtil.responseConstruct(true, null, "data deleted"), HttpStatus.OK);
} else {
return new ResponseEntity<>(ResponseUtil.responseConstruct(false, null, "nip not found"),
HttpStatus.OK);
}
}
}
}
| true
|
c8a7fd47f1fde07cec287a1029cb0832480384ea
|
Java
|
aivazm/bell_catalog_of_organizations
|
/src/main/java/com/am/catalog/dao/OrganizationDaoImpl.java
|
UTF-8
| 4,329
| 2.5
| 2
|
[] |
no_license
|
package com.am.catalog.dao;
import com.am.catalog.exception.NoObjectException;
import com.am.catalog.exception.NotUniqueException;
import com.am.catalog.model.Organization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.CriteriaUpdate;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
/**
* {@inheritDoc}
*/
@Repository
public class OrganizationDaoImpl implements OrganizationDao {
private final EntityManager em;
@Autowired
public OrganizationDaoImpl(EntityManager em) {
this.em = em;
}
/**
* {@inheritDoc}
*/
@Override
public void saveOrganization(Organization org) {
checkUniqueInn(org);
em.persist(org);
}
/**
* {@inheritDoc}
*/
@Override
public int updateOrganization(Organization org, Long id) {
Organization o = em.find(Organization.class, id);
if (o != null) {
checkUniqueInn(org);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaUpdate<Organization> update = cb.createCriteriaUpdate(Organization.class);
Root<Organization> root = update.from(Organization.class);
update.set(root.get("name"), org.getName());
update.set(root.get("fullName"), org.getFullName());
update.set(root.get("inn"), org.getInn());
update.set(root.get("kpp"), org.getKpp());
update.set(root.get("address"), org.getAddress());
if (org.getPhone() != null) {
update.set(root.get("phone"), org.getPhone());
}
update.set(root.get("isActive"), org.getIsActive());
update.where(root.get("id").in(id));
Query query = em.createQuery(update);
return (query.executeUpdate());
} else {
throw new NoObjectException("Нет организации с id: " + id);
}
}
/**
* {@inheritDoc}
*/
@Override
public Organization getOrganizationById(Long id) {
Organization o = em.find(Organization.class, id);
if (o == null) {
throw new NoObjectException("Нет организации с id: " + id);
}
return o;
}
/**
* {@inheritDoc}
*/
@Override
public List<Organization> getOrganizationList(String name, String inn, Boolean isActive) {
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Organization> criteriaQuery = criteriaBuilder.createQuery(Organization.class);
Root<Organization> root = criteriaQuery.from(Organization.class);
List<Predicate> predicates = new ArrayList<>();
predicates.add(criteriaBuilder.equal(root.get("name"), name));
if (inn != null) {
predicates.add(criteriaBuilder.equal(root.get("inn"), inn));
}
if (isActive != null) {
predicates.add(criteriaBuilder.equal(root.get("isActive"), isActive));
}
criteriaQuery.select(root)
.where(predicates.toArray(new Predicate[]{}));
List<Organization> organizations = em.createQuery(criteriaQuery).getResultList();
if (organizations == null || organizations.isEmpty()) {
throw new NoObjectException("Организации, удовлетворяющие параметрам, отсутствуют");
}
return organizations;
}
private void checkUniqueInn(Organization org){
final String FIND_BY_INN_QUERY = "SELECT o FROM Organization o WHERE o.inn = :inn";
TypedQuery<Organization> query = em.createQuery(FIND_BY_INN_QUERY, Organization.class);
query.setParameter("inn", org.getInn());
List<Organization> orgList = query.getResultList();
if (orgList != null && !orgList.isEmpty()) {
throw new NotUniqueException("Организация с ИНН " + org.getInn() + " уже существует");
}
}
}
| true
|
1555606681a8257ff8d7cfd8a89514f3a2dc4ef5
|
Java
|
sudheesha93/SpringBoot-RESTapi
|
/SpringBoot-REST Api/src/main/java/com/example/springcode/walmartcode/entity/ActiveStatus.java
|
UTF-8
| 94
| 1.554688
| 2
|
[] |
no_license
|
package com.example.springcode.walmartcode.entity;
public enum ActiveStatus {
Yes,
No
}
| true
|
79daa4e73cec3c6dc7a489be486311d15462140e
|
Java
|
GabrielOliveira198/mapas
|
/src/main/java/br/com/ifgoiano/mapas/web/GastosBean.java
|
UTF-8
| 7,215
| 1.921875
| 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 br.com.ifgoiano.mapas.web;
import br.com.ifgoiano.mapas.gastos.Gastos;
import br.com.ifgoiano.mapas.gastos.GastosRN;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.NoneScoped;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.faces.view.ViewScoped;
import javax.swing.JOptionPane;
/**
*
* @author 1513 FOX
*/
@ManagedBean(name = "gastosBean")
//@SessionScoped
//@NoneScoped
//@RequestScoped //(padrão),
//@ViewScoped
@SessionScoped
//@ApplicationScoped
public class GastosBean {
private Gastos gastos = new Gastos();
private List<Gastos> lista;
private List<Gastos> listaestado;
private List<Gastos> gastosPorEstado; /*Gastos por estado*/
private List<String> listacidade;
private List<SelectItem> estados;
private List<SelectItem> cidades;
private ArrayList<String> empresas;
private String estado;
private String cidade;
private String empresa;
private boolean excluirmenores;
public boolean isExcluirmenores() {
return excluirmenores;
}
public void setExcluirmenores(boolean excluirmenores) {
this.excluirmenores = excluirmenores;
}
public String getEmpresa() {
return empresa;
}
public void setEmpresa(String empresa) {
this.empresa = empresa;
}
public ArrayList<String> getEmpresas() {
//empresas = new ArrayList<String> String String = String;
for(Gastos g: listaestado)
{
if(g.getEmpresa().equals(empresa))
empresas.add(g.getEmpresa());
}
return empresas;
}
public void setEmpresas(ArrayList<String> empresas) {
this.empresas = empresas;
}
public void setListaestado(List<Gastos> listaestado) {
this.listaestado = listaestado;
}
public void setListacidade(List<String> listacidade) {
this.listacidade = listacidade;
}
public void setEstados(List<SelectItem> estados) {
this.estados = estados;
}
public void setCidades(List<SelectItem> cidades) {
this.cidades = cidades;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public List<Gastos> getGastosPorEstado() {
return gastosPorEstado;
}
public void setGastosPorEstado(List<Gastos> gastosSelecionados) {
this.gastosPorEstado = gastosSelecionados;
}
public void listaGastosEstado()
{ listaestado = this.getLista();
gastosPorEstado=new ArrayList<>();
for(Gastos g: listaestado)
{
if(g.getEstado().equals(estado))
gastosPorEstado.add(g);
}
}
/*retorna a lista de cidades para o estado atual*/
public List<String> getListacidade(){
listacidade = new ArrayList<String>();
for(Gastos g:listaestado)
{
if (g.getEstado().equals(estado))
listacidade.add(g.getCidade());
}
return listacidade;
}
public List<Gastos> getListaestado(){
//Set<Gastos> estados = new HashSet<Gastos>(listaestado);
//listaestado = new ArrayList<Gastos>(estados);
return listaestado;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public List<SelectItem> getEstados () {
SelectItem item = null;
lista = new GastosRN().listar();
estados = new ArrayList<>();
if (lista != null) {
for (Gastos gasto : lista) {
item = new SelectItem(gasto, gasto.getEstado());
//item.setEscape(false);
estados.add(item);
}
}
return estados;
}
public List<SelectItem> getCidades() {
SelectItem item = null;
lista = new GastosRN().listar();
cidades = new ArrayList<SelectItem>();
if (lista != null) {
for (Gastos gasto : lista) {
item = new SelectItem(gasto, gasto.getCidade());
item.setEscape(false);
cidades.add(item);
}
}
return cidades;
}
public String novoE() {
this.gastos = new Gastos();
this.lista=new GastosRN().listar();
return "teste.xhtml";
}
public Gastos getGastos() {
return gastos;
}
public void setGastos(Gastos gastos) {
this.gastos = gastos;
}
public List<Gastos> getLista() {
return new GastosRN().listar();
}
public void setLista(List<Gastos> lista) {
this.lista = lista;
}
/*public int buscarLocal(){
GastosRN estado = new GastosRN();
gastos.setCodigo(codigo);
Gastos e = estado.buscarPorCodigo(this.gastos.getCodigo());
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage facesMessage = new FacesMessage(Integer.toString(e.getPopulacao()));
context.addMessage(null, facesMessage);
return e.getPopulacao();
}*/
public List<Gastos> buscarEstado(String est){
List<Gastos> e = new GastosRN().listar();
for(Gastos g:e)
{
if(est.equals(g.getEstado()))
this.listaestado.add(g);
}
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage facesMessage = new FacesMessage(e.toString());
context.addMessage(null, facesMessage);
return listaestado;
}
public float buscarGastosEstado(String codigo){
GastosRN gastorn = new GastosRN();
gastos = new Gastos();
float total = gastorn.buscaTotalEstado(codigo);
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage facesMessage = new FacesMessage(Integer.toString(30));//gastos.getPopulacao()));
context.addMessage(null, facesMessage);
return total;
}
public List<Gastos> listar()
{
GastosRN gastosrn = new GastosRN();
this.lista = gastosrn.listar();
return gastosrn.listar();
}
}
| true
|
e37f177eb681a3bd0d1ca18673207d846e21c394
|
Java
|
coderKingDH/BnsCalculator
|
/app/src/main/java/com/wangdh/bnscalculator/adapter/OrderAdapter.java
|
UTF-8
| 2,639
| 2.265625
| 2
|
[] |
no_license
|
package com.wangdh.bnscalculator.adapter;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import com.wangdh.bnscalculator.R;
import com.wangdh.bnscalculator.common.CommonAdapter;
import com.wangdh.bnscalculator.common.ViewHolder;
import com.wangdh.bnscalculator.dao.GoodsList;
import com.wangdh.bnscalculator.dao.Order;
import com.wangdh.bnscalculator.dao.UpgradeList;
import com.wangdh.bnscalculator.utils.TLog;
import java.util.List;
/**
* 作者: wdh <br>
* 内容摘要: <br>
* 创建时间: 2016/9/9 14:11<br>
* 描述: <br>
*/
public class OrderAdapter extends CommonAdapter<Order> {
public OrderAdapter(Context context, List<Order> datas, int layoutId) {
super(context, datas, layoutId);
}
private TextView view;
private TextView tv_item_text_money;
private Button btn_item_delete;
private RadioButton tbtn_item;
@Override
public void convert(ViewHolder holder, final Order goods) {
view = holder.getView(R.id.tv_item_text);
tbtn_item = holder.getView(R.id.tbtn_item);
tv_item_text_money = holder.getView(R.id.tv_item_text_money);
tbtn_item.setVisibility(View.VISIBLE);
TLog.e("notifyDataSetChanged01",goods.isCheck()+"");
tbtn_item.setChecked(goods.isCheck());
TLog.e("notifyDataSetChanged02",goods.isCheck()+"");
tv_item_text_money.setText("");
btn_item_delete = holder.getView(R.id.btn_item_delete);
view.setText(goods.getName());
btn_item_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Order.deleteById(goods.getId());
getDatas().remove(goods);
notifyDataSetChanged();
GoodsList.deleteByMainId(goods.getId());
UpgradeList.deleteByMainId(goods.getId());
}
});
tbtn_item.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
goods.setCheck(!goods.isCheck());
if(c!=null){
TLog.e("notifyDataSetChanged","11");
c.check(OrderAdapter.this.getDatas());
}
OrderAdapter.this.notifyDataSetChanged();
}
});
}
private Choice c;
public Choice getC() {
return c;
}
public void setC(Choice c) {
this.c = c;
}
public interface Choice{
void check(List<Order> order);
}
}
| true
|
a98b64c8da1a4b11ec9b519f45cd41f7adfe3860
|
Java
|
ulyn/eos
|
/eos-plugin/src/com/sunsharing/idea_plugin/configurator/ApplicationConfig.java
|
UTF-8
| 2,668
| 1.84375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* @(#) ApplicationConfig
* 版权声明 厦门畅享信息技术有限公司, 版权所有 违者必究
*
* <br> Copyright: Copyright (c) 2017
* <br> Company:厦门畅享信息技术有限公司
* <br> @author ningyp
* <br> 2017-12-15 16:30:16
* <br> @version 1.0
* ————————————————————————————————
* 修改记录
* 修改者:
* 修改时间:
* 修改原因:
* ————————————————————————————————
*/
package com.sunsharing.idea_plugin.configurator;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.Nullable;
/**
* <pre></pre>
* <br>----------------------------------------------------------------------
* <br> <b>功能描述:</b>
* <br>
* <br> 注意事项:
* <br>
* <br>
* <br>----------------------------------------------------------------------
* <br>
*/
@State(
name="EosPluginProjectConfig",
storages = {
@Storage("EosPluginProjectConfig.xml")}
)
public class ApplicationConfig implements PersistentStateComponent<ApplicationConfig> {
private String eosURL = "http://192.168.0.235:8100";
private String eosUserName;
private String eosUserPassword;
public String getEosURL() {
return eosURL;
}
public void setEosURL(String eosURL) {
this.eosURL = eosURL;
}
public String getEosUserName() {
return eosUserName;
}
public void setEosUserName(String eosUserName) {
this.eosUserName = eosUserName;
}
public String getEosUserPassword() {
return eosUserPassword;
}
public void setEosUserPassword(String eosUserPassword) {
this.eosUserPassword = eosUserPassword;
}
@Nullable
@Override
public ApplicationConfig getState() {
return this;
}
@Override
public void loadState(ApplicationConfig config) {
XmlSerializerUtil.copyBean(config, this);
}
@Nullable
public static ApplicationConfig getInstance() {
ApplicationConfig config = ServiceManager.getService(ApplicationConfig.class);
return config;
}
public boolean ready(){
return !StringUtils.isBlank(eosURL)
&& !StringUtils.isBlank(eosUserName)
&& !StringUtils.isBlank(eosUserName);
}
}
| true
|
ccbf5a19dafc493caaa41b6abfe18a1da18a307b
|
Java
|
HongYooCho/Category-Admin-Page
|
/src/main/java/com/tmoncorp/admin/repository/OriginalCategoryRepository.java
|
UTF-8
| 310
| 1.65625
| 2
|
[] |
no_license
|
package com.tmoncorp.admin.repository;
import com.tmoncorp.admin.domain.OriginalCategory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface OriginalCategoryRepository extends JpaRepository<OriginalCategory, Long> {
}
| true
|
0733a52560631d4cd67cb583577f11405a3ee7dd
|
Java
|
mdpopa2001/design-patterns
|
/src/main/java/com/sample/challenge/command/App.java
|
UTF-8
| 1,243
| 2.625
| 3
|
[] |
no_license
|
package com.sample.challenge.command;
import com.sample.challenge.command.commands.CancelCommand;
import com.sample.challenge.command.commands.GenerateReportCommand;
import com.sample.challenge.command.commands.SendEmailCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.UUID;
public class App {
private static final Logger logger = LoggerFactory.getLogger(App.class);
public static void main(String[] args) throws InterruptedException {
Invoker invoker = new Invoker();
Thread thread = new Thread(invoker);
thread.start();
/*
for(int i = 0 ; i < 10; i++)
{
FinancialDocument document = new FinancialDocument(UUID.randomUUID().toString());
int type = ((int)(Math.random() *10)) % 3;
Command command = type == 0? new GenerateReportCommand(document) :
(type == 1) ? new SendEmailCommand(document) :
new CancelCommand(document);
invoker.enqueue(command);
Thread.sleep((int)(100* Math.random() ));
}
*/
logger.info("Finished sending the work!");
invoker.stop();
// thread.join();
}
}
| true
|
d59ef02f5428e7d7a366632184f0defcc20416bf
|
Java
|
LucianQu/yantai
|
/app/src/main/java/com/jsmy/pingshan/activity/PlayVideoActivity.java
|
UTF-8
| 4,955
| 2.09375
| 2
|
[] |
no_license
|
package com.jsmy.pingshan.activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.jsmy.pingshan.R;
import com.jsmy.pingshan.util.MyLog;
import com.jsmy.pingshan.util.UtilsTools;
import com.universalvideoview.UniversalMediaController;
import com.universalvideoview.UniversalVideoView;
import org.json.JSONException;
import butterknife.BindView;
public class PlayVideoActivity extends BaseActivity implements UniversalVideoView.VideoViewCallback {
private static final String TAG = "PlayVideoActivity";
private static final String SEEK_POSITION_KEY = "SEEK_POSITION_KEY";
@BindView(R.id.videoView)
UniversalVideoView videoView;
@BindView(R.id.media_controller)
UniversalMediaController mediaController;
@BindView(R.id.video_layout)
FrameLayout videoLayout;
private String url;
private int mSeekPosition;
private int cachedHeight;
private boolean isFullscreen;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected int getContenView() {
return R.layout.activity_play_video;
}
@Override
protected void initView() {
videoView.setMediaController(mediaController);
url = getIntent().getStringExtra("url");
setVideoAreaSize();
}
@Override
protected void initData() {
if (mSeekPosition > 0) {
videoView.seekTo(mSeekPosition);
}
videoView.start();
}
@Override
public void onSuccess(String type, String check, String code, String result, String msg) throws JSONException {
}
@Override
public void onFailure(String type, String arg1) {
}
@Override
public void onScaleChange(boolean isFullscreen) {
this.isFullscreen = isFullscreen;
if (isFullscreen) {
ViewGroup.LayoutParams layoutParams = videoLayout.getLayoutParams();
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
videoLayout.setLayoutParams(layoutParams);
//设置全屏时,无关的View消失,以便为视频控件和控制器控件留出最大化的位置
// mBottomLayout.setVisibility(View.GONE);
} else {
ViewGroup.LayoutParams layoutParams = videoLayout.getLayoutParams();
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
layoutParams.height = this.cachedHeight;
videoLayout.setLayoutParams(layoutParams);
// mBottomLayout.setVisibility(View.VISIBLE);
}
}
@Override
public void onPause(MediaPlayer mediaPlayer) {
// 视频暂停
if (videoView != null && videoView.isPlaying()) {
mSeekPosition = videoView.getCurrentPosition();
MyLog.showLog(TAG, "onPause mSeekPosition=" + mSeekPosition);
videoView.pause();
}
}
@Override
public void onStart(MediaPlayer mediaPlayer) {
// 视频开始播放或恢复播放
}
@Override
public void onBufferingStart(MediaPlayer mediaPlayer) {
// 视频开始缓冲
}
@Override
public void onBufferingEnd(MediaPlayer mediaPlayer) {
// 视频结束缓冲
}
@Override
public void onBackPressed() {
if (this.isFullscreen) {
videoView.setFullscreen(false);
} else {
super.onBackPressed();
}
}
/**
* 置视频区域大小
*/
private void setVideoAreaSize() {
videoLayout.post(new Runnable() {
@Override
public void run() {
int width = videoLayout.getWidth();
cachedHeight = (int) (width * 405f / 720f);
// cachedHeight = (int) (width * 3f / 4f);
// cachedHeight = (int) (width * 9f / 16f);
ViewGroup.LayoutParams videoLayoutParams = videoLayout.getLayoutParams();
videoLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
videoLayoutParams.height = cachedHeight;
videoLayout.setLayoutParams(videoLayoutParams);
videoView.setVideoPath(url);
videoView.requestFocus();
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
MyLog.showLog(TAG, "onSaveInstanceState Position=" + videoView.getCurrentPosition());
outState.putInt(SEEK_POSITION_KEY, mSeekPosition);
}
@Override
protected void onRestoreInstanceState(Bundle outState) {
super.onRestoreInstanceState(outState);
mSeekPosition = outState.getInt(SEEK_POSITION_KEY);
MyLog.showLog(TAG, "onRestoreInstanceState Position=" + mSeekPosition);
}
}
| true
|
f59bb12f9c4e7f646f8c9ea15a2348e7254b4047
|
Java
|
zhuifengshen/AntJUnit
|
/test/com/test/junit/CalculatorTest.java
|
UTF-8
| 1,045
| 2.640625
| 3
|
[] |
no_license
|
package com.test.junit;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Created with IntelliJ IDEA.
* User: Devin Date: 2016/12/8 17:15
* More wonderful content please pay attention to -> http://zhangchuzhao.site
*/
public class CalculatorTest {
Calculator calculator;
@org.junit.Before
public void setUp() throws Exception {
calculator = new Calculator();
}
@org.junit.After
public void tearDown() throws Exception {
calculator = null;
}
@org.junit.Test
public void add() throws Exception {
assertThat(calculator.add(1,2), is(3));
}
@org.junit.Test
public void subtact() throws Exception {
assertThat(calculator.subtact(3, 1), is(2));
}
@org.junit.Test
public void multiply() throws Exception {
assertThat(calculator.multiply(2, 3), is(5));
}
@org.junit.Test//(expected = RuntimeException.class)
public void divide() throws Exception {
calculator.divide(3, 0);
}
}
| true
|
45edf5126d3b7fabf68cb011bb50807f7c676d27
|
Java
|
NiteenRC/core-java-program-service
|
/src/java8/collection/Average.java
|
UTF-8
| 517
| 3.953125
| 4
|
[] |
no_license
|
package java8.collection;
import java.util.Arrays;
/**
* Given a list of numbers,
* square them and
* filter the numbers which are greater 10000
* and then find average of them
*/
public class Average {
public static void main(String[] args) {
int[] intArr = {100, 24, 13, 44, 114, 200, 40, 112};
Arrays.stream(intArr).boxed()
.mapToInt(x -> x * x)
.filter(x -> x > 10000)
.average()
.ifPresent(System.out::println);
}
}
| true
|
b22291a05d92126fe730910ed374dbe58c997f75
|
Java
|
shukal94/mockEx
|
/src/main/java/com/solvd/util/Calculator.java
|
UTF-8
| 347
| 2.546875
| 3
|
[] |
no_license
|
package com.solvd.util;
import com.solvd.util.interfaces.Calculation;
import com.solvd.util.calculation.AddCalculation;
public class Calculator {
private Calculation addCalculation = new AddCalculation();
public Calculator() {
}
public Number add(Number a, Number b) {
return addCalculation.calculate(a, b);
}
}
| true
|
8d4afab3c3ed7ee81aa036ae35685d8152266716
|
Java
|
ajinkya5130/AndroidTest
|
/app/src/main/java/com/ajinkya/axxesscodingapp/models/SearchPojo.java
|
UTF-8
| 1,860
| 2.34375
| 2
|
[] |
no_license
|
package com.ajinkya.axxesscodingapp.models;
import java.util.List;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class SearchPojo implements Parcelable
{
@SerializedName("data")
@Expose
private List<Datum> data = null;
@SerializedName("status")
@Expose
private Integer status;
@SerializedName("success")
@Expose
private Boolean success;
public final static Creator<SearchPojo> CREATOR = new Creator<SearchPojo>() {
@SuppressWarnings({
"unchecked"
})
public SearchPojo createFromParcel(Parcel in) {
return new SearchPojo(in);
}
public SearchPojo[] newArray(int size) {
return (new SearchPojo[size]);
}
}
;
protected SearchPojo(Parcel in) {
in.readList(this.data, (Datum.class.getClassLoader()));
this.status = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.success = ((Boolean) in.readValue((Boolean.class.getClassLoader())));
}
public SearchPojo() {
}
public List<Datum> getData() {
return data;
}
public void setData(List<Datum> data) {
this.data = data;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeList(data);
dest.writeValue(status);
dest.writeValue(success);
}
public int describeContents() {
return 0;
}
}
| true
|
6a25624055ed187b45da4be4a9a459d7985acf7d
|
Java
|
lakshsharma07/XorProces
|
/src/main/java/com/xoriant/xorpay/validate/services/Payment_ISO_421.java
|
UTF-8
| 1,311
| 2.359375
| 2
|
[] |
no_license
|
package com.xoriant.xorpay.validate.services;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import com.xoriant.xorpay.entity.AggregatedPaymentEntity;
import com.xoriant.xorpay.excepions.CustomError;
import com.xoriant.xorpay.excepions.InvalidDataException;
@Service
public class Payment_ISO_421 {
CustomError c = null;
HttpStatus status = null;
String type = null;
String message = null;
String errorMessage = null;
String description = null;
public CustomError validateData(List<AggregatedPaymentEntity> tagsList) {
try {
tagsList.forEach(tags -> {
if (null != tags.getCdtrNm() && tags.getCdtrNm().length() > 20) {
status = HttpStatus.FORBIDDEN;
type = "Error";
message = "Failed Payment File Generation";
errorMessage = "CdtrNm : Creditor name error";
description = "Creditor name cannot be of more than 20 charector";
c = new CustomError(type, "" + status, message, errorMessage, description);
throw new InvalidDataException(c.getErrorMessage());
}
});
} catch (Exception e) {
return c;
}
status = HttpStatus.OK;
type = "Success";
message = "Payment File Generated";
c = new CustomError(type, "" + status, message, errorMessage, description);
return c;
}
}
| true
|
f6ed731479a27fdb998349ece66f6f36256f6ad5
|
Java
|
cxz5309/Spring_Basic_Study
|
/core/src/main/java/hello/core/AutoAppConfig.java
|
UTF-8
| 723
| 1.929688
| 2
|
[] |
no_license
|
package hello.core;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
@Configuration
@ComponentScan(
basePackages = "hello.core",
excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION,
classes = Configuration.class))
//컴포넌트 스캔을 사용하면 Configuration이 붙은 설정 정보도 자동으로 등록되기 때문에
//excludeFilters를 이용해서 설정 정보를 제외했다. 보통은 제외하지 않으나 예제코드를 남기기 위하여 함
public class AutoAppConfig {
}
| true
|
23e01c84281a6f19ff4aaca03870cc45e7026792
|
Java
|
dmsyudha/gamatechno
|
/app/src/main/java/com/gamatechno/gtapps/Login/LoginViewFragment.java
|
UTF-8
| 946
| 1.953125
| 2
|
[] |
no_license
|
package com.gamatechno.gtapps.Login;
import android.os.Bundle;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import com.gamatechno.gtapps.Login.LoginInterface;
import com.gamatechno.gtapps.Login.LoginPresenter;
import com.gamatechno.gtapps.R;
public class LoginViewFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login, container, false);
return view;
}
}
| true
|
9cbd56727dad32ecb2d1fd8d3d9c96a81451ce2d
|
Java
|
LP1991/DataProcess
|
/src/main/java/com/cvnchina/emsquartz/report/dataaccess/CreateTableMapper.java
|
UTF-8
| 422
| 1.96875
| 2
|
[] |
no_license
|
package com.cvnchina.emsquartz.report.dataaccess;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
/**
* Created by Primo on 2016/8/28.
* project: EMSQuartz
* package: com.cvnchina.emsquartz.report.dataaccess
* COPYRIGHT BY CVNCHINA 2016.
*/
@Repository
public interface CreateTableMapper extends BaseMapper{
void createTmpTable(@Param("tName") String tableName);
}
| true
|
50d76970f4ede76e3b9a29481a83cb77eeb6bc36
|
Java
|
MouseSun846/MyHelloWorld
|
/springboot_jpa/src/main/java/com/mousesun/Controller/controller.java
|
UTF-8
| 607
| 2
| 2
|
[] |
no_license
|
package com.mousesun.Controller;
import com.mousesun.domain.User;
import com.mousesun.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class controller {
@Autowired
private UserRepository userRepository;
@ResponseBody
@RequestMapping("/jpaQuery")
public List<User> queryList(){
return userRepository.findAll();
}
}
| true
|
ff9bd79650cf2382311a01c5f66b19bf560f658a
|
Java
|
toothsy/leetcodePractice
|
/all/src/strings/editDis.java
|
UTF-8
| 1,212
| 2.921875
| 3
|
[] |
no_license
|
import java.util.Arrays;
public class editDis {
public static int editDistance(String s, String t) {
if(s.equals(t))
return 0;
if(s.length()==0||t.length()==0)
return s.length()==0?t.length():s.length();
int tlen = t.length(); int slen = s.length();
int [][] dp = new int[slen+1][tlen+1];
for(int i = 0;i<=slen;i++){
for(int j =0;j<=tlen;j++){
if(i==0)
dp[0][j] = j;
else if( j==0)
dp[i][0] = i;
else if(s.charAt(i-1)!=t.charAt(j-1))
dp[i][j] = 1+ min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1]);
else
dp[i][j] = dp[i-1][j-1];
}
}
return dp[slen][tlen];
}
static int min(int a, int b, int c){
int m = Math.min(a,b);
int n = Math.min(b,c);
return Math.min(n,m);
}
public static void main(String[] args) {
System.out.println(editDistance("abc","abcd"));
// char[] al = "ABCD".toCharArray();
// System.out.println(Arrays.toString(al));
// System.out.println(al[3]-64);
}
}
| true
|
56d29840a297be68a03018ea36fba3a8107e19c8
|
Java
|
Team1058/Programming-2019
|
/src/main/java/org/pvcpirates/frc2019/commands/AutoAssistHatchLow.java
|
UTF-8
| 530
| 1.921875
| 2
|
[] |
no_license
|
package org.pvcpirates.frc2019.commands;
import org.pvcpirates.frc2019.util.ShuffleBoardManager;
public class AutoAssistHatchLow extends Command{
public AutoAssistHatchLow(){
commands.add(new VisionMPDriveToDonut());
commands.add(new DonutToHatchLowPlace());
}
@Override
public void init() {
super.init();
}
@Override
public void exec() {
super.exec();
}
@Override
public void finished() {
super.finished();
}
}
| true
|
682ab21c2a9d9bcf6bf60650413ea78b4e4de75b
|
Java
|
hotienvu/hudi-demos
|
/src/main/java/com/vho/hudisparkstreaming/HoodieDeltaStreamerDemo.java
|
UTF-8
| 4,572
| 2.15625
| 2
|
[] |
no_license
|
package com.vho.hudisparkstreaming;
import com.beust.jcommander.JCommander;
import org.apache.commons.io.FileUtils;
import org.apache.hudi.utilities.deltastreamer.HoodieDeltaStreamer;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.streaming.OutputMode;
import org.apache.spark.sql.streaming.StreamingQuery;
import org.apache.spark.sql.streaming.StreamingQueryException;
import org.apache.spark.sql.streaming.Trigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.apache.spark.sql.functions.expr;
import static org.apache.spark.sql.functions.lit;
public class HoodieDeltaStreamerDemo {
private static Logger LOG = LoggerFactory.getLogger(HoodieDeltaStreamerDemo.class);
private static final String inputPath = "/tmp/hoodie/timeline_test/input";
/**
* --target-base-path file:///tmp/hoodie/timeline_test/cow
* --target-table hoodie_cow
* --table-type COPY_ON_WRITE
* --props file:///.../dfs-source.properties
* --source-class org.apache.hudi.utilities.sources.ParquetDFSSource
* --source-ordering-field ts
* --op UPSERT
* --continuous
* --min-sync-interval-seconds 30
*/
public static void main(String[] args) throws IOException {
HoodieDeltaStreamer.Config cfg = getConfig(args);
// FileUtils.deleteDirectory(new File(inputPath));
// FileUtils.deleteDirectory(new File(cfg.targetBasePath));
Files.createDirectories(Paths.get(inputPath));
Files.createDirectories(Paths.get(cfg.targetBasePath));
SparkSession spark = SparkSession.builder()
.appName("hoodie timeline demo")
.master("local[2]")
.enableHiveSupport()
.config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
.getOrCreate();
ExecutorService es = Executors.newFixedThreadPool(2);
Future<?> read = es.submit(() -> generateInput(spark));
Future<?> write = es.submit(() -> streamToHoodieTable(cfg, spark));
try {
read.get();
write.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
} finally {
es.shutdown();
}
}
private static void streamToHoodieTable(HoodieDeltaStreamer.Config cfg, SparkSession spark) {
try {
HoodieDeltaStreamer deltaStreamer = new HoodieDeltaStreamer(cfg,
JavaSparkContext.fromSparkContext(spark.sparkContext()));
HoodieDeltaStreamer.DeltaSyncService deltaSyncService = deltaStreamer.getDeltaSyncService();
deltaSyncService.start((error) -> {
LOG.error("DeltaSync shutdown. Closing write client. Error: {}", error);
deltaSyncService.close();
return true;
});
} catch (IOException e) {
e.printStackTrace();
}
}
private static HoodieDeltaStreamer.Config getConfig(String[] args) {
HoodieDeltaStreamer.Config cfg = new HoodieDeltaStreamer.Config();
JCommander cmd = new JCommander(cfg, null, args);
if (cfg.help || args.length == 0) {
cmd.usage();
System.exit(1);
}
return cfg;
}
private static void generateInput(SparkSession spark) {
Dataset<Row> inputStream = spark.readStream().format("rate").option("rowsPerSecond", 10000).load()
.withColumn("year", lit(2020))
.withColumn("month", expr("cast(rand(0)*2 as int) + 1"))
.withColumn("day", expr("cast(rand(0)*3 as int) + 1"))
.withColumn("ts", expr("current_timestamp()"))
.withColumn("dt", expr("concat(year, '-', month, '-', day)"))
.withColumn("id", expr("cast(rand(0) * 10000 as int) + 1"))
.withColumn("state", expr("if(cast(rand(0)*2 as int) == 0, 'Open', 'Closed') as state"));
StreamingQuery stream = inputStream.writeStream()
.format("parquet")
.option("checkpointLocation", inputPath + "/.checkpoint")
.outputMode(OutputMode.Append())
.trigger(Trigger.ProcessingTime("60 seconds"))
// DeltaStreamer currently don't support directory partitioning
.partitionBy("dt")
.start(inputPath);
try {
stream.awaitTermination();
} catch (StreamingQueryException e) {
e.printStackTrace();
stream.stop();
}
}
}
| true
|
3c3615a78b3040d3712b0c2c99b43669bc7c934b
|
Java
|
Swap1008/java-pract-1
|
/CollectionsDemo/src/setInterface/HashSetDemo.java
|
UTF-8
| 360
| 2.671875
| 3
|
[] |
no_license
|
package setInterface;
import java.util.HashSet;
public class HashSetDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet hs=new HashSet();
hs.add(25);
hs.add(5);
hs.add(51);
hs.add(34);
hs.add(102);
hs.add(58);
hs.add(25);
System.out.println(hs);
hs.remove(5);
System.out.println(hs);
}
}
| true
|
1127c876829b3bf36a5c35e03f8021e37127ce0b
|
Java
|
pdhssp/phgis
|
/src/java/gov/sp/health/data/DurationType.java
|
UTF-8
| 287
| 1.898438
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package gov.sp.health.data;
/**
*
*
*/
public enum DurationType {
Daily,
Weekly,
Fourtnight,
Monthly,
Quarterly,
Annually,
Variable,
}
| true
|
faf38c22f70f80e1584648182b84f584277ad776
|
Java
|
kongxiangyue/micro_android_base
|
/original/ch06/BaseAdapter/src/com/tarena/chapter6/baseadapter/MusicAdapter.java
|
GB18030
| 2,528
| 2.78125
| 3
|
[] |
no_license
|
package com.tarena.chapter6.baseadapter;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MusicAdapter extends BaseAdapter {
ArrayList<Music> musiclist;
LayoutInflater inflater;
/**
* @param context
* Ķ
* @param musiclist
* б
*/
public MusicAdapter(Context context, ArrayList<Music> musiclist) {
this.inflater = LayoutInflater.from(context);
this.musiclist = musiclist;
}
// ÷ķֵListView ҲζžgetViewĻص
@Override
public int getCount() {
// TODO Auto-generated method stub
return musiclist.size();
}
// һò Ǵ˴øȷķֵ listview.getItemAtPosition(position)
// Լadapter.getItem(position)ʱõ
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return musiclist.get(position);
}
// һò Ǵ˴øȷķֵ listview.getItemIdAtPosition(position)
// Լadapter.getItemId(position)ʱõ
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return musiclist.get(position).getId();
}
@Override
/*
* int position Ӧλ 0ʼ View convertView Ӧһitem ViewGroup parent
* itemĸListView return convertView ֵ ʾһitem
*/
public View getView(int position, View convertView, ViewGroup parent) {
// һļ
convertView = inflater.inflate(R.layout.item, null);
ImageView img = (ImageView) convertView.findViewById(R.id.img);
TextView musicName = (TextView) convertView
.findViewById(R.id.musicName);
TextView musicAlbum = (TextView) convertView
.findViewById(R.id.albumName);
TextView musicSinger = (TextView) convertView.findViewById(R.id.singer);
TextView musicDuration = (TextView) convertView
.findViewById(R.id.duration);
Music music = musiclist.get(position);
img.setImageResource(music.getMusicImg());
musicName.setText(music.getMusicName());
musicAlbum.setText(music.getMusicAlbum());
musicSinger.setText(music.getMusicSinger());
musicDuration.setText(music.getDuration());
return convertView;
}
}
| true
|
4b0d8c0e2263a914be57f0d3f31b31171c139ee8
|
Java
|
ZineddineBtc/BlindChat
|
/app/src/main/java/com/example/blindchat/adapter/ChatsAdapter.java
|
UTF-8
| 8,991
| 2.03125
| 2
|
[] |
no_license
|
package com.example.blindchat.adapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.blindchat.R;
import com.example.blindchat.StaticClass;
import com.example.blindchat.activity.core.MessagesActivity;
import com.example.blindchat.model.Chat;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.storage.FirebaseStorage;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class ChatsAdapter extends RecyclerView.Adapter<ChatsAdapter.ViewHolder> {
private List<Chat> chatsList;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
private Context context;
public ChatsAdapter(Context context, List<Chat> data) {
this.mInflater = LayoutInflater.from(context);
this.chatsList = data;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.chat_row, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Chat chat = chatsList.get(position);
getInterlocutorID(holder, chat);
setInterlocutorPhoto(holder, chat);
setInterlocutorName(holder, chat);
setLastMessageContent(holder, chat);
setLastMessageTime(holder, chat);
checkIfUnread(holder, chat);
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
context.startActivity(new Intent(context, MessagesActivity.class)
.putExtra(StaticClass.PROFILE_ID, holder.interlocutorID)
.putExtra(StaticClass.FROM, StaticClass.CHATS_FRAGMENT));
}
});
}
private void getInterlocutorID(ViewHolder holder, Chat chat){
for(String id: chat.getInterlocutors()){
if(!id.equals(holder.email)){
holder.interlocutorID = id;
}
}
}
private void setInterlocutorPhoto(final ViewHolder holder, Chat chat){
if(chat.getReacher().equals(holder.email)) {
final long ONE_MEGABYTE = 1024 * 1024;
holder.storage.getReference(holder.interlocutorID + StaticClass.PROFILE_PHOTO)
.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
@Override
public void onSuccess(byte[] bytes) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
holder.interlocutorIV.setImageBitmap(Bitmap.createScaledBitmap(bmp, holder.interlocutorIV.getWidth(),
holder.interlocutorIV.getHeight(), false));
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
Toast.makeText(context, "Failed at getting interlocutor photo", Toast.LENGTH_LONG).show();
}
});
}
}
private void setInterlocutorName(final ViewHolder holder, Chat chat){
if(chat.getReacher().equals(holder.email)) {
holder.database.collection("users")
.document(holder.interlocutorID)
.get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot document) {
if (document.exists()) {
holder.interlocutorTV.setText(String.valueOf(document.get("name")));
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(context, "Failed at getting interlocutor name", Toast.LENGTH_LONG).show();
}
});
}else{
holder.interlocutorTV.setText(chat.getReacherName());
}
}
private void setLastMessageContent(ViewHolder holder, Chat chat){
StringBuilder message = new StringBuilder();
if(chat.getSender().equals(holder.email)){
message.append("You: ");
}
if(chat.getLastMessageContent().length()>20){
message.append(chat.getLastMessageContent().substring(0, 20))
.append("...");
}else{
message.append(chat.getLastMessageContent());
}
holder.lastMessageContentTV.setText(message);
}
private void setLastMessageTime(ViewHolder holder, Chat chat){
long messageTime = chat.getLastMessageTime();
long currentTime = System.currentTimeMillis();
long difference = currentTime - messageTime;
String time;
if(difference < 60000){ // less than a minute
time = "now";
}else if(difference < 3600000){ // less than an hour
long minutes = difference/60000;
time = minutes+" Min";
}else if(difference < 86400000){ // less than a day
long hours = difference/3600000;
time = hours+" H";
}else{
Calendar c = Calendar.getInstance();
c.setTimeInMillis(messageTime);
int messageYear = c.get(Calendar.YEAR);
c.setTimeInMillis(currentTime);
int currentYear = c.get(Calendar.YEAR);
if(messageYear == currentYear){
time = new SimpleDateFormat("dd MMM").format(new Date(messageTime));
}else{
time = new SimpleDateFormat("dd MMM yyyy").format(new Date(messageTime));
}
}
holder.lastMessageTimeTV.setText(time);
}
private void checkIfUnread(ViewHolder holder, Chat chat){
if(!chat.isRead()) {
holder.interlocutorTV.setTypeface(holder.interlocutorTV.getTypeface(), Typeface.BOLD);
holder.lastMessageContentTV.setTypeface(holder.lastMessageContentTV.getTypeface(), Typeface.BOLD);
holder.lastMessageTimeTV.setTypeface(holder.lastMessageTimeTV.getTypeface(), Typeface.BOLD);
}
}
@Override
public int getItemCount() {
return chatsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView interlocutorIV;
private TextView interlocutorTV, lastMessageContentTV, lastMessageTimeTV;
private LinearLayout parentLayout;
private View itemView;
private FirebaseStorage storage;
private FirebaseFirestore database;
private String email, interlocutorID;
ViewHolder(final View itemView) {
super(itemView);
this.itemView = itemView;
getInstances();
findViewsByIds();
itemView.setOnClickListener(this);
}
void getInstances(){
database = FirebaseFirestore.getInstance();
storage = FirebaseStorage.getInstance();
email = context.getSharedPreferences(StaticClass.SHARED_PREFERENCES, Context.MODE_PRIVATE).getString(StaticClass.EMAIL, "email");
}
void findViewsByIds(){
interlocutorIV = itemView.findViewById(R.id.interlocutorIV);
interlocutorTV = itemView.findViewById(R.id.interlocutorTV);
lastMessageContentTV = itemView.findViewById(R.id.lastMessageContentTV);
lastMessageTimeTV = itemView.findViewById(R.id.lastMessageTimeTV);
parentLayout = itemView.findViewById(R.id.parentLayout);
}
@Override
public void onClick(View view) {
if (mClickListener != null)
mClickListener.onItemClick(view, getAdapterPosition());
}
}
Chat getItem(int id) {
return chatsList.get(id);
}
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
| true
|
96dea48ef9934853187014ab7c7e0d5cad5a9dfa
|
Java
|
agee5/Java
|
/168-Lab7/NumberCategory.java
|
UTF-8
| 902
| 3.65625
| 4
|
[] |
no_license
|
/*
*File name: CompareNumber.java
*
*Programmer: Aaron Gee
*ULID: agee1
*
*Date: Feb 25, 2020
*
*Class: IT 168
*Lecture Section: 01
*Lecture Instructor: Dr. Fang
*Lab Section: 02
*Lab Instructor: Allan Buckley
*/
package edu.ilstu;
import java.util.Scanner;
/**
* Determine is a number is positive, negative, or zero
*
*@author Aaron Gee
*
*/
public class NumberCategory
{
/**
* @param args
*/
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int myNumber = 0;
System.out.print("Please enter any negative or positive number: ");
myNumber = input.nextInt();
if (myNumber > 0)
{
System.out.println("\nThe number is positive.");
}
else if (myNumber < 0)
{
System.out.println("\nThe number is negative.");
}
else
{
System.out.println("\nThe number is 0.");
}
}
}
| true
|
cc52953b95382c6d2adeb29b94acffc17ba9e4c4
|
Java
|
Xin98/LeetCodePractice
|
/src/cn/codexin/questions/Q0498_Diagonal_Traverse.java
|
UTF-8
| 966
| 3.109375
| 3
|
[] |
no_license
|
package cn.codexin.questions;
/**
* Created by xinGao 2020/4/8
*/
public class Q0498_Diagonal_Traverse {
public int[] findDiagonalOrder(int[][] matrix) {
int m = matrix.length;
if(m == 0) return new int[0];
int n = matrix[0].length;
int[] ans = new int[m * n];
int idx = 0;
for (int k = 0; k < m + n - 1; k++) {
//up表示从左下到右上
boolean up = (k & 1) == 0;
//确认第k个对角线开始的坐标
int i = up ? (k < m ? k : m - 1) : (k < n ? 0 : k - n + 1);
int j = up ? (k < m ? 0 : k - m + 1) : (k < n ? k : n - 1);
if(up){
while(i >= 0 && j < n){
ans[idx++] = matrix[i--][j++];
}
}
else{
while(i < m && j >= 0){
ans[idx++] = matrix[i++][j--];
}
}
}
return ans;
}
}
| true
|
48aa9140e13246afdef292ab1c15740c1aec7538
|
Java
|
Rlong1218/java-practice-day-6
|
/tests/PrefixAgainTest.java
|
UTF-8
| 518
| 2.28125
| 2
|
[] |
no_license
|
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class PrefixAgainTest {
@Test
void prefixAgain() {
assertTrue(PrefixAgain.prefixAgain("prefixpre", 3));
assertTrue(PrefixAgain.prefixAgain("SuperManIsSuper", 5));
assertTrue(PrefixAgain.prefixAgain("pip", 1));
assertFalse(PrefixAgain.prefixAgain("prefixpr", 3));
assertFalse(PrefixAgain.prefixAgain("nope", 2));
assertFalse(PrefixAgain.prefixAgain("closeClose", 5));
}
}
| true
|
552ca3baf4c4615d84a145d05b836d64e5cd8332
|
Java
|
panachainy/SecurityDog
|
/src/securitydog/SecurityDog.java
|
UTF-8
| 1,568
| 3.390625
| 3
|
[] |
no_license
|
package securitydog;
public class SecurityDog extends Thread {
public static void main(String[] args) {
SecurityDog t1 = new SecurityDog();
SecurityDog t2 = new SecurityDog();
SecurityDog t3 = new SecurityDog();
SecurityDog t4 = new SecurityDog();
t1.setName("Owner");
t2.setName("Dog");
t3.setName("Police");
t4.setName("Thife");
/*
t1.setPriority(10);
t2.setPriority(1);
*/
t1.start();
t2.start();
t3.start();
t4.start();
}
public void run() {
try {
while (true) {
if (Thread.currentThread().getName().equals("Owner")) {
Thread.sleep(16000); //ตื่น
Thread.sleep(8000);
} else if (Thread.currentThread().getName().equals("Dog")) {
Thread.sleep(8000); //ตื่น
Thread.sleep(16000);
} else if (Thread.currentThread().getName().equals("Police")) {
Thread.sleep(24000); //ตื่น
} else if (Thread.currentThread().getName().equals("Thife")) {
for (int i = 200; i < 300; i++) {
Thread.sleep(16000);
Thread.sleep(8000); //ตื่น
}
}
}
} catch (InterruptedException ieo) {
System.out.println(ieo);
}
}
}
| true
|
894a83450bc5b0b25b969a884c5899daa5e8a657
|
Java
|
cry1900/macula-framework
|
/macula-boot/macula-boot-web/src/main/java/org/maculaframework/boot/web/mvc/annotation/TokenValidation.java
|
UTF-8
| 1,314
| 1.875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2004-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maculaframework.boot.web.mvc.annotation;
import org.springframework.web.context.request.NativeWebRequest;
/**
* <p> <b>TokenValidation</b> 是表单重复提交校验支持. </p>
*
* @since 2012-2-7
* @author Wilson Luo
* @version $Id: TokenValidation.java 3852 2012-12-14 08:15:36Z wilson $
*/
public interface TokenValidation {
/** 创建一个Token */
String createTokenId(NativeWebRequest webRequest);
/** 创建如果需要用户反馈的信息值 */
String createResponse(String tokenId);
/** 校验Token,同时销毁 */
boolean validate(FormBean formBeanAnnotation, NativeWebRequest webRequest);
/** 同时销毁 */
boolean destoryToken(String tokenId);
}
| true
|
002ca4e225c66c42c9340dc4415649dc30c4b2eb
|
Java
|
heboot/Candypie
|
/library/MUtils/src/main/java/com/heboot/bean/user/SetPriceVideoChatConfigBean.java
|
UTF-8
| 1,179
| 1.835938
| 2
|
[] |
no_license
|
package com.heboot.bean.user;
import java.util.List;
public class SetPriceVideoChatConfigBean {
private String title;
private String price;
private List<TagsChildBean> select_items;
private String tip;
private String icon;
private List<TagsChildBean> items;
public List<TagsChildBean> getSelect_items() {
return select_items;
}
public void setSelect_items(List<TagsChildBean> select_items) {
this.select_items = select_items;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getTip() {
return tip;
}
public void setTip(String tip) {
this.tip = tip;
}
public List<TagsChildBean> getItems() {
return items;
}
public void setItems(List<TagsChildBean> items) {
this.items = items;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
| true
|
8c4804ce67a4974c7aff2aab28f701d1720ec9bc
|
Java
|
abbhinay/java-files
|
/4-6/string/StringDemo2.java
|
UTF-8
| 498
| 3.046875
| 3
|
[] |
no_license
|
class StringDemo2
{
public static void main(String[] arr)
{
int a=10;
byte b=3;
short c=12;
long d=45l;
char e='Q';
float f=12.3f;
double g=2.5;
Integer i=new Integer(a);
//show(String.valueOf(a));
show(i.toString());
show(String.valueOf(b));
show(String.valueOf(c));
show(String.valueOf(d));
show(String.valueOf(e));
show(String.valueOf(f));
show(String.valueOf(g));
}
public static void show(String s)
{
System.out.println(s);
}
}
| true
|
1e5688f691c379ed50ed7e2b73311eb72c8b0b14
|
Java
|
moutainhigh/gomeo2o
|
/venus-trade-api/tags/release-1.0.0/src/main/java/cn/com/gome/trade/dto/io/product/request/AreaProductAvailableRequestDto.java
|
UTF-8
| 1,339
| 2.109375
| 2
|
[] |
no_license
|
/**
* @类名: AreaProductAvailableRequestDto.java
* @作者: libin-ds9
* @创建时间 2015年5月13日 下午6:03:19
*/
package cn.com.gome.trade.dto.io.product.request;
import java.io.Serializable;
import java.util.List;
/**
* @描述:
* @作者 libin-ds9
* @创建时间 2015年5月13日 下午6:03:19
*/
public class AreaProductAvailableRequestDto implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 销售渠道代码
*/
private String buid = "8270"; //销售渠道代码 可空N 默认 8270
/**
* 配送区域
*/
private String daId;
private List<AreaProductAvailableDetailDto> details;
/**
* @return the buid
*/
public String getBuid() {
return buid;
}
/**
* @param buid
* the buid to set
*/
public void setBuid(String buid) {
this.buid = buid;
}
/**
* @return the daId
*/
public String getDaId() {
return daId;
}
/**
* @param daId
* the daId to set
*/
public void setDaId(String daId) {
this.daId = daId;
}
/**
* @return the details
*/
public List<AreaProductAvailableDetailDto> getDetails() {
return details;
}
/**
* @param details
* the details to set
*/
public void setDetails(List<AreaProductAvailableDetailDto> details) {
this.details = details;
}
}
| true
|
c5050539d7881c894f7e7c87f7328f377b9323b8
|
Java
|
XiaoqingWang/esper-2015
|
/src/main/java/com/doctor/esper/subscriber/HttpLogSubscriber.java
|
UTF-8
| 1,046
| 2.609375
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.doctor.esper.subscriber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.doctor.esper.event.HttpLog;
/**
* @see http://www.espertech.com/esper/release-5.2.0/esper-reference/html_single/index.html#api-admin-subscriber
*
* The engine can deliver results to your subscriber in two ways:
*
* 1.Each evert in the insert stream results in a method invocation, and each event in the remove stream results in further method invocations. This is termed row-by-row delivery.
*
* 2. A single method invocation that delivers all rows of the insert and remove stream. This is termed multi-row delivery.
*
*
* @author doctor
*
* @time 2015年6月11日 下午3:51:08
*/
public class HttpLogSubscriber {
private static final Logger log = LoggerFactory.getLogger(HttpLogSubscriber.class);
/**
* Row-By-Row Delivery
*
* @param httpLog
* @param count
*/
public void update(HttpLog httpLog, long count) {
log.warn("报警阈值httplog{}超过访问次数{}", httpLog, count);
}
}
| true
|
8f6bde3b823d641f688ddef97c48c984eacb21e6
|
Java
|
NavpreetKaur1/Android_Apps
|
/Quiz SQLite/app/src/main/java/com/sample/multiplechoicequiz/QuestionBank2.java
|
UTF-8
| 1,508
| 2.75
| 3
|
[] |
no_license
|
package com.sample.multiplechoicequiz;
import java.util.*;
import android.content.Context;
/**
* Created by xcode on 2018-04-08.
*/
public class QuestionBank2 {
List<QuestionBank> list = new ArrayList<>();
DataBaseHelper dataBaseHelper;
public int getLength() {return list.size();}
public String getQuestion(int a) {return list.get(a).getQuestion();}
public String getChoice(int index, int num) {return list.get(index).getChoice(num-1);}
public String getCorrectAnswer(int a) {return list.get(a).getAnswer();}
public void initQuestions(Context context) {
dataBaseHelper = new DataBaseHelper(context);
list = dataBaseHelper.getAllQuestions();
if(list.isEmpty()) {
dataBaseHelper.addInitialQuestion(new QuestionBank("1. When did Google acquire Android? ", new String[] {"2001", "2003", "2004", "2005"}, "2005"));
dataBaseHelper.addInitialQuestion(new QuestionBank("2. What is the name of build toolkit for Android Studio?", new String[] {"JVM", "Gradle", "Dalvik", "HAXM"}, "Gradel"));
dataBaseHelper.addInitialQuestion(new QuestionBank("3. What widget can replace any use of radio buttons?", new String[] {"Toggle", "Spinner", "Switch", "CheckBox"}, "Spinner"));
dataBaseHelper.addInitialQuestion(new QuestionBank("4. What is the most recent Android OS ?", new String[] {"Oreo", "Nougat", "Marshmallow", "Octopus"}, "Oreo"));
list = dataBaseHelper.getAllQuestions();
}
}
}
| true
|
8eb40ab2b0b85ec4e12491aba74d23f4944dcb93
|
Java
|
ktmswzw/ng2-server
|
/src/main/java/com/xecoder/core/mapper/PermissionMapper.java
|
UTF-8
| 286
| 1.539063
| 2
|
[] |
no_license
|
package com.xecoder.core.mapper;
import com.xecoder.config.MybatisMapper;
import com.xecoder.core.entity.Permission;
import org.apache.ibatis.annotations.Mapper;
/**
* Created by vincent on 1/8/17.
*/
@Mapper
public interface PermissionMapper extends MybatisMapper<Permission> {
}
| true
|
e2698d4fe19a8dcbcc4f23d2d386334ae10b33bc
|
Java
|
Fighting2019/spring-study
|
/src/main/java/com/atzyy/service/AspectService.java
|
UTF-8
| 713
| 2.4375
| 2
|
[] |
no_license
|
package com.atzyy.service;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//@Advice
public class AspectService implements InvocationHandler {
public AspectService(Object obj) {
this.obj = obj;
}
@Autowired
private Object obj;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("动态代理执行");
Object invoke = method.invoke(obj, args);
System.out.println("代理结束");
return invoke;
}
}
| true
|
37d599dbe87e711f52b1555a0cc7a52c548776de
|
Java
|
ektanandwani/cube-materialization
|
/src/main/java/Pojo/Specs/Spec.java
|
UTF-8
| 1,323
| 2.515625
| 3
|
[] |
no_license
|
package Pojo.Specs;
import Pojo.Schema.Attribute;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import java.util.ArrayList;
public class Spec {
private String name;
private String customName;
private ArrayList<Attribute> attribute;
public Spec() {
attribute = new ArrayList<Attribute>();
}
@XmlAttribute
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlAttribute
public String getCustomName() { return customName; }
public void setCustomName(String customName) { this.customName = customName; }
@XmlElementWrapper(name = "attributeList")
@XmlElement
public ArrayList<Attribute> getAttribute() {
return attribute;
}
public void setAttribute(ArrayList<Attribute> attribute) {
this.attribute = attribute;
}
public void addAttribute(Attribute attribute)
{
this.attribute.add((attribute));
}
@Override
public String toString() {
return "Spec{" +
"name='" + name + '\'' +
", customName='" + customName + '\'' +
", attribute=" + attribute +
'}';
}
}
| true
|
03c2325b61f46c64731c6844c98df173cc1a3070
|
Java
|
cbdog94/Leetcode
|
/src/Q1169.java
|
UTF-8
| 1,598
| 3.03125
| 3
|
[] |
no_license
|
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Q1169 {
public List<String> invalidTransactions(String[] transactions) {
Map<String, List<Tran>> map = new HashMap<>();
for (String t : transactions) {
String[] sps = t.split(",");
if (!map.containsKey(sps[0])) {
map.put(sps[0], new ArrayList<>());
}
map.get(sps[0]).add(new Tran(sps[0], Integer.parseInt(sps[1]), Integer.parseInt(sps[2]), sps[3]));
}
List<String> res = new ArrayList<>();
for (List<Tran> ts : map.values()) {
for (int i = 0; i < ts.size(); i++) {
if (ts.get(i).amount > 1000) {
res.add(ts.get(i).toString());
continue;
}
for (int j = 0; j < ts.size(); j++) {
if (!ts.get(j).city.equals(ts.get(i).city) && Math.abs(ts.get(j).time - ts.get(i).time) <= 60) {
res.add(ts.get(i).toString());
break;
}
}
}
}
return res;
}
class Tran {
String name, city;
int time, amount;
Tran(String name, int time, int amount, String city) {
this.name = name;
this.time = time;
this.amount = amount;
this.city = city;
}
@Override
public String toString() {
return name + "," + time + "," + amount + "," + city;
}
}
}
| true
|
daa937dcbfc24dd919a1fe10344eec8d7f9cd00d
|
Java
|
DongGyu96/AndroidGameProgramming
|
/ListSample/app/src/main/java/kr/ac/kpu/game/andgp/donggyu/listsample/MainActivity.java
|
UTF-8
| 5,412
| 2.34375
| 2
|
[] |
no_license
|
package kr.ac.kpu.game.andgp.donggyu.listsample;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import kr.ac.kpu.game.andgp.donggyu.listsample.data.HighscoreItem;
import kr.ac.kpu.game.andgp.donggyu.listsample.data.Serializer;
public class MainActivity extends AppCompatActivity {
private ListView listView;
private static final String TAG = MainActivity.class.getSimpleName();
private ArrayList<HighscoreItem> scores = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scores = Serializer.Load(this);
listView = findViewById(R.id.listView);
listView.setAdapter(adapter);
}
private ListAdapter adapter = new BaseAdapter() {
@Override
public int getCount() {
return scores.size();
}
@Override
public Object getItem(int position) {
TextView tv = new TextView(MainActivity.this);
tv.setText("The Item " + position);
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d(TAG, "Pos:" + position + " convertView:" + convertView);
View view = convertView;
if(view == null) {
Log.d(TAG, "Loading from XML for:" + position);
LayoutInflater inflater = getLayoutInflater();
view = inflater.inflate(R.layout.score_item, null);
}
TextView tv = view.findViewById(R.id.scoreItemTextView);
ImageView iv = view.findViewById(R.id.scoreItemImageView);
// 인덱스는 포지션으로부터 얻는다
HighscoreItem s = scores.get(position);
tv.setText((s.date.getMonth() + 1) + "월 " + s.date.getDate() + "일 " + s.date.getHours() + ":" + s.date.getMinutes() + ":" + s.date.getSeconds() + "\n" +
"User : " + s.name + " Score : " + s.score
);
tv.setBackgroundColor(Color.LTGRAY);
if(s.score < 50000)
{
iv.setImageResource(R.mipmap.tier_01);
iv.setBackgroundColor(Color.GRAY);
}
else if(s.score < 100000)
{
iv.setImageResource(R.mipmap.tier_02);
iv.setBackgroundColor(Color.GRAY);
}
else if(s.score < 200000)
{
iv.setImageResource(R.mipmap.tier_03);
iv.setBackgroundColor(Color.GRAY);
}
else if(s.score < 300000)
{
iv.setImageResource(R.mipmap.tier_04);
iv.setBackgroundColor(Color.GRAY);
}
else if(s.score < 400000)
{
iv.setImageResource(R.mipmap.tier_05);
iv.setBackgroundColor(Color.GRAY);
}
else if(s.score < 500000)
{
iv.setImageResource(R.mipmap.tier_06);
iv.setBackgroundColor(Color.GRAY);
}
else if(s.score < 600000)
{
iv.setImageResource(R.mipmap.tier_07);
iv.setBackgroundColor(Color.GRAY);
}
else if(s.score < 700000)
{
iv.setImageResource(R.mipmap.tier_08);
iv.setBackgroundColor(Color.GRAY);
}
else
{
iv.setImageResource(R.mipmap.tier_09);
iv.setBackgroundColor(Color.GRAY);
}
return view;
}
};
public void onBtnAdd(View view) {
final EditText et = new EditText(this);
new AlertDialog.Builder(this)
.setTitle(R.string.highscore)
.setMessage(R.string.add_highscore_message)
.setView(et)
.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String name = et.getText().toString();
int score = new Random().nextInt(1000000);
addHighscore(name, score);
}
})
.setNegativeButton(R.string.cancel, null)
.create()
.show();
Serializer.Save(this, scores);
}
private void addHighscore(String name, int score) {
scores.add(new HighscoreItem(name, new Date(), score));
// 갱신됬음을 어댑터에게 알릴 필요가 있음
// adapter.notify();
}
public void onBtnDelete(View view) {
}
}
| true
|
ef5fb96553e6cb1cd6305883d98dda5e8e63c727
|
Java
|
tnqlsdl1300/Logitech
|
/src/common/controller/CompanyInfoController.java
|
UTF-8
| 381
| 1.828125
| 2
|
[] |
no_license
|
package common.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CompanyInfoController extends AbstractController {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
super.setRedirect(false);
super.setViewPage("/WEB-INF/companyInfo.jsp");
}
}
| true
|
43601f63a2507da697b5d1e320a24db7a04e587d
|
Java
|
dina-03/dina-03.basis-Java
|
/src/SelfWork/GF.java
|
UTF-8
| 1,926
| 3.15625
| 3
|
[] |
no_license
|
package SelfWork;
public class GF {
public static void main(String[] args) {
/*double pi = 3.14;
String myPI = String.valueOf(pi);
System.out.println(myPI);
String number = "10";
System.out.println(number);
int result = Integer.parseInt(number);
System.out.println(result);
String name = "Андрей";
char myChar = name.charAt(2); //д
System.out.println(myChar);*/
/*String s1 = "Das is String";
String s2 = "Das is String";
String s3 = "Das ist auch String";
int result = s1.compareTo(s2);
System.out.println(result);
result = s2.compareTo(s3);
System.out.println(result);
result = s3.compareTo(s1);
System.out.println(result);
String str = "Hello";
str = str.concat(" world!");
// System.out.println(str);
str = str.concat(" my dear Man!");
System.out.println(str);*/
int i = 0;
/* do {
System.out.println("i = " + i);
i += 10;
}
while (i < 20);
System.out.println(i);*/
while (true) {
System.out.print(i + ", ");
i++;
if (i > 20)
break;
}
System.out.println();
StringBuffer sb = new StringBuffer("Cat");
sb.setCharAt(1, 'o');
System.out.println(sb);
// tvInfo.setText(sb.toString());
sb.insert(3, " love");
System.out.println(sb);
//sb.delete(0, 4); // -> love
sb.deleteCharAt(2); // -> Co love
System.out.println(sb);
StringBuilder builder = new StringBuilder();
builder.append('c');
builder.append("orona");
System.out.println(builder);
builder.append(" virus");
String completedString = builder.toString();
System.out.println(completedString);
}
}
| true
|
b9d3978213a86dc85b345473237d6def49cff20e
|
Java
|
17721541089/springcloudstudy
|
/power-mockito/src/test/java/FlySunDemoTest.java
|
UTF-8
| 3,408
| 2.859375
| 3
|
[] |
no_license
|
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.File;
/**
* 如果你的测试用例里没有使用注解@PrepareForTest,
* 那么可以不用加注解@RunWith(PowerMockRunner.class),
* 反之亦然。
*/
//告诉JUnit使用PowerMockRunner进行测试
@RunWith(PowerMockRunner.class)
public class FlySunDemoTest {
//将@Mock注解的示例注入进来
@InjectMocks
private Object object;
//
@Mock
private Object object1;
/**
*普通Mock: Mock参数传递的对象
*/
@Test
public void callArgumentInstanceTest(){
File file = PowerMockito.mock(File.class);
FlySunDemo demo = new FlySunDemo();
PowerMockito.when(file.exists()).thenReturn(true);
Assert.assertTrue(demo.callArgumentInstance(file));
}
/**
* Mock方法内部new出来的对象
*/
@Test
//所有需要测试的类列在此处,适用于模拟final类或有final, private, static, native方法的类
@PrepareForTest(FlySunDemo.class)
public void callArgumentInstanceTest2(){
File file = PowerMockito.mock(File.class);
try {
// Mockito.anyString()
PowerMockito.whenNew(File.class).withArguments(Mockito.anyString()).thenReturn(file);
FlySunDemo demo = new FlySunDemo();
PowerMockito.when(file.exists()).thenReturn(true);
Assert.assertTrue(demo.callArgumentInstance("bbb"));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Mock普通对象的final方法
*/
@Test
@PrepareForTest(ClassDependency.class)
public void testCallFinalMethod() {
ClassDependency refer = PowerMockito.mock(ClassDependency.class);
PowerMockito.when(refer.isAlive()).thenReturn(true);
FlySunDemo demo = new FlySunDemo();
Assert.assertTrue(demo.callFinalMethod(refer));
}
/**
* Mock普通类的静态方法
*/
@Test
@PrepareForTest(ClassDependency.class)
public void testStaticMethod() {
PowerMockito.mockStatic(ClassDependency.class);
PowerMockito.when(ClassDependency.isAlive2()).thenReturn(true);
FlySunDemo demo = new FlySunDemo();
Assert.assertTrue(demo.callStaticMethod());
}
/**
* Mock 私有方法
* @throws Exception
*/
@Test
@PrepareForTest(FlySunDemo.class)
public void testCallPrivateMethod() throws Exception {
FlySunDemo demo = PowerMockito.mock(FlySunDemo.class);
PowerMockito.when(demo.callPrivateMethod()).thenCallRealMethod();
PowerMockito.when(demo, "isAlive").thenReturn(true);
Assert.assertTrue(demo.callPrivateMethod());
}
/**
* Mock系统类的静态和final方法
*/
@Test
@PrepareForTest(FlySunDemo.class)
public void testCallSystemStaticMethod(){
FlySunDemo demo = new FlySunDemo();
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.getProperty("aaa")).thenReturn("bbb");
Assert.assertEquals("bbb", demo.callSystemStaticMethod("aaa"));
}
}
| true
|
0df0f883910438f5cda71029a7fa2b4157f053b0
|
Java
|
chrisl4d046/thinkjavasolutions5
|
/old_solutions/QueueList/QueueNode.java
|
UTF-8
| 151
| 2.375
| 2
|
[] |
no_license
|
public class QueueNode {
Object item;
QueueNode next;
QueueNode (Object item_, QueueNode next_) {
item = item_;
next = next_;
}
}
| true
|
3631006a91ebe4df013d7b3dda2c0ab1f4e16d39
|
Java
|
bobby-bi/Blog
|
/src/main/java/com/bi/controller/admin/TagController.java
|
UTF-8
| 2,729
| 2.15625
| 2
|
[] |
no_license
|
package com.bi.controller.admin;
import com.bi.entity.Tag;
import com.bi.entity.Type;
import com.bi.service.TagService;
import com.bi.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/admin")
public class TagController {
@Autowired
TagService tagService;
@GetMapping("/tags")
public String list(Model model, @RequestParam(value = "page",required =false) String page){
if(page==null){
page="0";
}
model.addAttribute("page",tagService.listTag(page));
return "admin/tags";
}
@GetMapping("/tags/input")
public String input(Model model){
model.addAttribute("tag",new Tag());
return "admin/tags-input";
}
@GetMapping("/tags/{id}/input")
public String editInput(@PathVariable Long id,Model model){
model.addAttribute("tag",tagService.getTag(id));
return "admin/tags-input";
}
@PostMapping("/tags")
public String post(Tag tag, RedirectAttributes attributes){
Tag tag1 = tagService.getTagByName(tag.getName());
if(tag1!=null){
attributes.addFlashAttribute("message","标签已存在");
return "redirect:/admin/tags/input";
}
int i= tagService.saveTag(tag);
if(i==0){
attributes.addFlashAttribute("message","新增失败");
}else {
attributes.addFlashAttribute("message","新增成功");
}
return "redirect:/admin/tags";
}
@PostMapping("/tags/{id}")
public String editPost(Tag tag,@PathVariable Long id, RedirectAttributes attributes){
Tag tag1 = tagService.getTagByName(tag.getName());
if(tag1!=null){
attributes.addFlashAttribute("message","标签已存在");
return "redirect:/admin/tags/"+id+"/input";
}
int i= tagService.updateTag(id,tag);
if(i==0){
attributes.addFlashAttribute("message","更新失败");
}else {
attributes.addFlashAttribute("message","更新成功");
}
return "redirect:/admin/tags";
}
@GetMapping("/tags/{id}/delete")
public String delete(@PathVariable Long id,RedirectAttributes attributes){
int i = tagService.deleteTag(id);
if(i==0){
attributes.addFlashAttribute("message","删除失败");
}else {
attributes.addFlashAttribute("message","删除成功");
}
return "redirect:/admin/tags";
}
}
| true
|
d6de5d923995b08f4f3fe5c701ab26dea651d83a
|
Java
|
wightzhang/space
|
/src/com/zkg/observer/subject/Observer.java
|
UTF-8
| 276
| 2.359375
| 2
|
[] |
no_license
|
package com.zkg.observer.subject;
import com.zkg.observer.core.Event;
/*
* created by kgzhang 2018/10/7
*/
public class Observer {
public void advice(Event e){
System.out.println("添加事件被触发,记录日志");
System.out.println(e);
}
}
| true
|
d1a839079b0a8c540f9fcb5b5c4b22da2f51d8e2
|
Java
|
mabako/asteroid
|
/asteroid/src/shapes/Drawable.java
|
UTF-8
| 1,451
| 3.796875
| 4
|
[] |
no_license
|
package shapes;
/**
* Abstrakte Klasse, die ein Objekt auf einer Zeichenfläche zeichnet und bewegt
*
* @author Marcus Bauer
* @version 201103231934
*/
public abstract class Drawable
{
/**
* zeichnet ein Objekt auf der Zeichenfläche
*/
public abstract void draw( );
/**
* bewegt ein Objekt auf der Zeichenfläche um dx in Richtung x-Achse und um
* dy in Richtung y-Achse
*
* @param dx
* distanz in x
* @param dy
* distanz in y
* @return the drawable
*/
public abstract Drawable move( double dx, double dy );
/**
* Gibt den ersten Punkt zurück
*
* @return 1. Eckpunkt des Objektes, oder (0, 0) falls keiner
*/
public abstract Point getFirstPoint( );
/**
* Vergleicht ob die Objekte gleich sind, wenn verschoben
*
* @param other
* das Vergleichsobjekt
* @param delta
* Differenz zwischen beiden Figuren
* @return true falls gleich, false sonst
*/
public abstract boolean equalsRelative( Drawable other, Point delta );
/**
* Dreht das Objekt um einen bestimmten Winkel
*
* @param center
* Punkt, der als Ursprung für die Drehung dient
* @param phi
* Winkel, um den der Punkt gedreht werden soll
* @throws IllegalArgumentException
* , falls der Mittelpunkt ungültig ist.
*/
public abstract void rotate( Point center, double phi );
}
| true
|
7738cc77b311b508bf0b0080d99d84bb662a9fae
|
Java
|
tchupp/476project1
|
/app/src/main/java/edu/msu/chuppthe/steampunked/game/SelectionArea.java
|
UTF-8
| 10,201
| 2.578125
| 3
|
[] |
no_license
|
package edu.msu.chuppthe.steampunked.game;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import edu.msu.chuppthe.steampunked.game.Pipe;
import edu.msu.chuppthe.steampunked.game.PipeArea;
import edu.msu.chuppthe.steampunked.game.Player;
import edu.msu.chuppthe.steampunked.ui.SelectionAreaView;
public class SelectionArea extends PipeArea {
private final static String PIPE_IDS = "SelectionPipe.ids";
private final static String PIPE_IMAGE_IDS = "SelectionPipe.image.ids";
private final static String PLAYER_IDS = "SelectionPipe.player.ids";
/**
* Paint for the selection area
*/
private Paint selectionAreaPaint;
/**
* This variable is set to a piece we are dragging. If
* we are not dragging, the variable is null.
*/
private Pipe dragging = null;
/**
* Most recent relative X touch when dragging
*/
private float lastRelX;
/**
* Most recent relative Y touch when dragging
*/
private float lastRelY;
/**
* List of pipes in the selection view
*/
private Map<Player, List<Pipe>> pipeMap;
/**
* Random generator
*/
private Random random = new Random();
/**
* Width of the view
*/
private float cWidth;
/**
* Height of the view
*/
private float cHeight;
private Context context;
private boolean passMovement = false;
public SelectionArea(Context context) {
this.context = context;
this.selectionAreaPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
this.selectionAreaPaint.setColor(0xffadf99d);
this.pipeMap = new HashMap<>();
}
/**
* Handle touch events in the selection area
*
* @param view view context of the touch
* @param event the touch event
* @param player player that made the touch
* @return if the touch was successful
*/
public boolean onTouchEvent(SelectionAreaView view, MotionEvent event, Player player) {
float relX = event.getX();
float relY = event.getY();
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
return onTouched(relX, relY, player);
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
return onReleased();
case MotionEvent.ACTION_MOVE:
if (passMovement) {
return view.passTouch(event);
}
return translatePipe(view, relX, relY, player);
}
return false;
}
/**
* Handle drawing the selection area
*
* @param canvas context to draw to
* @param player player to draw for
*/
public void draw(Canvas canvas, Player player) {
float gridSize = 6;
this.cWidth = canvas.getWidth();
this.cHeight = canvas.getHeight();
float cSize = cWidth > cHeight ? cWidth : cHeight;
float horizontal = cWidth > cHeight ? cWidth : 0;
float vertical = cWidth > cHeight ? 0 : cHeight;
canvas.drawRect(0, 0, cWidth, cHeight, this.selectionAreaPaint);
List<Pipe> pipes = this.pipeMap.get(player);
if (pipes == null) {
return;
}
for (int i = 0; i < pipes.size(); i++) {
Pipe pipe = pipes.get(i);
float pSize = pipe.getImageSize();
float scale = cSize / (gridSize * pSize);
float facX = (i) / (gridSize - 1f);
float facY = (i + 1f) / (gridSize - 1f);
float dx = horizontal * facX;
float dy = vertical * facY;
if (cWidth > cHeight) {
dx += Math.abs(cWidth - pSize) / 32;
dy = 7 * Math.abs(cHeight - dy) / 8;
} else {
dx = Math.abs(cWidth - pSize);
dy -= Math.abs(cWidth - pSize) / 8;
}
pipe.setBasePosition(dx, dy, scale);
pipe.draw(canvas);
}
}
/**
* Generate new random pipes
*/
public void generatePipes(Player player) {
if (this.pipeMap.get(player) == null) {
this.pipeMap.put(player, new ArrayList<Pipe>());
}
List<Pipe> pipes = this.pipeMap.get(player);
while (pipes.size() < 5) {
switch (random.nextInt(6)) {
case 0:
pipes.add(Pipe.createCapPipe(context, player));
break;
case 1:
case 2:
pipes.add(Pipe.createTeePipe(context, player));
break;
case 3:
pipes.add(Pipe.createStraightPipe(context, player));
break;
case 4:
case 5:
pipes.add(Pipe.createNinetyPipe(context, player));
break;
default:
break;
}
}
setAllPipesMovable(player, true);
}
public void saveToBundle(Bundle bundle) {
ArrayList<String> pipeIds = new ArrayList<>();
ArrayList<Integer> imageIds = new ArrayList<>();
ArrayList<String> playerIds = new ArrayList<>();
Set<Map.Entry<Player, List<Pipe>>> entrySet = this.pipeMap.entrySet();
for (Map.Entry<Player, List<Pipe>> entry : entrySet) {
for (Pipe pipe : entry.getValue()) {
pipe.saveToBundle(bundle, pipeIds, imageIds, playerIds);
}
}
// Store the arrays in the bundle
bundle.putStringArray(PIPE_IDS, pipeIds.toArray(new String[pipeIds.size()]));
bundle.putIntArray(PIPE_IMAGE_IDS, toIntArray(imageIds));
bundle.putStringArray(PLAYER_IDS, playerIds.toArray(new String[playerIds.size()]));
}
public void getFromBundle(Bundle bundle, Player playerOne, Player playerTwo) {
this.pipeMap.clear();
String[] pipeIds = bundle.getStringArray(PIPE_IDS);
int[] imageIds = bundle.getIntArray(PIPE_IMAGE_IDS);
String[] playerIds = bundle.getStringArray(PLAYER_IDS);
if (pipeIds == null || imageIds == null || playerIds == null) {
return;
}
for (int index = 0; index < pipeIds.length; index++) {
Player player;
if (playerIds[index].equals(playerOne.getName())) {
player = playerOne;
} else {
player = playerTwo;
}
Pipe pipe = createPipe(context, imageIds[index], player);
pipe.getFromBundle(pipeIds[index], bundle);
if (this.pipeMap.get(player) == null) {
this.pipeMap.put(player, new ArrayList<Pipe>());
}
this.pipeMap.get(player).add(pipe);
}
}
/**
* Handle a touch message. This is when we get an initial touch
*
* @param x x location for the touch, relative to the puzzle - 0 to 1 over the puzzle
* @param y y location for the touch, relative to the puzzle - 0 to 1 over the puzzle
* @param player player that made the touch
* @return true if the touch is handled
*/
private boolean onTouched(float x, float y, Player player) {
List<Pipe> pipes = this.pipeMap.get(player);
if (pipes == null) {
return false;
}
// Check each piece to see if it has been hit
for (int p = pipes.size() - 1; p >= 0; p--) {
if (pipes.get(p).hit(x, y)) {
// We hit a piece!
dragging = pipes.get(p);
lastRelX = x;
lastRelY = y;
return true;
}
}
return false;
}
/**
* @return if the release was successful
*/
private boolean onReleased() {
passMovement = false;
if (dragging != null) {
dragging = null;
return true;
}
return false;
}
/**
* Move the pipe, check to see if its out of the view
*
* @param view view context
* @param relX x position relative to the touch
* @param relY y position relative to the touch
* @param player player who is dragging the piece
* @return if the translation was successful
*/
private boolean translatePipe(SelectionAreaView view, float relX, float relY, Player player) {
if (dragging == null) {
return false;
}
float dx = relX - lastRelX;
float dy = relY - lastRelY;
float x = dragging.getPositionX() + dx;
float y = dragging.getPositionY() + dy;
float pSize = dragging.getImageSize() * dragging.getScale();
float left = this.cWidth > cHeight ? x : x + pSize / 2;
float top = this.cWidth > cHeight ? y - pSize / 2 : y - pSize;
float bounds = this.cWidth > cHeight ? top : left;
float otherBounds = this.cWidth < cHeight ? top : left;
List<Pipe> pipes = this.pipeMap.get(player);
if ((otherBounds > 0)
&& (x + pSize < cWidth) && (y < cHeight)) {
this.dragging.move(dx, dy);
}
if ((bounds <= 0) && (pipes.indexOf(this.dragging) != -1)) {
view.notifyPieceSelected(this.dragging, this.cWidth > cHeight);
pipes.remove(this.dragging);
setAllPipesMovable(player, false);
passMovement = true;
}
lastRelX = relX;
lastRelY = relY;
view.invalidate();
return true;
}
/**
* @param player Player who owns the pieces to modify
* @param isMovable if the pipes should be movable
*/
private void setAllPipesMovable(Player player, boolean isMovable) {
List<Pipe> pipes = this.pipeMap.get(player);
if (pipes == null) return;
for (Pipe pipe : pipes) {
pipe.setMovable(isMovable);
pipe.resetMovement();
}
}
}
| true
|
e165fa780aa8763df9652a2c62563fc693eac03c
|
Java
|
Agomezmo00/ADFicheros
|
/ADFicheros/src/jaxbLibros/Libreria.java
|
UTF-8
| 1,367
| 2.65625
| 3
|
[] |
no_license
|
package jaxbLibros;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
//La anotacion @XmlRootElement significa que la clase Libreria es el elemento raiz del fichero xml
//el namespace es opcional
//@XmlRootElement(namespace = "ejemplo1.xml")
//@XmlRootElement(namespace = "")
@XmlRootElement()
public class Libreria {
private ArrayList<Libro> listaLibros;
private String nombre;
private String lugar;
public Libreria(ArrayList<Libro> listaLibros, String nombre, String lugar) {
super();
this.listaLibros = listaLibros;
this.nombre = nombre;
this.lugar = lugar;
}
public Libreria(){}
public void setNombre(String nombre) { this.nombre = nombre; }
public void setLugar(String lugar) { this.lugar = lugar; }
public String getNombre() {return nombre; }
public String getLugar() { return lugar; }
//Wrapper, envoltura alrededor la representación XML
@XmlElementWrapper(name = "ListaLibros") //
@XmlElement(name = "Libro")
public ArrayList<Libro> getListaLibros() {
return listaLibros; }
public void setListaLibros(ArrayList<Libro> listaLibros) {
this.listaLibros = listaLibros; }
}
| true
|
4a52ac34ed91aebf7c6140aac00c0c034c935d4a
|
Java
|
jhcpokemon/ServletDemo
|
/src/servlet/PageRedirect.java
|
UTF-8
| 741
| 2.359375
| 2
|
[] |
no_license
|
package servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "PageRedirect")
public class PageRedirect extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.sendRedirect("https://www.google.jp");
}
}
| true
|
e1f3f688cddb9e6c68c2d232fb2b17c1f77ee404
|
Java
|
ettwin1/javafun
|
/note15SOOP/src/note15SOOP/Simulator.java
|
UTF-8
| 1,034
| 3.6875
| 4
|
[] |
no_license
|
package note15SOOP;
import java.util.ArrayList;
import note15SOOP.Vehicle.VehicleClassType;
public class Simulator {
public static void main(String[] args) {
System.out.println("A vehicle Simulation.");
//Array list to keep a list of vehicles to simulate
ArrayList<Vehicle> vehicles = new ArrayList<Vehicle>();
vehicles.add(new Car());
for (Vehicle device : vehicles) {//goes through each vehicle in the array, and referenced as device
int distance = (int)(device.getMaxSpeed() * 4);
//Simulate driving the device for the distance
device.drive(distance);
if (device.vehicleKind() == VehicleClassType.CAR) {
Car specVehicle = (Car) device;
System.out.println("Trunk size: "+specVehicle.getTrunkSize());
System.out.println("The On Star Test returned: " + specVehicle.onStarTest(Ford.ModelNames.FOCUS));
}else if (device.vehicleKind() == VehicleClassType.TRUCK){
Truck specVehicle = (Truck) device;
System.out.println("Bed size: "+specVehicle.getBedSize());
}
}
}
}
| true
|
ef3ec9f542123cf6e6d0efb2d4f68be99695a9dc
|
Java
|
hanghaifeng1994/java
|
/java的老年大学项目/.svn/pristine/4c/4ca4a6a4da08a7d4b26387cdaf9d9bed4e5d51be.svn-base
|
UTF-8
| 207
| 1.648438
| 2
|
[] |
no_license
|
package com.learnyeai.learnai.net;
import com.learnyeai.learnai.net.netConf.MBTransConfBean;
public interface INetConfParser {
public abstract MBTransConfBean findTransConfById(String id, String pre);
}
| true
|
375b80db08c59ecdee1fcf1a6a8863acfe9a42e0
|
Java
|
calthaz/elefind
|
/elefind-java/src/general/SketchPad1.java
|
GB18030
| 27,129
| 2.4375
| 2
|
[] |
no_license
|
package general;
import static java.lang.Math.sqrt;
//import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.awt.image.RasterFormatException;
import java.awt.image.RescaleOp;
import java.io.File;
import java.io.IOException;
import java.text.NumberFormat;
import javax.imageio.ImageIO;
import javax.swing.*;
import imprSearch.Impression;
/**
* This class serves as the drawing pad
* onto which the user paint the impression of the photo.
* It then offers the main program this sketch for processing.
*
* Note: the implementation for undo and redo is not completed.
* Note: the mouseMove method may cause exception
* Note: the relativity value is currently not used in the comparison method
* Note: the contrast value is currently not used
* IMPORTANT Note: this version is not completed. Choosing files as draft to search is not supporter
*/
public class SketchPad1 extends JPanel implements ActionListener, MouseMotionListener, MouseListener{
private static final long serialVersionUID = 1L;
//dimensions
public static final int PAD_HEIGHT = Utils.DISPLAY_HEIGHT;
public static final int CANVAS_WIDTH = Utils.DISPLAY_WIDTH;
public static final int TOOL_WIDTH = 320;
public static final int MAX_R = 50;
public static final int MAX_RLY = 10;
private static final int MAX_STEPS = 10;
//swing components
private JButton reset,fillUp,undo,redo,bgChooser,penChooser,save,load;
private JFormattedTextField width, height;
private JTextField nameField;
private ButtonGroup tools;
private JSlider contrast,radius,reliability;
private Canvas canvas;
//private JColorChooser cchooser;
private Color bgColor = Color.WHITE;
private Color penColor = Color.BLACK;
private JRadioButton bg,pen;
private JLabel position = new JLabel("Current Position: ");
//Appearances background imgs
private BufferedImage display = new BufferedImage(CANVAS_WIDTH,PAD_HEIGHT,BufferedImage.TYPE_INT_ARGB);
private BufferedImage draft;
/**
* x1,y1 should be the absolute coordination of the upper left corner of the selected region.
* x2,y2 should be the absolute coordination of the lower right corner of the selected region.
*/
private int x1,y1,x2,y2;
private int offsetX,offsetY;
private double ratio;
private BufferedImage mask;
int cnt=0;
//int lastX,lastY;
private BufferedImage[] versions = new BufferedImage[MAX_STEPS];
private int currentVersion = 0;
public SketchPad1(){
//this.setOneTouchExpandable(true);
//initialize layout
this.setLayout(new BorderLayout());
Dimension setD = new Dimension(TOOL_WIDTH,PAD_HEIGHT);
Dimension scrollD = new Dimension(CANVAS_WIDTH,PAD_HEIGHT);
reset = new JButton("Reset ");
fillUp = new JButton("Fill up the canvas 仭");
undo = new JButton("Undo ");
undo.setEnabled(false);
redo = new JButton("Redo ");
redo.setEnabled(false);
bgChooser = new JButton();
bgChooser.setBackground(Color.WHITE);
penChooser = new JButton();
penChooser.setBackground(Color.BLACK);
//cchooser = new JColorChooser();
save=new JButton("Save Draft ");
load=new JButton("Load Draft ");
width = new JFormattedTextField(NumberFormat.getNumberInstance());
width.setValue(5);
height = new JFormattedTextField(NumberFormat.getNumberInstance());
height.setValue(4);
nameField = new JTextField();
nameField.setText("My Impression");
tools = new ButtonGroup();
bg = new JRadioButton("Background");
pen = new JRadioButton("Pen");
pen.setSelected(true);
tools.add(bg);
tools.add(pen);
Dimension preferredSize = new Dimension (180,50);
contrast = new JSlider(JSlider.HORIZONTAL,0,100,50);
radius = new JSlider(JSlider.HORIZONTAL,10,MAX_R,MAX_R/4);
reliability = new JSlider(JSlider.HORIZONTAL,1,MAX_RLY,MAX_RLY/2);
contrast.setMajorTickSpacing(10);
contrast.setMinorTickSpacing(5);
contrast.setPaintTicks(true);
contrast.setPaintLabels(true);
contrast.setPreferredSize(preferredSize);
radius.setMajorTickSpacing(10);
radius.setMinorTickSpacing(5);
radius.setPaintTicks(true);
radius.setPaintLabels(true);
radius.setPreferredSize(preferredSize);
reliability.setMajorTickSpacing(1);
//reliability.setMinorTickSpacing(5);
reliability.setPaintTicks(true);
reliability.setPaintLabels(true);
/*//Sample code from Java tutorial
* //Create the slider
JSlider framesPerSecond = new JSlider(JSlider.VERTICAL,
FPS_MIN, FPS_MAX, FPS_INIT);
framesPerSecond.addChangeListener(this);
framesPerSecond.setMajorTickSpacing(10);
framesPerSecond.setPaintTicks(true);
//Create the label table
Hashtable labelTable = new Hashtable();
labelTable.put( new Integer( 0 ), new JLabel("Stop") );
labelTable.put( new Integer( FPS_MAX/10 ), new JLabel("Slow") );
labelTable.put( new Integer( FPS_MAX ), new JLabel("Fast") );
framesPerSecond.setLabelTable( labelTable );
framesPerSecond.setPaintLabels(true);
*/
JPanel settings = new JPanel();
settings.setLayout(new GridBagLayout());
settings.setPreferredSize(setD);
organizeSettings(settings);
//JScrollPane canvas = new JScrollPane();
//canvas.setPreferredSize(new Dimension(700,1000));
//this.setLeftComponent(canvas);
//this.setRightComponent(settings);
this.add(settings,BorderLayout.EAST);
//this.setColumnHeaderView(settings);
canvas = new Canvas();
//canvas.setCursor(cursor);//I wish for a pen-shaped cursor...
JScrollPane scroller = new JScrollPane(canvas);
scroller.setPreferredSize(scrollD);
this.add(scroller,BorderLayout.CENTER);
this.add(position, BorderLayout.NORTH);
//add listeners
reset.addActionListener(this);
fillUp.addActionListener(this);
undo.addActionListener(this);
redo.addActionListener(this);
bgChooser.addActionListener(this);
penChooser.addActionListener(this);
save.addActionListener(this);
load.addActionListener(this);
//these listener listen for events in canvas, so the returned coordinates should be inside canvas?
canvas.addMouseMotionListener(this);
canvas.addMouseListener(this);
versions[currentVersion]= copy(display);//TODO fix later
resetCanvas();
draft = new BufferedImage(Utils.DRAFT_WIDTH,Utils.DRAFT_HEIGHT,Impression.IMAGE_TYPE);
x1=y1=0;
x2=draft.getWidth()-1;
y2=draft.getHeight()-1;
System.out.println(String.format("upper left corner: %s %s, lower right corner: %s %s. ", x1,y1,x2,y2));
drawDisplayFromDraft();
refresh();
setDimenFieldsByDraft();
}
private void organizeSettings(JPanel settings){
GridBagConstraints c = new GridBagConstraints();
c.weightx=0.5;
c.weighty=0.5;
//c.anchor=GridBagConstraints.CENTER;
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=0;
c.gridwidth=2;
settings.add(new JLabel("Width : Height"),c);
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=1;
c.gridwidth=1;
settings.add(width,c);
/*
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=1;
c.gridy=1;
c.gridwidth=1;
settings.add(new JLabel(" : "),c);
*/
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=1;
c.gridy=1;
c.gridwidth=1;
settings.add(height,c);
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=2;
c.gridwidth=2;
settings.add(reset,c);
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=3;
c.gridwidth=1;
settings.add(bg,c);
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=1;
c.gridy=3;
c.gridwidth=1;
settings.add(new JLabel("Contrast Աȶ"),c);
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=4;
c.gridwidth=1;
settings.add(bgChooser,c);
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=1;
c.gridy=4;
c.gridwidth=1;
settings.add(contrast,c);
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=5;
c.gridwidth=2;
settings.add(fillUp,c);
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=6;
c.gridwidth=1;
settings.add(pen,c);
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=1;
c.gridy=6;
c.gridwidth=1;
settings.add(new JLabel("Radius 뾶"),c);
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=7;
c.gridwidth=1;
settings.add(penChooser,c);
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=1;
c.gridy=7;
c.gridwidth=1;
settings.add(radius,c);
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=8;
c.gridwidth=1;
settings.add(undo,c);
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=1;
c.gridy=8;
c.gridwidth=1;
settings.add(redo,c);
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=9;
c.gridwidth=2;
settings.add(new JLabel("Your draft name:"),c);//"Reliability"
/*
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=10;
c.gridwidth=2;
settings.add(reliability,c);
*/
c.fill=GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=10;
c.gridwidth=2;
settings.add(nameField,c);
c.gridy=11;
settings.add(save, c);
c.gridy=12;
settings.add(load, c);
}
@SuppressWarnings("serial")
public class Canvas extends JPanel{
public int lastX,lastY;
//What a surprise that I can write an entire class here.
//TODOdouble reference? Check the pointer?
protected void paintComponent(Graphics g) {
super.paintComponent(g);//Why?
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.drawImage(display, 0, 0, display.getWidth(), display.getHeight(), null);
if(mask!=null)g2.drawImage(mask, 0, 0, mask.getWidth(), mask.getHeight(), null);
}
}
/**
* The main program or any clients should call this method
* to get what is displayed on canvas of this sketch pad.
* @return the image on display on canvas
*/
public BufferedImage getDraft() {
return draft;
}
/**
* The client call this method to get a user-defined coefficient for further processing.
* @return the coefficient hereby called reliability
*/
public int getRly(){
return reliability.getValue();
}
public String getDraftName(){
return nameField.getText();
}
public void displayImage(File file){
try {
BufferedImage temp = (BufferedImage)ImageIO.read(file);
Dimension d = Utils.scaleUniformFit(temp.getWidth(),temp.getHeight(),CANVAS_WIDTH,PAD_HEIGHT);
display = new BufferedImage(d.width,d.height,Impression.IMAGE_TYPE);
display.getGraphics().drawImage(temp, 0, 0, d.width, d.height, null);
refresh();
nameField.setText(file.getName());
} catch (IOException e) {
e.printStackTrace();
}
refresh();
setDimenFieldsByDisplay();
}
public void displayImage(BufferedImage img){
//display = copy(img); //Attention! display's value remains unchanged after this block! Really? Maybe not.
display=img;
mask=null;
refresh();
setDimenFieldsByDisplay();
}
public void displayMask(BufferedImage img){
//must properly mask the current display
mask=new BufferedImage(display.getWidth(),display.getHeight(),BufferedImage.TYPE_INT_ARGB);
BufferedImage temp = new BufferedImage(display.getWidth(),display.getHeight(),BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) temp.getGraphics();
g2d.drawImage(img, 0, 0, display.getWidth(), display.getHeight(), null);
g2d.dispose();
//TODO transparency:
Graphics2D g2d1 = (Graphics2D) mask.getGraphics();
float[] scales = { 1f, 1f, 1f, 0.8f };
float[] offsets = new float[4];
RescaleOp rop = new RescaleOp(scales, offsets, null);
g2d1.drawImage(temp, rop, 0, 0);
g2d1.dispose();
refresh();
}
/**
* project what is drawn onto the draft to the display object, only the selected area
*/
private void drawDisplayFromDraft(){
BufferedImage shown = draft.getSubimage(x1, y1, x2-x1, y2-y1);
Dimension d = Utils.scaleUniformFit(shown.getWidth(),shown.getHeight(),display.getWidth(),display.getHeight());
Graphics2D g = display.createGraphics();
offsetX=0;
offsetY=0;
ratio = (double)d.height/shown.getHeight();
if(d.width<display.getWidth())offsetX=(display.getWidth()-d.width)/2;
if(d.height<display.getHeight())offsetY=(display.getHeight()-d.height)/2;
//System.out.println(String.format("offsetX %s, offsetY %s, ratio %s", offsetX,offsetY,ratio));
g.drawImage(shown, offsetX, offsetY, d.width, d.height, null);
g.dispose();
}
/**
* project what is drawn onto the draft to the display object, only the selected area
* be careful, these values may not be within the draft.
* what about repaint?
*/
private void drawDisplayFromDraft(int x, int y, int w, int h){
int cx = (int) (this.x1+(x-offsetX)/ratio);
int cy = (int) (this.y1+(y-offsetY)/ratio);
int cw = (int)(w/ratio);
int ch = (int)(h/ratio);
if(cx<0)cx=0;
if(cy<0)cy=0;
if(cx+cw>draft.getWidth()-1)cw=draft.getWidth()-cx-1;
if(cy+ch>draft.getHeight()-1)ch=draft.getHeight()-cy-1;
try{
BufferedImage clip = draft.getSubimage(cx, cy, cw, ch);
Graphics2D g = display.createGraphics();
//System.out.println(String.format("offsetX %s, offsetY %s, ratio %s", offsetX,offsetY,ratio));
//g.drawImage(clip, x+offsetX, y+offsetY, (int)(cw*ratio), (int)(ch*ratio), null);
g.drawImage(clip, x, y,cw, ch, null);//TODO
//g.drawRect(x, y, w, h);
g.dispose();
}catch(RasterFormatException e){
//e.printStackTrace();
System.out.println(String.format("Outside raster! Clip dimensions: x:%s y:%s w:%s h:%s", cx, cy, cw, ch));
}
}
/**
* invoked after the display object has been modified
* to tell the scroll pane to adjust to the new size
* and update the size information in the text fields
*/
private void refresh(){
canvas.setPreferredSize(new Dimension(display.getWidth(),display.getHeight()));
//tells its parent component:"I wish I could have a space of that size!"
//so the scroller says "OK, I can give you a pair of scrollbars."
canvas.revalidate();
//"REVALIDATE! Now your dream has come true." Says the scroller.
repaint();
/*
int w = draft.getWidth();
int h = draft.getHeight();
int r = findCommonFactor(w,h);
width.setValue(w/r);
height.setValue(h/r);
*/
}
private void setDimenFieldsByDraft(){
int w = draft.getWidth();
int h = draft.getHeight();
int r = findCommonFactor(w,h);
width.setValue(w/r);
height.setValue(h/r);
}
private void setDimenFieldsByDisplay(){
int w = display.getWidth();
int h = display.getHeight();
int r = findCommonFactor(w,h);
width.setValue(w/r);
height.setValue(h/r);
}
private BufferedImage copy(BufferedImage old){
//TODO: improve efficiency
BufferedImage img = new BufferedImage(old.getWidth(),old.getHeight(),Impression.IMAGE_TYPE);
//img=old.getSubimage(0, 0, old.getWidth(), old.getHeight());
//Returns a subimage defined by a specified rectangular region.
//The returned BufferedImage SHARES the same data array as the original image.
for (int i=0; i<old.getHeight(); i++){
for(int j=0; j<old.getWidth(); j++){
img.setRGB(j, i, old.getRGB(j,i));
}
}
return img;
}
private int findCommonFactor(int a, int b) {
int nu = Math.max(a, b);
int de = Math.min(a, b);
while(true){
int t = de;
de = nu%de;
nu = t;
if(de == 0)break;
}
return nu;
}
private void resetCanvas(){
//commit edit?
int w=((Number)width.getValue()).intValue();
int h= ((Number)height.getValue()).intValue();
if(w>0&&h>0){
int r = findCommonFactor(w,h);
width.setValue((Number)(w/r));
height.setValue(h/r);
display = new BufferedImage(CANVAS_WIDTH,PAD_HEIGHT,BufferedImage.TYPE_INT_ARGB);
Dimension d = Utils.scaleUniformFit(w, h, Utils.DRAFT_WIDTH, Utils.DRAFT_HEIGHT);
draft = new BufferedImage(d.width,d.height,Impression.IMAGE_TYPE);
x1=y1=0;
x2=draft.getWidth()-1;
y2=draft.getHeight()-1;
System.out.println(String.format("upper left corner: %s %s, lower right corner: %s %s. ", x1,y1,x2,y2));
drawDisplayFromDraft();
mask=null;
//display=new BufferedImage(w,h,Impression.IMAGE_TYPE);
//TODO clear versions.;
currentVersion=0;
for(int i = 0; i<versions.length;i++){
versions[i]=null;
}
System.out.println(String.format("offsetX %s, offsetY %s, ratio %s", offsetX,offsetY,ratio));
versions[currentVersion]= copy(display);
refresh();
//setDimenFieldsByDraft();
//System.out.println("Reset canvas size to "+w/r+" : "+h/r+" and clear versions memory.");
System.out.println("Reset canvas size to "+w+" : "+h+" and clear versions memory.");
}
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==reset){
resetCanvas();
}else if(e.getSource()== fillUp){
if(bgColor==Color.BLACK||bgColor==Color.WHITE){
Graphics g = draft.getGraphics();
g.setColor(bgColor);
g.fillRect(0, 0, draft.getWidth(), draft.getHeight());
g.dispose();//TODO a silly way to make the region opaque. And it doesn't work!
for(int j = 0; j<draft.getHeight();j++){
for(int i = 0; i<draft.getWidth();i++){
if((i+j)%2==0) draft.setRGB(i, j, 0);
else draft.setRGB(i, j, 0xFFFFFF);
}
}
}else{
Graphics g = draft.getGraphics();
g.setColor(bgColor);
g.fillRect(0, 0, draft.getWidth(), draft.getHeight());
g.dispose();
}
drawDisplayFromDraft(0,0,display.getWidth(),display.getHeight());
repaint();
}else if(e.getSource()== bgChooser ){
Color newColor = JColorChooser.showDialog(this, "Choose Background Color", bgColor);
if (newColor != null) {
bgColor = newColor;
bgChooser.setBackground(newColor);
}
}else if(e.getSource()== penChooser ){
Color newColor = JColorChooser.showDialog(this, "Choose Background Color", penColor);
if (newColor != null) {
penColor = newColor;
penChooser.setBackground(newColor);
}
}else if(e.getSource()==undo){
display=copy(versions[--currentVersion%MAX_STEPS]);//Copy it! you will modify the content of this element otherwise
redo.setEnabled(true);
if(currentVersion==0)undo.setEnabled(false); //TODO something is wrong here/%MAX_STEPS
refresh();
System.out.println("Undo: Current version: "+currentVersion+" and versions count: "+versions.length);
}else if(e.getSource()== redo){
display=copy(versions[++currentVersion%MAX_STEPS]);
if(currentVersion%MAX_STEPS == MAX_STEPS-1)redo.setEnabled(false);
refresh();
System.out.println("Redo: Current version: "+currentVersion+" and versions count: "+versions.length);
}else if(e.getSource()==save){
//This is the only awt component in this project. How to specify the saving type?
System.out.println("try to save");
JFrame saveDialog = new JFrame();
//saveDialog.setVisible(true);
FileDialog saveFile = new FileDialog(saveDialog, "Save Draft", FileDialog.SAVE);
//JFileChooser chooser = new JFileChooser("...");
saveFile.setFile(Utils.DEPOSIT_POSITION+nameField.getText()+".png");
//saveFile.setFilenameFilter();
saveFile.setVisible(true);
File outFile = null;
if(saveFile.getFile()!= null){
String name = saveFile.getFile();
if(name.indexOf(".")==-1)name+=".png";
outFile = new File(saveFile.getDirectory(),name);
try {
ImageIO.write(draft, "png", outFile);
System.out.println("Saved as:"+name);
} catch (IOException e1) {
e1.printStackTrace();
}
}
saveDialog.dispose();//How do I know if this works?--Set it visible first.
}else if(e.getSource()==load){
System.out.println("loading draft");
JFrame loadDialog = new JFrame();
FileDialog loadFile = new FileDialog(loadDialog, "Load Draft", FileDialog.LOAD);
loadFile.setVisible(true);
if(loadFile.getFile()!=null){
try {
System.out.println("try to load draft:"+loadFile.getDirectory()+loadFile.getFile());
loadDraft(ImageIO.read(new File(loadFile.getDirectory()+loadFile.getFile()))); //loadFile.getFile()
//stupid
nameField.setText(loadFile.getFile());
//refresh();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
public void loadDraft(BufferedImage draft){
this.draft=draft;
x1=y1=0;
x2=draft.getWidth()-1;
y2=draft.getHeight()-1;
display=new BufferedImage(CANVAS_WIDTH,PAD_HEIGHT,BufferedImage.TYPE_INT_ARGB);
drawDisplayFromDraft();
refresh();
setDimenFieldsByDraft();
}
/**
*
* @param x of the center of the dot
* @param y of the center of the dot
* @param r radius of the circle
*/
private void drawBackgroundDot(int x, int y, int r){
Graphics2D g = draft.createGraphics();
g.fillOval(x-r, y-r, 2*r, 2*r);
g.dispose();//TODO a silly way to make the circle opaque.
for(int j = y-r; j < y+r+1; j++){
if (!(j<0)&&j<draft.getHeight()){
for(int i = x-r; i<x+r+1; i++){
if(!(i<0)&&i<draft.getWidth() && !(sqrt((i-x)*(i-x)+(j-y)*(j-y))>r)){
if((i+j)%2==0)draft.setRGB(i, j, 0); //TODO pixel transparent!
else draft.setRGB(i, j, 0xFFFFFF);
}
}
}
}
}
@Override
//TODO e.x, e.y may be out of the border of display.
public void mouseDragged(MouseEvent e) {
//cnt++;
//System.out.println("Draw a dot "+cnt);
int x1=canvas.lastX;
int y1=canvas.lastY;
int x2 = (int) (this.x1+(e.getX()-offsetX)/ratio);//e.getX();//
int y2 = (int) (this.y1+(e.getY()-offsetY)/ratio);//e.getY();
int r = radius.getValue();
//r = inkStyle(x1-x2,y1-y2,r);
if(pen.isSelected()){//&& cnt%5==0
Graphics2D g = (Graphics2D) draft.getGraphics();
g.setColor(penColor);
/*//it looks very strange, especially when you drag your mouse slowly
BasicStroke str = new BasicStroke(2*r, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_BEVEL);
g.setStroke(str);
*/
if (x1-x2!=0 && (y1-y2)/(double)(x1-x2)<=1&&(y1-y2)/(double)(x1-x2)>=-1) {
double k = (y1-y2)/(double)(x1-x2);
int x = x1;
int y = y1;
while(x!=x2){
y = (int) ((x-x1)*(k)+y1);
g.fillOval(x-r, y-r, 2*r, 2*r);
drawDisplayFromDraft((int)(e.getX()-r*ratio),(int)(e.getY()-r*ratio),(int)(2*r*ratio),(int)(2*r*ratio));
canvas.repaint((int)(e.getX()-r*ratio),(int)(e.getY()-r*ratio),(int)(2*r*ratio),(int)(2*r*ratio));
if(x1>x2)x--;
else x++;
}
}else{
//int y = y1;
double k = (x1-x2)/(double)(y1-y2);
int x = x1;
int y = y1;
while(y!=y2){
x = (int) ((y-y1)*(k)+x1);
g.fillOval(x-r, y-r, 2*r, 2*r);
drawDisplayFromDraft((int)(e.getX()-r*ratio),(int)(e.getY()-r*ratio),(int)(2*r*ratio),(int)(2*r*ratio));
canvas.repaint((int)(e.getX()-r*ratio),(int)(e.getY()-r*ratio),(int)(2*r*ratio),(int)(2*r*ratio));
if(y1>y2)y--;
else y++;
}
}
/*for(int x = x1; x<=x2; x++){
int y = (int) ((x-x1)*(k)+y1);
g.fillOval(x-r, y-r, 2*r, 2*r);
canvas.repaint(x-r,y-r,2*r,2*r);
//System.out.println("Draw a dot");
}
*/
//TODO Too slow,can't catch up with my movement.
//g.drawLine(lastX, lastY, x, y);
//repaint(lastX, lastY, x, y);
//repaint();
}else if(bg.isSelected()){
int ctr = contrast.getValue();
if (x1-x2!=0 && (y1-y2)/(double)(x1-x2)<=1&&(y1-y2)/(double)(x1-x2)>=-1) {
double k = (y1-y2)/(double)(x1-x2);
int x = x1;
int y = y1;
while(x!=x2){
y = (int) ((x-x1)*(k)+y1);
drawBackgroundDot(x, y, r);
drawDisplayFromDraft((int)(e.getX()-r*ratio),(int)(e.getY()-r*ratio),(int)(2*r*ratio),(int)(2*r*ratio));
canvas.repaint((int)(e.getX()-r*ratio),(int)(e.getY()-r*ratio),(int)(2*r*ratio),(int)(2*r*ratio));
if(x1>x2)x--;
else x++;
}
}else{
//int y = y1;
double k = (x1-x2)/(double)(y1-y2);
int x = x1;
int y = y1;
while(y!=y2){
x = (int) ((y-y1)*(k)+x1);
drawBackgroundDot(x, y, r);
drawDisplayFromDraft((int)(e.getX()-r*ratio),(int)(e.getY()-r*ratio),(int)(2*r*ratio),(int)(2*r*ratio));
canvas.repaint((int)(e.getX()-r*ratio),(int)(e.getY()-r*ratio),(int)(2*r*ratio),(int)(2*r*ratio));
if(y1>y2)y--;
else y++;
}
}
}
canvas.lastX=x2;
canvas.lastY=y2;
//drawDisplayFromDraft();
}
private int inkStyle(int dx, int dy, int r){
double ds = sqrt(dx*dx+dy*dy);
if(ds/r<1)r+=5*ds/r;
else r-=5*(1-r/ds);
return r;
}
@Override
public void mouseMoved(MouseEvent e) {
int x = e.getX();
int y = e.getY();
//for debugging, testing the frequency of such event
//cnt++;
//System.out.println("Draw a dot "+cnt);
/*
cnt++;
if(pen.isSelected()){//&& cnt%5==0
int r = radius.getValue();
Graphics g = display.getGraphics();
g.setColor(penColor);
g.fillOval(x-r, y-r, 2*r, 2*r);
//System.out.println("Draw a dot");
repaint(x-r,y-r,2*r,2*r);//TODO Too slow,can't catch up with my movement.
}*/
if(!(x<0)&&!(x>=display.getWidth())&&!(y<0)&&!(y>=display.getHeight())){
//TODO: canvas x,y? draft x,y?
//try{
int c = display.getRGB(x, y);
int r = (c>>16)&0xFF;
int g = (c>>8)&0xFF;
int b = c&0xFF;
position.setText("Curent Position: ("+x+","+y+") and the color at this position is "+r+", "+g+", "+b+".");
//}catch(ArrayIndexOutOfBoundsException e1){
//System.out.println("Coordinate out of bounds! "+x+","+y);
//}
}
}
@Override
public void mouseClicked(MouseEvent arg0) {
// Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent arg0) {
// Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
int x = (int) (this.x1+(e.getX()-offsetX)/ratio);//e.getX();
int y = (int) (this.y1+(e.getY()-offsetY)/ratio);//e.getY();
canvas.lastX=x;
canvas.lastY=y;
int r = radius.getValue();
if(pen.isSelected()){
Graphics g = draft.getGraphics();
g.setColor(penColor);
g.fillOval(x-r, y-r, 2*r, 2*r);
//System.out.println("Draw a dot");
}else if(bg.isSelected()){
int ctr = contrast.getValue();
//display.setRGB(arg0, arg1, arg2);
drawBackgroundDot(x,y,r);
}
drawDisplayFromDraft((int)(e.getX()-r*ratio),(int)(e.getY()-r*ratio),(int)(2*r*ratio),(int)(2*r*ratio));
canvas.repaint((int)(e.getX()-r*ratio),(int)(e.getY()-r*ratio),(int)(2*r*ratio),(int)(2*r*ratio));//
}
@Override
/**
* Note: should save a copy now!
*/
public void mouseReleased(MouseEvent arg0) {
drawDisplayFromDraft();
canvas.repaint();
undo.setEnabled(true);
redo.setEnabled(false);
versions[++currentVersion%10]= copy(display);
System.out.println("MouseReleased saved as version "+currentVersion);
//System.out.println("Current version: "+currentVersion+" and versions count: "+versions.size());
}
}
| true
|
92b3b82e4b8576b1d46c8f6981b242baac0004c9
|
Java
|
DSC-SIT/Java-For-Android
|
/inheritance.java
|
UTF-8
| 648
| 3.875
| 4
|
[] |
no_license
|
class Animal{
public void eat(){
System.out.println("i can eat");
}
public void feature(){
System.out.println("i have a feature!");
}
}
class Dog extends Animal{
public void feature(){
System.out.println("i can gaurd");
}
}
class Cat extends Animal{
public void feature(){
System.out.println("i just scratch you!");
}
class GuineaPig extends Animal{
public void feature(){
System.out.println("i can be cute..:P");
}
}
class inheritance{
public static void main(String args[]){
Animal living = new Animal();
Animal tommy = new Dog();
Animal kitty = new Cat();
kitty.feature();
tommy.feature();
}
}
| true
|
5bb6e987e3a76a4c0f45ed56f64b3c37438ef4bd
|
Java
|
cando46/Hobbyland_v1.1
|
/app/src/main/java/com/hobbyland/version1/HomeActivity.java
|
UTF-8
| 12,206
| 1.789063
| 2
|
[] |
no_license
|
package com.hobbyland.version1;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import com.ismaeldivita.chipnavigation.ChipNavigationBar;
public class HomeActivity extends AppCompatActivity{
private static final String TAG = "HomeActivity";
int LOCATION_REQUEST_CODE = 10001;
Geocoder geocoder;
double latitude;
double longitude;
FusedLocationProviderClient fusedLocationProviderClient;
LocationRequest locationRequest;
DatabaseReference mRef;
ChipNavigationBar navigationBar;
FragmentManager fragmentManager;
LocationManager lm;
LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for(Location location: locationResult.getLocations()) {
latitude=location.getLatitude();
longitude=location.getLongitude();
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
String state;
String country;
if(addresses.get(0).getAdminArea()!=null && addresses.get(0).getCountryName()!=null){
state = addresses.get(0).getAdminArea();
country = addresses.get(0).getCountryName();
}else {
state="Sea";
country=" ";
}
sendLocationDataToFirebase(latitude,longitude,state,country);
Log.d(TAG, "onLocationResult: " + location.toString());
}
}
};
private void sendLocationDataToFirebase(double latitude, double longitude, String state, String country) {
mRef.child("LastKnownLocation").child("latitude").setValue(latitude);
mRef.child("LastKnownLocation").child("longitude").setValue(longitude);
mRef.child("LastKnownLocation").child("state").setValue(state);
mRef.child("LastKnownLocation").child("country").setValue(country);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_home);
//LOCATION START
geocoder = new Geocoder(this, Locale.getDefault());
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
locationRequest = LocationRequest.create();
locationRequest.setInterval(4000);
locationRequest.setFastestInterval(2000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//LOCATION END
mRef = FirebaseDatabase.getInstance()
.getReference("Users").child(FirebaseAuth.getInstance()
.getCurrentUser().getUid());
navigationBar = findViewById(R.id.chip_nav);
if (savedInstanceState == null) {
navigationBar.setItemSelected(R.id.bottom_home, true);
fragmentManager = getSupportFragmentManager();
HomeFragment homeFragment = new HomeFragment();
fragmentManager.beginTransaction().replace(R.id.fragment_container, homeFragment).commit();
}
navigationBar.setOnItemSelectedListener(new ChipNavigationBar.OnItemSelectedListener() {
@Override
public void onItemSelected(int id) {
Fragment fragment = null;
switch (id) {
case R.id.bottom_home:
fragment = new HomeFragment();
break;
case R.id.bottom_my_events:
fragment = new MyEventsFragment();
break;
case R.id.Messages:
fragment = new MessagesFragment();
break;
}
if (fragment != null) {
fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment_container, fragment).commit();
}
}
});
}
@Override
protected void onStart() {
super.onStart();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// getLastLocation();
checkSettingsAndStartLocationUpdates();
} else {
askLocationPermission();
}
}
@Override
protected void onStop() {
super.onStop();
stopLocationUpdates();
}
private void checkSettingsAndStartLocationUpdates() {
LocationSettingsRequest request = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest).build();
SettingsClient client = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> locationSettingsResponseTask = client.checkLocationSettings(request);
locationSettingsResponseTask.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
//Settings of device are satisfied and we can start location updates
startLocationUpdates();
}
});
locationSettingsResponseTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
if (e instanceof ResolvableApiException) {
ResolvableApiException apiException = (ResolvableApiException) e;
try {
apiException.startResolutionForResult(HomeActivity.this, 1001);
} catch (IntentSender.SendIntentException ex) {
ex.printStackTrace();
}
}
}
});
}
private void startLocationUpdates() {
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
}
private void stopLocationUpdates() {
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
}
private void getLastLocation() {
Task<Location> locationTask = fusedLocationProviderClient.getLastLocation();
locationTask.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
//We have a location
Log.d(TAG, "onSuccess: " + location.toString());
Log.d(TAG, "onSuccess: " + location.getLatitude());
Log.d(TAG, "onSuccess: " + location.getLongitude());
} else {
Log.d(TAG, "onSuccess: Location was null...");
}
}
});
locationTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "onFailure: " + e.getLocalizedMessage() );
}
});
}
private void askLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
Log.d(TAG, "askLocationPermission: you should show an alert dialog...");
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
} else {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == LOCATION_REQUEST_CODE) {
if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted
// getLastLocation();
checkSettingsAndStartLocationUpdates();
} else {
//Permission not granted
}
}
}
@Override
public void onBackPressed() {
//null
}
/* private void isLocationEnabled() {
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Enable Location");
alertDialog.setMessage("Your locations setting is not enabled. Please enabled it in settings menu.");
alertDialog.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = alertDialog.create();
alert.show();
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Confirm Location");
alertDialog.setMessage("Your Location is enabled, please enjoy");
alertDialog.setNegativeButton("Back to interface", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = alertDialog.create();
alert.show();
}
}*/
}
| true
|
a33a89b5233442ede7dd00524f0dc687fdc5acf2
|
Java
|
soarpatriot/com.soar.ax
|
/ax-web/src/main/java/com/soar/ax/controller/ovp/OrderController.java
|
UTF-8
| 770
| 2.03125
| 2
|
[] |
no_license
|
/**
*
*/
package com.soar.ax.controller.ovp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.soar.ax.client.Person;
import com.soar.ax.controller.BaseController;
import com.soar.ax.service.ovp.OrderService;
/**
* @author liuhb7
*
*/
@Controller
@RequestMapping("/order")
public class OrderController extends BaseController{
@Autowired
private OrderService orderService;
@RequestMapping(method = RequestMethod.GET)
public String create() {
Person p = new Person("132213",20);
orderService.saveToMongo(p);
return "redirect:/right";
}
}
| true
|
54b0a8e85c4011a142108c4d1c2855caccdd3ebe
|
Java
|
msaadq/face-flag
|
/app/src/main/java/com/faceflag/android/CheekFlagOverlay.java
|
UTF-8
| 9,146
| 2.484375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.faceflag.android;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.Log;
/**
* Created by usmankhan on 2/5/2016.
*/
public class CheekFlagOverlay {
private int CHEEK_OFFSET_RIGHT;
private int CHEEK_OFFSET_LEFT;
private double DEFAULT_CHEECK_OFFSET_RANGE=3.0;
private int DEFAULT_FACE_POSITION_IN_BACKGROUND_X=250;
private int DEFAULT_FACE_POSITION_IN_BACKGROUND_Y=350;
private int DEFAULT_FACE_RADIUS_IN_BACKGROUND=125;
private Bitmap backgroundImage;
private Bitmap originalImage;
private Bitmap flagImageLeft;
private Bitmap flagImageRight;
private Bitmap leftFlag;
private Bitmap rightFlag;
private int[] croppingMetrics;
private int[] cheeksLeftPos;
private int[] cheeksRightPos;
private int[] nosePos;
private int[] eyesLeftPos;
private int[] eyesRightPos;
private double eulerY;
private double eulerZ;
CheekFlagOverlay(Bitmap backgroundImage, Bitmap originalImage, Bitmap flagImageLeft,Bitmap flagImageRight, int[] cheeksLeftPos, int[] cheeksRightPos,
int[] nosePos,int[] eyesLeftPos, int[] eyesRightPos,Double eulerY,Double eulerZ,int[] croppingMetrics){
this.backgroundImage=backgroundImage;
this.originalImage = originalImage;
this.flagImageLeft=flagImageLeft;
this.flagImageRight=flagImageRight;
this.cheeksLeftPos = cheeksLeftPos;
this.cheeksRightPos = cheeksRightPos;
this.nosePos = nosePos;
this.eyesLeftPos = eyesLeftPos;
this.eyesRightPos = eyesRightPos;
this.eulerZ=-eulerZ;
this.croppingMetrics=croppingMetrics;
if(eulerY!=null) {
this.eulerY=eulerY;
CHEEK_OFFSET_LEFT = (int) ((originalImage.getWidth() / 480) * DEFAULT_CHEECK_OFFSET_RANGE
+
(eulerY * (Math.PI / 180) * (15 * DEFAULT_CHEECK_OFFSET_RANGE * (originalImage.getWidth() / 480))));
CHEEK_OFFSET_RIGHT = (int) ((originalImage.getWidth() / 480) * DEFAULT_CHEECK_OFFSET_RANGE
-
(eulerY * (Math.PI / 180) * (15 * DEFAULT_CHEECK_OFFSET_RANGE * (originalImage.getWidth() / 480))));
}else{
CHEEK_OFFSET_LEFT = (int) ((originalImage.getWidth() / 480) * DEFAULT_CHEECK_OFFSET_RANGE);
CHEEK_OFFSET_RIGHT = (int) ((originalImage.getWidth() / 480) * DEFAULT_CHEECK_OFFSET_RANGE);
}
this.cheeksLeftPos[0] = this.cheeksLeftPos[0] - CHEEK_OFFSET_LEFT;
this.cheeksRightPos[0] = this.cheeksRightPos[0] + CHEEK_OFFSET_RIGHT;
}
/**
*
* @return Flag Width & Flag Height
*/
public Bitmap tiltFlag(Bitmap flagImage, int tiltAngle){
Matrix matrix = new Matrix();
matrix.postRotate(tiltAngle);
return Bitmap.createBitmap(flagImage, 0, 0, flagImage.getWidth(),flagImage.getHeight(),
matrix,false);
}
public int[] getRequiredFlagSize(Bitmap flagImage){
int flagHeight;
int flagWidth;
flagHeight = -(eyesLeftPos[1]+eyesRightPos[1])/2 + (nosePos[1]);
flagWidth = (int)(flagImage.getWidth()*((double)flagHeight/flagImage.getHeight()));
Log.v("FlagHeight",String.valueOf(flagHeight));
Log.v("FlagWidth", String.valueOf(flagWidth));
return new int[] {flagHeight, flagWidth};
}
public Bitmap[] overlayFlag(){
Bitmap transparentBitmap = getTransparentBitmap(originalImage.getWidth(),
originalImage.getHeight());
int[] flagDestLeft = getRequiredFlagSize(flagImageLeft);
int[] flagDestRight = getRequiredFlagSize(flagImageRight);
Bitmap resizedFlagImageLeft = flagImageLeft.createScaledBitmap(flagImageLeft, flagDestLeft[0], flagDestLeft[1],
false);
Bitmap resizedFlagImageRight= flagImageRight.createScaledBitmap(flagImageRight, flagDestRight[0], flagDestRight[1],
false);
leftFlag = tiltFlag(resizedFlagImageLeft, (int) (-5 + eulerZ));
rightFlag = tiltFlag(resizedFlagImageRight, (int) (5+eulerZ));
// For flag overlay on left cheek
int xLeft1 = cheeksLeftPos[0] - flagDestLeft[0]/2;
int xRight1 = cheeksLeftPos[0]+flagDestLeft[0]/2;
int yTop1 = cheeksLeftPos[1] - flagDestLeft[1]/2;
int yBottom1 = cheeksLeftPos[1] + flagDestLeft[1]/2;
// For flag overlay on right cheek
int xLeft2 = cheeksRightPos[0] - flagDestRight[0]/2;
int xRight2 = cheeksRightPos[0]+flagDestRight[0]/2;
int yTop2 = cheeksRightPos[1] - flagDestRight[1]/2;
int yBottom2 = cheeksRightPos[1] + flagDestRight[1]/2;
for (int i=xLeft1;i<xRight1;i++){
for (int j = yTop1;j<yBottom1;j++){
transparentBitmap.setPixel(i,j,leftFlag.getPixel(i - xLeft1, j - yTop1));
}
}
for (int i=xLeft2;i<xRight2;i++){
for (int j = yTop2;j<yBottom2;j++){
transparentBitmap.setPixel(i,j,rightFlag.getPixel(i - xLeft2, j - yTop2));
}
}
Bitmap faceWithFlagsOnCheeks=overlay(originalImage, transparentBitmap);
Bitmap croppedBitmap = Bitmap.createBitmap(originalImage, croppingMetrics[0],
croppingMetrics[1] , croppingMetrics[2] , croppingMetrics[3] );
Log.v("Cropped width,hieght",croppedBitmap.getWidth()+" "+croppedBitmap.getHeight());
int croppingExtention= (int) ((double)(croppedBitmap.getWidth()*300)/(double)560);
if((faceWithFlagsOnCheeks.getWidth()-croppingExtention)>croppedBitmap.getWidth()&&
((faceWithFlagsOnCheeks.getHeight()-croppingExtention)>croppedBitmap.getHeight())
&&croppingMetrics[0]>croppingExtention&&croppingMetrics[1]>croppingExtention){
croppedBitmap = Bitmap.createBitmap(faceWithFlagsOnCheeks, croppingMetrics[0]-croppingExtention/2,
croppingMetrics[1]-croppingExtention/2, croppingMetrics[2] + croppingExtention, croppingMetrics[3] + croppingExtention);
}else{
croppedBitmap=originalImage;
}
Bitmap resizedFaceWithFlag=croppedBitmap;
if(croppedBitmap.getWidth()>croppedBitmap.getHeight()) {
resizedFaceWithFlag = flagImageLeft.createScaledBitmap(croppedBitmap, (int) (DEFAULT_FACE_RADIUS_IN_BACKGROUND *
2*((double)croppedBitmap.getWidth()/(double)croppedBitmap.getHeight())),
DEFAULT_FACE_RADIUS_IN_BACKGROUND * 2,
false);
}else {
resizedFaceWithFlag = flagImageLeft.createScaledBitmap(croppedBitmap, DEFAULT_FACE_RADIUS_IN_BACKGROUND * 2,
(int) (DEFAULT_FACE_RADIUS_IN_BACKGROUND * 2 * (double) ((double) croppedBitmap.getHeight() / (double) croppedBitmap.getWidth())),
false);
}
int widthOfFaceWithFlags=resizedFaceWithFlag.getWidth();
int heightOfFaceWithFlags=resizedFaceWithFlag.getHeight();
int faceLimitLeft=DEFAULT_FACE_POSITION_IN_BACKGROUND_X-DEFAULT_FACE_RADIUS_IN_BACKGROUND;
int faceLimitRight=DEFAULT_FACE_POSITION_IN_BACKGROUND_X+DEFAULT_FACE_RADIUS_IN_BACKGROUND;
int faceLimitTop=DEFAULT_FACE_POSITION_IN_BACKGROUND_Y-DEFAULT_FACE_RADIUS_IN_BACKGROUND;
int faceLimitBottom=DEFAULT_FACE_POSITION_IN_BACKGROUND_Y+DEFAULT_FACE_RADIUS_IN_BACKGROUND;
Bitmap transparentBitmap2=getTransparentBitmap(500,833);
for(int i=0; i<500; i++){
for(int j=0; j<833;j++){
if(isInsideEyeCircle(new int[]{i,j},DEFAULT_FACE_POSITION_IN_BACKGROUND_X,
DEFAULT_FACE_POSITION_IN_BACKGROUND_Y,DEFAULT_FACE_RADIUS_IN_BACKGROUND)){
transparentBitmap2.setPixel(i, j, resizedFaceWithFlag.getPixel(i - faceLimitLeft, j - faceLimitTop));
}else{
transparentBitmap2.setPixel(i,j,backgroundImage.getPixel(i,j));
}
}
}
return new Bitmap[]{faceWithFlagsOnCheeks,transparentBitmap2};
}
private Bitmap getTransparentBitmap(int xRes,int yRes){
Bitmap bmOverlay = Bitmap.createBitmap(xRes, yRes, Bitmap.Config.ARGB_4444);
Canvas canvas = new Canvas(bmOverlay);
Paint paint = new Paint();
paint.setAlpha(0);
canvas.drawBitmap(bmOverlay,new Matrix(),paint);
return bmOverlay;
}
private Bitmap overlay(Bitmap bmp1, Bitmap bmp2) {
Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
Canvas canvas = new Canvas(bmOverlay);
Paint paint = new Paint();
paint.setAlpha(150);
canvas.drawBitmap(bmp1, new Matrix(), null);
canvas.drawBitmap(bmp2, new Matrix(), paint);
return bmOverlay;
}
public boolean isInsideEyeCircle(int[] coordinates,int h,int k,int radius){
return (
radius>(Math.sqrt(Math.pow(coordinates[0]-h,2)+Math.pow(coordinates[1]-k,2)))
);
}
}
| true
|
080e71f6ad78b08b1beda21af872350248cad6df
|
Java
|
fanx-dev/fantom
|
/src/sys/java/fan/sys/Month.java
|
UTF-8
| 3,032
| 2.453125
| 2
|
[
"AFL-3.0"
] |
permissive
|
//
// Copyright (c) 2006, Brian Frank and Andy Frank
// Licensed under the Academic Free License version 3.0
//
// History:
// 19 Sep 06 Brian Frank Creation
//
package fan.sys;
/**
* Month
*/
public final class Month
extends Enum
{
public static final Month jan = new Month(0, "jan");
public static final Month feb = new Month(1, "feb");
public static final Month mar = new Month(2, "mar");
public static final Month apr = new Month(3, "apr");
public static final Month may = new Month(4, "may");
public static final Month jun = new Month(5, "jun");
public static final Month jul = new Month(6, "jul");
public static final Month aug = new Month(7, "aug");
public static final Month sep = new Month(8, "sep");
public static final Month oct = new Month(9, "oct");
public static final Month nov = new Month(10, "nov");
public static final Month dec = new Month(11, "dec");
static final Month[] array =
{
jan, feb, mar, apr, may, jun,
jul, aug, sep, oct, nov, dec
};
public static final List vals = (List)new List(Sys.MonthType, array).toImmutable();
public static Month fromOrdinal(int ord) { return array[ord]; }
private Month(int ordinal, String name)
{
Enum.make$(this, FanInt.pos[ordinal], name.intern());
this.ord = ordinal;
this.localeAbbrKey = name + "Abbr";
this.localeFullKey = name + "Full";
}
public static Month fromStr(String name) { return fromStr(name, true); }
public static Month fromStr(String name, boolean checked)
{
return (Month)doFromStr(Sys.MonthType, name, checked);
}
public Type typeof() { return Sys.MonthType; }
public Month increment() { return array[(ord+1)%array.length]; }
public Month decrement() { return ord == 0 ? array[array.length-1] : array[ord-1]; }
public long numDays(long year)
{
if (DateTime.isLeapYear((int)year))
return DateTime.daysInMonLeap[ord];
else
return DateTime.daysInMon[ord];
}
public String toLocale() { return toLocale(null, null); }
public String toLocale(String pattern) { return toLocale(pattern, null); }
public String toLocale(String pattern, Locale locale)
{
if (locale == null) locale = Locale.cur();
if (pattern == null) return abbr(locale);
if (FanStr.isEveryChar(pattern, 'M'))
{
switch (pattern.length())
{
case 1: return String.valueOf(ord+1);
case 2: return ord < 9 ? "0" + (ord+1) : String.valueOf(ord+1);
case 3: return abbr(locale);
case 4: return full(locale);
}
}
throw ArgErr.make("Invalid pattern: " + pattern);
}
public String localeAbbr() { return abbr(Locale.cur()); }
public String abbr(Locale locale)
{
return Env.cur().locale(Sys.sysPod, localeAbbrKey, name(), locale);
}
public String localeFull() { return full(Locale.cur()); }
public String full(Locale locale)
{
return Env.cur().locale(Sys.sysPod, localeFullKey, name(), locale);
}
final int ord;
final String localeAbbrKey;
final String localeFullKey;
}
| true
|
323b8b3bd039f2565fa6df45d7fd3994cff38e05
|
Java
|
chungeOrganization/aik
|
/aik-app/aik-common-service/src/main/java/com/aik/service/UserManageServiceImpl.java
|
UTF-8
| 4,124
| 2.3125
| 2
|
[] |
no_license
|
package com.aik.service;
import com.aik.dao.AccUserAccountMapper;
import com.aik.model.AccUserAccount;
import com.aik.util.MD5Utils;
import com.aik.util.PageUtils;
import com.aik.vo.AccUserAccountVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* Description: 用户管理服务
* Created by as on 2017/8/6.
*/
@Service
public class UserManageServiceImpl implements UserManageService {
private static final Logger logger = LoggerFactory.getLogger(UserManageServiceImpl.class);
private AccUserAccountMapper accUserAccountMapper;
@Autowired
public void setAccUserAccountMapper(AccUserAccountMapper accUserAccountMapper) {
this.accUserAccountMapper = accUserAccountMapper;
}
@Override
public AccUserAccount findByPrimaryKey(Integer id) throws Exception {
if (null == id) {
logger.error("用户查询,根据主键查询,主键为空");
throw new Exception("用户查询,根据主键查询,主键为空");
}
return accUserAccountMapper.selectByPrimaryKey(id);
}
@Override
public void deleteByPrimaryKey(Integer id) throws Exception {
if (null == id) {
logger.error("用户删除,根据主键删除,主键为空");
throw new Exception("用户删除,根据主键删除,主键为空");
}
accUserAccountMapper.deleteByPrimaryKey(id);
}
@Override
public void save(AccUserAccount accUserAccount) throws Exception {
if (null == accUserAccount) {
logger.error("用户保存,根据对象保存,对象为空");
throw new Exception("用户保存,根据对象保存,对象为空");
}
//密码MD5加密
String passWord = accUserAccount.getPassword();
accUserAccount.setPassword(MD5Utils.md5(passWord));
accUserAccount.setCreateDate(new Date());
accUserAccountMapper.insert(accUserAccount);
}
@Override
public void update(AccUserAccount accUserAccount) throws Exception {
if (null == accUserAccount || null == accUserAccount.getId()) {
logger.error("用户修改,根据对象修改,对象为空");
throw new Exception("用户修改,根据对象修改,对象为空");
}
AccUserAccount userAccountOld = new AccUserAccount();
userAccountOld = accUserAccountMapper.selectByPrimaryKey(accUserAccount.getId());
//userAccount.setId(userInfoDTO.getAccountId());
userAccountOld.setHeadImg(accUserAccount.getHeadImg());
userAccountOld.setNickName(accUserAccount.getNickName());
userAccountOld.setSex(accUserAccount.getSex());
userAccountOld.setBirthday(accUserAccount.getBirthday());
userAccountOld.setAreaProvince(accUserAccount.getAreaProvince());
userAccountOld.setAreaCity(accUserAccount.getAreaCity());
userAccountOld.setIsElseIllness(accUserAccount.getIsElseIllness());
userAccountOld.setUpdateDate(new Date());
userAccountOld.setDeleteStatus(accUserAccount.getDeleteStatus());
accUserAccountMapper.updateByPrimaryKeySelective(userAccountOld);
}
@Override
public Page<AccUserAccount> findPage(AccUserAccountVo accUserAccountVo, PageUtils pgeUtils) throws Exception {
PageHelper.startPage(pgeUtils.getPage(), pgeUtils.getSize());
return accUserAccountMapper.findByPage(accUserAccountVo);
}
@Override
public List<AccUserAccount> findAll(AccUserAccount accUserAccount)
throws Exception {
return accUserAccountMapper.findAll(accUserAccount);
}
@Override
public AccUserAccount selectByUserName(String userName) throws Exception {
if (null == userName || "".equals(userName)) {
logger.error("用户查询,根据用户名,用户名为空");
throw new Exception("用户查询,根据用户名,用户为空");
}
AccUserAccount accUserAccount = accUserAccountMapper.selectByUserName(userName);
return accUserAccount;
}
}
| true
|
939f8d4d9e1e68b0b2c992cb987837e07237cd89
|
Java
|
P8P-7/android-app
|
/app/src/main/java/nl/team_goliath/app/model/MessageFormatter.java
|
UTF-8
| 174
| 1.859375
| 2
|
[
"MIT"
] |
permissive
|
package nl.team_goliath.app.model;
import com.google.protobuf.Message;
import java.util.List;
public interface MessageFormatter<T> {
List<T> format(Message message);
}
| true
|
5e7cf9dc926917d686b2da4a02b8b9dafdd33c8a
|
Java
|
sunilkoni/practice-algorithms
|
/src/com/data/trees/Node.java
|
UTF-8
| 242
| 2.671875
| 3
|
[] |
no_license
|
package com.data.trees;
public class Node{
int data;
int hd;
Node left=null;
Node right=null;
Node(int data)
{
this.data=data;
}
@Override
public String toString() {
return "Node [data=" + data + ", hd=" + hd + "]";
}
}
| true
|
46a2cde126bd944b35267bfa6a1bca405357ad3e
|
Java
|
zhengyouxiang/yihaodian_android
|
/src/com/thoughtworks/xstream/io/xml/xppdom/Xpp3Dom.java
|
UTF-8
| 2,870
| 2.265625
| 2
|
[] |
no_license
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
package com.thoughtworks.xstream.io.xml.xppdom;
import java.util.*;
public class Xpp3Dom
{
public Xpp3Dom(String s)
{
name = s;
childList = new ArrayList();
childMap = new HashMap();
}
public void addChild(Xpp3Dom xpp3dom)
{
xpp3dom.setParent(this);
childList.add(xpp3dom);
childMap.put(xpp3dom.getName(), xpp3dom);
}
public String getAttribute(String s)
{
String s1;
if(attributes != null)
s1 = (String)attributes.get(s);
else
s1 = null;
return s1;
}
public String[] getAttributeNames()
{
String as[];
if(attributes == null)
as = new String[0];
else
as = (String[])attributes.keySet().toArray(new String[0]);
return as;
}
public Xpp3Dom getChild(int i)
{
return (Xpp3Dom)childList.get(i);
}
public Xpp3Dom getChild(String s)
{
return (Xpp3Dom)childMap.get(s);
}
public int getChildCount()
{
int i;
if(childList == null)
i = 0;
else
i = childList.size();
return i;
}
public Xpp3Dom[] getChildren()
{
Xpp3Dom axpp3dom[];
if(childList == null)
axpp3dom = new Xpp3Dom[0];
else
axpp3dom = (Xpp3Dom[])childList.toArray(new Xpp3Dom[0]);
return axpp3dom;
}
public Xpp3Dom[] getChildren(String s)
{
Xpp3Dom axpp3dom[];
if(childList == null)
{
axpp3dom = new Xpp3Dom[0];
} else
{
ArrayList arraylist = new ArrayList();
int i = childList.size();
for(int j = 0; j < i; j++)
{
Xpp3Dom xpp3dom = (Xpp3Dom)childList.get(j);
if(s.equals(xpp3dom.getName()))
arraylist.add(xpp3dom);
}
axpp3dom = (Xpp3Dom[])arraylist.toArray(new Xpp3Dom[0]);
}
return axpp3dom;
}
public String getName()
{
return name;
}
public Xpp3Dom getParent()
{
return parent;
}
public String getValue()
{
return value;
}
public void setAttribute(String s, String s1)
{
if(attributes == null)
attributes = new HashMap();
attributes.put(s, s1);
}
public void setParent(Xpp3Dom xpp3dom)
{
parent = xpp3dom;
}
public void setValue(String s)
{
value = s;
}
protected Map attributes;
protected List childList;
protected Map childMap;
protected String name;
protected Xpp3Dom parent;
protected String value;
}
| true
|
834852296a655b1bd3acb96340fd298d4acf3916
|
Java
|
hongquan16101995/Demo-Crud-Md4
|
/src/main/java/service/impl/CustomerServiceImpl.java
|
UTF-8
| 1,086
| 2.34375
| 2
|
[] |
no_license
|
package service.impl;
import model.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import repository.ICustomerRepository;
import service.CustomerService;
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
public ICustomerRepository iCustomerRepository;
@Override
public Page<Customer> findAll(Pageable pageable) {
return iCustomerRepository.findAll(pageable);
}
@Override
public Customer findById(int id) {
return iCustomerRepository.findOne(id);
}
@Override
public void save(Customer customer) {
iCustomerRepository.save(customer);
}
@Override
public void remove(int id) {
iCustomerRepository.delete(id);
}
@Override
public Page<Customer> findAllByLastNameContaining(String name, Pageable pageable) {
return iCustomerRepository.findAllByNameContaining(name, pageable);
}
}
| true
|