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
1634301449bd364299d5a9b8752aa999afe02539
Java
alex-estela/peerframe
/src/main/java/fr/estela/peerframe/device/entity/SmugmugProviderEntity.java
UTF-8
1,731
2.03125
2
[ "MIT" ]
permissive
package fr.estela.peerframe.device.entity; import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import fr.estela.peerframe.device.service.AbstractDownloadManager; import fr.estela.peerframe.device.service.SmugmugDownloadManager; @Entity @DiscriminatorValue("SmugmugProvider") public class SmugmugProviderEntity extends ProviderEntity { private String albumId; @Column(name="clientId") private String consumerKey; @Column(name="clientSecret") private String consumerSecret; private String accessToken; private String accessTokenSecret; public String getAlbumId() { return albumId; } public void setAlbumId(String albumId) { this.albumId = albumId; } public String getConsumerKey() { return consumerKey; } public void setConsumerKey(String consumerKey) { this.consumerKey = consumerKey; } public String getConsumerSecret() { return consumerSecret; } public void setConsumerSecret(String consumerSecret) { this.consumerSecret = consumerSecret; } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public String getAccessTokenSecret() { return accessTokenSecret; } public void setAccessTokenSecret(String accessTokenSecret) { this.accessTokenSecret = accessTokenSecret; } public AbstractDownloadManager getDownloadManagerInstance() throws Exception { return new SmugmugDownloadManager(); } }
true
5da00439d3a890bb414a1ac621c4076abdd3ba49
Java
zhangle05/PuzzleMaster
/app/src/main/java/master/sudoku/widgets/WidgetBase.java
UTF-8
1,063
2.4375
2
[]
no_license
/** * */ package master.sudoku.widgets; import android.graphics.Canvas; import android.graphics.Rect; import java.util.Vector; import master.sudoku.event.EventSource; import master.sudoku.shapes.ShapeBase; import master.sudoku.views.ViewBase; /** * @author dannyzha * */ public abstract class WidgetBase extends EventSource { protected ViewBase mParentView; protected Vector<ShapeBase> mFixedShapes = new Vector<ShapeBase>(); protected Rect mBound; /** * Constructor * @param parent */ public WidgetBase(ViewBase parent) { this.mParentView = parent; } public void setBound(Rect rect) { this.mBound = rect; } public Rect getBound() { return mBound; } abstract public void paint(Canvas canvas); abstract public boolean onTap(int x, int y); abstract public boolean onPointerPressed(int x, int y); abstract public boolean onPointerReleased(int x, int y); abstract public boolean onKeyEvent(int key); }
true
7398e005902e2afaaf21316c46ae4ac1315139d2
Java
SiarheiBialtsou/JavaLearn
/task02/Task02.java
UTF-8
1,363
3.625
4
[]
no_license
/* №2. Вычислить значение выражения по формуле (все переменные принимают * действительные знвчения): z = ((b + sqrt(b*b+4*a*c)/2/a - a*a*a*c + 1/b/b); */ package by.java.training.task02; /** * @author Siarhei Bialtsou */ import java.util.Scanner; public class Task02 { public static void main(String[] args) { double a; double b; double c; double z; /** * a = 5.1; b = 13; c = 2; hardcore data; */ Scanner sc = new Scanner(System.in); System.out.println("Write basic data:"); System.out.print("Write a>"); while (!sc.hasNextDouble()) { sc.next(); System.out.print("WRITE a>"); } a = sc.nextDouble(); System.out.print("Write b>"); while (!sc.hasNextDouble()) { sc.next(); System.out.print("WRITE b>"); } b = sc.nextDouble(); System.out.print("Write c>"); while (!sc.hasNextDouble()) { sc.next(); System.out.print("WRITE c>"); } c = sc.nextDouble(); sc.close(); z = (b + Math.sqrt(b * b + 4 * a * c)) / 2 / a - a * a * a * c + 1 / (b * b); System.out.print("Result equals > z = " + z); } }
true
e95e8b31209bbe664177ab1ddc24585670f013d5
Java
kdvolder/tyRuBa
/src/tyRuBa/engine/visitor/CollectTemplateVarsVisitor.java
UTF-8
1,884
2.1875
2
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package tyRuBa.engine.visitor; import java.util.HashSet; import tyRuBa.engine.RBCountAll; import tyRuBa.engine.RBDisjunction; import tyRuBa.engine.RBExistsQuantifier; import tyRuBa.engine.RBFindAll; import tyRuBa.engine.RBIgnoredVariable; import tyRuBa.engine.RBNotFilter; import tyRuBa.engine.RBTemplateVar; import tyRuBa.engine.RBTestFilter; import tyRuBa.engine.RBUniqueQuantifier; import tyRuBa.engine.RBVariable; import tyRuBa.modes.TypeModeError; public class CollectTemplateVarsVisitor extends AbstractCollectVarsVisitor { public CollectTemplateVarsVisitor() { super(new HashSet(), null); } public Object visit(RBDisjunction disjunction) throws TypeModeError { for (int i = 0; i < disjunction.getNumSubexps(); i++) { disjunction.getSubexp(i).accept(this); } return null; } public Object visit(RBExistsQuantifier exists) throws TypeModeError { exists.getExp().accept(this); return null; } public Object visit(RBFindAll findAll) throws TypeModeError { findAll.getQuery().accept(this); findAll.getResult().accept(this); findAll.getExtract().accept(this); return null; } public Object visit(RBCountAll count) throws TypeModeError { count.getQuery().accept(this); count.getResult().accept(this); count.getExtract().accept(this); return null; } public Object visit(RBNotFilter notFilter) throws TypeModeError { notFilter.getNegatedQuery().accept(this); return null; } public Object visit(RBTestFilter testFilter) throws TypeModeError { testFilter.getQuery().accept(this); return null; } public Object visit(RBUniqueQuantifier unique) throws TypeModeError { unique.getExp().accept(this); return null; } public Object visit(RBIgnoredVariable ignoredVar) { return null; } public Object visit(RBVariable var) { return null; } public Object visit(RBTemplateVar var) { vars.add(var); return null; } }
true
4eff58529d2e6b3dc9ef14d77ecb9a8d84c505c3
Java
JinlongLiao/easy-tools
/commons/commons-common/src/test/java/io/github/jinlonghliao/common/core/date/TimeZoneTest.java
UTF-8
1,309
2.390625
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2020-2021 JinlongLiao * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.jinlonghliao.common.core.date; import java.util.TimeZone; import org.junit.Assert; import org.junit.Test; import io.github.jinlonghliao.common.core.date.format.FastDateFormat; public class TimeZoneTest { @Test public void timeZoneConvertTest() { DateTime dt = DateUtil.parse("2018-07-10 21:44:32", // FastDateFormat.getInstance(DatePattern.NORM_DATETIME_PATTERN, TimeZone.getTimeZone("GMT+8:00"))); Assert.assertEquals("2018-07-10 21:44:32", dt.toString()); dt.setTimeZone(TimeZone.getTimeZone("Europe/London")); int hour = dt.getField(DateField.HOUR_OF_DAY); Assert.assertEquals(14, hour); Assert.assertEquals("2018-07-10 14:44:32", dt.toString()); } }
true
bc0de1e6c8aff1a5cb8d882126b600c49d504bd2
Java
coelhae/flickrized
/app/src/main/java/pt/alex/flickrized/data/DataHelper.java
UTF-8
847
2.265625
2
[]
no_license
package pt.alex.flickrized.data; import com.googlecode.flickrjandroid.photos.PhotoList; /** * Created by nb19875 on 24/06/16. */ public class DataHelper { /*** * Data que é consistente e deve ser assevivel em todas as actividades. * Definir como singleton para facil acesso. */ private static DataHelper instance; private DataHelper() { photos = new PhotoList(); } public static DataHelper of(){ if(instance == null){ instance = new DataHelper(); } return instance; } // vars private PhotoList photos ; /** TODO: add realm DB objects */ // fazer peristencia em bd para maior rapidez public PhotoList getPhotos() { return photos; } public void setPhotos(PhotoList photos) { this.photos = photos; } }
true
9792a2532920c4bc3bf9c2dcf531f024f2295059
Java
rewritehackathon/tech-miners
/src/main/java/com/hackathon/tech_miners/controllers/SendMerchantSelectionController.java
UTF-8
770
2.171875
2
[ "MIT" ]
permissive
package com.hackathon.tech_miners.controllers; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.hackathon.tech_miners.beans.MerchantInfo; @RestController public class SendMerchantSelectionController { @RequestMapping("/sendMerchantInfo/{merchantName}") public MerchantInfo greeting(@PathVariable String merchantName) { //This hardcoded data is going to be replaced by actual data that the merchant/small business owner (that is using the app to get insurance coverage) enters in the app. return new MerchantInfo(merchantName, "Bakery", "AZ", 85027, 10, 100000, "03/01/2019", "Scottsdale"); } }
true
cd7be84848f6eec213a9c3137b0fcf7a3e7a691c
Java
AAEfremov/VkRestApi
/src/main/java/core/VkApiGetCitiesMethod.java
UTF-8
3,765
2.125
2
[]
no_license
package core; import beans.VkGetCitiesAnswer; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import io.restassured.RestAssured; import io.restassured.builder.RequestSpecBuilder; import io.restassured.builder.ResponseSpecBuilder; import io.restassured.http.ContentType; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; import io.restassured.specification.ResponseSpecification; import org.apache.http.HttpStatus; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Random; import static core.VkMethodsConstants.*; import static org.hamcrest.Matchers.lessThan; public class VkApiGetCitiesMethod { private VkApiGetCitiesMethod() { } //Vk Api methods parameters private HashMap<String,String> params = new HashMap<>(); //Builder class for GetCities method public static class CitiesApiBuilder { VkApiGetCitiesMethod getCitiesApi; private CitiesApiBuilder(VkApiGetCitiesMethod gcApi){ getCitiesApi = gcApi; } public CitiesApiBuilder country_id(Integer country_id){ getCitiesApi.params.put(PARAM_COUNTRY_ID, String.valueOf(country_id)); return this; } public CitiesApiBuilder region_id(Integer region_id){ getCitiesApi.params.put(PARAM_REGION_ID, String.valueOf(region_id)); return this; } public CitiesApiBuilder search_query(String query){ getCitiesApi.params.put(PARAM_SEARCH_QUERY, query); return this; } public CitiesApiBuilder need_all(Integer flag){ getCitiesApi.params.put(PARAM_NEED_ALL, String.valueOf(flag)); return this; } public CitiesApiBuilder offset(Integer offset){ getCitiesApi.params.put(PARAM_OFFSET, String.valueOf(offset)); return this; } public CitiesApiBuilder count(Integer count){ getCitiesApi.params.put(PARAM_COUNT, String.valueOf(count)); return this; } public CitiesApiBuilder version(String version) { getCitiesApi.params.put(PARAM_VERSION, version); return this; } public Response callApi(){ return RestAssured.with() .queryParams(getCitiesApi.params) .log().all() .get(VK_API_CITIES_URI).prettyPeek(); } } //Builder constructor for GetCities method public static CitiesApiBuilder with() { VkApiGetCitiesMethod api = new VkApiGetCitiesMethod(); return new CitiesApiBuilder(api); } //set base request and response specifications to use in tests public static ResponseSpecification successResponse(){ return new ResponseSpecBuilder() .expectContentType(ContentType.JSON) .expectResponseTime(lessThan(10000L)) .expectStatusCode(HttpStatus.SC_OK) .build(); } public static RequestSpecification baseRequestConfiguration(String url){ return new RequestSpecBuilder() .setAccept(ContentType.XML) .setBaseUri(url) .build(); } public static List<VkGetCitiesAnswer> getVkGetCitiesAnswers(Response response) { String responseStr = response.print(); int beginIndex = responseStr.indexOf("{", 13); int endIndex = responseStr.lastIndexOf("]"); String jsonStr = "[" + responseStr.substring(beginIndex, endIndex) + "]"; Type listType = new TypeToken<List<VkGetCitiesAnswer>>() { }.getType(); return new Gson().fromJson(jsonStr, listType); } }
true
9668d3de853129943aa1c881c814d353dcb0bd9d
Java
shl4sg/Blog
/src/com/servlet/IndexServlet.java
UTF-8
2,258
2.265625
2
[]
no_license
package com.servlet; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.dao.ArticleDao; import com.dao.UserDao; import com.toolsBean.Change; import com.valueBean.UserSingle; @SuppressWarnings("serial") public class IndexServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { doPost(request,response); } @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { request.setAttribute("mainPage",getInitParameter("defaultPage")); String forward=""; HttpSession session=request.getSession(); int userid=Change.strToInt(request.getParameter("master")); UserSingle logoner=(UserSingle)session.getAttribute("logoner"); if(null!=logoner){ session.setAttribute("logoner",logoner); if(userid==logoner.getId()){ request.setAttribute("isSelf","1"); }else{ request.setAttribute("isSelf","0"); } } try{ // 获取最新的文章前10条 List newArticlelist = new ArrayList(); ArticleDao articleDao = new ArticleDao(); newArticlelist = articleDao.getNewArticle(); request.setAttribute("newArticlelist", newArticlelist); // 获取点击排行的文章前10条 List mostArticlelist = new ArrayList(); mostArticlelist = articleDao.getMostArticle(); request.setAttribute("mostArticlelist", mostArticlelist); /* 获取右侧栏位置上的点击率排行前10名的博客 */ UserDao userDao = new UserDao(); List toplist = userDao.getTopList(); session.setAttribute("toplist", toplist); forward = getInitParameter("index"); }catch(Exception e){ forward=this.getServletContext().getInitParameter("messagePage"); System.out.println("'获取首页信息错误!"); e.printStackTrace(); } RequestDispatcher rd=request.getRequestDispatcher(forward); rd.forward(request,response); } }
true
40e4a91490608210e015316ff0735a3159edeb91
Java
luolinyin/MilkTea
/app/src/main/java/com/xiaozhi/frame/main/view/SetTickeyView.java
UTF-8
911
1.960938
2
[]
no_license
package com.xiaozhi.frame.main.view; import android.content.Context; import android.view.View; import android.view.ViewGroup; import com.xiaozhi.frame.main.R; import com.xiaozhi.frame.mvp.v.view.BaseView; /** * Created by Fynner on 2017/1/1. * 账户信息视图 */ public class SetTickeyView extends BaseView { private Context context; private View view; public SetTickeyView(Context context) { super(context); this.context=context; } @Override public View initGroupView() { view=View.inflate(context, R.layout.view_ticket_set,null); view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); return view; } @Override public void initView() { } @Override public void initData() { } @Override public void initListenner() { } }
true
78605bcc5e07044482e1d95199a88f14ab919add
Java
brownry1986/CleenSweeper
/HardwareInterface/src/main/java/com/sweeper/hardware/interfaces/MovementApparatus.java
UTF-8
178
1.992188
2
[]
no_license
package com.sweeper.hardware.interfaces; public interface MovementApparatus { void moveLeft(); void moveRight(); void moveForward(); void moveBackward(); }
true
8fb6fa92473aafd6545f657dee780305dfd07550
Java
power-coders/javatrack-cmdhandler
/src/StreamExercises/Exercise2.java
UTF-8
560
3.71875
4
[]
no_license
package StreamExercises; import java.util.Arrays; import java.util.List; /** * Created by joris on 19.01.17. */ /* Given is a list of the following Strings: "adam", "anna", "eva". Print the first string names if any. Use streams in combination with stream operations to solve the problem. Output is: adam */ public class Exercise2 { public static void main(String[] args) { List<String> mylist = Arrays.asList("adam","adam","eva"); mylist.stream() .findFirst() .ifPresent(System.out::println); } }
true
bb33ddfba46aba5eff5601e5d6a08d93ea44c3be
Java
HlubyLuk/Euler_java
/src/main/java/cz/hlubyluk/euler/problems/Problem31.java
UTF-8
732
3.546875
4
[]
no_license
package cz.hlubyluk.euler.problems; import cz.hlubyluk.euler.solvers.SolverKnapsack; /** * * * In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation: * * 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). * * It is possible to make £2 in the following way: * * 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p * * How many different ways can £2 be made using any number of coins? * * Created by HlubyLuk on 12/11/2016. */ public class Problem31 extends Problem{ @Override public Number solve() { int target = 200; int[] values = {1, 2, 5, 10, 20, 50, 100, 200}; return new SolverKnapsack(target, values).solve(); } }
true
28ddeae17dd52efd0d4dd67cda92add64d9fc639
Java
ingridc/WhereOnEarthIsRickyFortAndroidGrupo9
/app/src/main/java/com/example/gaston/rickyapp/CarmenSanDiegoService.java
UTF-8
1,108
1.953125
2
[]
no_license
package com.example.gaston.rickyapp; import com.example.gaston.rickyapp.model.Caso; import com.example.gaston.rickyapp.model.PistaAdapter; import com.example.gaston.rickyapp.model.Villano; import com.example.gaston.rickyapp.model.Lugar; import retrofit.Callback; import retrofit.http.Body; import retrofit.http.GET; import retrofit.http.POST; import java.util.List; import javax.xml.transform.Result; public interface CarmenSanDiegoService { @GET("/villanos") void getVillanos(Callback<List<Villano>> callback); @POST("/iniciarjuego") void iniciarJuego(Callback<Caso> callback); @POST("/viajar/{PaisId}") void viajarAPais(@retrofit.http.Path("PaisId") int id, Callback<Caso> callback); @GET("/pistaDelLugar/{Lugar}/{casoId}") void darPista(@retrofit.http.Path(value="Lugar" ,encode= false) String lugar, @retrofit.http.Path("casoId") int id, Callback<PistaAdapter> callback); @POST("/emitirOrdenPara/{VillanoId}/{CasoId}") void emitirOrden(@retrofit.http.Path("VillanoId") int villanoId, @retrofit.http.Path("CasoId") int id, Callback<Result> callback); }
true
d6cff987e7008227f16103114edce7da5bdd4f44
Java
NoorMohamme/firstassi
/Assignement/src/test/java/Assignment1Tests.java
UTF-8
1,115
2.8125
3
[]
no_license
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileSystemUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * @author STUDENT_NAME //TODO * */ public class Assignment1Tests { /** * This will prepare the environment to run all tests */ @BeforeClass public static void initialSetup() { System.out.println("Initialising the start running the tests tests "); } /** * This will test ..... */ @Test public void test1() { System.out.println("running test1"); } /** * This will test the free space * @throws IOException */ @Test public void test9() throws IOException { int sizeInMB = (int) (FileSystemUtils.freeSpaceKb("C:") / 1024); int sizeInKB = (int) FileSystemUtils.freeSpaceKb("C:"); assertEquals(sizeInKB / 1024, sizeInMB); } /** * This will test making a directory */ @Test public void test10() { File file = new File("my Folder"); boolean isCreated = file.mkdir(); assertTrue(isCreated); } }
true
06c58f054c4fda4769a46f620178b5c2a60e8f70
Java
d391/UBB-Advanced-Methods-of-Programming
/ToyLanguageInterpreter/src/model/expressions/VarExp.java
UTF-8
659
2.390625
2
[]
no_license
package model.expressions; import model.adt.Heap; import model.type.Type; import model.value.Value; import model.MyException; import model.adt.MyIDictionary; public class VarExp implements Exp { private String id; public VarExp(String _id) {id = _id;} @Override public String toString() { return id; } @Override public Value eval(MyIDictionary<String, Value> tbl, Heap<Integer, Value> hp) throws MyException { return tbl.lookup(id); } @Override public Type typecheck(MyIDictionary<String, Type> typeEnv) throws MyException { return typeEnv.lookup(id); } }
true
e224c5f61808b704e16d54a07733ffc852056f5b
Java
B3tah3/DSA
/Tests/graphs/GraphTest.java
UTF-8
1,571
3.015625
3
[]
no_license
package graphs; import static org.junit.Assert.assertEquals; import org.junit.Test; public class GraphTest { @Test(expected = IllegalArgumentException.class) public void depthFirstSearchNoPath() { int[][] k = { { 0, 1 } }; Graph g = new Graph(k); g.depthFirstSearch(1, 0); } @Test(expected = IllegalArgumentException.class) public void depthFirstSearchTestWrongParameters() { int[][] k = { { 0, 1 } }; Graph g = new Graph(k); g.depthFirstSearch(0, 2); } @Test public void depthFirstSearchTest() { int[][] k = { { 0, 1 }, { 1, 0 }, { 0, 3 }, { 1, 3 }, { 3, 4 }, { 4, 2 }, { 2, 4 }, { 2, 2 } }; Graph g = new Graph(k); int[] expected = { 0, 3 }; int[] path = g.depthFirstSearch(0, 3); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], path[i]); } } @Test(expected = IllegalArgumentException.class) public void topolySortTestCycle() { int[][] k = { { 0, 1 }, { 1, 0 }, { 0, 3 }, { 1, 3 }, { 3, 4 }, { 4, 2 }, { 2, 4 }, { 2, 2 } }; Graph g = new Graph(k); g.topologySort(); } @Test public void topolySortTest1() { int[][] k = { { 0, 1 }, { 0, 2 }, { 2, 1 } }; Graph g = new Graph(k); System.out.println(g.topologySort()); } @Test public void topolySortTest2() { int[][] k = { { 0, 1 }, { 0, 2 }, { 2, 1 }, { 2, 3 }, { 3, 4 }, { 3, 5 } }; Graph g = new Graph(k); System.out.println(g.topologySort()); } @Test public void topolySortTest3() { int[][] k = { { 0, 1 }, { 0, 2 }, { 2, 1 }, { 4, 5 } }; Graph g = new Graph(k); System.out.println(g.topologySort()); } }
true
065320f46ff685ff58fae03b245ee8cfe835ebcb
Java
cha63506/CompSecurity
/Entertainment/youtube_kids_source/src/crk.java
UTF-8
5,510
1.804688
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc import android.net.Uri; import android.text.TextUtils; import java.text.ParseException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; public final class crk { public final List a; public crk(String s, Map map, int i) { this(Collections.singletonList(s), map, i); } public crk(List list, Map map, int i) { a = Collections.unmodifiableList((List)b.b(list, "videoIds can not be null")); boolean flag; if (!a.isEmpty()) { flag = true; } else { flag = false; } b.a(flag, "videoIds cannot be empty"); Collections.unmodifiableMap((Map)b.b(map, "params can not be null")); } public static int a(Uri uri, Map map) { String s = (String)map.get("t"); map = s; if (s == null) { uri = Uri.decode(uri.getEncodedFragment()); map = s; if (!TextUtils.isEmpty(uri)) { String as1[] = uri.split("&"); int j = as1.length; int i = 0; uri = s; do { map = uri; if (i >= j) { break; } String as[] = as1[i].split("="); map = uri; if (as.length == 2) { map = uri; if ("t".equals(as[0])) { map = as[1]; } } i++; uri = map; } while (true); } } return a(((String) (map))); } public static int a(String s) { if (s == null) { return 0; } int j = s.indexOf("h"); String s1; int i; int k; if (j >= 0) { i = a.b(s.substring(0, j), 0) * 0x36ee80 + 0; s1 = s.substring(j + 1); } else { i = 0; s1 = s; } k = s1.indexOf("m"); j = i; s = s1; if (k >= 0) { j = i + a.b(s1.substring(0, k), 0) * 60000; s = s1.substring(k + 1); } s1 = s; if (s.endsWith("s")) { s1 = s.substring(0, s.length() - 1); } return (int)(a.a(s1, 0.0F) * 1000F) + j; } public static Map a(Uri uri) { if (uri.isOpaque()) { return Collections.emptyMap(); } HashMap hashmap = new HashMap(); String s; for (Iterator iterator = uri.getQueryParameterNames().iterator(); iterator.hasNext(); hashmap.put(s, uri.getQueryParameter(s))) { s = (String)iterator.next(); } return hashmap; } public static Map a(Map map) { map = new HashMap(map); map.remove("v"); map.remove("video_id"); map.remove("video_ids"); map.remove("feature"); return map; } public static crk b(Uri uri) { Map map = a(uri); String s = (String)map.get("v"); String s2 = (String)map.get("video_ids"); Object obj = s; if (TextUtils.isEmpty(s)) { obj = s; if (TextUtils.isEmpty(s2)) { obj = uri.getPathSegments(); int i = ((List) (obj)).indexOf("watch"); if (i < 0) { uri = String.valueOf(uri); throw new ParseException((new StringBuilder(String.valueOf(uri).length() + 28)).append("No /watch/ part in the Uri: ").append(uri).toString(), 0); } if (i + 1 >= ((List) (obj)).size()) { uri = String.valueOf(uri); throw new ParseException((new StringBuilder(String.valueOf(uri).length() + 24)).append("No id found in the Uri: ").append(uri).toString(), 0); } String s1 = (String)((List) (obj)).get(i + 1); obj = s1; if (TextUtils.isEmpty(s1)) { uri = String.valueOf(uri); throw new ParseException((new StringBuilder(String.valueOf(uri).length() + 24)).append("No video id in the Uri: ").append(uri).toString(), 0); } } } if (s2 == null) { return new crk(((String) (obj)), a(map), a(uri, map)); } else { return new crk(Arrays.asList(s2.split(",")), a(map), a(uri, map)); } } public static crk c(Uri uri) { uri = uri.getLastPathSegment().split("&"); String s = uri[0]; HashMap hashmap = new HashMap(); for (int i = 1; i < uri.length; i++) { String as[] = uri[i].split("="); if (as.length == 2) { hashmap.put(as[0], as[1]); } } return new crk(s, hashmap, a((String)hashmap.get("start"))); } }
true
87dfba4aa879f565523295b455bf013031f04dcf
Java
metroliu/NewBalanceServer
/src/com/newbalance/rickie/services/UserServiceImp.java
GB18030
2,501
2.40625
2
[]
no_license
package com.newbalance.rickie.services; import java.sql.SQLException; import javax.management.RuntimeErrorException; import com.newbalance.rickie.dao.UserDao; import com.newbalance.rickie.dao.UserDaoImp; import com.newbalance.rickie.utils.Macro; import com.newbalance.rickie.vo.UserVO; public class UserServiceImp implements UserService { public void signIn( UserVO userVO ) { try{ UserDao dao = new UserDaoImp(); dao.insertUser(userVO); } catch( SQLException e ){ throw new RuntimeException( Macro.CODE_SYSERROE ); } catch( RuntimeException e ){ throw new RuntimeException( Macro.CODE_ACCOUNT_ALREADY_EXIST ); } } public UserVO login(String user_name, String user_password) { UserVO userVO = new UserVO(); try{ //ݷʲѯ UserDao dao = new UserDaoImp(); userVO = dao.queryByUserName(user_name); if( userVO == null ){ throw new RuntimeException(Macro.CODE_ACCOUNT_NOT_EXIST); } if( !user_password.equals( userVO.getUser_password() ) ){ throw new RuntimeException(Macro.CODE_WRONG_PASSWORD); } }catch( SQLException e ){ // daoqueryByUserName׳ݿ쳣 throw new RuntimeException(Macro.CODE_SYSERROE); } return userVO; } public void modifyUserInfo(int user_id, String user_nickname, int user_sex, String user_birthday, int user_city_id ){ try{ UserDao dao = new UserDaoImp(); dao.modifyUserInfoById(user_id, user_nickname, user_sex, user_birthday, user_city_id); } catch( SQLException e ){ throw new RuntimeException( Macro.CODE_SYSERROE ); } } public String getSecuQuestion( String user_name ){ String user_secu_question = ""; try{ UserDao dao = new UserDaoImp(); user_secu_question = dao.getSecuQuestionByUsername(user_name); } catch ( SQLException e ){ throw new RuntimeException( Macro.CODE_SYSERROE ); } return user_secu_question; } public String getPassword( String user_name, String user_secu_answer ){ String user_password = ""; try{ UserDao dao = new UserDaoImp(); user_password = dao.getPasswordByUsernameAndSecuAns(user_name, user_secu_answer); } catch( SQLException e ){ throw new RuntimeException( Macro.CODE_SYSERROE ); } catch( RuntimeException e ){ throw new RuntimeException( Macro.CODE_WRONG_SECU_ANSWER ); } return user_password; } }
true
fe66039f32e9c72217a3a3e4e97ef9cb233143e8
Java
Milica775/Design-patterns
/DO Project/src/export/SaveToDrawFile.java
UTF-8
825
2.96875
3
[]
no_license
package export; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayList; public class SaveToDrawFile implements Export{ @Override public void export(ArrayList<Object> data, String path) { try { //cuvanje objekta u fajl FileOutputStream file=new FileOutputStream(path); ObjectOutputStream objectStream=new ObjectOutputStream(file); //metoda za serijalizaciju objekta objectStream.writeObject(data); objectStream.close(); file.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
f0c52cb9b32b5636b884d7a7dd57943ecc5656ef
Java
isaacherrera47/polish-j
/src/modelos/Articulo.java
UTF-8
6,745
2
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 modelos; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author isaac */ @Entity @Table(name = "articulo") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Articulo.findAll", query = "SELECT a FROM Articulo a"), @NamedQuery(name = "Articulo.findByCodigo", query = "SELECT a FROM Articulo a WHERE a.codigo = :codigo"), @NamedQuery(name = "Articulo.findByNombre", query = "SELECT a FROM Articulo a WHERE a.nombre = :nombre"), @NamedQuery(name = "Articulo.findByDetalles", query = "SELECT a FROM Articulo a WHERE a.detalles = :detalles"), @NamedQuery(name = "Articulo.findByImagen", query = "SELECT a FROM Articulo a WHERE a.imagen = :imagen"), @NamedQuery(name = "Articulo.findByUrl", query = "SELECT a FROM Articulo a WHERE a.url = :url"), @NamedQuery(name = "Articulo.findByPrecioReal", query = "SELECT a FROM Articulo a WHERE a.precioReal = :precioReal"), @NamedQuery(name = "Articulo.findByPrecioDescuento", query = "SELECT a FROM Articulo a WHERE a.precioDescuento = :precioDescuento"), @NamedQuery(name = "Articulo.findByPrecioCupon", query = "SELECT a FROM Articulo a WHERE a.precioCupon = :precioCupon"), @NamedQuery(name = "Articulo.findByPrecioVenta", query = "SELECT a FROM Articulo a WHERE a.precioVenta = :precioVenta")}) public class Articulo implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "codigo") private String codigo; @Basic(optional = false) @Column(name = "nombre") private String nombre; @Basic(optional = false) @Column(name = "detalles") private String detalles; @Basic(optional = false) @Column(name = "imagen") private String imagen; @Column(name = "url") private String url; @Basic(optional = false) @Column(name = "precio_real") private float precioReal; @Basic(optional = false) @Column(name = "precio_descuento") private float precioDescuento; @Basic(optional = false) @Column(name = "precio_cupon") private float precioCupon; @Basic(optional = false) @Column(name = "precio_venta") private float precioVenta; @JoinColumn(name = "id_categoria", referencedColumnName = "idcategoria") @ManyToOne(optional = false) private Categoria idCategoria; @JoinColumn(name = "id_tienda", referencedColumnName = "codigo") @ManyToOne(optional = false) private Tienda idTienda; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idArticulo") private List<ArticuloTalla> articuloTallaList; public Articulo() { } public Articulo(String codigo) { this.codigo = codigo; } public Articulo(String codigo, String nombre, String detalles, String imagen, float precioReal, float precioDescuento, float precioCupon, float precioVenta) { this.codigo = codigo; this.nombre = nombre; this.detalles = detalles; this.imagen = imagen; this.precioReal = precioReal; this.precioDescuento = precioDescuento; this.precioCupon = precioCupon; this.precioVenta = precioVenta; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDetalles() { return detalles; } public void setDetalles(String detalles) { this.detalles = detalles; } public String getImagen() { return imagen; } public void setImagen(String imagen) { this.imagen = imagen; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public float getPrecioReal() { return precioReal; } public void setPrecioReal(float precioReal) { this.precioReal = precioReal; } public float getPrecioDescuento() { return precioDescuento; } public void setPrecioDescuento(float precioDescuento) { this.precioDescuento = precioDescuento; } public float getPrecioCupon() { return precioCupon; } public void setPrecioCupon(float precioCupon) { this.precioCupon = precioCupon; } public float getPrecioVenta() { return precioVenta; } public void setPrecioVenta(float precioVenta) { this.precioVenta = precioVenta; } public Categoria getIdCategoria() { return idCategoria; } public void setIdCategoria(Categoria idCategoria) { this.idCategoria = idCategoria; } public Tienda getIdTienda() { return idTienda; } public void setIdTienda(Tienda idTienda) { this.idTienda = idTienda; } @XmlTransient public List<ArticuloTalla> getArticuloTallaList() { return articuloTallaList; } public void setArticuloTallaList(List<ArticuloTalla> articuloTallaList) { this.articuloTallaList = articuloTallaList; } @Override public int hashCode() { int hash = 0; hash += (codigo != null ? codigo.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Articulo)) { return false; } Articulo other = (Articulo) object; if ((this.codigo == null && other.codigo != null) || (this.codigo != null && !this.codigo.equals(other.codigo))) { return false; } return true; } @Override public String toString() { return "modelos.Articulo[ codigo=" + codigo + " ]"; } }
true
850d5aadbd73897c82d58d5ed7e38ecfa7b9f829
Java
giridhar/TactfulTokenizer
/src/tactful/tokenizer/Doc.java
UTF-8
2,793
3.359375
3
[]
no_license
package tactful.tokenizer; import java.io.BufferedReader; import java.io.StringReader; import java.util.ArrayList; import java.util.List; //A document represents the input text. It holds a list of fragments generated //from the text. public class Doc { public List<Frag> frags = new ArrayList<Frag>(); // # Receives a text, which is then broken into fragments. // # A fragment ends with a period, quesetion mark, or exclamation mark // followed // # possibly by right handed punctuation like quotation marks or closing // braces // # and trailing whitespace. Failing that, it'll accept something like // "I hate cheese\n" // # No, it doesn't have a period, but that's the end of paragraph. // # // # Input assumption: Paragraphs delimited by line breaks. public Doc(String text) { String line = null; BufferedReader br; try { // Creating Stream with BufferedReader to given Text.. br = new BufferedReader(new StringReader(text)); while ((line = br.readLine()) != null) { //line.split("(.*?[.!?](?:[\"')\\]}]|(?:<.*>))*[\\s])"); String[] res = line.split("(?<=[.!?])\\s+"); if(res.length > 0 ){ for (String string : res) { string = string.replace("\\n",""); string = string.replace("\\r",""); string = string.replaceAll("\\s+"," "); if (string.trim().equals("") || string.trim().equals(" ")) continue; Frag frag = new Frag(string); if (!frags.isEmpty() && frag.getCleaned().length > 0) { frags.get(frags.size() - 1).setNext( frag.getCleaned()[0]); } this.frags.add(frag); } } } }catch (Exception e) { e.printStackTrace(); } } // # Segments the text. More precisely, it reassembles the fragments into // sentences. // # We call something a sentence whenever it is more likely to be a // sentence than not. public String[] segment() { ArrayList<String> sent = new ArrayList<String>(); ArrayList<String> sents = new ArrayList<String>(); float thresh = (float) 0.5; for (Frag frag : frags) { sent.add(frag.getOrig()); if (frag.getPred() > thresh) { if (frag.getOrig() == null) break; String addall = ""; for (String add : sent) { addall = addall + add + " "; } addall = addall.trim(); sents.add(addall); sent = new ArrayList<String>(); } } // (String[])sents.toArray(); this is not working //so here creating string array from arraylist... String[] sentences; if (sents.size() > 0) { sentences = new String[sents.size()]; for (int i = 0; i < sents.size(); i++) { sentences[i] = sents.get(i); } } else { sentences = new String[sent.size()]; for (int i = 0; i < sent.size(); i++) { sentences[i] = sent.get(i); } } return sentences; } }
true
86286a7578ad3b78416172060b075c41a6dc665e
Java
avantikasingh/Hotel-Management-System
/Sprint 4/src/main/java/com/cg/hotelmanagement/test/HotelTest.java
UTF-8
1,697
2.3125
2
[]
no_license
package com.cg.hotelmanagement.test; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.cg.hotelmanagement.dao.AdminDao; import com.cg.hotelmanagement.dao.IAdminDao; import com.cg.hotelmanagement.dto.City; import com.cg.hotelmanagement.dto.Hotel; import com.cg.hotelmanagement.dto.Room; import com.cg.hotelmanagement.exception.HotelException; class HotelTest { IAdminDao adminDao; City city; Hotel hotel; Room room; @BeforeEach void createObject() { adminDao = new AdminDao(); city = new City(); city.setCityName("Kanpur"); hotel = new Hotel(); hotel.setHotelAddress("Pune"); hotel.setHotelPhoneNumber(8108734667l); hotel.setHotelRating(4.9f); room = new Room(); room.setRoomNumber("101"); room.setRoomRent(100d); room.setRoomType("S"); } @Test void addCityUnitTest() throws Exception{ Assertions.assertEquals(true, adminDao.addCity(city)); } @Test void addHotelUnitTest() throws Exception{ Assertions.assertEquals(true, adminDao.addHotel(1l, hotel)); } @Test void addRoomUnitTest() throws Exception{ Assertions.assertEquals(true, adminDao.addRoom(1l, room)); } @Test void removeCityUnitTest() throws Exception{ Assertions.assertEquals(true, adminDao.removeCity(1l)); } @Test void removeHotelUnitTest() throws Exception{ Assertions.assertEquals(true, adminDao.removeHotel(1l,1l)); } @Test void removeRoomUnitTest() throws Exception{ Assertions.assertEquals(true, adminDao.removeRoom(1l,1l)); } }
true
85398671116240f279b7466a893cd2056c7472fc
Java
archimatetool/archi
/org.eclipse.gef/src/org/eclipse/gef/RootEditPart.java
UTF-8
1,745
2.265625
2
[ "EPL-1.0", "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
/******************************************************************************* * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.gef; /** * A RootEditPart is the <i>root</i> of an EditPartViewer. It bridges the gap * between the EditPartViewer and its {@link EditPartViewer#getContents() * contents}. It does not correspond to anything in the model, and typically can * not be interacted with by the User. The Root provides a homogeneous context * for the applications "real" EditParts. */ public interface RootEditPart extends EditPart { /** * Returns the <i>contents</i> EditPart. A RootEditPart only has a single * child, called its <i>contents</i>. * * @return the contents. */ EditPart getContents(); /** * Returns the root's EditPartViewer. * * @return The <code>EditPartViewer</code> */ @Override EditPartViewer getViewer(); /** * Sets the <i>contents</i> EditPart. A RootEditPart only has a single * child, called its <i>contents</i>. * * @param editpart * the contents */ void setContents(EditPart editpart); /** * Sets the root's EditPartViewer. * * @param viewer * the EditPartViewer */ void setViewer(EditPartViewer viewer); }
true
f50d222788ca417aeaec18589dd213758c18df58
Java
lilperso/gesEmp
/src/test/java/ca/ulaval/glo4003/ULavalWebTimeSheet/Domaine/Travail/TacheTest.java
UTF-8
1,269
2.40625
2
[]
no_license
package ca.ulaval.glo4003.ULavalWebTimeSheet.Domaine.Travail; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; public class TacheTest { private static final String EMPLOYE1 = "employe1"; private static final String EMPLOYE2 = "employe2"; private Tache tache; @Before public void initialiser(){ tache = new Tache(); } @Test public void etantDonneUneListeDemployeSelectionneCeuxCiSontAssignerALaTache(){ List<String> listeEmploye = creerDeuxEmailEmploye(); tache.ajouterEmployesACetteTache(listeEmploye); assertEquals(2, tache.getListeRessourceHumainesAssignees().size()); } @Test public void etantDonneUneListeDemployeSelectionneDejaDansLaTacheCeuxCiNeSontPasAssignerEnDouble(){ List<String> listeEmploye = creerDeuxEmailEmploye(); tache.ajouterEmployesACetteTache(listeEmploye); tache.ajouterEmployesACetteTache(listeEmploye); assertEquals(2, tache.getListeRessourceHumainesAssignees().size()); } private List<String> creerDeuxEmailEmploye() { List<String> listeEmail = new ArrayList<String>(); listeEmail.add(EMPLOYE1); listeEmail.add(EMPLOYE2); return listeEmail; } }
true
682aa3408a311a1ceb42077318227ea994e7f4d4
Java
jasonyell/JasonyellCode
/2020-08-18-项目-在线抽奖系统/javaee-study/lucky-draw/src/main/java/jasonyell/service/MemberService.java
UTF-8
484
2.0625
2
[]
no_license
package jasonyell.service; import jasonyell.mapper.MemberMapper; import jasonyell.model.Award; import jasonyell.model.Member; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class MemberService { @Autowired private MemberMapper memberMapper; public List<Member> query(Member member) { return memberMapper.selectByCondition(member); } }
true
5e66e4f2e662f9aeecfe9847192bd52dc1a83850
Java
NaruseII/ServerManager-GitDeploy
/src/org/eclipse/jgit/api/RemoteAddCommand.java
UTF-8
2,688
2.328125
2
[]
no_license
/* * Copyright (C) 2015, Kaloyan Raev <kaloyan.r@zend.com> and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.api; import java.io.IOException; import java.net.URISyntaxException; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.JGitInternalException; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.StoredConfig; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.URIish; /** * Used to add a new remote. * * This class has setters for all supported options and arguments of this * command and a {@link #call()} method to finally execute the command. * * @see <a href= * "http://www.kernel.org/pub/software/scm/git/docs/git-remote.html" > Git * documentation about Remote</a> * @since 4.2 */ public class RemoteAddCommand extends GitCommand<RemoteConfig> { private String name; private URIish uri; /** * Constructor for RemoteAddCommand. * * @param repo * the {@link org.eclipse.jgit.lib.Repository} */ protected RemoteAddCommand(Repository repo) { super(repo); } /** * The name of the remote to add. * * @param name * a remote name * @return this instance * @since 5.0 */ public RemoteAddCommand setName(String name) { this.name = name; return this; } /** * The URL of the repository for the new remote. * * @param uri * an URL for the remote * @return this instance * @since 5.0 */ public RemoteAddCommand setUri(URIish uri) { this.uri = uri; return this; } /** * {@inheritDoc} * <p> * Executes the {@code remote add} command with all the options and * parameters collected by the setter methods of this class. */ @Override public RemoteConfig call() throws GitAPIException { checkCallable(); try { StoredConfig config = repo.getConfig(); RemoteConfig remote = new RemoteConfig(config, name); RefSpec refSpec = new RefSpec(); refSpec = refSpec.setForceUpdate(true); refSpec = refSpec.setSourceDestination(Constants.R_HEADS + "*", //$NON-NLS-1$ Constants.R_REMOTES + name + "/*"); //$NON-NLS-1$ remote.addFetchRefSpec(refSpec); remote.addURI(uri); remote.update(config); config.save(); return remote; } catch (IOException | URISyntaxException e) { throw new JGitInternalException(e.getMessage(), e); } } }
true
8c81c586ed1e5d1585af1acb452c9d7faa7003f2
Java
ajperalt/BPMN-Cmof2Ecore
/fr.obeo.bpmn.cmof/src/bpmdi/BpmdiFactory.java
UTF-8
2,153
1.71875
2
[]
no_license
/** * <copyright> * </copyright> * * $Id$ */ package bpmdi; import org.eclipse.emf.ecore.EFactory; /** * <!-- begin-user-doc --> * The <b>Factory</b> for the model. * It provides a create method for each non-abstract class of the model. * <!-- end-user-doc --> * @see bpmdi.BpmdiPackage * @generated */ public interface BpmdiFactory extends EFactory { /** * The singleton instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ BpmdiFactory eINSTANCE = bpmdi.impl.BpmdiFactoryImpl.init(); /** * Returns a new object of class '<em>BPMN Plane</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>BPMN Plane</em>'. * @generated */ BPMNPlane createBPMNPlane(); /** * Returns a new object of class '<em>BPMN Shape</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>BPMN Shape</em>'. * @generated */ BPMNShape createBPMNShape(); /** * Returns a new object of class '<em>BPMN Label</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>BPMN Label</em>'. * @generated */ BPMNLabel createBPMNLabel(); /** * Returns a new object of class '<em>BPMN Label Style</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>BPMN Label Style</em>'. * @generated */ BPMNLabelStyle createBPMNLabelStyle(); /** * Returns a new object of class '<em>BPMN Edge</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>BPMN Edge</em>'. * @generated */ BPMNEdge createBPMNEdge(); /** * Returns a new object of class '<em>BPMN Diagram</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>BPMN Diagram</em>'. * @generated */ BPMNDiagram createBPMNDiagram(); /** * Returns the package supported by this factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the package supported by this factory. * @generated */ BpmdiPackage getBpmdiPackage(); } //BpmdiFactory
true
2e69ca64eab195adf38b1cfa9a2e6f73f6889578
Java
tu-nd/Java
/HocString_TachChuoi_Split/src/communityuni/com/Test_Split.java
UTF-8
704
3.5
4
[]
no_license
package communityuni.com; public class Test_Split { public static void main(String[] args) { String s = "Obama>putin kim Jong Un"; String []arr = s.split("\\ "); // "\\" dùng để đánh dấu đây là ký hiệu đặc biệt trong mọi trường hợp đều thêm "\\" if(arr.length == 3); { // System.out.println("Ten 1 :" + arr[0]); // System.out.println("Ten 2 :" + arr[1]); // System.out.println("Ten 3 :" + arr[2]); } System.out.println("-------------------------"); for(int i = 0 ; i < arr.length ; i++) { System.out.println(arr[i]); } System.out.println("-------------------------"); for(String x : arr) { System.out.println(x); } } }
true
796237cd287cc6f2b514681d36ce2d94fa0c10f9
Java
Phynvi/Library
/src/entity/geometry/path/PathNode.java
UTF-8
584
2.90625
3
[]
no_license
package entity.geometry.path; import java.util.ArrayList; import java.util.List; import entity.geometry.Point3D; /** * * @author Albert Beaupre */ public class PathNode extends Point3D { public PathNode(int x, int y, int z) { super(x, y, z); } /** * */ public List<PathNode> neighbors(int radius) { List<PathNode> list = new ArrayList<>(radius * radius * radius); for (int nx = -radius; nx <= radius; nx++) { for (int ny = -radius; ny <= radius; ny++) { if (nx == 0 && ny == 0) continue; list.add(new PathNode(nx, ny, z)); } } return list; } }
true
7c732be0a0ef94fcf8856074d54ed62eaf4c08cf
Java
hpplayer/CrackingCodeNew
/src/Chapter5/p_5_3.java
UTF-8
859
3.484375
3
[]
no_license
package Chapter5; public class p_5_3 { /* * count the num of 1 in the input */ static int CountOne(int num){ int count = 0; String binary = Integer.toBinaryString(num); for(int i = 0; i < binary.length(); i++){ if(binary.charAt(i) == '1'){ count ++; } } return count; } static int findmax(int num){ int count = CountOne(num); String binary = Integer.toBinaryString(num); int firstOne = binary.length()-1; while(binary.charAt(firstOne) != '1'){ firstOne --; } StringBuilder sb = new StringBuilder(); sb.append("0B"); for (int i = 0; i < count; i++){ sb.append('1'); } int temp = Integer.valueOf(sb.toString()); int max = temp << (firstOne - (count - 1)); return max; } public static void main(String[] args){ System.out.println(CountOne(11)); System.out.println(findmax(11)); } }
true
aaffbb781983c534d28e61dd57073e269c59cd6e
Java
veronicaL510/EclipseWorkspaceCompSci20
/tutorial/src/Lesson11/number6.java
UTF-8
271
2.546875
3
[]
no_license
package Lesson11; public class number6 { public static void main(String[] args) { // TODO Auto-generated method stub double d = 100.01; int b = 0; for (int iMus = 0; iMus < 10; iMus++) b = 19 + iMus; d++; System.out.println(d); } }
true
e9a8e810a9e8988e6d94911fcc2951adcc62da5f
Java
valentinokusec/lolmains
/src/main/java/com/lolmains/services/NotificationServiceImpl.java
UTF-8
1,888
1.851563
2
[]
no_license
package com.lolmains.services; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.hibernate.exception.ConstraintViolationException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; 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 com.lolmains.domains.Mains; import com.lolmains.domains.Notification; import com.lolmains.domains.User; import com.lolmains.domains.Discussion; import com.lolmains.domains.Knowledge; import com.lolmains.repository.DiscussionDao; import com.lolmains.repository.KnowledgeDao; import com.lolmains.repository.NotificationDao; @Service public class NotificationServiceImpl implements NotificationService { @Autowired NotificationDao notificationdao; @Override public void deleteNotification(Notification Notification) { // TODO Auto-generated method stub notificationdao.delete(Notification); } @Override public Notification addNotification(Notification Notification) { // TODO Auto-generated method stub return notificationdao.save(Notification); } @Override public Notification findNotification(int id) { // TODO Auto-generated method stub return notificationdao.findOne(id); } @Override public Page<Notification> findAll(Pageable pageable) { // TODO Auto-generated method stub return notificationdao.findAll(pageable); } }
true
6587abe78455f1e15c97d4206fa16dde3e1bd216
Java
stormbaron/ImageLoaderHelper
/ImageHelperlibrary/src/main/java/com/juli/library/ImageHelper/imageLoader/ImageLoaderManager.java
UTF-8
3,021
2.25
2
[]
no_license
package com.juli.library.ImageHelper.imageLoader; import android.view.View; import com.juli.library.ImageHelper.ImageShowActivity; /** * Created by stormbaron on 17-7-17. */ public class ImageLoaderManager { private static ImageLoaderManager instance = new ImageLoaderManager(); private ImageLoaderHelper mImageLoader; private ImageLoaderOption mImageLoaderOption = new ImageLoaderOption(); private int drawableId = -1; private String url = null; private View view = null; public ImageLoaderManager() { mImageLoader = new GlideImageLoader(); } /** * 返回实例 * * @return */ public static ImageLoaderManager getInstance() { instance.mImageLoaderOption.clear(); return instance; } /** * 加载资源路径 * @param url * @return */ public ImageLoaderManager load(String url){ this.url=url; return this; } public ImageLoaderManager load(int drawableId){ this.drawableId=drawableId; return this; } /** * 进行加载操作 * @param view */ public void into(View view){ if(url!=null){ setMatrix(view, mImageLoaderOption); mImageLoader.showImage(view, url, mImageLoaderOption); return; } if(drawableId!=-1){ setMatrix(view, mImageLoaderOption); mImageLoader.showImage(view, drawableId, mImageLoaderOption); return; } } public ImageLoaderManager setImageSize(ImageLoaderOption.ImageSize imageSize) { mImageLoaderOption.setImageSize(imageSize); return this; } public ImageLoaderManager setIsCrossFade(boolean isCrossFade) { mImageLoaderOption.setCrossFade(isCrossFade); return this; } public ImageLoaderManager setIsSkipMemoryCache(boolean isSkipMemoryCache) { mImageLoaderOption.setSkipMemoryCache(isSkipMemoryCache); return this; } public ImageLoaderManager setPlaceHolder(int placeHolder) { mImageLoaderOption.setPlaceHolder(placeHolder); return this; } public ImageLoaderManager setErrorDrawableId(int drawableId) { mImageLoaderOption.setErrorDrawableId(drawableId); return this; } public ImageLoaderManager setBigUrl(String url) { mImageLoaderOption.setBigUrl(url); return this; } /** * 更具参数实例子判断是否可以点击查看大图 * * @param view * @param option */ private void setMatrix(final View view, final ImageLoaderOption option) { if (option == null) { return; } if (option.getBigUrl() == null) { return; } view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ImageShowActivity.actionStart(view.getContext(), option.getBigUrl()); } }); } }
true
5449303dfcefa8a763e6329c0384148f042954e2
Java
mayankkumar0078/CollegeDaysProject
/src/main/java/com/collegeDays/factory/ProcessorFactory.java
UTF-8
627
2.53125
3
[]
no_license
package com.collegeDays.factory; import java.util.Map; import com.collegeDays.processors.IModuleProcessor; public class ProcessorFactory { private Map<ProcessorFactory.Module, IModuleProcessor> processorsMap; public Map<ProcessorFactory.Module, IModuleProcessor> getProcessorsMap() { return processorsMap; } public void setProcessorsMap( Map<ProcessorFactory.Module, IModuleProcessor> processorsMap) { this.processorsMap = processorsMap; } public enum Module { Books, Colleges,user } public IModuleProcessor getProcessor(ProcessorFactory.Module module) { return processorsMap.get(module); } }
true
85fe5e0a9424863cda9cdd3cd6cbb6fda417e170
Java
NitinChella/Carifit
/app/src/main/java/com/example/android/carifit/CharityActivity.java
UTF-8
2,274
2.3125
2
[]
no_license
package com.example.android.carifit; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; public class CharityActivity extends AppCompatActivity { int totsteps = 0; double amount = 0; ArrayList<Integer> stepList; /*private String mUserId1; private FirebaseUser mfu; private DatabaseReference mdata;*/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_charity); stepList = new ArrayList<Integer>(); //mdata = FirebaseDatabase.getInstance().getReference(); FirebaseDatabase.getInstance().getReference().child("users").child("Person") .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot snapshot : dataSnapshot.getChildren()) { int stepvalue = snapshot.getValue(Integer.class); /*if(snapshot.getValue()==null) { }*/ //add person to your list stepList.add(stepvalue); //create a list view, and add the apapter, passing in your list } } @Override public void onCancelled(DatabaseError databaseError) { } }); for(int i: stepList){ totsteps = totsteps+i; } amount = totsteps*0.1; TextView t = (TextView)findViewById(R.id.textView3); t.setText(""+amount); } public void donateCharity(View view){ Intent intent = new Intent(this,DonateCharityActivity.class); startActivity(intent); } }
true
8e6660f11fe02b1d3f3380f869dd29de12026ece
Java
cbnusw/Judger-Main
/professor/src/test/java/com/qt/homework/HomeworkAcceptanceTest.java
UTF-8
1,682
1.976563
2
[]
no_license
//package com.qt.homework; // //import org.junit.jupiter.api.BeforeEach; //import org.junit.jupiter.api.DisplayName; //import org.junit.jupiter.api.extension.ExtendWith; //import org.springframework.boot.test.context.SpringBootTest; //import org.springframework.http.MediaType; //import org.springframework.test.context.junit.jupiter.SpringExtension; //import org.springframework.test.web.reactive.server.WebTestClient; //import org.springframework.web.reactive.function.BodyInserters; // //import java.time.LocalDateTime; // //@ExtendWith(SpringExtension.class) //@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) //public class HomeworkAcceptanceTest { // // // private WebTestClient webTestClient; // private String homeworkId; // // @BeforeEach // @DisplayName("Homework Register Test") // void createHomework() { // WebTestClient.ResponseSpec responseSpec = webTestClient.post() // .uri("/homeworks") // .contentLength(MediaType.MULTIPART_FORM_DATA) // .body(BodyInserters.fromFormData("name", "homework1") // .with()) // .exchange() // .expectStatus() // .isCreated() // .expectHeader().valueMatches("location", "/contests/[1-9]+[0-9]*"); // // homeworkId = AcceptanceTestUtils.extractDomainIdFromCreatedResourceAddress(responseSpec); // // } // // //}
true
222a981a1445d09defa07c7d88fb73e2d5177501
Java
jaimeefrainguira/mis-proyectos
/Sistema-De-Ventas/src/clases/FacturaDetalle.java
UTF-8
2,890
2.421875
2
[]
no_license
package clases; public class FacturaDetalle { private int FAC_CAB_ID; private int PRO_ID; private int FAC_DET_CANTIDAD; private double FAC_DET_PVP; private double FAC_DET_DESCUENTO; private double FAC_DET_TOTAL; private double FAC_DET_PC; public FacturaDetalle() { } public FacturaDetalle( int FAC_CAB_ID, int PRO_ID, int FAC_DET_CANTIDAD, double FAC_DET_PVP, double FAC_DET_DESCUENTO, double FAC_DET_TOTAL, double FAC_DET_PC) { this.FAC_CAB_ID=FAC_CAB_ID; this.PRO_ID=PRO_ID; this.FAC_DET_CANTIDAD=FAC_DET_CANTIDAD; this.FAC_DET_PVP=FAC_DET_PVP; this.FAC_DET_DESCUENTO=FAC_DET_DESCUENTO; this.FAC_DET_TOTAL=FAC_DET_TOTAL; this.FAC_DET_PC= FAC_DET_PC; } /** * @return the FAC_CAB_ID */ public int getFAC_CAB_ID() { return FAC_CAB_ID; } /** * @param FAC_CAB_ID the FAC_CAB_ID to set */ public void setFAC_CAB_ID(int FAC_CAB_ID) { this.FAC_CAB_ID = FAC_CAB_ID; } /** * @return the PRO_ID */ public int getPRO_ID() { return PRO_ID; } /** * @param PRO_ID the PRO_ID to set */ public void setPRO_ID(int PRO_ID) { this.PRO_ID = PRO_ID; } /** * @return the FAC_DET_CANTIDAD */ public int getFAC_DET_CANTIDAD() { return FAC_DET_CANTIDAD; } /** * @param FAC_DET_CANTIDAD the FAC_DET_CANTIDAD to set */ public void setFAC_DET_CANTIDAD(int FAC_DET_CANTIDAD) { this.FAC_DET_CANTIDAD = FAC_DET_CANTIDAD; } /** * @return the FAC_DET_PVP */ public double getFAC_DET_PVP() { return FAC_DET_PVP; } /** * @param FAC_DET_PVP the FAC_DET_PVP to set */ public void setFAC_DET_PVP(double FAC_DET_PVP) { this.FAC_DET_PVP = FAC_DET_PVP; } /** * @return the FAC_DET_TOTAL */ public double getFAC_DET_TOTAL() { return FAC_DET_TOTAL; } /** * @param FAC_DET_TOTAL the FAC_DET_TOTAL to set */ public void setFAC_DET_TOTAL(double FAC_DET_TOTAL) { this.FAC_DET_TOTAL = FAC_DET_TOTAL; } /** * @return the FAC_DET_PC */ public double getFAC_DET_PC() { return FAC_DET_PC; } /** * @param FAC_DET_PC the FAC_DET_PC to set */ public void setFAC_DET_PC(double FAC_DET_PC) { this.FAC_DET_PC = FAC_DET_PC; } /** * @return the FAC_DET_DESCUENTO */ public double getFAC_DET_DESCUENTO() { return FAC_DET_DESCUENTO; } /** * @param FAC_DET_DESCUENTO the FAC_DET_DESCUENTO to set */ public void setFAC_DET_DESCUENTO(double FAC_DET_DESCUENTO) { this.FAC_DET_DESCUENTO = FAC_DET_DESCUENTO; } }
true
8befc5d16dee9025a5213da5bbfa13c8d703f3d4
Java
Chepell/JavaRushTasks
/2.JavaCore/src/com/javarush/task/task15/task1507/Solution.java
UTF-8
3,514
4.03125
4
[]
no_license
package com.javarush.task.task15.task1507; /* ООП - Перегрузка Перегрузите метод printMatrix 8 различными способами. В итоге должно получиться 10 различных методов printMatrix. Требования: 1. В классе Solution должны быть реализованы 10 методов printMatrix с различными аргументами. 2. Класс Solution должен быть public. 3. Все методы класса Solution должны быть статическими. 4. Все методы класса Solution должны быть публичными. */ public class Solution { public static void main(String[] args) { printMatrix(2, 3, "fDf"); printMatrix(2, 3, Byte.MAX_VALUE); printMatrix(2, 3, Short.MAX_VALUE); printMatrix(2, 3, Integer.MAX_VALUE); printMatrix(2, 3, Long.MAX_VALUE); printMatrix(2, 3, Float.MAX_VALUE); printMatrix(2, 3, Double.MAX_VALUE); printMatrix(2, 3, 'X'); printMatrix(2, 3, false); } public static void printMatrix(int m, int n, boolean value) { System.out.println("Заполняем объектами Boolean"); printMatrix(m, n, (Object) value); } public static void printMatrix(int m, int n, char value) { System.out.println("Заполняем объектами Char"); printMatrix(m, n, (Object) value); } public static void printMatrix(int m, int n, double value) { System.out.println("Заполняем объектами Double"); printMatrix(m, n, (Object) value); } public static void printMatrix(int m, int n, float value) { System.out.println("Заполняем объектами Float"); printMatrix(m, n, (Object) value); } public static void printMatrix(int m, int n, long value) { System.out.println("Заполняем объектами Long"); printMatrix(m, n, (Object) value); } public static void printMatrix(int m, int n, int value) { System.out.println("Заполняем объектами Int"); printMatrix(m, n, (Object) value); } public static void printMatrix(int m, int n, short value) { System.out.println("Заполняем объектами Short"); printMatrix(m, n, (Object) value); } public static void printMatrix(int m, int n, byte value) { System.out.println("Заполняем объектами Byte"); printMatrix(m, n, (Object) value); } // перегрузка метода с вызовом внутри этого же метода с объектом // в качестве аргумента и приведением типа к этому общему типу public static void printMatrix(int m, int n, String value) { System.out.println("Заполняем объектами String"); printMatrix(m, n, (Object) value); } // общий метод заполнения матрицы объектами public static void printMatrix(int m, int n, Object value) { // столбец for (int i = 0; i < m; i++) { // строка for (int j = 0; j < n; j++) { System.out.print(value); } // переход на новую строку System.out.println(); } } }
true
06470f67fcec35713afd4a2d85b7fd1a21656d5a
Java
witoza/algh-4-fun
/test/org/wito/BSTTest.java
UTF-8
565
2.65625
3
[]
no_license
package org.wito; import org.junit.Test; public class BSTTest { @Test public void sampleTest() { BST<Integer> bst = new BST<Integer>(); bst.add(30, 60, 70, 80, 90, 12, 5, 6, 7, 8, 9, 100, 200, 300, 56, 57, 58); bst.getInOrder(); bst.findAndPrint(10); bst.findAndPrint(99); bst.findAndPrint(101); bst.findAndPrint(100); bst.findAndPrint(57); bst.printMinMan(); bst.printInOrderUsingSucc(); bst.printInOrderUsingPred(); bst.delete(30, 70, 80, 90, 12, 5, 6, 7, 8, 9, 100, 200, 300, 56, 57, 58, 60); bst.printInOrderUsingPred(); } }
true
ba9944c6afe487e14776efecc5a021a313360fdc
Java
HanSolo/charts
/src/main/java/eu/hansolo/fx/charts/YPane.java
UTF-8
26,884
1.734375
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2017 by Gerrit Grunwald * * 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 eu.hansolo.fx.charts; import eu.hansolo.fx.charts.data.ValueItem; import eu.hansolo.fx.charts.font.Fonts; import eu.hansolo.fx.charts.series.YSeries; import eu.hansolo.fx.charts.tools.Helper; import eu.hansolo.fx.charts.tools.Point; import javafx.beans.property.BooleanProperty; import javafx.beans.property.BooleanPropertyBase; import javafx.beans.property.DoubleProperty; import javafx.beans.property.DoublePropertyBase; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ObjectPropertyBase; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.geometry.VPos; import javafx.scene.Node; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.layout.Region; import javafx.scene.paint.Color; import javafx.scene.paint.CycleMethod; import javafx.scene.paint.Paint; import javafx.scene.paint.RadialGradient; import javafx.scene.shape.ArcType; import javafx.scene.shape.StrokeLineCap; import javafx.scene.text.Font; import javafx.scene.text.TextAlignment; import java.util.ArrayList; import java.util.List; import java.util.Locale; import static eu.hansolo.fx.charts.tools.Helper.clamp; public class YPane<T extends ValueItem> extends Region implements ChartArea { private static final double PREFERRED_WIDTH = 250; private static final double PREFERRED_HEIGHT = 250; private static final double MINIMUM_WIDTH = 0; private static final double MINIMUM_HEIGHT = 0; private static final double MAXIMUM_WIDTH = 4096; private static final double MAXIMUM_HEIGHT = 4096; private static double aspectRatio; private boolean keepAspect; private double size; private double width; private double height; private Paint _chartBackground; private ObjectProperty<Paint> chartBackground; private List<YSeries<T>> listOfSeries; private Canvas canvas; private GraphicsContext ctx; private double _thresholdY; private DoubleProperty thresholdY; private boolean _thresholdYVisible; private BooleanProperty thresholdYVisible; private Color _thresholdYColor; private ObjectProperty<Color> thresholdYColor; private Color _categoryColor; private ObjectProperty<Color> categoryColor; private boolean valid; private double _lowerBoundY; private DoubleProperty lowerBoundY; private double _upperBoundY; private DoubleProperty upperBoundY; private ObservableList<Category> categories; // ******************** Constructors ************************************** public YPane(final YSeries<T>... SERIES) { this(Color.TRANSPARENT, new ArrayList<>(), SERIES); } public YPane(final List<Category> CATEGORIES, final YSeries<T>... SERIES) { this(Color.TRANSPARENT, CATEGORIES, SERIES); } public YPane(final Paint BACKGROUND, final YSeries<T>... SERIES) { this(BACKGROUND, new ArrayList<>(), SERIES); } public YPane(final Paint BACKGROUND, final List<Category> CATEGORIES, final YSeries<T>... SERIES) { getStylesheets().add(YPane.class.getResource("chart.css").toExternalForm()); aspectRatio = PREFERRED_HEIGHT / PREFERRED_WIDTH; keepAspect = false; _chartBackground = BACKGROUND; listOfSeries = FXCollections.observableArrayList(SERIES); _thresholdY = 100; _thresholdYVisible = false; _thresholdYColor = Color.RED; _categoryColor = Color.BLACK; _lowerBoundY = 0; _upperBoundY = 100; categories = FXCollections.observableArrayList(CATEGORIES); valid = isChartTypeValid(); initGraphics(); registerListeners(); } // ******************** Initialization ************************************ private void initGraphics() { if (Double.compare(getPrefWidth(), 0.0) <= 0 || Double.compare(getPrefHeight(), 0.0) <= 0 || Double.compare(getWidth(), 0.0) <= 0 || Double.compare(getHeight(), 0.0) <= 0) { if (getPrefWidth() > 0 && getPrefHeight() > 0) { setPrefSize(getPrefWidth(), getPrefHeight()); } else { setPrefSize(PREFERRED_WIDTH, PREFERRED_HEIGHT); } } getStyleClass().setAll("chart", "xy-chart"); canvas = new Canvas(PREFERRED_WIDTH, PREFERRED_HEIGHT); ctx = canvas.getGraphicsContext2D(); getChildren().setAll(canvas); } private void registerListeners() { widthProperty().addListener(o -> resize()); heightProperty().addListener(o -> resize()); listOfSeries.forEach(series -> series.setOnSeriesEvent(seriesEvent -> redraw())); categories.addListener(new ListChangeListener<Category>() { @Override public void onChanged(final Change<? extends Category> c) { while (c.next()) { if (c.wasAdded()) { } else if (c.wasRemoved()) { } } redraw(); } }); } // ******************** Methods ******************************************* @Override protected double computeMinWidth(final double HEIGHT) { return MINIMUM_WIDTH; } @Override protected double computeMinHeight(final double WIDTH) { return MINIMUM_HEIGHT; } @Override protected double computePrefWidth(final double HEIGHT) { return super.computePrefWidth(HEIGHT); } @Override protected double computePrefHeight(final double WIDTH) { return super.computePrefHeight(WIDTH); } @Override protected double computeMaxWidth(final double HEIGHT) { return MAXIMUM_WIDTH; } @Override protected double computeMaxHeight(final double WIDTH) { return MAXIMUM_HEIGHT; } @Override public ObservableList<Node> getChildren() { return super.getChildren(); } public Paint getChartBackground() { return null == chartBackground ? _chartBackground : chartBackground.get(); } public void setChartBackground(final Paint PAINT) { if (null == chartBackground) { _chartBackground = PAINT; redraw(); } else { chartBackground.set(PAINT); } } public ObjectProperty<Paint> chartBackgroundProperty() { if (null == chartBackground) { chartBackground = new ObjectPropertyBase<Paint>(_chartBackground) { @Override protected void invalidated() { redraw(); } @Override public Object getBean() { return YPane.this; } @Override public String getName() { return "chartBackground"; } }; _chartBackground = null; } return chartBackground; } public double getThresholdY() { return null == thresholdY ? _thresholdY : thresholdY.get(); } public void setThresholdY(final double THRESHOLD) { if (null == thresholdY) { _thresholdY = THRESHOLD; redraw(); } else { thresholdY.set(THRESHOLD); } } public DoubleProperty thresholdYProperty() { if (null == thresholdY) { thresholdY = new DoublePropertyBase(_thresholdY) { @Override protected void invalidated() { redraw(); } @Override public Object getBean() { return YPane.this; } @Override public String getName() { return "thresholdY"; } }; } return thresholdY; } public boolean isThresholdYVisible() { return null == thresholdYVisible ? _thresholdYVisible : thresholdYVisible.get(); } public void setThresholdYVisible(final boolean VISIBLE) { if (null == thresholdYVisible) { _thresholdYVisible = VISIBLE; redraw(); } else { thresholdYVisible.set(VISIBLE); } } public BooleanProperty thresholdYVisibleProperty() { if (null == thresholdYVisible) { thresholdYVisible = new BooleanPropertyBase(_thresholdYVisible) { @Override protected void invalidated() { redraw(); } @Override public Object getBean() { return YPane.this; } @Override public String getName() { return "thresholdYVisible"; } }; } return thresholdYVisible; } public Color getThresholdYColor() { return null == thresholdYColor ? _thresholdYColor : thresholdYColor.get(); } public void setThresholdYColor(final Color COLOR) { if (null == thresholdYColor) { _thresholdYColor = COLOR; redraw(); } else { thresholdYColor.set(COLOR); } } public ObjectProperty<Color> thresholdYColorProperty() { if (null == thresholdYColor) { thresholdYColor = new ObjectPropertyBase<Color>(_thresholdYColor) { @Override protected void invalidated() { redraw(); } @Override public Object getBean() { return YPane.this; } @Override public String getName() { return "thresholdYColor"; } }; _thresholdYColor = null; } return thresholdYColor; } public Color getCategoryColor() { return null == categoryColor ? _categoryColor : categoryColor.get(); } public void setCategoryColor(final Color COLOR) { if (null == categoryColor) { _categoryColor = COLOR; redraw(); } else { categoryColor.set(COLOR); } } public ObjectProperty<Color> categoryColorProperty() { if (null == categoryColor) { categoryColor = new ObjectPropertyBase<Color>(_categoryColor) { @Override protected void invalidated() { redraw(); } @Override public Object getBean() { return YPane.this; } @Override public String getName() { return "categoryColor"; } }; _categoryColor = null; } return categoryColor; } public double getLowerBoundY() { return null == lowerBoundY ? _lowerBoundY : lowerBoundY.get(); } public void setLowerBoundY(final double VALUE) { if (null == lowerBoundY) { _lowerBoundY = VALUE; redraw(); } else { lowerBoundY.set(VALUE); } } public DoubleProperty lowerBoundYProperty() { if (null == lowerBoundY) { lowerBoundY = new DoublePropertyBase(_lowerBoundY) { @Override protected void invalidated() { redraw(); } @Override public Object getBean() { return YPane.this; } @Override public String getName() { return "lowerBoundY"; } }; } return lowerBoundY; } public double getUpperBoundY() { return null == upperBoundY ? _upperBoundY : upperBoundY.get(); } public void setUpperBoundY(final double VALUE) { if (null == upperBoundY) { _upperBoundY = VALUE; redraw(); } else { upperBoundY.set(VALUE); } } public DoubleProperty upperBoundYProperty() { if (null == upperBoundY) { upperBoundY = new DoublePropertyBase(_upperBoundY) { @Override protected void invalidated() { redraw(); } @Override public Object getBean() { return YPane.this; } @Override public String getName() { return "upperBoundY"; } }; } return upperBoundY; } public ObservableList<Category> getCategories() { return categories; } public void setCategories(final List<Category> categories) { this.categories.setAll(categories); } public double getRangeY() { return getUpperBoundY() - getLowerBoundY(); } public double getDataMinY() { return listOfSeries.stream().mapToDouble(YSeries::getMinY).min().getAsDouble(); } public double getDataMaxY() { return listOfSeries.stream().mapToDouble(YSeries::getMaxY).max().getAsDouble(); } public double getDataRangeY() { return getDataMaxY() - getDataMinY(); } public List<YSeries<T>> getListOfSeries() { return listOfSeries; } public boolean containsRadarChart() { for(YSeries<T> series : listOfSeries) { ChartType type = series.getChartType(); if (ChartType.RADAR_POLYGON == type || ChartType.RADAR_SECTOR == type || ChartType.SMOOTH_RADAR_POLYGON == type) { return true; } } return false; } // ******************** Draw Chart **************************************** private void drawChart() { if (null == listOfSeries || listOfSeries.isEmpty()) return; ctx.clearRect(0, 0, width, height); ctx.setFill(getChartBackground()); ctx.fillRect(0, 0, width, height); if (containsRadarChart()) { drawRadarOverlay(listOfSeries.get(0).getItems().size(), listOfSeries.get(0).getChartType()); } for(YSeries<T> series : listOfSeries) { final ChartType TYPE = series.getChartType(); switch(TYPE) { case DONUT : drawDonut(series); break; case RADAR_POLYGON : case SMOOTH_RADAR_POLYGON: case RADAR_SECTOR : drawRadar(series); break; } } } private void drawDonut(final YSeries<T> SERIES) { if (null == SERIES) return; List<T> items = SERIES.getItems(); int noOfItems = items.size(); double center = size * 0.5; double innerRadius = size * 0.275; double outerRadius = size * 0.4; double barWidth = size * 0.1; double sum = items.stream().mapToDouble(T::getValue).sum(); double stepSize = 360.0 / sum; double angle = 0; double startAngle = 90; double xy = size * 0.1; double wh = size * 0.8; double x; double y; ctx.setLineCap(StrokeLineCap.BUTT); ctx.setTextAlign(TextAlignment.CENTER); ctx.setTextBaseline(VPos.CENTER); for (T item : items) { double value = item.getValue(); startAngle -= angle; angle = value * stepSize; // Segment ctx.setLineWidth(barWidth); ctx.setStroke(item.getFill()); ctx.strokeArc(xy, xy, wh, wh, startAngle, -angle, ArcType.OPEN); // Percentage //if (angle > 8) { // x = innerRadius * Math.cos(Math.toRadians(startAngle - (angle * 0.5))); // y = -innerRadius * Math.sin(Math.toRadians(startAngle - (angle * 0.5))); // ctx.setFill(Color.BLACK); // ctx.fillText(String.format(Locale.US, "%.0f%%", (value / sum * 100.0)), center + x, center + y, barWidth); //} // Value if (angle > 8) { x = outerRadius * Math.cos(Math.toRadians(startAngle - (angle * 0.5))); y = -outerRadius * Math.sin(Math.toRadians(startAngle - (angle * 0.5))); ctx.setFill(Color.WHITE); ctx.fillText(String.format(Locale.US, "%.0f", value), center + x, center + y, barWidth); } } } private void drawRadar(final YSeries<T> SERIES) { final double CENTER_X = 0.5 * size; final double CENTER_Y = CENTER_X; final double CIRCLE_SIZE = 0.9 * size; final double LOWER_BOUND_Y = getLowerBoundY(); final double DATA_RANGE = getRangeY(); final double RANGE = 0.35714 * CIRCLE_SIZE; final double OFFSET = 0.14286 * CIRCLE_SIZE; final int NO_OF_SECTORS = SERIES.getItems().size(); final double angleStep = 360.0 / NO_OF_SECTORS; // draw the chart data ctx.save(); if (SERIES.getFill() instanceof RadialGradient) { ctx.setFill(new RadialGradient(0, 0, size * 0.5, size * 0.5, size * 0.45, false, CycleMethod.NO_CYCLE, ((RadialGradient) SERIES.getFill()).getStops())); } else { ctx.setFill(SERIES.getFill()); } ctx.setLineWidth(SERIES.getStrokeWidth() > -1 ? SERIES.getStrokeWidth() : size * 0.0025); ctx.setStroke(SERIES.getStroke()); switch(SERIES.getChartType()) { case RADAR_POLYGON: ctx.save(); ctx.beginPath(); ctx.moveTo(CENTER_X, 0.36239 * size); SERIES.getItems().forEach(item -> { double r1 = (item.getValue() - LOWER_BOUND_Y) / DATA_RANGE; ctx.lineTo(CENTER_X, CENTER_Y - OFFSET - r1 * RANGE); Helper.rotateCtx(ctx, CENTER_X, CENTER_Y, angleStep); }); //ADDED resuse first point if wrapping required double r2 = SERIES.isWithWrapping() ? ((SERIES.getItems().get(0).getValue() - LOWER_BOUND_Y) / DATA_RANGE) : ((SERIES.getItems().get(NO_OF_SECTORS - 1).getValue() - LOWER_BOUND_Y) / DATA_RANGE); ctx.lineTo(CENTER_X, CENTER_Y - OFFSET - r2 * RANGE); ctx.closePath(); ctx.fill(); ctx.stroke(); ctx.restore(); break; case SMOOTH_RADAR_POLYGON: double radAngle = Math.toRadians(180); double radAngleStep = Math.toRadians(angleStep); List<Point> points = new ArrayList<>(); double x = CENTER_X + (-Math.sin(radAngle) * (CENTER_Y - (0.36239 * size))); double y = CENTER_Y + (+Math.cos(radAngle) * (CENTER_Y - (0.36239 * size))); if(!SERIES.isWithWrapping()){ points.add(new Point(x, y)); } for (T item : SERIES.getItems()) { double r1 = (CENTER_Y - (CENTER_Y - OFFSET - ((item.getValue() - LOWER_BOUND_Y) / DATA_RANGE) * RANGE)); x = CENTER_X + (-Math.sin(radAngle) * r1); y = CENTER_Y + (+Math.cos(radAngle) * r1); points.add(new Point(x, y)); radAngle += radAngleStep; } double r3 = (SERIES.isWithWrapping()) ? (CENTER_Y - (CENTER_Y - OFFSET - ((SERIES.getItems().get(0).getValue() - LOWER_BOUND_Y) / DATA_RANGE) * RANGE)) : (CENTER_Y - (CENTER_Y - OFFSET - ((SERIES.getItems().get(NO_OF_SECTORS - 1).getValue() - LOWER_BOUND_Y) / DATA_RANGE) * RANGE)); x = CENTER_X + (-Math.sin(radAngle) * r3); y = CENTER_Y + (+Math.cos(radAngle) * r3); points.add(new Point(x, y)); Point[] interpolatedPoints = (SERIES.isWithWrapping())?Helper.subdividePointsRadial(points.toArray(new Point[0]), 16):Helper.subdividePoints(points.toArray(new Point[0]), 16); ctx.beginPath(); ctx.moveTo(interpolatedPoints[0].getX(), interpolatedPoints[0].getY()); for (int i = 0 ; i < interpolatedPoints.length - 1 ; i++) { Point point = interpolatedPoints[i]; ctx.lineTo(point.getX(), point.getY()); } ctx.lineTo(interpolatedPoints[interpolatedPoints.length - 1].getX(), interpolatedPoints[interpolatedPoints.length - 1].getY()); ctx.closePath(); ctx.fill(); ctx.stroke(); break; case RADAR_SECTOR: Helper.rotateCtx(ctx, CENTER_X, CENTER_Y, -90); SERIES.getItems().forEach(item -> { double r1 = (item.getValue() - LOWER_BOUND_Y) / DATA_RANGE; ctx.beginPath(); ctx.moveTo(CENTER_X, CENTER_Y); ctx.arc(CENTER_X, CENTER_Y, r1 * RANGE + OFFSET, r1 * RANGE + OFFSET, 0, -angleStep); ctx.closePath(); ctx.fill(); ctx.stroke(); Helper.rotateCtx(ctx, CENTER_X, CENTER_Y, angleStep); }); break; } ctx.restore(); } private void drawRadarOverlay(final int NO_OF_SECTORS, final ChartType TYPE) { final double CENTER_X = 0.5 * size; final double CENTER_Y = CENTER_X; final double CIRCLE_SIZE = 0.90 * size; final double DATA_RANGE = getRangeY(); final double MIN_VALUE = listOfSeries.stream().mapToDouble(YSeries::getMinY).min().getAsDouble(); final double RANGE = 0.35714 * CIRCLE_SIZE; final double OFFSET = 0.14286 * CIRCLE_SIZE; final double angleStep = 360.0 / NO_OF_SECTORS; // draw concentric rings ctx.setLineWidth(1); ctx.setStroke(Color.GRAY); double ringStepSize = size / 20.0; double pos = 0.5 * (size - CIRCLE_SIZE); double ringSize = CIRCLE_SIZE; for (int i = 0 ; i < 11 ; i++) { ctx.strokeOval(pos, pos, ringSize, ringSize); pos += ringStepSize; ringSize -= 2 * ringStepSize; } // draw star lines ctx.save(); for (int i = 0 ; i < NO_OF_SECTORS ; i++) { ctx.strokeLine(CENTER_X, 0.05 * size, CENTER_X, 0.5 * size); Helper.rotateCtx(ctx, CENTER_X, CENTER_Y, angleStep); } ctx.restore(); // draw threshold line if (isThresholdYVisible()) { double r = ((getThresholdY() - MIN_VALUE) / DATA_RANGE); ctx.setLineWidth(clamp(1d, 3d, size * 0.005)); ctx.setStroke(getThresholdYColor()); ctx.strokeOval(0.5 * size - OFFSET - r * RANGE, 0.5 * size - OFFSET - r * RANGE, 2 * (r * RANGE + OFFSET), 2 * (r * RANGE + OFFSET)); } // prerotate if sectormode ctx.save(); if (ChartType.RADAR_SECTOR == TYPE) { Helper.rotateCtx(ctx, CENTER_X, CENTER_Y, angleStep * 0.5); } // draw text ctx.save(); ctx.setFont(Fonts.latoRegular(0.025 * size)); ctx.setTextAlign(TextAlignment.CENTER); ctx.setTextBaseline(VPos.CENTER); ctx.setFill(getCategoryColor()); int index = categories.size(); if (index > NO_OF_SECTORS) { index = NO_OF_SECTORS; } for (int i = 0 ; i < index ; i++) { ctx.fillText(categories.get(i).getName(), CENTER_X, size * 0.03); Helper.rotateCtx(ctx, CENTER_X, CENTER_Y, angleStep); } ctx.restore(); ctx.restore(); // draw min and max Text Font font = Fonts.latoRegular(0.025 * size); String minValueText = String.format(Locale.US, "%.0f", getLowerBoundY()); String maxValueText = String.format(Locale.US, "%.0f", getUpperBoundY()); ctx.save(); ctx.setFont(font); Helper.drawTextWithBackground(ctx, minValueText, font, Color.WHITE, Color.BLACK, CENTER_X, CENTER_Y - size * 0.018); Helper.drawTextWithBackground(ctx, maxValueText, font, Color.WHITE, Color.BLACK, CENTER_X, CENTER_Y - CIRCLE_SIZE * 0.48); ctx.restore(); } private boolean isChartTypeValid() { boolean containsDonut = false; boolean containsRadarSector = false; boolean containsRadarPolygon = false; boolean containsSmoothRadarPolygon = false; for(YSeries<T> series : getListOfSeries()) { final ChartType TYPE = series.getChartType(); containsDonut = ChartType.DONUT == TYPE && !containsDonut; containsRadarSector = ChartType.RADAR_SECTOR == TYPE && !containsRadarSector; containsRadarPolygon = ChartType.RADAR_POLYGON == TYPE && !containsRadarPolygon; containsSmoothRadarPolygon = ChartType.SMOOTH_RADAR_POLYGON == TYPE && !containsSmoothRadarPolygon; } boolean valid = false; if (containsDonut && !containsRadarSector && !containsRadarPolygon && !containsSmoothRadarPolygon) { valid = true; } else if (containsRadarSector && !containsDonut && !containsRadarPolygon && !containsSmoothRadarPolygon) { valid = true; } else if (containsRadarPolygon | containsSmoothRadarPolygon && !containsDonut && !containsRadarSector) { valid = true; } return valid; } // ******************** Resizing ****************************************** private void resize() { width = getWidth() - getInsets().getLeft() - getInsets().getRight(); height = getHeight() - getInsets().getTop() - getInsets().getBottom(); size = width < height ? width : height; if (keepAspect) { if (aspectRatio * width > height) { width = 1 / (aspectRatio / height); } else if (1 / (aspectRatio / height) > width) { height = aspectRatio * width; } } if (width > 0 && height > 0) { canvas.setWidth(size); canvas.setHeight(size); //canvas.relocate((getWidth() - width) * 0.5, (getHeight() - height) * 0.5); canvas.relocate((width - size) * 0.5, (height - size) * 0.5); redraw(); } } protected void redraw() { drawChart(); } }
true
4cf4c88565b92d3a26b94f53ea05bb3397bebabe
Java
mian4work/Algorithm
/Autocomplete System/src/Main.java
UTF-8
317
2.734375
3
[]
no_license
public class Main { public static void main(String[] args) { String[] strings = new String[]{"dog", "deer", "deal"}; Solution solution = new Solution(strings); String[] result = solution.search("de"); for(int i = 0; i < result.length; i++) { System.out.println(result[i]); } } }
true
faaa6e232f4d1e3d52d1613e6ae84602cc93c9ce
Java
colps/handson
/battleship/src/test/java/com/tw/battleship/game/PlayerUnitTest.java
UTF-8
3,061
2.9375
3
[]
no_license
package com.tw.battleship.game; import com.tw.battleship.game.board.BattleArea; import com.tw.battleship.game.piece.AttackResult; import com.tw.battleship.game.piece.Target; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; public class PlayerUnitTest { @Mock private BattleArea area; @Mock private Target target; private String [] validTargets = {"A1", "B1", "D1"}; @Before public void init () { MockitoAnnotations.initMocks(this); } @Test public void initialStateShouldBeActiveWithValidTargets () { Player player = new Player("P1", area, validTargets); assertTrue(player.isActive()); } @Test public void initialStateShouldBeActiveWithEmptyTargets () { String [] empty = {}; Player player = new Player("P1", area, empty); assertTrue(player.isOutOfMoves()); } @Test public void gameStateWillBeInProgressUntilOpponentSurrenders() { // given Player player = new Player("P1", area, validTargets); Player opponent = new Player("P2", area, validTargets); given(target.attack(anyInt(), anyString())).willReturn(AttackResult.HIT); given(area.seek(anyString())).willReturn(target); given(area.areAllTargetsDestroyed()).willReturn(false); //when Game.State state = player.play(opponent); // then assertTrue(state.inProgress()); assertTrue(opponent.isActive()); assertTrue(player.isOutOfMoves()); } @Test public void gameStateWillBeDrawnWhenBothPlayersAreOutOfMoves() { // given Player player = new Player("P1", area, validTargets); Player opponent = new Player("P2", area, validTargets); given(target.attack(anyInt(), anyString())).willReturn(AttackResult.HIT); given(area.seek(anyString())).willReturn(target); given(area.areAllTargetsDestroyed()).willReturn(false); //when Game.State state = player.play(opponent); assertTrue(state.inProgress()); state = opponent.play(player); // then assertTrue(state.isDrawn()); assertTrue(player.isOutOfMoves()); assertTrue(opponent.isOutOfMoves()); } @Test public void gameStateWillBeOverWhenOnePlayerWins() { // given Player player = new Player("P1", area, validTargets); Player opponent = new Player("P2", area, validTargets); given(target.attack(anyInt(), anyString())).willReturn(AttackResult.HIT); given(area.seek(anyString())).willReturn(target); given(area.areAllTargetsDestroyed()).willReturn(true); //when Game.State state = player.play(opponent); // then assertTrue(state.isOver()); assertTrue(player.hasWon()); } }
true
57f46cdbc1a58e515f401a3e7d3f684e043fbdde
Java
nstdio/assertj-core
/assertj-core/src/test/java/org/assertj/core/presentation/StandardRepresentation_unambiguousToStringOf_Test.java
UTF-8
21,449
2.125
2
[ "Apache-2.0" ]
permissive
/* * 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. * * Copyright 2012-2022 the original author or authors. */ package org.assertj.core.presentation; import static java.lang.Integer.toHexString; import static java.lang.String.format; import static java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowableOfType; import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.api.Assertions.tuple; import static org.assertj.core.util.Arrays.array; import static org.assertj.core.util.Lists.list; import java.io.File; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.GregorianCalendar; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import java.util.concurrent.atomic.AtomicMarkableReference; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.concurrent.atomic.AtomicStampedReference; import org.assertj.core.data.MapEntry; import org.assertj.core.groups.Tuple; import org.assertj.core.util.OtherStringTestComparator; import org.assertj.core.util.OtherStringTestComparatorWithAt; import org.assertj.core.util.StringTestComparator; import org.junit.jupiter.api.Test; /** * Tests for {@link StandardRepresentation#unambiguousToStringOf(Object)}. * * @author Alexandre Dutra */ class StandardRepresentation_unambiguousToStringOf_Test extends AbstractBaseRepresentationTest { private static final StandardRepresentation STANDARD_REPRESENTATION = new StandardRepresentation(); @Test void should_return_null_if_object_is_null() { assertThat(unambiguousToStringOf(null)).isNull(); } @Test void should_quote_String() { String obj = "Hello"; assertThat(unambiguousToStringOf(obj)).isEqualTo(format("\"Hello\" (String@%s)", toHexString(System.identityHashCode(obj)))); } @Test void should_quote_empty_String() { String obj = ""; assertThat(unambiguousToStringOf(obj)).isEqualTo(format("\"\" (String@%s)", toHexString(System.identityHashCode(obj)))); } @Test void should_return_toString_of_File() { File obj = new MyTestFile("/someFile.txt"); assertThat(unambiguousToStringOf(obj)).isEqualTo(format("/someFile.txt (MyTestFile@%s)", toHexString(System.identityHashCode(obj)))); } @Test void should_return_toString_of_anonymous_class() { Object obj = new Object() { @Override public String toString() { return "my object"; } }; assertThat(unambiguousToStringOf(obj)).isEqualTo(format("my object (%s@%s)", obj.getClass().getName(), toHexString(System.identityHashCode(obj)))); } @Test void should_return_toString_of_Class_with_its_name() { assertThat(unambiguousToStringOf(Object.class)).isEqualTo(format("java.lang.Object (Class@%s)", toHexString(System.identityHashCode(Object.class)))); } @Test void should_return_toString_of_Collection_of_String() { Collection<String> collection = list("s1", "s2"); assertThat(unambiguousToStringOf(collection)).isEqualTo(format("[\"s1\", \"s2\"] (ArrayList@%s)", toHexString(System.identityHashCode(collection)))); } @Test void should_return_toString_of_Collection_of_arrays() { List<Boolean[]> collection = list(array(true, false), array(true, false, true)); assertThat(unambiguousToStringOf(collection)).isEqualTo(format("[[true, false], [true, false, true]] (ArrayList@%s)", toHexString(System.identityHashCode(collection)))); } @Test void should_return_toString_of_Collection_of_arrays_up_to_the_maximum_allowed_elements() { List<Boolean[]> collection = list(array(true, false), array(true), array(true, false), array(true, false, true, false, true), array(true, true)); StandardRepresentation.setMaxElementsForPrinting(4); assertThat(unambiguousToStringOf(collection)).isEqualTo(format("[[true, false], [true], ... [true, false, ... false, true], [true, true]] (ArrayList@%s)", toHexString(System.identityHashCode(collection)))); } @Test void should_return_toString_of_Collection_of_Collections() { Collection<List<String>> collection = list( list("s1", "s2"), list("s3", "s4", "s5")); assertThat(unambiguousToStringOf(collection)).isEqualTo(format("[[\"s1\", \"s2\"], [\"s3\", \"s4\", \"s5\"]] (ArrayList@%s)", toHexString(System.identityHashCode(collection)))); } @Test void should_return_toString_of_Collection_of_Collections_up_to_the_maximum_allowed_elements() { Collection<List<String>> collection = list(list("s1", "s2"), list("s3", "s4", "s5", "s6", "s7"), list("s8", "s9"), list("s10", "s11"), list("s12")); StandardRepresentation.setMaxElementsForPrinting(2); assertThat(unambiguousToStringOf(collection)).isEqualTo(format("[[\"s1\", \"s2\"], ... [\"s12\"]] (ArrayList@%s)", toHexString(System.identityHashCode(collection)))); } @Test void should_return_toString_of_Map() { Map<String, String> map = new LinkedHashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); assertThat(unambiguousToStringOf(map)).isEqualTo(format("{\"key1\"=\"value1\", \"key2\"=\"value2\"} (LinkedHashMap@%s)", toHexString(System.identityHashCode(map)))); } @Test void should_return_toString_of_array() { String[] array = array("s1", "s2"); assertThat(unambiguousToStringOf(array)).isEqualTo(format("[\"s1\", \"s2\"] (String[]@%s)", toHexString(System.identityHashCode(array)))); } @Test void should_return_toString_of_array_of_arrays() { String[][] array = array(array("s1", "s2"), array("s3", "s4", "s5")); assertThat(unambiguousToStringOf(array)).isEqualTo(format("[[\"s1\", \"s2\"], [\"s3\", \"s4\", \"s5\"]] (String[][]@%s)", toHexString(System.identityHashCode(array)))); } @Test void should_return_toString_of_array_of_arrays_up_to_the_maximum_allowed_elements() { String[][] array = array(array("s1", "s2"), array("s3", "s4", "s5", "s6", "s7"), array("s8", "s9"), array("s10", "s11"), array("s12")); StandardRepresentation.setMaxElementsForPrinting(4); assertThat(unambiguousToStringOf(array)).isEqualTo(format("[[\"s1\", \"s2\"], [\"s3\", \"s4\", ... \"s6\", \"s7\"], ... [\"s10\", \"s11\"], [\"s12\"]] (String[][]@%s)", toHexString(System.identityHashCode(array)))); } @Test void should_return_toString_of_array_of_Class() { Class<?>[] array = { String.class, File.class }; assertThat(unambiguousToStringOf(array)).isEqualTo(format("[java.lang.String, java.io.File] (Class[]@%s)", toHexString(System.identityHashCode(array)))); } @Test void should_return_toString_of_calendar() { GregorianCalendar calendar = new GregorianCalendar(2011, Calendar.JANUARY, 18, 23, 53, 17); assertThat(unambiguousToStringOf(calendar)).isEqualTo("2011-01-18T23:53:17 (java.util.GregorianCalendar)"); } @Test void should_return_toString_of_date() { Date date = new GregorianCalendar(2011, Calendar.JUNE, 18, 23, 53, 17).getTime(); assertThat(unambiguousToStringOf(date)).isEqualTo("2011-06-18T23:53:17.000 (java.util.Date)"); } @Test void should_return_toString_of_AtomicReference() { AtomicReference<String> atomicReference = new AtomicReference<>("actual"); assertThat(unambiguousToStringOf(atomicReference)).isEqualTo(format("AtomicReference[\"actual\"] (AtomicReference@%s)", toHexString(System.identityHashCode(atomicReference)))); } @Test void should_return_toString_of_AtomicMarkableReference() { AtomicMarkableReference<String> atomicMarkableReference = new AtomicMarkableReference<>("actual", true); assertThat(unambiguousToStringOf(atomicMarkableReference)).isEqualTo(format("AtomicMarkableReference[marked=true, reference=\"actual\"] (AtomicMarkableReference@%s)", toHexString(System.identityHashCode(atomicMarkableReference)))); } @Test void should_return_toString_of_AtomicStampedReference() { AtomicStampedReference<String> atomicStampedReference = new AtomicStampedReference<>("actual", 123); assertThat(unambiguousToStringOf(atomicStampedReference)).isEqualTo(format("AtomicStampedReference[stamp=123, reference=\"actual\"] (AtomicStampedReference@%s)", toHexString(System.identityHashCode(atomicStampedReference)))); } @Test void should_return_toString_of_AtomicIntegerFieldUpdater() { AtomicIntegerFieldUpdater<Person> updater = AtomicIntegerFieldUpdater.newUpdater(Person.class, "age"); assertThat(unambiguousToStringOf(updater)).isEqualTo(format("AtomicIntegerFieldUpdater (%s@%s)", updater.getClass().getSimpleName(), toHexString(System.identityHashCode(updater)))); } @Test void should_return_toString_of_AtomicLongFieldUpdater() { AtomicLongFieldUpdater<Person> updater = AtomicLongFieldUpdater.newUpdater(Person.class, "account"); assertThat(unambiguousToStringOf(updater)).isEqualTo(format("AtomicLongFieldUpdater (%s@%s)", updater.getClass().getSimpleName(), toHexString(System.identityHashCode(updater)))); } @Test void should_return_toString_of_AtomicReferenceFieldUpdater() { AtomicReferenceFieldUpdater<Person, String> updater = newUpdater(Person.class, String.class, "name"); assertThat(unambiguousToStringOf(updater)).isEqualTo(format("AtomicReferenceFieldUpdater (%s@%s)", updater.getClass().getSimpleName(), toHexString(System.identityHashCode(updater)))); } @Test void toString_with_anonymous_comparator() { Comparator<String> anonymousComparator = new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.length() - s2.length(); } }; assertThat(unambiguousToStringOf(anonymousComparator)).isEqualTo(format("'anonymous comparator class' (%s@%s)", anonymousComparator.getClass().getName(), toHexString(System.identityHashCode(anonymousComparator)))); } @Test void toString_with_lambda_comparator() { Comparator<String> lambda = (s1, s2) -> s1.length() - s2.length(); assertThat(unambiguousToStringOf(lambda)).isEqualTo(format("%s (%s@%s)", lambda.getClass().getSimpleName(), lambda.getClass().getSimpleName(), toHexString(System.identityHashCode(lambda)))); } @Test void toString_with_builtin_comparator() { Comparator<String> comparator = Comparator.comparingInt(String::length); assertThat(unambiguousToStringOf(comparator)).isEqualTo(format("%s (%s@%s)", comparator.getClass().getSimpleName(), comparator.getClass().getSimpleName(), toHexString(System.identityHashCode(comparator)))); } @Test void toString_with_anonymous_comparator_overriding_toString() { Comparator<String> anonymousComparator = new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.length() - s2.length(); } @Override public String toString() { return "foo"; } }; assertThat(unambiguousToStringOf(anonymousComparator)).isEqualTo(format("foo (%s@%s)", anonymousComparator.getClass().getName(), toHexString(System.identityHashCode(anonymousComparator)))); } @Test void toString_with_comparator_not_overriding_toString() { StringTestComparator obj = new StringTestComparator(); assertThat(unambiguousToStringOf(obj)).isEqualTo(format("StringTestComparator (StringTestComparator@%s)", toHexString(System.identityHashCode(obj)))); } @Test void toString_with_comparator_overriding_toString() { OtherStringTestComparator obj = new OtherStringTestComparator(); assertThat(unambiguousToStringOf(obj)).isEqualTo(format("other String comparator (OtherStringTestComparator@%s)", toHexString(System.identityHashCode(obj)))); } @Test void toString_with_comparator_overriding_toString_and_having_at() { OtherStringTestComparatorWithAt obj = new OtherStringTestComparatorWithAt(); assertThat(unambiguousToStringOf(obj)).isEqualTo(format("other String comparator with @ (OtherStringTestComparatorWithAt@%s)", toHexString(System.identityHashCode(obj)))); } @Test void should_format_longs_and_integers() { Long l = 20L; Integer i = 20; assertThat(unambiguousToStringOf(l)).isNotEqualTo(unambiguousToStringOf(i)); assertThat(unambiguousToStringOf(i)).isEqualTo(format("20 (Integer@%s)", toHexString(System.identityHashCode(i)))); assertThat(unambiguousToStringOf(l)).isEqualTo(format("20L (Long@%s)", toHexString(System.identityHashCode(l)))); } @Test void should_format_bytes_chars_and_shorts() { Byte b = (byte) 20; Character c = (char) 20; Short s = (short) 20; assertThat(unambiguousToStringOf(b)).isNotEqualTo(unambiguousToStringOf(c)); assertThat(unambiguousToStringOf(b)).isNotEqualTo(unambiguousToStringOf(s)); assertThat(unambiguousToStringOf(c)).isNotEqualTo(unambiguousToStringOf(s)); assertThat(unambiguousToStringOf(b)).isEqualTo(format("20 (Byte@%s)", toHexString(System.identityHashCode(b)))); assertThat(unambiguousToStringOf(c)).isEqualTo(format("'\u0014' (Character@%s)", toHexString(System.identityHashCode(c)))); assertThat(unambiguousToStringOf(s)).isEqualTo(format("20 (Short@%s)", toHexString(System.identityHashCode(s)))); } @Test void should_format_doubles_and_floats() { Float f = 20.0f; Double d = 20.0d; assertThat(unambiguousToStringOf(f)).isNotEqualTo(unambiguousToStringOf(d)); assertThat(unambiguousToStringOf(d)).isEqualTo(format("20.0 (Double@%s)", toHexString(System.identityHashCode(d)))); assertThat(unambiguousToStringOf(f)).isEqualTo(format("20.0f (Float@%s)", toHexString(System.identityHashCode(f)))); } @Test void should_format_tuples() { Tuple tuple = tuple(1, 2, 3); assertThat(unambiguousToStringOf(tuple)).isEqualTo(format("(1, 2, 3) (Tuple@%s)", toHexString(System.identityHashCode(tuple)))); } @Test void should_format_tuples_up_to_the_maximum_allowed_elements() { StandardRepresentation.setMaxElementsForPrinting(2); Tuple tuple = tuple(1, 2, 3, 4, 5); assertThat(unambiguousToStringOf(tuple)).isEqualTo(format("(1, ... 5) (Tuple@%s)", toHexString(System.identityHashCode(tuple)))); } @Test void should_format_simple_date_format() { SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy"); assertThat(unambiguousToStringOf(sdf)).isEqualTo(format("ddMMyyyy (SimpleDateFormat@%s)", toHexString(System.identityHashCode(sdf)))); } @Test void should_format_assertj_map_entry() { MapEntry<String, Integer> entry = entry("A", 1); assertThat(unambiguousToStringOf(entry)).isEqualTo(format("\"A\"=1 (MapEntry@%s)", toHexString(System.identityHashCode(entry)))); } @Test void should_return_unambiguousToStringOf_method() throws NoSuchMethodException { Method method = GenericClass.class.getDeclaredMethod("someGenericMethod", Person.class, List.class, Object.class); assertThat(unambiguousToStringOf(method)).isEqualTo(format("%s (Method@%s)", method.toGenericString(), toHexString(System.identityHashCode(method)))); } @Test void should_disambiguate_non_equal_objects_with_same_hash_code_and_toString_representations() { assertThat(unambiguousToStringOf(new Ambiguous(0, 1))).isNotEqualTo(unambiguousToStringOf(new Ambiguous(0, 2))); } @Test void isEqualTo_should_show_disambiguated_objects_with_same_hash_code_and_toString_representations() { // GIVEN Ambiguous ambiguous1 = new Ambiguous(0, 1); Ambiguous ambiguous2 = new Ambiguous(0, 2); // WHEN AssertionError error = catchThrowableOfType(() -> assertThat(ambiguous1).isEqualTo(ambiguous2), AssertionError.class); // THEN assertThat(error).hasMessageContaining(unambiguousToStringOf(ambiguous1)) .hasMessageContaining(unambiguousToStringOf(ambiguous2)); } private static String unambiguousToStringOf(Object o) { return STANDARD_REPRESENTATION.unambiguousToStringOf(o); } private static class MyTestFile extends File { private static final long serialVersionUID = 1L; private final String path; MyTestFile(String path) { super(path); this.path = path; } @Override public String getAbsolutePath() { return path; } } private static class Person { volatile String name; volatile int age; volatile long account; @Override public String toString() { return format("Person [name=%s, age=%s, account=%s]", name, age, account); } } private static class GenericClass<T> { @SuppressWarnings("unused") public <R extends Person> T someGenericMethod(R input, List<? extends R> list, T input2) { return input2; } } private static class Ambiguous { int x; int y; Ambiguous(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Ambiguous that = (Ambiguous) o; return this.x == that.x && this.y == that.y; } @Override public int hashCode() { return x; } @Override public String toString() { return String.format("Ambiguous(%d)", x); } } }
true
418a1ef532bee4eeedb1702df7e42be8ebb45843
Java
wangjianlin1985/android_hotel
/安卓服务器/src/com/chengxusheji/action/EvaluateAction.java
GB18030
11,706
2.171875
2
[]
no_license
package com.chengxusheji.action; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import org.apache.struts2.ServletActionContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import com.opensymphony.xwork2.ActionContext; import com.chengxusheji.dao.EvaluateDAO; import com.chengxusheji.domain.Evaluate; import com.chengxusheji.dao.RoomInfoDAO; import com.chengxusheji.domain.RoomInfo; import com.chengxusheji.dao.UserInfoDAO; import com.chengxusheji.domain.UserInfo; import com.chengxusheji.utils.FileTypeException; import com.chengxusheji.utils.ExportExcelUtil; @Controller @Scope("prototype") public class EvaluateAction extends BaseAction { /*Ҫѯ: ۵ķ*/ private RoomInfo roomObj; public void setRoomObj(RoomInfo roomObj) { this.roomObj = roomObj; } public RoomInfo getRoomObj() { return this.roomObj; } /*Ҫѯ: ۵û*/ private UserInfo userObj; public void setUserObj(UserInfo userObj) { this.userObj = userObj; } public UserInfo getUserObj() { return this.userObj; } /*Ҫѯ: ʱ*/ private String evaluateTime; public void setEvaluateTime(String evaluateTime) { this.evaluateTime = evaluateTime; } public String getEvaluateTime() { return this.evaluateTime; } /*ǰڼҳ*/ private int currentPage; public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getCurrentPage() { return currentPage; } /*һҳ*/ private int totalPage; public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getTotalPage() { return totalPage; } private int evaluateId; public void setEvaluateId(int evaluateId) { this.evaluateId = evaluateId; } public int getEvaluateId() { return evaluateId; } /*ǰѯܼ¼Ŀ*/ private int recordNumber; public void setRecordNumber(int recordNumber) { this.recordNumber = recordNumber; } public int getRecordNumber() { return recordNumber; } /*ҵ*/ @Resource RoomInfoDAO roomInfoDAO; @Resource UserInfoDAO userInfoDAO; @Resource EvaluateDAO evaluateDAO; /*Evaluate*/ private Evaluate evaluate; public void setEvaluate(Evaluate evaluate) { this.evaluate = evaluate; } public Evaluate getEvaluate() { return this.evaluate; } /*תEvaluateͼ*/ public String AddView() { ActionContext ctx = ActionContext.getContext(); /*ѯеRoomInfoϢ*/ List<RoomInfo> roomInfoList = roomInfoDAO.QueryAllRoomInfoInfo(); ctx.put("roomInfoList", roomInfoList); /*ѯеUserInfoϢ*/ List<UserInfo> userInfoList = userInfoDAO.QueryAllUserInfoInfo(); ctx.put("userInfoList", userInfoList); return "add_view"; } /*EvaluateϢ*/ @SuppressWarnings("deprecation") public String AddEvaluate() { ActionContext ctx = ActionContext.getContext(); try { RoomInfo roomObj = roomInfoDAO.GetRoomInfoByRoomNumber(evaluate.getRoomObj().getRoomNumber()); evaluate.setRoomObj(roomObj); UserInfo userObj = userInfoDAO.GetUserInfoByUser_name(evaluate.getUserObj().getUser_name()); evaluate.setUserObj(userObj); evaluateDAO.AddEvaluate(evaluate); ctx.put("message", java.net.URLEncoder.encode("Evaluateӳɹ!")); return "add_success"; } catch(FileTypeException ex) { ctx.put("error", java.net.URLEncoder.encode("ͼƬļʽ!")); return "error"; } catch (Exception e) { e.printStackTrace(); ctx.put("error", java.net.URLEncoder.encode("Evaluateʧ!")); return "error"; } } /*ѯEvaluateϢ*/ public String QueryEvaluate() { if(currentPage == 0) currentPage = 1; if(evaluateTime == null) evaluateTime = ""; List<Evaluate> evaluateList = evaluateDAO.QueryEvaluateInfo(roomObj, userObj, evaluateTime, currentPage); /*ܵҳܵļ¼*/ evaluateDAO.CalculateTotalPageAndRecordNumber(roomObj, userObj, evaluateTime); /*ȡܵҳĿ*/ totalPage = evaluateDAO.getTotalPage(); /*ǰѯܼ¼*/ recordNumber = evaluateDAO.getRecordNumber(); ActionContext ctx = ActionContext.getContext(); ctx.put("evaluateList", evaluateList); ctx.put("totalPage", totalPage); ctx.put("recordNumber", recordNumber); ctx.put("currentPage", currentPage); ctx.put("roomObj", roomObj); List<RoomInfo> roomInfoList = roomInfoDAO.QueryAllRoomInfoInfo(); ctx.put("roomInfoList", roomInfoList); ctx.put("userObj", userObj); List<UserInfo> userInfoList = userInfoDAO.QueryAllUserInfoInfo(); ctx.put("userInfoList", userInfoList); ctx.put("evaluateTime", evaluateTime); return "query_view"; } /*̨excel*/ public String QueryEvaluateOutputToExcel() { if(evaluateTime == null) evaluateTime = ""; List<Evaluate> evaluateList = evaluateDAO.QueryEvaluateInfo(roomObj,userObj,evaluateTime); ExportExcelUtil ex = new ExportExcelUtil(); String title = "EvaluateϢ¼"; String[] headers = { "۵ķ","۵û","(5)","","ʱ"}; List<String[]> dataset = new ArrayList<String[]>(); for(int i=0;i<evaluateList.size();i++) { Evaluate evaluate = evaluateList.get(i); dataset.add(new String[]{evaluate.getRoomObj().getRoomNumber(), evaluate.getUserObj().getName(), evaluate.getEvalueScore() + "",evaluate.getEvaluateContent(),evaluate.getEvaluateTime()}); } /* OutputStream out = null; try { out = new FileOutputStream("C://output.xls"); ex.exportExcel(title,headers, dataset, out); out.close(); } catch (Exception e) { e.printStackTrace(); } */ HttpServletResponse response = null;//һHttpServletResponse OutputStream out = null;//һ try { response = ServletActionContext.getResponse();//ʼHttpServletResponse out = response.getOutputStream();// response.setHeader("Content-disposition","attachment; filename="+"Evaluate.xls");//filenameصxlsӢ response.setContentType("application/msexcel;charset=UTF-8");// response.setHeader("Pragma","No-cache");//ͷ response.setHeader("Cache-Control","no-cache");//ͷ response.setDateHeader("Expires", 0);//ͷ String rootPath = ServletActionContext.getServletContext().getRealPath("/"); ex.exportExcel(rootPath,title,headers, dataset, out); out.flush(); } catch (IOException e) { e.printStackTrace(); }finally{ try{ if(out!=null){ out.close(); } }catch(IOException e){ e.printStackTrace(); } } return null; } /*ǰ̨ѯEvaluateϢ*/ public String FrontQueryEvaluate() { if(currentPage == 0) currentPage = 1; if(evaluateTime == null) evaluateTime = ""; List<Evaluate> evaluateList = evaluateDAO.QueryEvaluateInfo(roomObj, userObj, evaluateTime, currentPage); /*ܵҳܵļ¼*/ evaluateDAO.CalculateTotalPageAndRecordNumber(roomObj, userObj, evaluateTime); /*ȡܵҳĿ*/ totalPage = evaluateDAO.getTotalPage(); /*ǰѯܼ¼*/ recordNumber = evaluateDAO.getRecordNumber(); ActionContext ctx = ActionContext.getContext(); ctx.put("evaluateList", evaluateList); ctx.put("totalPage", totalPage); ctx.put("recordNumber", recordNumber); ctx.put("currentPage", currentPage); ctx.put("roomObj", roomObj); List<RoomInfo> roomInfoList = roomInfoDAO.QueryAllRoomInfoInfo(); ctx.put("roomInfoList", roomInfoList); ctx.put("userObj", userObj); List<UserInfo> userInfoList = userInfoDAO.QueryAllUserInfoInfo(); ctx.put("userInfoList", userInfoList); ctx.put("evaluateTime", evaluateTime); return "front_query_view"; } /*ѯҪ޸ĵEvaluateϢ*/ public String ModifyEvaluateQuery() { ActionContext ctx = ActionContext.getContext(); /*evaluateIdȡEvaluate*/ Evaluate evaluate = evaluateDAO.GetEvaluateByEvaluateId(evaluateId); List<RoomInfo> roomInfoList = roomInfoDAO.QueryAllRoomInfoInfo(); ctx.put("roomInfoList", roomInfoList); List<UserInfo> userInfoList = userInfoDAO.QueryAllUserInfoInfo(); ctx.put("userInfoList", userInfoList); ctx.put("evaluate", evaluate); return "modify_view"; } /*ѯҪ޸ĵEvaluateϢ*/ public String FrontShowEvaluateQuery() { ActionContext ctx = ActionContext.getContext(); /*evaluateIdȡEvaluate*/ Evaluate evaluate = evaluateDAO.GetEvaluateByEvaluateId(evaluateId); List<RoomInfo> roomInfoList = roomInfoDAO.QueryAllRoomInfoInfo(); ctx.put("roomInfoList", roomInfoList); List<UserInfo> userInfoList = userInfoDAO.QueryAllUserInfoInfo(); ctx.put("userInfoList", userInfoList); ctx.put("evaluate", evaluate); return "front_show_view"; } /*޸EvaluateϢ*/ public String ModifyEvaluate() { ActionContext ctx = ActionContext.getContext(); try { RoomInfo roomObj = roomInfoDAO.GetRoomInfoByRoomNumber(evaluate.getRoomObj().getRoomNumber()); evaluate.setRoomObj(roomObj); UserInfo userObj = userInfoDAO.GetUserInfoByUser_name(evaluate.getUserObj().getUser_name()); evaluate.setUserObj(userObj); evaluateDAO.UpdateEvaluate(evaluate); ctx.put("message", java.net.URLEncoder.encode("EvaluateϢ³ɹ!")); return "modify_success"; } catch (Exception e) { e.printStackTrace(); ctx.put("error", java.net.URLEncoder.encode("EvaluateϢʧ!")); return "error"; } } /*ɾEvaluateϢ*/ public String DeleteEvaluate() { ActionContext ctx = ActionContext.getContext(); try { evaluateDAO.DeleteEvaluate(evaluateId); ctx.put("message", java.net.URLEncoder.encode("Evaluateɾɹ!")); return "delete_success"; } catch (Exception e) { e.printStackTrace(); ctx.put("error", java.net.URLEncoder.encode("Evaluateɾʧ!")); return "error"; } } }
true
18a25959954c639e92af512ba4a8bf627ac9a3d0
Java
yinhanxy/volunteer
/.svn/pristine/e8/e899cb89d9db10a1481ee5363dc5de6b8fc489c7.svn-base
UTF-8
535
2
2
[]
no_license
package com.topstar.volunteer.service; import java.util.List; import com.github.pagehelper.PageInfo; import com.topstar.volunteer.model.LockUser; public interface LockUserService { /** * 分页显示被锁住的用户信息 * @param userName 供查询的用户名或昵称 * @param pageIndex * @param pageSize * @return */ public PageInfo<LockUser> getList(String userName,int pageIndex,int pageSize); /** * 解锁用户 * @param userNames * @return */ public int unlockUser(List<String> userNames); }
true
34fd3315c773d7bbf78de3608195635599122afd
Java
galahade/Common_SSO
/domain/src/main/java/com/yang/young/common/sso/persistance/jpa/repository/RoleRepository.java
UTF-8
348
1.890625
2
[ "Apache-2.0" ]
permissive
package com.yang.young.common.sso.persistance.jpa.repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import com.yang.young.common.sso.persistance.jpa.entity.RoleEntity; public interface RoleRepository extends JpaRepository<RoleEntity, Long>{ Optional<RoleEntity> findByName(String name); }
true
737a4da08fe8d2f6e574f99d3e0702718546f469
Java
kaissapy/IntroduccionJavaGS
/TareaTercerParcial/src/py/com/uaa/pooj/interfaces/Mascota.java
UTF-8
104
1.617188
2
[]
no_license
package py.com.uaa.pooj.interfaces; public interface Mascota { public String desplegarNombre(); }
true
412bb5e903d6bd70845b31890f2ca706fbe678a2
Java
Aleks-Ya/yaal_examples
/Java+/Libs+/WebDav+/Sardine/test/sardine/ListTest.java
UTF-8
1,302
2.15625
2
[]
no_license
package sardine; import com.github.sardine.DavResource; import com.github.sardine.Sardine; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; class ListTest extends BaseWebDavTest { private final Sardine sardine = newSardineClient(); @BeforeEach void beforeEach() { uploadResource("/", "f1.txt", "f1"); uploadResource("/d1", "f2.txt", "f2"); } @Test void listRootFiles() throws IOException { var url = getBaseUri().toString(); var resources = sardine.list(url); assertThat(resources).map(DavResource::getPath).containsExactlyInAnyOrder("/", "/d1/", "/f1.txt"); } @Test void listSingleRootResource() throws IOException { var url = getBaseUri().toString(); var resources = sardine.list(url, 0); assertThat(resources).map(DavResource::getPath).containsExactlyInAnyOrder("/"); } @Test void listNotRootResource() throws IOException { var url = getBaseUri().resolve("/d1").toString(); var resources = sardine.list(url, 0); assertThat(resources).map(DavResource::getPath).containsExactlyInAnyOrder("/d1/"); } }
true
3c07ffb96b7561e93cb8ac97e8a77aa4cd1b3d41
Java
DreamCloudWalker/ChestnutShell
/app/src/main/java/com/dengjian/chestnutshell/highlevelui/particleexplode/FallingParticle.java
UTF-8
1,204
2.515625
3
[ "MIT" ]
permissive
package com.dengjian.chestnutshell.highlevelui.particleexplode; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.Log; import com.dengjian.common.utils.Utils; public class FallingParticle extends Particle { private static final String TAG = "FallingParticle"; private final Rect mBound; private float mRadius = FallingParticleFactory.PART_WH; private float mAlpha = 1.0f; public FallingParticle(int color, int cx, int cy, Rect bound) { super(color, cx, cy); mBound = bound; } @Override protected void calculate(float factor) { cx = cx + factor * Utils.RANDOM.nextInt(mBound.width()) * (Utils.RANDOM.nextFloat() * 2f - 1f); cy = cy + factor * Utils.RANDOM.nextInt(mBound.height() / 2); mRadius = mRadius - factor * Utils.RANDOM.nextInt(2); mAlpha = (1.0f - factor) * (1 + Utils.RANDOM.nextFloat()); } @Override protected void draw(Canvas canvas, Paint paint) { paint.setColor(color); paint.setAlpha((int) (Color.alpha(color) * mAlpha)); canvas.drawCircle(cx, cy, mRadius, paint); } }
true
603538483a859339950581006666c7be6bf6881d
Java
jison228/MarioPartyChuckNorris
/src/main/java/com/chucknorris/server/Sala.java
UTF-8
666
2.21875
2
[]
no_license
package com.chucknorris.server; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.chucknorris.game.Game; public class Sala { public List<String> players; public Map<String,ClientLobbyThread> threadsMap; public boolean playing; public String name; public Game juego; public String password; public boolean priv; public Sala(String name, String password, boolean priv) { this.players = new ArrayList<String>(); this.threadsMap = new HashMap<String, ClientLobbyThread>(); this.playing = false; this.name = name; this.juego = null; this.password = password; this.priv = priv; } }
true
0b417792fa64c7a4a6ac58199bc7ba576b4f751b
Java
cherieruan/DawgDebauchery
/app/src/main/java/edu/uw/cruan/dawgdebauchery/LoginActivity.java
UTF-8
6,730
2.265625
2
[]
no_license
package edu.uw.cruan.dawgdebauchery; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.toolbox.NetworkImageView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthInvalidUserException; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; /** * A login screen that offers login via email/password. */ public class LoginActivity extends AppCompatActivity { private FirebaseAuth mAuth; private DatabaseReference mDatabase; public static final String TAG = "LoginActivity"; public static final String EMAIL_EXTRA_KEY = "email_key"; // UI references. private AutoCompleteTextView mEmailView; private EditText mPasswordView; private View mProgressView; private View mLoginFormView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); mAuth = FirebaseAuth.getInstance(); // Set up the login form. mEmailView = (AutoCompleteTextView) findViewById(R.id.email); mPasswordView = (EditText) findViewById(R.id.password); mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) { attemptLogin(); return true; } return false; } }); Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button); // TODO Reimplement the below code when we get the login logic sorted out with Firebase. mEmailSignInButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { attemptLogin(); } }); Button registerButton = (Button) findViewById(R.id.login_register_button); registerButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { openRegistration(); } }); } private void openRegistration() { Intent intent = new Intent(LoginActivity.this, RegistrationActivity.class); intent.putExtra(EMAIL_EXTRA_KEY, mEmailView.getText().toString()); startActivity(intent); } /** * Attempts to sign in or register the account specified by the login form. * If there are form errors (invalid email, missing fields, etc.), the * errors are presented and no actual login attempt is made. */ private void attemptLogin() { String password = mPasswordView.getText().toString(); String email = mEmailView.getText().toString(); boolean validEmail = isEmailValid(email); boolean validPassword = isPasswordValid(password); if(validEmail && validPassword) { Log.v(TAG, "Email & Password valid, logging in"); mAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.v(TAG, "signInWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); } else { Exception e = task.getException(); if(e instanceof FirebaseAuthInvalidUserException) { //have them create an account Log.v(TAG, "Invalid user"); final Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Account not found. Would you like to create an account?", Snackbar.LENGTH_LONG); snackbar.setAction("Create account", new View.OnClickListener() { @Override public void onClick(View view) { openRegistration(); } }); snackbar.show(); }else { // If sign in fails, display a message to the user. Log.v(TAG, "signInWithEmail:failure", task.getException()); Toast.makeText(LoginActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } } } }); }else if(!validEmail){ Toast.makeText(this, "Invalid Email, must be a '@uw.edu' domain", Toast.LENGTH_LONG).show(); }else if(!validPassword) { Toast.makeText(this, "Invalid password: must be at least 8 characters long", Toast.LENGTH_LONG).show(); } } private boolean isEmailValid(String email) { return email.endsWith("@uw.edu"); } private boolean isPasswordValid(String password) { return password.length() >= 8; } }
true
e1a1d345c36635364608633f6b7919e581c5e0f7
Java
jishuke/Lj_costomapp
/app/src/main/java/com/defence/costomapp/adapter/BuhuoCeguiGoodsAdapter.java
UTF-8
2,566
2.171875
2
[]
no_license
package com.defence.costomapp.adapter; import android.content.Context; import android.graphics.Color; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.defence.costomapp.R; import com.defence.costomapp.bean.BuhuoInfoEntity; import com.defence.costomapp.bean.CeGuiGoodsBean; import com.defence.costomapp.myinterface.RVItemClickListener; import java.util.Comparator; import java.util.List; /** * Created by fangfafengfu on 2017/12/6. */ public class BuhuoCeguiGoodsAdapter extends RecyclerView.Adapter<BuhuoCeguiGoodsAdapter.BuhuoInfoViewholder> { private List<CeGuiGoodsBean.ListBean> buhuoInfoEntities; private Context context; private RVItemClickListener rvItemClickListener; public BuhuoCeguiGoodsAdapter(List<CeGuiGoodsBean.ListBean> buhuoInfoEntities, Context context, RVItemClickListener rvItemClickListener) { this.buhuoInfoEntities = buhuoInfoEntities; this.context = context; this.rvItemClickListener = rvItemClickListener; } @Override public BuhuoInfoViewholder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(context).inflate(R.layout.item_buhuocegui_info, parent, false); return new BuhuoInfoViewholder(v); } @Override public void onBindViewHolder(BuhuoInfoViewholder holder, final int position) { CeGuiGoodsBean.ListBean buhuoInfoEntity = buhuoInfoEntities.get(position); holder.huodao.setText(buhuoInfoEntity.getShangpin_name()); holder.cunliang.setText(buhuoInfoEntity.getKu_cun()+""); holder.infoLL.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { rvItemClickListener.onItemClick(position); return false; } }); } @Override public int getItemCount() { return buhuoInfoEntities == null ? 0 : buhuoInfoEntities.size(); } public class BuhuoInfoViewholder extends RecyclerView.ViewHolder { private TextView huodao, cunliang, buqi; private LinearLayout infoLL; public BuhuoInfoViewholder(View itemView) { super(itemView); huodao = itemView.findViewById(R.id.huodao); cunliang = itemView.findViewById(R.id.buhuoinfokucun); infoLL = itemView.findViewById(R.id.buhuoinfoll); } } }
true
1ddd282ba6122e8a270ed5c2fd24a8b30dddba36
Java
shmuelse/Ray-tracing-project
/src/unittests/ImprovementsTests.java
UTF-8
17,173
3.03125
3
[]
no_license
package unittests; import org.junit.Test; import elements.*; import geometries.*; import primitives.*; import renderer.*; import renderer.Render; import scene.Scene; import java.io.IOException; /** * Tests for improvements features: * anti-aliasing * soft-shadow * multi-threading * adaptive anti-aliasing * * @author Shmuel & Yossef * */ public class ImprovementsTests { /** * Produce a picture of a sphere and triangle with point light and shade * features: none */ @Test public void SphereTriangle1() { Scene scene = new Scene("Test scene"); scene.setCamera(new Camera(new Point3D(0, 0, -1000), new Vector(0, 0, 1), new Vector(0, -1, 0))); scene.setDistance(1000); scene.setBackground(Color.BLACK); scene.setAmbientLight(new AmbientLight(Color.BLACK, 0)); scene.addGeometries(new Sphere(new Color(java.awt.Color.BLUE), new Material(0.5, 0.5, 30), // 60, new Point3D(0, 0, 200)), // new Triangle(new Color(java.awt.Color.BLUE), new Material(0.5, 0.5, 30), // new Point3D(-70, 40, 0), new Point3D(-40, 70, 0), new Point3D(-68, 68, 4))); scene.addLights(new SpotLight(new Color(400, 240, 0), // new Point3D(-100, 100, -200), new Vector(1, -1, 3), 1, 1E-5, 1.5E-7, 10 )); ImageWriter imageWriter = new ImageWriter("sphereTriangle1", 200, 200, 400, 400); Render render = new Render(imageWriter, scene); render.renderImage(false, false, false); render.writeToImage(); } /** * Produce a picture of a sphere and triangle with point light and shade * features: anti-aliasing */ @Test public void SphereTriangle2() { Scene scene = new Scene("Test scene"); scene.setCamera(new Camera(new Point3D(0, 0, -1000), new Vector(0, 0, 1), new Vector(0, -1, 0))); scene.setDistance(1000); scene.setBackground(Color.BLACK); scene.setAmbientLight(new AmbientLight(Color.BLACK, 0)); scene.addGeometries(new Sphere(new Color(java.awt.Color.BLUE), new Material(0.5, 0.5, 30), // 60, new Point3D(0, 0, 200)), // new Triangle(new Color(java.awt.Color.BLUE), new Material(0.5, 0.5, 30), // new Point3D(-70, 40, 0), new Point3D(-40, 70, 0), new Point3D(-68, 68, 4))); scene.addLights(new SpotLight(new Color(400, 240, 0), // new Point3D(-100, 100, -200), new Vector(1, -1, 3), 1, 1E-5, 1.5E-7, 10 )); ImageWriter imageWriter = new ImageWriter("sphereTriangle2", 200, 200, 400, 400); Render render = new Render(imageWriter, scene). setMultithreading(3). setDebugPrint(); render.renderImage(true, true, false); render.writeToImage(); } /** * Produce a picture of a sphere and triangle with point light and shade * features: soft Shadow */ @Test public void SphereTriangle3() { Scene scene = new Scene("Test scene"); scene.setCamera(new Camera(new Point3D(0, 0, -1000), new Vector(0, 0, 1), new Vector(0, -1, 0))); scene.setDistance(1000); scene.setBackground(Color.BLACK); scene.setAmbientLight(new AmbientLight(Color.BLACK, 0)); scene.addGeometries(new Sphere(new Color(java.awt.Color.BLUE), new Material(0.5, 0.5, 30), // 60, new Point3D(0, 0, 200)), // new Triangle(new Color(java.awt.Color.BLUE), new Material(0.5, 0.5, 30), // new Point3D(-70, 40, 0), new Point3D(-40, 70, 0), new Point3D(-68, 68, 4))); scene.addLights(new SpotLight(new Color(400, 240, 0), // new Point3D(-100, 100, -200), new Vector(1, -1, 3), 1, 1E-5, 1.5E-7, 10 )); ImageWriter imageWriter = new ImageWriter("sphereTriangle3", 200, 200, 400, 400); Render render = new Render(imageWriter, scene); render.renderImage(false, true, false); render.writeToImage(); } /** * Produce a picture of a sphere and triangle with point light and shade * features: anti-aliasing, soft-shadows */ @Test public void SphereTriangle4() { Scene scene = new Scene("Test scene"); scene.setCamera(new Camera(new Point3D(0, 0, -1000), new Vector(0, 0, 1), new Vector(0, -1, 0))); scene.setDistance(1000); scene.setBackground(Color.BLACK); scene.setAmbientLight(new AmbientLight(Color.BLACK, 0)); scene.addGeometries(new Sphere(new Color(java.awt.Color.BLUE), new Material(0.5, 0.5, 30), // 60, new Point3D(0, 0, 200)), // new Triangle(new Color(java.awt.Color.BLUE), new Material(0.5, 0.5, 30), // new Point3D(-70, 40, 0), new Point3D(-40, 70, 0), new Point3D(-68, 68, 4))); scene.addLights(new SpotLight(new Color(400, 240, 0), // new Point3D(-100, 100, -200), new Vector(1, -1, 3), 1, 1E-5, 1.5E-7, 10 )); ImageWriter imageWriter = new ImageWriter("sphereTriangle4", 200, 200, 400, 400); Render render = new Render(imageWriter, scene); render.renderImage(true, true, false); render.writeToImage(); } /** * Produce a picture of a sphere and triangle with point light and shade * features: soft-shadows, multi-threading, adaptive anti-aliasing */ @Test public void SphereTriangle5() { Scene scene = new Scene("Test scene"); scene.setCamera(new Camera(new Point3D(0, 0, -1000), new Vector(0, 0, 1), new Vector(0, -1, 0))); scene.setDistance(1000); scene.setBackground(Color.BLACK); scene.setAmbientLight(new AmbientLight(Color.BLACK, 0)); scene.addGeometries(new Sphere(new Color(java.awt.Color.BLUE), new Material(0.5, 0.5, 30), // 60, new Point3D(0, 0, 200)), // new Triangle(new Color(java.awt.Color.BLUE), new Material(0.5, 0.5, 30), // new Point3D(-70, 40, 0), new Point3D(-40, 70, 0), new Point3D(-68, 68, 4))); scene.addLights(new SpotLight(new Color(400, 240, 0), // new Point3D(-100, 100, -200), new Vector(1, -1, 3), 1, 1E-5, 1.5E-7, 10 )); ImageWriter imageWriter = new ImageWriter("sphereTriangle5", 200, 200, 400, 400); Render render = new Render(imageWriter, scene); render.renderImage(false, true, true); render.writeToImage(); } /** * Produce a complex picture with many geometries and many light sources * features: none */ @Test public void finalTest1() { Scene scene = new Scene("Test scene"); scene.setCamera(new Camera( new Point3D(0, 250, -80), new Vector(0, -250, 80), new Vector(0,-250,80).crossProduct(new Vector(-1,0,0)))); scene.setDistance(200); scene.setBackground(Color.BLACK); scene.setAmbientLight(new AmbientLight(Color.BLACK, 0)); scene.addGeometries(new Plane( Color.BLACK, new Material(0.4,0.6,150,0.2,0.4), new Point3D(0,0,50), new Vector(0,0,1))); //********************************** Sphere ************************************// scene.addGeometries( new Sphere(new Color(java.awt.Color.BLACK), new Material(0, 1, 100, 0.2, 0.8), 20, new Point3D(-50, -20, 30))); scene.addGeometries( new Sphere(new Color(java.awt.Color.BLACK), new Material(0, 1, 100, 0.2, 0.8), 30, new Point3D(-65, -75, 20))); //********************************** Polygons ************************************// scene.addGeometries(new geometries.Polygon (new Color(java.awt.Color.YELLOW), new Material(0.5, 0.5, 150, 0.8, 0.2), new Point3D(0, -40, 0), new Point3D(20, -20, 50), new Point3D(20, -60, 50)), new geometries.Polygon (new Color(java.awt.Color.YELLOW), new Material(0, 1, 150, 0.7, 0.3), new Point3D(20, -20, 50), new Point3D(3.52, -36.88, 50), new Point3D(0, -40, 0)), new geometries.Polygon (new Color(java.awt.Color.YELLOW), new Material(0, 1, 150, 0.7, 0.3), new Point3D(3.52, -36.88, 50), new Point3D(0, -40, 0), new Point3D(-3.65, -36.76, 50)), new geometries.Polygon (new Color(java.awt.Color.YELLOW), new Material(0, 1, 150, 0.7, 0.3), new Point3D(-3.65, -36.67, 50), new Point3D(0, -40, 0), new Point3D(-20.1, -20, 50)), new geometries.Polygon (new Color(java.awt.Color.YELLOW), new Material(0, 1, 150, 0.7, 0.3), new Point3D(-20.1, -20, 50), new Point3D(0, -40, 0), new Point3D(-20, -60, 50)), new geometries.Polygon (new Color(java.awt.Color.YELLOW), new Material(0, 1, 150, 0.7, 0.3), new Point3D(-20, -60, 50), new Point3D(0, -40, 0), new Point3D(-3.78, -43.85, 50)), new geometries.Polygon (new Color(java.awt.Color.YELLOW), new Material(0, 1, 150, 0.7, 0.3), new Point3D(-3.78, -43.85, 50), new Point3D(0, -40, 0), new Point3D(3.39, -43.51, 50)), new geometries.Polygon (new Color(java.awt.Color.YELLOW), new Material(0, 1, 150, 0.7, 0.3), new Point3D(3.39, -43.51, 50), new Point3D(0, -40, 0), new Point3D(20, -60, 50))); //********************************** Cylinder ************************************// scene.addGeometries( new Cylinder( new Color(java.awt.Color.red), new Material(0.3,0.3,150,0.3,0.3), 25, new Ray( new Point3D(50, -40, 12), new Vector(0,0,1)), 100)); scene.addLights(new PointLight( new Color(1000, 600, 0), new Point3D(-100, -100, 34), 0.0004, 0.0000006, 30)); scene.addLights(new SpotLight(new Color(1000, 600, 0), new Point3D(41.68, -67.52, 28.84), new Vector(34.29, 9.93, 0), 1, 0.0004, 0.000006, 40)); scene.addLights(new SpotLight(new Color(1000, 600, 0), new Point3D(-100, 100, -500), new Vector(-1, 1, 2), 1, 0.0004, 0.0000006, 30)); ImageWriter imageWriter = new ImageWriter("finalTest1", 150, 150, 1000, 1000); Render render = new Render(imageWriter, scene); render.renderImage(false, false, false); render.writeToImage(); } /** * Produce a complex picture with many geometries and many light sources * features: soft-shadows, multi-threading, adaptive anti-aliasing */ @Test public void finalTest2() { Scene scene = new Scene("Test scene"); scene.setCamera(new Camera( new Point3D(0, 250, -80), new Vector(0, -250, 80), new Vector(0,-250,80).crossProduct(new Vector(-1,0,0)))); scene.setDistance(200); scene.setBackground(Color.BLACK); scene.setAmbientLight(new AmbientLight(Color.BLACK, 0)); scene.addGeometries(new Plane( Color.BLACK, new Material(0.4,0.6,150,0.2,0.4), new Point3D(0,0,50), new Vector(0,0,1))); //********************************** Sphere ************************************// scene.addGeometries( new Sphere(new Color(java.awt.Color.BLACK), new Material(0, 1, 100, 0.2, 0.8), 20, new Point3D(-50, -20, 30))); scene.addGeometries( new Sphere(new Color(java.awt.Color.BLACK), new Material(0, 1, 100, 0.2, 0.8), 30, new Point3D(-65, -75, 20))); //********************************** Polygons ************************************// scene.addGeometries(new geometries.Polygon (new Color(java.awt.Color.YELLOW), new Material(0.5, 0.5, 150, 0.8, 0.2), new Point3D(0, -40, 0), new Point3D(20, -20, 50), new Point3D(20, -60, 50)), new geometries.Polygon (new Color(java.awt.Color.YELLOW), new Material(0, 1, 150, 0.7, 0.3), new Point3D(20, -20, 50), new Point3D(3.52, -36.88, 50), new Point3D(0, -40, 0)), new geometries.Polygon (new Color(java.awt.Color.YELLOW), new Material(0, 1, 150, 0.7, 0.3), new Point3D(3.52, -36.88, 50), new Point3D(0, -40, 0), new Point3D(-3.65, -36.76, 50)), new geometries.Polygon (new Color(java.awt.Color.YELLOW), new Material(0, 1, 150, 0.7, 0.3), new Point3D(-3.65, -36.67, 50), new Point3D(0, -40, 0), new Point3D(-20.1, -20, 50)), new geometries.Polygon (new Color(java.awt.Color.YELLOW), new Material(0, 1, 150, 0.7, 0.3), new Point3D(-20.1, -20, 50), new Point3D(0, -40, 0), new Point3D(-20, -60, 50)), new geometries.Polygon (new Color(java.awt.Color.YELLOW), new Material(0, 1, 150, 0.7, 0.3), new Point3D(-20, -60, 50), new Point3D(0, -40, 0), new Point3D(-3.78, -43.85, 50)), new geometries.Polygon (new Color(java.awt.Color.YELLOW), new Material(0, 1, 150, 0.7, 0.3), new Point3D(-3.78, -43.85, 50), new Point3D(0, -40, 0), new Point3D(3.39, -43.51, 50)), new geometries.Polygon (new Color(java.awt.Color.YELLOW), new Material(0, 1, 150, 0.7, 0.3), new Point3D(3.39, -43.51, 50), new Point3D(0, -40, 0), new Point3D(20, -60, 50))); //********************************** Cylinder ************************************// scene.addGeometries( new Cylinder( new Color(java.awt.Color.red), new Material(0.3,0.3,150,0.3,0.3), 25, new Ray( new Point3D(50, -40, 12), new Vector(0,0,1)), 100)); scene.addLights(new PointLight( new Color(1000, 600, 0), new Point3D(-100, -100, 34), 0.0004, 0.0000006, 30)); scene.addLights(new SpotLight(new Color(1000, 600, 0), new Point3D(41.68, -67.52, 28.84), new Vector(34.29, 9.93, 0), 1, 0.0004, 0.000006, 40)); scene.addLights(new SpotLight(new Color(1000, 600, 0), new Point3D(-100, 100, -500), new Vector(-1, 1, 2), 1, 0.0004, 0.0000006, 30)); ImageWriter imageWriter = new ImageWriter("finalTest2", 150, 150, 1000, 1000); Render render = new Render(imageWriter, scene). setMultithreading(3). setDebugPrint(); render.renderImage(false, true, true); render.writeToImage(); } }
true
97e3b49a0e705cf38a591ad71779feeba7625c31
Java
apache/cxf
/services/xkms/xkms-client/src/test/java/org/apache/cxf/xkms/cache/XKMSClientCacheTest.java
UTF-8
4,792
2.171875
2
[ "LicenseRef-scancode-unknown", "Apache-2.0" ]
permissive
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.xkms.cache; import java.math.BigInteger; import java.security.KeyStore; import java.security.cert.X509Certificate; import org.apache.cxf.common.classloader.ClassLoaderUtils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * A test for the XKMSClientCache */ public class XKMSClientCacheTest { private final XKMSClientCache cache; private final X509Certificate alice; private final X509Certificate bob; public XKMSClientCacheTest() throws Exception { cache = new EHCacheXKMSClientCache(); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", XKMSClientCacheTest.class), "password".toCharArray()); alice = (X509Certificate)keystore.getCertificate("alice"); keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(ClassLoaderUtils.getResourceAsStream("keys/bob.jks", XKMSClientCacheTest.class), "password".toCharArray()); bob = (X509Certificate)keystore.getCertificate("bob"); } @org.junit.Test public void testCache() { assertNotNull(alice); assertNotNull(bob); XKMSCacheToken aliceToken = new XKMSCacheToken(); aliceToken.setX509Certificate(alice); // Put storeCertificateInCache(alice, false); storeCertificateInCache(bob, false); // Get XKMSCacheToken cachedToken = cache.get(alice.getSubjectX500Principal().getName()); assertEquals(alice, cachedToken.getX509Certificate()); assertFalse(cachedToken.isXkmsValidated()); cache.get(getKeyForIssuerSerial(alice.getIssuerX500Principal().getName(), alice.getSerialNumber())); assertEquals(alice, cachedToken.getX509Certificate()); assertFalse(cachedToken.isXkmsValidated()); cachedToken = cache.get(bob.getSubjectX500Principal().getName()); assertEquals(bob, cachedToken.getX509Certificate()); assertFalse(cachedToken.isXkmsValidated()); cache.get(getKeyForIssuerSerial(bob.getIssuerX500Principal().getName(), bob.getSerialNumber())); assertEquals(bob, cachedToken.getX509Certificate()); assertFalse(cachedToken.isXkmsValidated()); // Validate cachedToken = cache.get(alice.getSubjectX500Principal().getName()); cachedToken.setXkmsValidated(true); cachedToken = cache.get(alice.getSubjectX500Principal().getName()); assertTrue(cachedToken.isXkmsValidated()); cache.get(getKeyForIssuerSerial(alice.getIssuerX500Principal().getName(), alice.getSerialNumber())); assertTrue(cachedToken.isXkmsValidated()); } private void storeCertificateInCache(X509Certificate certificate, boolean validated) { XKMSCacheToken cacheToken = new XKMSCacheToken(certificate); cacheToken.setXkmsValidated(validated); // Store it using IssuerSerial String issuerSerialKey = getKeyForIssuerSerial(certificate.getIssuerX500Principal().getName(), certificate.getSerialNumber()); cache.put(issuerSerialKey, cacheToken); // Store it using the Subject DN as well String subjectDNKey = certificate.getSubjectX500Principal().getName(); cache.put(subjectDNKey, cacheToken); } private String getKeyForIssuerSerial(String issuer, BigInteger serial) { return issuer + "-" + serial.toString(16); } }
true
0aab9e3db46ddd6a34bb0c895110f2fb6a38502a
Java
hakanai/TimeFlow
/src/timeflow/app/ui/ReorderFieldsPanel.java
UTF-8
2,032
2.5625
3
[]
no_license
package timeflow.app.ui; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.util.ArrayList; import java.util.Enumeration; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.table.TableColumn; import timeflow.data.db.Field; import timeflow.model.ModelPanel; import timeflow.model.TFEvent; import timeflow.model.TFModel; import timeflow.views.TableView; public class ReorderFieldsPanel extends ModelPanel { TableView table; public ReorderFieldsPanel(TFModel model) { super(model); setLayout(new BorderLayout()); JPanel top = new JPanel(); top.setLayout(new GridLayout(3, 1)); top.add(new JPanel()); JLabel instructions = new JLabel("Drag and drop the column headers to reorder fields."); top.add(instructions); top.add(new JPanel()); add(top, BorderLayout.NORTH); table = new TableView(model); add(table, BorderLayout.CENTER); table.setEditable(false); table.setReorderable(true); table.onscreen(true); } public void applyReordering() { Enumeration<TableColumn> columns = table.getTable().getTableHeader().getColumnModel().getColumns(); ArrayList<Field> newOrder = new ArrayList<Field>(); while (columns.hasMoreElements()) { TableColumn col = columns.nextElement(); String name = col.getHeaderValue().toString(); newOrder.add(getModel().getDB().getField(name)); } getModel().getDB().setNewFieldOrder(newOrder); } public void detachFromModel() { TFModel model = getModel(); model.removeListener(table); model.removeListener(this); } public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); return new Dimension(Math.max(700, d.width), 250); } @Override public void note(TFEvent e) { // TODO Auto-generated method stub } }
true
8db00b5e1093fb927e639d2d44466352f862f538
Java
Corinne-zhu/Head_first_Java
/src/Chapter3_VariableType/Dog.java
UTF-8
610
3.703125
4
[ "MIT" ]
permissive
package Chapter3_VariableType; // 創建dog 對象 public class Dog { public String name; public int size; // 大小影響叫聲 public Dog() { super(); } public Dog(String name, int size) { super(); this.name = name; this.size = size; } public void bark() { if (this.size > 60) { System.out.println("Woof! Woof!"); } else if (this.size > 14) { System.out.println("Ruff ! Ruff !"); } else { System.out.println("Yip ! Yip!"); } } public void eat() { System.out.println("I like eat meat!"); } public void chaseCat() { System.out.println("I can chase cat!"); } }
true
0f92a91fb3a29765a334ac9b0a4eebe4b950ae82
Java
Ethon/logmaker
/logmaker-desktop/src/main/java/cc/ethon/logmaker/gen/model/WeightModel.java
UTF-8
1,374
2.703125
3
[]
no_license
package cc.ethon.logmaker.gen.model; import java.text.DecimalFormat; import freemarker.template.SimpleScalar; import freemarker.template.TemplateMethodModelEx; import freemarker.template.TemplateModelException; public class WeightModel { private static final String DEFAULT_FORMAT = "$KGkg"; private static final DecimalFormat WEIGHT_FORMATTER = new DecimalFormat("0.##"); private static final int GRAMS_PER_KILOGRAM = 1000; private final int grams; public WeightModel(int grams) { super(); this.grams = grams; } public int getGrams() { return grams; } public int getKilograms() { return grams / GRAMS_PER_KILOGRAM; } public int getGramsOfKilogram() { return getGrams() - getKilograms() * GRAMS_PER_KILOGRAM; } public TemplateMethodModelEx getFormatWeight() { return (args) -> { try { String string = !args.isEmpty() ? ((SimpleScalar) args.get(0)).getAsString() : DEFAULT_FORMAT; string = string.replace("$G", String.valueOf(getGrams())); string = string.replace("$g", String.valueOf(getGramsOfKilogram())); string = string.replace("$kg", String.valueOf(getKilograms())); string = string.replace("$KG", WEIGHT_FORMATTER.format(1.0 * getGrams() / GRAMS_PER_KILOGRAM)); return string; } catch (final Exception e) { throw new TemplateModelException("Usage: formatWeight([formatString])", e); } }; } }
true
59bd1ccaec1a16aab616e27b9d2708e0b7452977
Java
mhelmi/CarShowroom
/app/src/main/java/com/bugevil/mhelmi/carshowroom/features/cars/domain/models/Car.java
UTF-8
952
2.34375
2
[]
no_license
package com.bugevil.mhelmi.carshowroom.features.cars.domain.models; import android.content.Context; import androidx.annotation.Keep; import com.bugevil.mhelmi.carshowroom.R; import com.google.gson.annotations.SerializedName; @Keep public class Car { @SerializedName("id") private int id; @SerializedName("brand") private String brand; @SerializedName("constructionYear") private String constructionYear; @SerializedName("isUsed") private boolean isUsed; @SerializedName("imageUrl") private String imageUrl; public int getId() { return id; } public String getBrand() { return brand; } public String getConstructionYear() { return constructionYear; } public boolean isUsed() { return isUsed; } public String getImageUrl() { return imageUrl; } public String isUsedText(Context context) { return isUsed ? context.getString(R.string.used) : context.getString(R.string.is_new); } }
true
15b6c79ab0df24e0531870de0874c3a9187a7368
Java
atsisy/yes_bomber
/src/filed/BattleField.java
UTF-8
433
2.390625
2
[]
no_license
package filed; import javafx.scene.input.KeyCode; /** * Created by Akihiro on 2017/04/30. */ public class BattleField extends Field { public BattleField(){ super(); } @Override public void ReceiveKeyCode(KeyCode code){ if(code.equals(KeyCode.UP)){ }else if(code.equals(KeyCode.DOWN)){ }else if(code.equals(KeyCode.ENTER)){ System.out.println("a"); } } }
true
2e3cdb9769ac7e1ff68f988b39e0044b67ae98cb
Java
chyciu/hibernate_pacjentUpo_Embedded_Embeddable
/src/main/java/rozwiazanie/Zadanie1_rozwiazanie.java
UTF-8
243
1.5
2
[]
no_license
package rozwiazanie; import org.hibernate.Session; public class Zadanie1_rozwiazanie { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); session.close(); } }
true
4fcbf71962ed7f7a5ab78b3861ec170875cbd9df
Java
SN4NTR/TelegramBot
/src/main/java/com/company/bot/service/BotService.java
UTF-8
648
2.03125
2
[]
no_license
package com.company.bot.service; import org.telegram.telegrambots.meta.api.methods.send.SendChatAction; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup; import java.util.Optional; public interface BotService { Optional<Long> getChatId(Update update); Optional<String> getIncomingMessage(Update update); SendMessage createOutgoingMessage(Long chatId, String incomingMessage); SendChatAction createChatAction(Long chatId); ReplyKeyboardMarkup getKeyBoard(); }
true
d0c222deb974ed4f79a7b9c4b98c6a432faaa2e6
Java
IF3110-II-7/IF3110-02-Simple-Blog-Java
/src/java/Bean/UnpublishedPost.java
UTF-8
1,276
2.296875
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 Bean; import Database.DatabaseAccess; import Model.Post; import Model.Posts; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; /** * * @author kevinyu */ @ManagedBean @RequestScoped public class UnpublishedPost { private ArrayList<Post> unpublishedPosts; public ArrayList<Post> getUnpublishedPosts() { return unpublishedPosts; } public void setUnpublishedPosts(ArrayList<Post> unpublishedPosts) { this.unpublishedPosts = unpublishedPosts; } public UnpublishedPost() { try { DatabaseAccess dbManager = DatabaseAccess.getInstance(); dbManager.openConnection(); unpublishedPosts = Posts.getInstance().getUnpublishedPost(); dbManager.closeConnection(); } catch (SQLException ex) { Logger.getLogger(PublishPostBean.class.getName()).log(Level.SEVERE, null, ex); } } }
true
fd28cd4cb7fbaf5cbb9c8517b1c85acd491f276f
Java
mateusgon/TesteSoftware
/src/test/java/PaginaTeste.java
UTF-8
919
1.953125
2
[]
no_license
import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.PageFactory; // public class PaginaTeste { static WebDriver driver; @BeforeClass public static void configura() { System.setProperty("webdriver.gecko.driver", "C:\\Users\\Mateus G\\Desktop\\geckodriver.exe"); driver = (WebDriver) new FirefoxDriver(); driver.get("https://accounts.google.com/signup/v2/webcreateaccount?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ltmpl=default&flowName=GlifWebSignIn&flowEntry=SignUp"); } @Test public void test() { myFirstTest pag = PageFactory.initElements(driver, myFirstTest.class); pag.preencheDados("Cassioooooo", "Coringao"); pag.loga(); //WebElement ddd; //assertNotNull(ddd); } }
true
41e53151c750f4e7383df68ee04e453312f80a4f
Java
AviAvin/ArrayJavaScript
/Avinash2/src/webdriver/DropdownPB.java
UTF-8
908
2.125
2
[]
no_license
package webdriver; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.Select; public class DropdownPB { public static void main(String[] args) { WebDriver driver=new FirefoxDriver(); driver.get("http://primusbank.qedgetech.com/"); WebElement from1=driver.findElement(By.xpath(".//*[@id='drlist']")); // Get the list from the drop down list Selenium WebDriver List<WebElement> list1=from1.findElements(By.tagName("option")); for(WebElement i:list1) { System.out.println(i.getText()); //Reporter.log(i.getText()); } Select drop=new Select(driver.findElement(By.xpath(".//*[@id='drlist']"))); drop.selectByVisibleText("ameerpet"); driver.close(); } }
true
4d09daf75024072f4ae12abdfe519f4efc20a3f0
Java
merkle-open/spring-configuration-support
/spring-configuration-support/src/main/java/com/namics/oss/spring/support/configuration/model/ConfigurationValue.java
UTF-8
1,718
2.390625
2
[ "MIT" ]
permissive
/* * Copyright 2000-2011 namics ag. All rights reserved. */ package com.namics.oss.spring.support.configuration.model; import com.namics.oss.spring.support.configuration.Environment; import java.io.Serializable; /** * Represents a configuration value. * * @author Sandro Ruch, namics ag * @since namics-configuration 2.2 */ public class ConfigurationValue implements Serializable { private static final long serialVersionUID = -5472586633561237500L; private Environment env; private String key; private String value; /** * Default constructor. * * @param env the environment * @param key the key * @param value the value */ public ConfigurationValue(Environment env, String key, String value) { super(); this.env = env; this.key = key; this.value = value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ConfigurationValue that = (ConfigurationValue) o; if (env != null ? !env.equals(that.env) : that.env != null) { return false; } return key != null ? key.equals(that.key) : that.key == null; } @Override public int hashCode() { int result = env != null ? env.hashCode() : 0; result = 31 * result + (key != null ? key.hashCode() : 0); return result; } @Override public String toString() { return "ConfigurationValue{" + "key='" + key + '\'' + ", env=" + env + ", value='" + value + '\'' + '}'; } public String getKey() { return key; } public String getValue() { return value; } public Environment getEnv() { return env; } public void setEnv(Environment env) { this.env = env; } }
true
48f9b0ed7ae9b9f82f9f3aa3e28bb9b8ae854a06
Java
623162052/spring-demo
/src/main/java/com/dubbo/service/impl/CustomerServiceImpl.java
UTF-8
660
2.125
2
[]
no_license
package com.dubbo.service.impl; import com.dubbo.service.ICustomerService; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; /** * 客户信息接口 * Created by shiwx on 2017/6/15. */ @Service public class CustomerServiceImpl implements ICustomerService { /** * 查询客户信息 * @return * @throws Exception */ @Override public Map<String, Object> queryCustomerInfo() throws Exception { Map<String, Object> customerInfo = new HashMap<>(); customerInfo.put("customName", "ooOoo"); customerInfo.put("age", 18); return customerInfo; } }
true
d295fdd9b2a2ae89d6bac4e477650fefdcd4706c
Java
ElisaaRodrigues/Agenda-Telefonica
/src/main/java/poo/Principal.java
UTF-8
556
2.734375
3
[]
no_license
package poo; import java.time.LocalDate; public class Principal { public static void main(String[] args) { Agenda agenda = new Agenda(); Pessoa stefanie = new Pessoa("Stefanie", "Martins", LocalDate.of(1997,7,14)); stefanie.addTelefone("celular", "48996948370"); stefanie.addEmail("aluno.ifsc", "stefanie.m@aluno.ifsc.edu.br"); agenda.addPessoa(stefanie); System.out.println(agenda.toString()); agenda.removePessoa("Stefanie", "Martins"); System.out.println(agenda.toString() + "agenda vazia"); } }
true
d8e34295835886b5913171e020636ad195598231
Java
edwinvanelk/multifactor-authentication
/javasource/googleauthenticator/proxies/constants/Constants.java
UTF-8
625
1.585938
2
[]
no_license
// This file was generated by Mendix Studio Pro. // // WARNING: Code you write here will be lost the next time you deploy the project. package googleauthenticator.proxies.constants; import com.mendix.core.Core; public class Constants { // These are the constants for the GoogleAuthenticator module public static java.lang.Long getDaysBeforeExpiry() { return (java.lang.Long)Core.getConfiguration().getConstantValue("GoogleAuthenticator.DaysBeforeExpiry"); } public static java.lang.String getIssuerMFA() { return (java.lang.String)Core.getConfiguration().getConstantValue("GoogleAuthenticator.IssuerMFA"); } }
true
0f45b95ec5bec8fde77a3dae756e1be7306772e6
Java
SulthanRafif/PushNotification
/app/src/main/java/com/example/pushnotification/MainActivity.java
UTF-8
3,713
2.03125
2
[]
no_license
package com.example.pushnotification; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.NotificationCompat; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class MainActivity extends AppCompatActivity { private EditText editTextNama, editTextMakanan, editTextJumlah, editTextAlamat, editTextNotelp; private String nama, makanan, jumlah, alamat, notelp; private DatabaseReference mDatabase; private NotificationManager mNotificationManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Get the database in firebase mDatabase = FirebaseDatabase.getInstance().getReference(); // define the textview editTextNama = findViewById(R.id.edit_nama); editTextMakanan = findViewById(R.id.edit_makanan); editTextJumlah = findViewById(R.id.edit_jumlah_makanan); editTextAlamat = findViewById(R.id.edit_alamat); editTextNotelp = findViewById(R.id.edit_no_telp); } public void onSubmit(View view) { nama = editTextNama.getText().toString(); makanan = editTextMakanan.getText().toString(); jumlah = editTextJumlah.getText().toString(); alamat = editTextAlamat.getText().toString(); notelp = editTextNotelp.getText().toString(); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel("YOUR_CHANNEL_ID", "YOUR_CHANNEL_NAME", NotificationManager.IMPORTANCE_DEFAULT); channel.setDescription("YOUR_NOTIFICATION_CHANNEL_DISCRIPTION"); mNotificationManager.createNotificationChannel(channel); } final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), "YOUR_CHANNEL_ID") .setSmallIcon(R.mipmap.ic_launcher) // notification icon .setContentTitle("Pemesanan Makanan") // title for notification .setContentText("Pemesanan berhasil!")// message for notification .setAutoCancel(true); // clear notification after click Intent intent = new Intent(getApplicationContext(), MainActivity.class); PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pi); mNotificationManager.notify(0, mBuilder.build()); DatabaseReference newData = mDatabase.child("data"); newData.child("notelp").setValue(notelp); newData.child("alamat").setValue(alamat); newData.child("jumlah").setValue(jumlah); newData.child("makanan").setValue(makanan); newData.child("nama").setValue(nama).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); nm.notify(0, mBuilder.build()); } }); } }
true
796eae5df700b9b7acd6f761dd3d71751d6be449
Java
zhangweimtan/zhangweiJava
/proj3MyFlowControl/src/com/mytest_for_03/ForTest_99_Table.java
UTF-8
361
3.125
3
[]
no_license
package com.mytest_for_03; /* 九九乘法口诀 */ public class ForTest_99_Table { public static void main(String[] args) { // 定义变量 for(int i=1; i<10; i++ ) { for(int j =1; j<=i; j++) { System.out.printf("%d*%d=%2d%s",i, j, i*j,"\t"); } System.out.println(); } } }
true
0a97e44eb80b02174bd025012ff23d922c9770a4
Java
chun2333/incubator-inlong
/inlong-manager/manager-workflow-engine/src/main/java/org/apache/inlong/manager/workflow/util/WorkflowFormParserUtils.java
UTF-8
3,598
2.203125
2
[ "Apache-2.0", "LicenseRef-scancode-compass", "MIT", "BSD-3-Clause" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.inlong.manager.workflow.util; import com.fasterxml.jackson.databind.JavaType; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.inlong.manager.common.util.JsonUtils; import org.apache.inlong.manager.common.util.Preconditions; import org.apache.inlong.manager.workflow.exception.FormParseException; import org.apache.inlong.manager.workflow.model.definition.Process; import org.apache.inlong.manager.workflow.model.definition.ProcessForm; import org.apache.inlong.manager.workflow.model.definition.Task; import org.apache.inlong.manager.workflow.model.definition.TaskForm; import org.apache.inlong.manager.workflow.model.definition.UserTask; import org.apache.inlong.manager.workflow.model.instance.TaskInstance; /** * Process form analysis tool */ @Slf4j public class WorkflowFormParserUtils { /** * Parse the task form in JSON string format into a Task instance */ public static <T extends TaskForm> T parseTaskForm(TaskInstance taskInstance, Process process) throws FormParseException { Preconditions.checkNotNull(taskInstance, "taskInstance can't be null"); Preconditions.checkNotNull(process, "process can't be null"); if (StringUtils.isEmpty(taskInstance.getFormData())) { return null; } Task task = process.getTaskByName(taskInstance.getName()); Preconditions.checkNotNull(task, () -> "user task not exist " + taskInstance.getName()); Preconditions.checkTrue(task instanceof UserTask, () -> "task should be userTask " + taskInstance.getName()); UserTask userTask = (UserTask) task; try { JavaType javaType = JsonUtils.MAPPER.constructType(userTask.getFormClass()); return JsonUtils.parse(taskInstance.getFormData(), javaType); } catch (Exception e) { log.error("task form parse failed! formData is: {}", taskInstance.getFormData(), e); throw new FormParseException("task form parse failed!"); } } /** * Parse the process form in JSON string format into a Process instance */ public static <T extends ProcessForm> T parseProcessForm(String formDate, Process process) throws FormParseException { Preconditions.checkNotNull(process, "process can't be null"); if (StringUtils.isEmpty(formDate)) { return null; } try { JavaType javaType = JsonUtils.MAPPER.constructType(process.getFormClass()); return JsonUtils.parse(formDate, javaType); } catch (Exception e) { log.error("process form parse failed! formData is: {}", formDate, e); throw new FormParseException("process form parse failed!"); } } }
true
21451cbb18f7c5f8fdb67c6c4b5fbf9a51251d75
Java
yonathanliem2489/DEMO-CONFIGURATION-SPRING-BOOT
/src/main/java/demo/configuration/service/cache/DefaultDirectoryCache.java
UTF-8
679
2.28125
2
[]
no_license
package demo.configuration.service.cache; import demo.configuration.service.model.entity.Directory; import org.springframework.data.redis.core.ReactiveRedisTemplate; import org.springframework.util.Assert; import reactor.core.publisher.Mono; public class DefaultDirectoryCache implements DirectoryCache { private final ReactiveRedisTemplate<Object, Object> redisTemplate; public DefaultDirectoryCache( ReactiveRedisTemplate<Object, Object> redisTemplate) { Assert.notNull(redisTemplate, "redisTemplate must be provide"); this.redisTemplate = redisTemplate; } @Override public Mono<Boolean> exist(Directory directory) { return Mono.empty(); } }
true
03460926938cdece1b617e2affa18574e88f267f
Java
snobotsim/CoordinateGui
/CoordinateGuiCore/src/main/java/org/snobot/coordinate_gui/ui/layers/BaseGuiController.java
UTF-8
8,598
2.046875
2
[ "MIT" ]
permissive
package org.snobot.coordinate_gui.ui.layers; import javafx.scene.paint.Color; import org.snobot.coordinate_gui.model.FieldLoader; import org.snobot.coordinate_gui.model.Coordinate; import org.snobot.coordinate_gui.model.DataProvider; import org.snobot.coordinate_gui.model.Distance; import org.snobot.coordinate_gui.model.PixelConverter; import javafx.beans.binding.Bindings; import javafx.fxml.FXML; import javafx.scene.Group; import javafx.scene.image.Image; import javafx.scene.layout.Pane; import javafx.scene.transform.Scale; import org.snobot.coordinate_gui.model.Position2dDistance; import org.snobot.coordinate_gui.ui.render_props.CoordinateLayerRenderProps; import java.util.List; @SuppressWarnings("PMD.TooManyFields") public class BaseGuiController { private final Image mFieldImage; private final Distance mFieldShortDimension; private final Distance mFieldLongDimension; private final Distance mRobotWidth; private final Distance mRobotHeight; protected final PixelConverter mPixelConverter; private final DataProvider<Coordinate> mCoordinatesDataProvider; private final CoordinateLayerRenderProps mCoordinatesRenderProperties; private final DataProvider<Coordinate> mIdealTrajectoryDataProvider; private final CoordinateLayerRenderProps mIdealTrajectoryRenderProperties; private final DataProvider<Coordinate> mIdealRamseteDataProvider; private final CoordinateLayerRenderProps mIdealRamseteRenderProperties; @FXML protected Pane mTopPane; @FXML protected FieldLayerController mFieldController; @FXML protected Group mLayers; @FXML private CameraRayLayerController mCameraLayerController; @FXML private RobotPositionLayerController mRobotPositionController; @FXML private TrajectoryConfigLayerController mTrajectoryConfigController; @FXML private GoToPositionController mGoToPositionController; @FXML private CoordinateLayerController mFadingCoordinatesController; @FXML private CoordinateLayerController mIdealTrajectoryCoordinatesController; @FXML private CoordinateLayerController mIdealRamseteCoordinatesController; @FXML private PurePursuitLayerController mPurePursuitController; protected BaseGuiController(FieldLoader.FieldsConfig aFieldConfig) { this(new FieldLoader(aFieldConfig), Distance.fromInches(36), Distance.fromInches(44)); } protected BaseGuiController(FieldLoader aFieldLoader, Distance aRobotWidth, Distance aRobotHeight) { this(aFieldLoader.getImage(), aFieldLoader.getShortDim(), aFieldLoader.getLongDim(), aRobotWidth, aRobotHeight, PixelConverter.Orientation.Landscape, PixelConverter.OriginPosition.BottomLeft); } protected BaseGuiController(String aFieldImageUrl, Distance aShortDirection, Distance aLongDirection, Distance aRobotWidth, Distance aRobotHeight, PixelConverter.Orientation aOrientation, PixelConverter.OriginPosition aOriginPosition) { this(new Image(BaseGuiController.class.getResource(aFieldImageUrl).toExternalForm()), aShortDirection, aLongDirection, aRobotWidth, aRobotHeight, aOrientation, aOriginPosition); } protected BaseGuiController(Image aFieldImage, Distance aShortDirection, Distance aLongDirection, Distance aRobotWidth, Distance aRobotHeight, PixelConverter.Orientation aOrientation, PixelConverter.OriginPosition aOriginPosition) { mFieldImage = aFieldImage; mFieldShortDimension = aShortDirection; mFieldLongDimension = aLongDirection; mRobotWidth = aRobotWidth; mRobotHeight = aRobotHeight; mPixelConverter = new PixelConverter(mFieldShortDimension, mFieldLongDimension, aOrientation, aOriginPosition); mCoordinatesRenderProperties = new CoordinateLayerRenderProps(100, 5, Color.ORANGERED, true); mCoordinatesDataProvider = new DataProvider<>(750); mIdealTrajectoryRenderProperties = new CoordinateLayerRenderProps(100, 1, Color.YELLOWGREEN, false); mIdealTrajectoryDataProvider = new DataProvider<>(); mIdealRamseteRenderProperties = new CoordinateLayerRenderProps(100, 5, Color.DARKRED, false); mIdealRamseteDataProvider = new DataProvider<>(); } /** * Called after FXML fields have been initialized. */ public void initialize() { mFieldController.setFieldParameters(mFieldImage); Scale scale = new Scale(); scale.xProperty() .bind(Bindings.createDoubleBinding( () -> Math.min(mTopPane.getWidth() / mFieldImage.getWidth(), mTopPane.getHeight() / mFieldImage.getHeight()), mTopPane.widthProperty(), mTopPane.heightProperty())); scale.yProperty() .bind(Bindings.createDoubleBinding( () -> Math.min(mTopPane.getWidth() / mFieldImage.getWidth(), mTopPane.getHeight() / mFieldImage.getHeight()), mTopPane.widthProperty(), mTopPane.heightProperty())); mLayers.getTransforms().add(scale); mPixelConverter.setImageScale(scale, mFieldImage.getWidth(), mFieldImage.getHeight(), mFieldShortDimension, mFieldLongDimension); mRobotPositionController.setRobotDimensions(mPixelConverter, mRobotWidth, mRobotHeight); mFadingCoordinatesController.setup(mCoordinatesRenderProperties, mCoordinatesDataProvider, mPixelConverter); mIdealTrajectoryCoordinatesController.setup(mIdealTrajectoryRenderProperties, mIdealTrajectoryDataProvider, mPixelConverter); mIdealRamseteCoordinatesController.setup(mIdealRamseteRenderProperties, mIdealRamseteDataProvider, mPixelConverter); mPurePursuitController.setup(mPixelConverter); } public PixelConverter getPixelConverter() { return mPixelConverter; } /** * Adds a robot position to the layers. * * @param aRobotPosition * The position of the robot */ public void addRobotPosition(Coordinate aRobotPosition) { mRobotPositionController.setPosition(mPixelConverter, aRobotPosition); mCoordinatesDataProvider.addData(aRobotPosition); mFadingCoordinatesController.render(); } public void setCameraRays(List<CameraRayLayerController.Ray> aRays) { mCameraLayerController.setRays(mPixelConverter, aRays); } public void setWaypoints(List<Coordinate> aWaypoints) { mTrajectoryConfigController.setTrajectoryPoints(mPixelConverter, aWaypoints); } public List<Coordinate> getWaypoints() { return mTrajectoryConfigController.getWaypoints(); } /** * Sets the ideal trajectory to draw on the display. * * @param aCoordinates * The ideal trajectory */ public void setIdealTrajectory(List<Coordinate> aCoordinates) { mIdealTrajectoryDataProvider.clear(); for (Coordinate coord : aCoordinates) { mIdealTrajectoryDataProvider.addData(coord); } mIdealTrajectoryCoordinatesController.render(); } /** * Sets the ideal trajectory to draw on the display. * * @param aCoordinates * The ideal trajectory */ public void setIdealRamsete(List<Coordinate> aCoordinates) { mIdealRamseteDataProvider.clear(); for (Coordinate coord : aCoordinates) { mIdealRamseteDataProvider.addData(coord); } mIdealRamseteCoordinatesController.render(); } public TrajectoryConfigLayerController.CoodrinateWrapper getSelectedWaypoint() { return mTrajectoryConfigController.getSelectedWaypoint(); } public void addIdealTrajectory(Coordinate aCoordinate) { mTrajectoryConfigController.addPoint(mPixelConverter, aCoordinate); } public void setGoToXYPosition(Position2dDistance aPosition) { mGoToPositionController.setGoToXYPosition(mPixelConverter, aPosition); } public void setPurePursuitWaypoints(List<Coordinate> aCoordinates, List<Coordinate> aUpSampled, List<Coordinate> aSmoothed) { mPurePursuitController.setWaypoints(aCoordinates, aUpSampled, aSmoothed); } public void setPurePursuitLookahead(PurePursuitLayerController.PurePursuitLookaheadData aData) { mPurePursuitController.setLookaheadLine(aData); } }
true
7498093e384770a049feab81ceb7d1a02788f416
Java
geakstr/labs
/corp-dev/lab5/src/ru/aspu/javaee/lab5/datamanager/dao/UserDao.java
UTF-8
387
2.046875
2
[]
no_license
package ru.aspu.javaee.lab5.datamanager.dao; import java.util.List; import ru.aspu.javaee.lab5.datamanager.dao.generics.IGenericDao; import ru.aspu.javaee.lab5.entities.Comment; import ru.aspu.javaee.lab5.entities.User; public interface UserDao extends IGenericDao<User> { public abstract List<User> getAll(); public abstract List<Comment> getUserComments(User user); }
true
c4d9b584e79672c73dfb9933c79555de311d102a
Java
nlp-lap/Version_Compatible_HL7_Parser
/hl7/pseudo/message/MFR_M06.java
UTF-8
298
1.617188
2
[]
no_license
package hl7.pseudo.message; import hl7.bean.Structure; public class MFR_M06 extends hl7.model.V2_6.message.MFR_M06{ public MFR_M06(){ super(); } public static MFR_M06 CLASS; static{ CLASS = new MFR_M06(); } public Structure[][] getComponents(){ return super.getComponents(); } }
true
c98336edd10f73ed2b58536a780134d11f093063
Java
DongPhamBK/Java_Eclipse
/Exception/src/exp/None.java
UTF-8
504
3.484375
3
[]
no_license
package exp; public class None { public static void main(String[] args) { //chia2So(1, 2);//không thể đứng 1 mình, bắt buộc try catch try { chia2So(1, 0); } catch (NewException e) { //System.out.println(e); System.out.println(e.getErr());// vi diệu } } public static void chia2So(int a, int b) throws NewException { try{ int c = a/b;// lỗi nếu chia cho 0 System.out.println(c); }catch(Exception e){ throw new NewException("Lỗi chia cho 0");// dùng constructor } } }
true
b7b4bc6a35c69fb8f919168ce11cc49e3eeafd98
Java
sameer9314/Log_In_SignUp_UsingServlet
/src/com/bridgelabzservlet/dao/JdbcImpl.java
UTF-8
5,348
2.765625
3
[]
no_license
package com.bridgelabzservlet.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.bridgelabzservlet.dto.ConnectionPoolManager; import com.bridgelabzservlet.dto.UserBean; /** * Purpose : To authenticate email,password ,user log in details and Update Account. * @author : Sameer Saurabh * @version : 1.0 * @since : 29/06/2018 */ public class JdbcImpl implements UserDao{ public boolean emailChecker(String email) { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; ConnectionPoolManager pool = null; try { pool = ConnectionPoolManager.getInstance(); con = pool.getConnectionFromPool(); String query = " select * from user_detail where email = ?"; pstmt =con.prepareStatement(query); pstmt.setString(1, email); rs = pstmt.executeQuery(); if(rs.next()) { return true; } else{ return false; } } catch (Exception e) { e.printStackTrace(); return false; } finally{ try { if(pstmt!=null){ pstmt.close(); } if(rs!=null){ rs.close(); } pool.returnConnectionToPool(con); } catch (SQLException e) { e.printStackTrace(); } }//End of outer try-catch } public boolean passwordChecker(String email,String password) { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; ConnectionPoolManager pool = null; try { pool = ConnectionPoolManager.getInstance(); con = pool.getConnectionFromPool(); String query = " select * from user_detail "+ " where email = ? "+ " and password = ?"; pstmt =con.prepareStatement(query); pstmt.setString(1, email); pstmt.setString(2, password); rs = pstmt.executeQuery(); if(rs.next()) { return true; } else{ return false; } } catch (Exception e) { e.printStackTrace(); return false; } finally{ try { if(pstmt!=null){ pstmt.close(); } if(rs!=null){ rs.close(); } pool.returnConnectionToPool(con); } catch (SQLException e) { e.printStackTrace(); } }//End of outer try-catc } public UserBean authenticate(String email, String password) { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; ConnectionPoolManager pool = null; try { pool = ConnectionPoolManager.getInstance(); con = pool.getConnectionFromPool(); String query = " select * from user_detail "+ " where email = ? "+ " and password = ?"; pstmt =con.prepareStatement(query); pstmt.setString(1, email); pstmt.setString(2, password); rs = pstmt.executeQuery(); //4. Process the Results returned by SQL Queries if(rs.next()) { UserBean bean=new UserBean(); bean.setId(rs.getInt("Sl_No")); bean.setUser_name(rs.getString("user_name")); bean.setEmail(rs.getString("email")); bean.setPhoneNumber("phoneNumber"); bean.setPassword(rs.getString("password")); System.out.println("bean set"); return bean; } else{ return null; } } catch (Exception e) { e.printStackTrace(); return null; } finally{ //5. Close ALL JDBC Objects try { if(pstmt!=null){ pstmt.close(); } if(rs!=null){ rs.close(); } pool.returnConnectionToPool(con); } catch (SQLException e) { e.printStackTrace(); } }//End of outer try-catch }//End of authenticate public int updateAccount(String user_name, String email,String phoneNumber,String password) { Connection con = null; PreparedStatement pstmt = null; ConnectionPoolManager pool = null; int count=0; try { pool = ConnectionPoolManager.getInstance(); con = pool.getConnectionFromPool(); // inserting values into the table account. String query = "insert into user_detail(user_name,email,phoneNumber,password) values(?,?,?,?)"; pstmt = con.prepareStatement(query); pstmt.setString(1, user_name); pstmt.setString(2, email); pstmt.setString(3,phoneNumber); pstmt.setString(4, password); count = pstmt.executeUpdate(); }catch(Exception e) { e.printStackTrace(); }finally { try { if (pstmt != null) { pstmt.close(); } pool.returnConnectionToPool(con); } catch (SQLException e) { e.printStackTrace(); } } return count; } static Connection getConnection() { Connection con = null; ConnectionPoolManager pool = null; try { pool = ConnectionPoolManager.getInstance(); con = pool.getConnectionFromPool(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return con; } public String returnPassword(String email) { String password=null; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; ConnectionPoolManager pool = null; try { pool = ConnectionPoolManager.getInstance(); con = pool.getConnectionFromPool(); String query = " select * from user_detail where email = ?"; pstmt =con.prepareStatement(query); pstmt.setString(1, email); rs = pstmt.executeQuery(); if(rs.next()){ password=rs.getString("password"); } }catch (Exception e) { e.printStackTrace(); } return password; } }
true
30346adef9c839873334b91b7577d116e5282693
Java
SudokuLover/ChildVaccination
/app/src/main/java/com/example/gauranggoel/childvacination/DatabaseVaccinationDetails.java
UTF-8
4,793
2.5625
3
[]
no_license
package com.example.gauranggoel.childvacination; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.util.ArrayList; import java.util.List; /** * Created by gaurang goel on 03-09-2018. */ public class DatabaseVaccinationDetails extends SQLiteOpenHelper{ public static final int DATABASE_VERSION=1; public static final String DATABASE_NAME="VaccineDatabase"; public static final String DATABASE_TABLE="vaccine_record"; public static final String ID = "id"; public static final String NAME="name"; public static final String SCHEDULE="schedule_time"; public static final String GIVEN="given_on"; public static final String STATUS="status"; public static final String TAG="VaccineDatabase"; @Override public void onCreate(SQLiteDatabase db) { Log.d(TAG,"on Create"); String query="create table "+DATABASE_TABLE+" ( "+ ID +" TEXT , "+ NAME+" TEXT, "+SCHEDULE+" TEXT, "+GIVEN+" TEXT, "+STATUS+" TEXT "+ ");"; db.execSQL(query); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.d(TAG,"on upgrade"); db.execSQL("DROP TABLE IF EXISTS"+DATABASE_TABLE+";"); onCreate(db); } public DatabaseVaccinationDetails(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); Log.d(TAG,"constructor"); } public void addRecord(VaccinationObject vaccinationObject){ Log.d(TAG,"add record"); SQLiteDatabase db=getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(ID,vaccinationObject.getId()); contentValues.put(NAME,vaccinationObject.getName()); contentValues.put(SCHEDULE,vaccinationObject.getScheduleTime()); contentValues.put(GIVEN,vaccinationObject.getGivenTime()); contentValues.put(STATUS,vaccinationObject.getStatus()); db.insert(DATABASE_TABLE,null,contentValues); } public void updateRecord(VaccinationObject vaccinationObject ){ Log.d(TAG,"update record"); SQLiteDatabase db = getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(ID,vaccinationObject.getId()); contentValues.put(NAME,vaccinationObject.getName()); contentValues.put(SCHEDULE,vaccinationObject.getScheduleTime()); contentValues.put(GIVEN,vaccinationObject.getGivenTime()); contentValues.put(STATUS,vaccinationObject.getStatus()); db.update(DATABASE_TABLE,contentValues,ID +" =? AND "+NAME+" =? ",new String[]{vaccinationObject.getId(),vaccinationObject.getName()}); db.close(); } public List<VaccinationObject> getAllRecords(String Id){ Log.d(TAG,"get all records"); SQLiteDatabase db=getReadableDatabase(); ArrayList<VaccinationObject> arrayList = new ArrayList<VaccinationObject>(); String query= "select * from "+ DATABASE_TABLE + " where "+ID+" = '"+Id+"';"; Cursor cursor =db.rawQuery(query,null); if(cursor!=null) { if(cursor.moveToFirst()) { do{ VaccinationObject record = new VaccinationObject(); record.setId(cursor.getString(0)); record.setName(cursor.getString(1)); record.setScheduleTime(cursor.getString(2)); record.setGivenTime(cursor.getString(3)); record.setStatus(cursor.getString(4)); arrayList.add(record); } while(cursor.moveToNext()); } } return arrayList; } public VaccinationObject getSingleRecord(String id,String name){ Log.d(TAG,"get single record"); SQLiteDatabase db = getReadableDatabase(); String query="select * from "+ DATABASE_TABLE + " where " + ID +" = '" + id + "' and "+NAME+ " = '"+name+"';" ; Cursor cursor = db.query(DATABASE_TABLE,new String[]{ID,NAME,SCHEDULE,GIVEN,STATUS},ID + " =? AND "+NAME+" =? ", new String[]{id,name},null,null,null); if(cursor!=null) cursor.moveToFirst(); VaccinationObject record = new VaccinationObject(cursor.getString(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4)); return record; } public void deleteRecord(String id){ Log.d(TAG,"on delete"); SQLiteDatabase db = getWritableDatabase(); db.delete(DATABASE_TABLE,ID + " =?" , new String[]{id}); } }
true
6042d55d63a400d73c07cbe7f488f0c376c3017c
Java
mod-magnabeo/Ainur-UHC
/AinurUHC/src/com/Wolf_IV/AnuirUHC/Role/BalrogNoir.java
ISO-8859-1
627
2.265625
2
[]
no_license
package com.Wolf_IV.AnuirUHC.Role; import org.bukkit.entity.Player; import com.Wolf_IV.AnuirUHC.Commands.CStart; import com.Wolf_IV.AnuirUHC.Timers.TimerMort; public class BalrogNoir { static boolean pou = false; public static boolean u(CStart p, Player player, String[] args) { if(p.balrog_noir == null || p.balrog_noir != player) { return false; } if(pou == false) { pou = true; TimerMort.lastMort.stop = true; player.sendMessage("aLe role de ce joueur ne serat pas dvoiler a tous le monde"); }else { player.sendMessage("4Vous vous etes dj servit de votre role"); } return true; } }
true
1cd28cd4003c6e19c114825403bd9950a37b7571
Java
beat-virus/corona_tracker
/backend/corona-server/src/main/java/de/govhackathon/wvsvcoronatracker/model/mapper/UserMapper.java
UTF-8
864
1.875
2
[]
no_license
package de.govhackathon.wvsvcoronatracker.model.mapper; import de.govhackathon.wvsvcoronatracker.model.User; import org.mapstruct.*; import de.ghwct.service.model.UserDto; @Mapper(componentModel = "spring", collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED, nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS, uses = { HealthDataSetMapper.class }) public interface UserMapper { @Mappings({ @Mapping(target = "healthDataSetList", source = "healthHistory"), @Mapping(target = "contactDetails.phoneHash", source = "phoneHash") }) User toEntity(UserDto dto); @InheritInverseConfiguration @Mappings({ @Mapping(target = "healthHistory", source = "healthDataSetList"), @Mapping(target = "phoneHash", source = "contactDetails.phoneHash") }) UserDto toDto(User entity); }
true
d383e2db95feaa44d57e9bff257a83e8941ee67a
Java
Shuo93/Ticker
/common/src/main/java/com/ticker/common/model/Label.java
UTF-8
885
2.328125
2
[]
no_license
package com.ticker.common.model; import java.util.List; import java.util.Map; public class Label extends AbstractProduct { private Map<String, Double> price; private String unit; private double scale; public Map<String, Double> getPrice() { return price; } public void setPrice(Map<String, Double> price) { this.price = price; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public double getScale() { return scale; } public void setScale(double scale) { this.scale = scale; } public static class Menu { private List<String> type; public List<String> getType() { return type; } public void setType(List<String> type) { this.type = type; } } }
true
170e9d003acebc9a7f3737f403fa0c32d999f11c
Java
sikdernizam/Simple-Chatty-Bot
/Problems/The (un)-ordered sequence/src/Main.java
UTF-8
846
3.296875
3
[]
no_license
import java.util.Scanner; class Main { public static void main(String[] args) { // put your code here Scanner scanner = new Scanner(System.in); int[] a = new int[10]; int n = a.length; int count1 = 0; int count2 = 0; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); if (a[i] == 0) { break; } } for (int i = 0; i < n - 1; i++) { if (a[i] != 0) { if (a[i] <= a[i + 1]) { count1++; } if (a[i] > a[i + 1]) { count2++; } } } if (count1 > 1 && count2 > 1) { System.out.println(false); } else { System.out.println(true); } } }
true
e648780df9e172a5e9200dc55120b9266fd64533
Java
statecs/KTH
/ID1005/EnArmadBandit/src/SlotControl.java
UTF-8
2,563
3.5625
4
[]
no_license
import java.awt.event.ActionListener; /** * This interface defines the methods available for interacting * with a slot machine simulator. * * @author fki@kth.se * */ public interface SlotControl { /** * Returns information about the wheel model provided by the * simulator. The returned matrix contains one row for each wheel, * starting with the leftmost wheel. Each column assigns an integer * to each unique symbol on the wheel. For example, if this method * returns the following matrix: * { * {0, 1, 2, 3, 2, 1}, // left wheel * {0, 1, 2, 3, 2, 1} // right wheel * } * then it describes a slot machine with two identical wheels. * On each wheel, the symbols 1 and 2 occur two times, while symbols * 0 and 3 only occur once. * * @return A matrix describing the wheel model */ public int [][] getWheelModel(); /** * Returns the next event from the slot machine simulator. * Events are reported as strings. * All slot machine simulators must report at least the following * two events: * * creditbutton - the player has inserted a coin * rollbutton - the player has clicked the ROLL button * * @return A string describing the next event */ public String getNextEvent(); /** * Sets the amount to be displayed in the credit field of the simulator's * display. * @param n The new credit. */ public void setCredit(int n); /** * Activates or deactivates the WIN sign in the display. An amount of * zero will deactivate the sign. Any positive amount activates the sign. * * @param amount Zero to deactivate, positive to activate */ public void win(int amount); /** * Animates the display of symbol wheels by rolling them and then * stopping them in sequence from left to right. When stopped, the * symbols under the payline corresponds to the content of the parameter * array. * * Index 0 of the parameter array corresponds to the leftmost wheel, * symbols for the next wheel is read from the next index for as many * as are needed by the simulator. * * The elements in the array are column indexes in the simulator's * wheel model. Thus, if the simulator has the following wheel model: * { * {0, 1, 2, 3, 2, 1}, // left wheel * {0, 1, 2, 3, 2, 1} // right wheel * } * then the parameter array {4, 5} would cause the simulator to display * symbol 3 on the left wheel and symbol 1 on the right wheel. * * @param ar Array of symbol to show on the payline. */ public void roll(int [] ar); }
true
722d858ec9365d093c30854fcb74129b6343a76b
Java
maxrporto/RestWithSpringBoot
/02 rest-with-spring-boot-scaffold-calculator/src/main/java/br/com/studies/request/converters/NumberConverter.java
UTF-8
496
3.03125
3
[]
no_license
package br.com.studies.request.converters; public class NumberConverter { public static Double convertToDouble(String number) { if(number == null) return 0D; String num = number.replaceAll(",", "."); if (isNumeric(num)) return Double.parseDouble(num); return 0D; } public static boolean isNumeric(String number) { if(number == null) return false; String num = number.replaceAll(",", "."); return num.matches("[-+]?[0-9]*\\.?[0-9]+");//verifica se é um number } }
true
e258424884a39305ca62fe315993f08be3ddf51c
Java
Migaloco/SD_TP1
/BackUpReal/src/microgram/api/rest/RestProfiles.java
UTF-8
1,394
2.375
2
[]
no_license
package microgram.api.rest; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import microgram.api.Profile; /** * REST API of the Profiles service. * * Refer to the Java interface for the semantics * @author smd * */ @Path(RestProfiles.PATH) public interface RestProfiles { static final String PATH="/profiles"; @Path("/{userId}") @Produces(MediaType.APPLICATION_JSON) Profile getProfile( @PathParam("userId") String userId ); @POST @Consumes(MediaType.APPLICATION_JSON) void createProfile( Profile profile ); @GET @Produces(MediaType.APPLICATION_JSON) List<Profile> search( @QueryParam("query") String name ); @PUT @Path("/{userId1}/following/{userId2}") @Consumes(MediaType.APPLICATION_JSON) void follow( @PathParam("userId1") String userId1, @PathParam("userId2") String userId2, boolean isFollowing); @GET @Path("/{userId1}/following/{userId2}") boolean isFollowing( @PathParam("userId1") String userId1, @PathParam("userId2") String userId2); @DELETE @Path("/{userId}") void deleteProfile(@PathParam("userId") String userId); }
true
b50e1198d3e1445033c1068167bde4936e767c01
Java
prashant-pant/fabcards
/src/main/java/com/fabhotels/assignment/fabcards/dao/FabCardDao.java
UTF-8
645
2.203125
2
[]
no_license
/** * */ package com.fabhotels.assignment.fabcards.dao; import org.hibernate.Query; import org.hibernate.Session; import org.springframework.stereotype.Repository; import com.fabhotels.assignment.fabcards.model.FabCard; /** * @author prashant * */ @Repository public class FabCardDao extends BaseDao { public FabCard getByUserId(long userId){ Session currentSession = getCurrentSession(); Query query = currentSession.createQuery("from FabCard fabCard where fabCard.user.id = :userId").setLong("userId", userId); return (FabCard) query.uniqueResult(); } public FabCard get(long id){ return fetch(FabCard.class, id); } }
true
90bf5f9f2e5e16d4c44c05330931175049793edd
Java
bjk96/COJI
/app/src/main/java/com/cojigae/coji/item/SettingItem.java
UTF-8
806
2.5625
3
[]
no_license
package com.cojigae.coji.item; public class SettingItem { private String title; private String subtitle; private Boolean isSwitchExist; public SettingItem(String title, String subtitle, Boolean isSwitchExist) { this.title = title; this.subtitle = subtitle; this.isSwitchExist = isSwitchExist; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSubtitle() { return subtitle; } public void setSubtitle(String subtitle) { this.subtitle = subtitle; } public Boolean getSwitchExist() { return isSwitchExist; } public void setSwitchExist(Boolean switchExist) { isSwitchExist = switchExist; } }
true
d2f982757fdb31be195ed5e08cf701070306c4ff
Java
mohamedabdo99/e-learning
/app/src/main/java/com/bin/smart/za/Model/Lecture.java
UTF-8
497
2.1875
2
[]
no_license
package com.bin.smart.za.Model; public class Lecture { int state; String pdf; String video; public int getState() { return state; } public void setState(int state) { this.state = state; } public String getPdf() { return pdf; } public void setPdf(String pdf) { this.pdf = pdf; } public String getVideo() { return video; } public void setVideo(String video) { this.video = video; } }
true
f336bfa5cc29c2277937afe2578d8fae1a384b3a
Java
SKlimczuk/clinic-app
/src/main/java/custom/clinic/dao/DoctorDao.java
UTF-8
231
2
2
[]
no_license
package custom.clinic.dao; import custom.clinic.model.Doctor; import org.springframework.data.jpa.repository.JpaRepository; public interface DoctorDao extends JpaRepository<Doctor, Integer> { Doctor getDoctorById(int id); }
true
0df55e69bdc1fb0e8da9172cc18d8cdf6a75fb37
Java
jakedv24/senior-design-sdmay21-26
/src/main/java/edu/iastate/ece/sd/sdmay2126/runner/gui/driver/SeleniumDriverUtilities.java
UTF-8
748
2.84375
3
[ "MIT" ]
permissive
package edu.iastate.ece.sd.sdmay2126.runner.gui.driver; /** * General utilities for interaction with Selenium drivers. */ public class SeleniumDriverUtilities { /** * Identifies a Selenium driver enum value from its string. */ public static SeleniumDrivers getDriverFromString(String driverName) throws InvalidSeleniumDriverException { switch (driverName.toLowerCase()) { case "chrome": return SeleniumDrivers.CHROME; case "firefox": return SeleniumDrivers.FIREFOX; case "chrome_remote": return SeleniumDrivers.CHROME_REMOTE; default: throw new InvalidSeleniumDriverException(driverName); } } }
true
30a671b2289abe1f6181f9e4e208db2d9697d553
Java
gowoonsori/weTaYo
/wetayo-api/src/main/java/wetayo/wetayoapi/WetayoApiApplication.java
UTF-8
626
1.851563
2
[ "MIT" ]
permissive
package wetayo.wetayoapi; import org.modelmapper.ModelMapper; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; @SpringBootApplication @PropertySource(value = { "classpath:jdbc.properties" }) public class WetayoApiApplication { @Bean public ModelMapper modelMapper(){ return new ModelMapper(); } public static void main(String[] args) { SpringApplication.run(WetayoApiApplication.class, args); } }
true
96bd3dba955aa341b57855211529ece53fef2168
Java
ben12138/msj
/src/com/jlkj/msj/test/TestEncryption.java
UTF-8
3,950
2.234375
2
[]
no_license
package com.jlkj.msj.test; import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; import com.aliyuncs.exceptions.ClientException; import com.jlkj.msj.uitl.EncryptionUtil; import com.jlkj.msj.uitl.SendMail; import org.junit.Test; import java.math.BigInteger; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import static com.jlkj.msj.uitl.SendMessage.querySendDetails; import static com.jlkj.msj.uitl.SendMessage.sendSms; public class TestEncryption { @Test public void test(){ // Calendar calendar = Calendar.getInstance(); // calendar.set(2017,11,1); // System.out.println(calendar.get(Calendar.YEAR)); Date date = new Date(2017,11,1); System.out.println(date.getMonth()); // Date date = new Date(1509674906646L); // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // System.out.println(sdf.format(date)); // try { // SendSmsResponse response = sendSms("13151567657", "1111"); // System.out.println("短信接口返回的数据----------------"); // System.out.println("Code=" + response.getCode()); // System.out.println("Message=" + response.getMessage()); // System.out.println("RequestId=" + response.getRequestId()); // System.out.println("BizId=" + response.getBizId()); // // //查明细 // if(response.getCode() != null && response.getCode().equals("OK")) { // QuerySendDetailsResponse querySendDetailsResponse = querySendDetails(response.getBizId()); // System.out.println("短信明细查询接口返回数据----------------"); // System.out.println("Code=" + querySendDetailsResponse.getCode()); // System.out.println("Message=" + querySendDetailsResponse.getMessage()); // int i = 0; // for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs()) // { // System.out.println("SmsSendDetailDTO["+i+"]:"); // System.out.println("Content=" + smsSendDetailDTO.getContent()); // System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode()); // System.out.println("OutId=" + smsSendDetailDTO.getOutId()); // System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum()); // System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate()); // System.out.println("SendDate=" + smsSendDetailDTO.getSendDate()); // System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus()); // System.out.println("Template=" + smsSendDetailDTO.getTemplateCode()); // } // System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount()); // System.out.println("RequestId=" + querySendDetailsResponse.getRequestId()); // } // }catch (ClientException e){ // System.out.println("exception"); // e.printStackTrace(); // } //// String result = EncryptionUtil.encoder("1212","12"); //// System.out.println(result.equals(EncryptionUtil.encoder("1212","12"))); //// SendMail mail = new SendMail(); //// try{ //// mail.send("m13814545863@163.com"); //// System.out.println(mail.getContent()); //// }catch (Exception e){ //// System.out.println("exception"); //// } } // @Test // public void testMail(){ // SendMail mail = new SendMail(); // try{ // mail.send("m13814545863@163.com"); // System.out.println(mail.getContent()); // }catch (Exception e){ // System.out.println("exception"); // } // // } }
true
95124b4433e99c9edc0fb84587b8aac5d486370e
Java
NashiKanjou/Space-Invaders-PLUS
/src/main/java/scene/PausedScene.java
UTF-8
1,435
2.59375
3
[]
no_license
package main.java.scene; import main.java.manager.GameSceneManager; import main.java.manager.InputManager; import java.awt.Graphics; import java.awt.Color; public class PausedScene extends BaseScene { private String topMsg, bottomMsg; private int xOffset; public PausedScene(GameSceneManager gsm) { super(gsm); topMsg = "PRESS ESCAPE TO RESUME"; bottomMsg = "PRESS Q TO QUIT"; xOffset = 65; } @Override public void update() { if (inputSource == null || inputSource == InputManager.InputSource.KEYBOARD) { topMsg = "PRESS ESCAPE TO RESUME"; bottomMsg = "PRESS Q TO QUIT"; xOffset = 40; } else { topMsg = "PRESS START TO RESUME"; bottomMsg = "PRESS SELECT TO QUIT"; xOffset = 65; } } @Override public void draw(Graphics g) { g.setColor(Color.WHITE); g.drawString("GAME PAUSED", (BOARD_WIDTH / 2 ) - 40, (BOARD_HEIGHT / 2 ) - 32); g.drawString(topMsg, (BOARD_WIDTH / 2 ) - 70, (BOARD_HEIGHT / 2 ) + 52); g.drawString(bottomMsg, (BOARD_WIDTH / 2 ) - xOffset, (BOARD_HEIGHT / 2 ) + 72); } @Override public void dispose() { } @Override public void input(InputManager inputManager) { super.input(inputManager); if (inputManager.quit.clicked) { gsm.ingame = false; } } }
true
004e1672e78eabc76f7d8ab1ce087dd811b0dc3c
Java
ntsprashantjha/myfirstproject
/garbagecollector/src/com/nts/annexvi/model/MasterTableAnx.java
UTF-8
1,788
2.234375
2
[]
no_license
package com.nts.annexvi.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "master_table_annexvi") public class MasterTableAnx { @Id @GeneratedValue private int entry_id; @Column(name = "entry_type", length = 100) private String entry_type; @Column(name = "entry_date", length = 30) private String entry_date; @Column(name = "entry_date_only", length = 10) private String entry_date_only; public int getEntry_id() { return entry_id; } public void setEntry_id(int entry_id) { this.entry_id = entry_id; } public String getEntry_type() { return entry_type; } public void setEntry_type(String entry_type) { this.entry_type = entry_type; } public String getEntry_date() { return entry_date; } public void setEntry_date(String entry_date) { this.entry_date = entry_date; } public String getEntry_date_only() { return entry_date_only; } public void setEntry_date_only(String entry_date_only) { this.entry_date_only = entry_date_only; } public String getTimezone() { return timezone; } public void setTimezone(String timezone) { this.timezone = timezone; } public int getEntry_strike_cond() { return entry_strike_cond; } public void setEntry_strike_cond(int entry_strike_cond) { this.entry_strike_cond = entry_strike_cond; } @Column(name = "timezone", length = 10) private String timezone; @Column(name = "entry_strike_cond", length = 5, insertable = false, updatable = false, nullable = false, columnDefinition = "int(5) default '0'") private int entry_strike_cond; }
true
0e625ec364514de32ed264e0b1e5364bf73f8d7e
Java
JohanSvartdal/Roforbund
/src/main/java/servlets/Sider/TrenerServlets/TrenerDash.java
UTF-8
2,402
2.5
2
[]
no_license
package servlets.Sider.TrenerServlets; import servlets.AbstractAppServlet; import tools.databaseTools.DatabaseReader; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; // Servlet for trenerdashboard // Formål: "Hjemside" for trener, fungerer på samme måte som Superdash. @WebServlet(name= "TrenerDash", urlPatterns = "/TrenerDash/") public class TrenerDash extends AbstractAppServlet { int UID = 1; @Override protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { writeResponse(request, response, "Dashboard!"); } @Override protected void writeBody(HttpServletRequest req, PrintWriter out) { } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookies[] = request.getCookies(); int UID = -1; for (Cookie cookie: cookies) { if (cookie.getName().equals("UID")) { String uidString = cookie.getValue(); UID = Integer.parseInt(uidString); } } if (UID == -1) { request.setAttribute("title", "Fant ikke UID"); request.setAttribute("description", "Vennligst kontakt IT avdelingen for hjelp"); request.setAttribute("backlink", "../"); RequestDispatcher rq = request.getRequestDispatcher("../Error/index.jsp"); rq.forward(request, response); return; } String name = DatabaseReader.getString("roforbund.bruker","Bruker_id", UID, "Fornavn"); request.setAttribute("WelcomeMessage", "Velkommen, " + name + "!"); RequestDispatcher rq = request.getRequestDispatcher("../TrenerDash/index.jsp"); rq.forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; } }
true
3576fc6c1054b1e45296f55bb73a36a99e96715f
Java
gavin2010/JavaSE
/jse/src/main/java/com/gavin/generic/Generic.java
UTF-8
2,211
3.453125
3
[]
no_license
package com.gavin.generic; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; /** * 泛型类测试 */ public class Generic { /** * 由于没有添加泛型,会造成类转换异常 */ public void generci(){ List arrayList = new ArrayList(); arrayList.add("AAA"); arrayList.add(100); for(int i=0;i<arrayList.size();i++){ String temp = (String)arrayList.get(i); System.out.println(temp); } } /** * 使用了泛型,类型不一致会报错 */ @Test public void generciA() { List<String> arrList = new ArrayList<>(); arrList.add("AAA"); // arrList.add(100); 会报错,编译不通过 for(int i=0;i<arrList.size();i++){ String temp = (String)arrList.get(i); System.out.println(temp); } } /** * 泛型类的测试 */ @Test public void testGenericClass(){ GenericClass g = new GenericClass(123); GenericClass g1 = new GenericClass("AAA"); System.out.println(g.getKey()); System.out.println(g1.getKey()); GenericClass<Integer> g3 = new GenericClass<>(10); // GenericClass<Integer> g4 = new GenericClass<>("BB"); 报错,泛型限制 Apple apple = new Apple(); GenericClass<Apple> g5 = new GenericClass<>(apple); if(g5 instanceof GenericClass){} // if(g5 instanceof GenericClass<Apple>){} 报错,泛型是编译的事情,instanceof是运行的事 } } //===================== 分隔线 =========================== /** * 泛型类 * @param <T> */ class GenericClass<T>{ private T key; public GenericClass(T key){ this.key = key; } public T getKey() { return key; } public void setKey(T key) { this.key = key; } } class Apple{ public String getName() { return name; } public void setName(String name) { this.name = name; } private String name; @Override public String toString() { return "Apple{" + "name='" + name + '\'' + '}'; } }
true
55175c7cf348b0f21390eb6326ae367a4b1bbab5
Java
FitnessTime/mobile-app
/FitnessTime/app/src/main/java/com/fitnesstime/fitnesstime/Servicios/ServicioRegistro.java
UTF-8
1,449
2.0625
2
[]
no_license
package com.fitnesstime.fitnesstime.Servicios; import android.util.Log; import com.fitnesstime.fitnesstime.Application.FitnessTimeApplication; import com.fitnesstime.fitnesstime.Configuracion.Constantes; import com.fitnesstime.fitnesstime.Modelo.ResponseHelper; import com.fitnesstime.fitnesstime.Modelo.SecurityToken; import com.fitnesstime.fitnesstime.ModelosFlujo.Registro; import com.fitnesstime.fitnesstime.Util.HelperLeerMensajeResponse; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * Created by julian on 08/02/16. */ public class ServicioRegistro { public ResponseHelper registrar(Registro registro) { Gson gson = new GsonBuilder().serializeNulls().create(); String requestURL = "/usuarios?usuario=" + gson.toJson(registro, Registro.class); return ServicioRequestHelper.PostRequest(requestURL); } public ResponseHelper actualizar(Registro registro) { Gson gson = new GsonBuilder().serializeNulls().create(); String param = gson.toJson(registro, Registro.class); param = param.replace(" ", "%20"); String requestURL = "/usuarios?authToken=" + FitnessTimeApplication.getSession().getAuthToken() +"&usuario=" + param; return ServicioRequestHelper.PutRequest(requestURL); } }
true
1db97cbb143a60763811d285a4aff55d10ae8863
Java
zhou8361907/sog-shop
/SOG-shop/src/main/java/com/sog/service/ChooseServiceImpl.java
UTF-8
2,166
2.359375
2
[]
no_license
package com.sog.service; import java.util.List; import java.util.Map; import com.sog.dao.AdminDaoI; import com.sog.dao.AdminDaoImpl; import com.sog.dao.ChooseDaoI; import com.sog.dao.ChooseDaoImpl; import com.sog.entity.Admin; import com.sog.entity.Choose; /** * * @类名: ChooseServiceImpl * @描述: choose的接口实现 利用 循环删除 实现clear * @作者:周帅 * @日期:2018年7月3日下午1:45:18 */ public class ChooseServiceImpl implements ChooseServiceI<Choose> { private static ChooseDaoI cdi=new ChooseDaoImpl(); @Override public boolean add(Choose t) throws Exception { List<Choose> list = cdi.selectWhere(" and user_id='"+ t.getUser_id() + "'"+" and goods_id='"+ t.getGoods_id() + "'"+" and type='"+ 0 + "'"); if(list.size()>0) { Choose ch1=list.get(0); int num=ch1.getNumber()+t.getNumber(); t.setChoose_id(ch1.getChoose_id()); t.setNumber(num); return cdi.update(t); }else { return cdi.insert(t); } } @Override public boolean modify(Choose t) throws Exception { // TODO Auto-generated method stub return cdi.update(t); } @Override public boolean remove(int id) throws Exception { // TODO Auto-generated method stub return cdi.delete(id); } @Override public List<Choose> findByAll() throws Exception { // TODO Auto-generated method stub return null; } @Override public Map<String, Object> getPageAll(String wheresql, int currentPage, int pageSize) throws Exception { // TODO Auto-generated method stub return null; } @Override public List<Choose> getWhere(String whereSql) throws Exception { // TODO Auto-generated method stub return cdi.selectWhere(whereSql); } @Override public void clear(int user_id) throws Exception { List <Choose> list=cdi.SelectByUser(user_id); for(Choose choose :list) { cdi.delete(choose.getChoose_id()); } } @Override public List<Choose> SelectByUser(int user_id) throws Exception { // TODO Auto-generated method stub return cdi.SelectByUser(user_id); } @Override public Choose SelectBych_id(int choose_id, int num) throws Exception { return cdi.SelectBych_id(choose_id, num); } }
true
e5c1fd4005b7376dc4d3f3cb4d58630058b90312
Java
peytondodd/CodCraftPlugins
/CodCraftPerks/src/main/java/com/codcraft/perks/lightweight/LightWight.java
UTF-8
340
1.851563
2
[]
no_license
package com.codcraft.perks.lightweight; import com.codcraft.perks.Perks; public class LightWight { @SuppressWarnings("unused") private Perks plugin; public LightWight(Perks plugin) { this.plugin =plugin; plugin.getServer().getPluginManager().registerEvents(new LightWeightListener(plugin), plugin); } }
true