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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
2098f93011aecda582e14845a21d07b41ad93e1b | Java | amjad-haffar/strategy-game | /src/javaapplication2/Player.java | UTF-8 | 681 | 3.21875 | 3 | [] | no_license | package javaapplication2;
import java.util.ArrayList;
public class Player {
public int player_coins;
public String player_name;
public ArrayList<Soldier> player_soldires;
public ArrayList<Square> player_squares;
Player(String name){
if(name!=""){
this.player_soldires= new ArrayList<Soldier>();
this.player_squares= new ArrayList<Square>();
this.player_coins=15;
}else{
this.player_coins=0;
}
this.player_name=name;
}
void addPlayer_square(Square s){
this.player_squares.add(s);
}
void addSoldier(Soldier s){
this.player_soldires.add(s);
}
}
| true |
c3436e4dc82d6cbe89110678010fbdee76ee7569 | Java | ahmedalies/SwapAndroid | /app/src/main/java/itboom/com/swap/auth/interests/mvp/InterestsPresenter.java | UTF-8 | 4,133 | 2.25 | 2 | [] | no_license | package itboom.com.swap.auth.interests.mvp;
import android.util.Log;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.Arrays;
import io.reactivex.CompletableObserver;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import itboom.com.swap.pojo.interests.Interest;
import itboom.com.swap.pojo.interests.InterestsResponse;
import itboom.com.swap.support.NetworkResult;
public class InterestsPresenter implements SelectInterestsMVP.Presenter {
SelectInterestsMVP.View view;
SelectInterestsMVP.Model model;
Disposable disposable;
public InterestsPresenter(SelectInterestsMVP.Model model) {
this.model = model;
}
@Override
public void setView(SelectInterestsMVP.View view) {
this.view = view;
}
@Override
public void onViewLoad() {
if (view != null) {
view.showProgress();
model.getAllInterests()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<InterestsResponse>() {
@Override
public void onSubscribe(Disposable d) {
disposable = d;
}
@Override
public void onSuccess(InterestsResponse interestsResponse) {
view.hideProgress();
if (interestsResponse != null){
if (interestsResponse.isError()){
view.onFailure(NetworkResult.UNEXPECTED_ERROR);
} else {
view.onSuccess(new ArrayList<>(Arrays.asList(interestsResponse.getInterests())));
}
} else {
view.onFailure(NetworkResult.NETWORK_ERROR);
}
}
@Override
public void onError(Throwable e) {
view.hideProgress();
Log.i("RESULT_ERROR", "onError: " + e.getMessage());
view.onFailure(NetworkResult.UNEXPECTED_ERROR);
}
});
}
}
@Override
public void submitInterests(ArrayList<String> interests, String userId) {
if (view != null){
view.showProgress();
JsonObject object = new JsonObject();
object.addProperty("userId", userId);
JsonArray array = new JsonArray();
for (String i:interests) {
array.add(i);
}
object.add("interests", array);
model.submitInterests(object)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new CompletableObserver() {
@Override
public void onSubscribe(Disposable d) {
disposable = d;
}
@Override
public void onComplete() {
view.hideProgress();
view.navigateToApp();
}
@Override
public void onError(Throwable e) {
view.hideProgress();
Log.i("RESULT_ERROR", "onError: " + e);
view.onFailure(NetworkResult.UNEXPECTED_ERROR);
}
});
}
}
@Override
public void rxUnsubscribe() {
if (view != null){
if (disposable != null && !disposable.isDisposed()){
disposable.dispose();
}
}
}
}
| true |
e63e0afdfa99b798bef3ab346af00564db115eb4 | Java | vaibhavkw/GraphPoem | /GraphPoem/src/topic/TFIDF.java | UTF-8 | 8,046 | 2.84375 | 3 | [] | no_license | package topic;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
//Doing TF-IDF mapping on Poetry Foundation 12831 poems dataset
public class TFIDF {
public static String basePath = System.getProperty("user.dir") + "/resources/";
public static int batches = 10;
//List of all documents for TF calculation
ArrayList<Doc> docList = new ArrayList<Doc>();
//Map to store Term to Document reference for IDF calculation
HashMap<String, Set<String>> termToDocMap = new HashMap<String, Set<String>>();
public static void main(String args[]){
TFIDF obj = new TFIDF();
obj.readInputFolderPoetryFoundation();
obj.calculateTFIDF();
}
public void calculateTFIDF(){
int totalDocs = docList.size();
for(int i=0;i<docList.size();i++){
Doc doc = docList.get(i);
System.out.println("Document : " + doc.docName);
HashMap<String, Term> terms = doc.terms;
Iterator it = terms.entrySet().iterator();
while(it.hasNext()){
Map.Entry el = (Entry) it.next();
String word = (String) el.getKey();
Term currentTerm = (Term) el.getValue();
int count = currentTerm.count;
int docPresence = termToDocMap.get(word).size() + 1;
double tf = Math.sqrt(count);
double idf = Math.log((double)totalDocs/docPresence);
double tfidf = tf * idf;
System.out.println(word + ":" + tfidf);
}
}
}
public void readInputFolderPoetryFoundation(){
String inputFolder = basePath + "poetry_foundation_final_subset/";
File inpFolder = new File(inputFolder);
File[] children = inpFolder.listFiles();
int batchSize = children.length / batches;
int count = -1;
for(int loop=0; loop<batches; loop++){
for(int i=0;i<batchSize;i++){
count++;
File currentFile = children[count];
if(currentFile.isFile() && currentFile.getName().contains(".txt")){
String fileName = currentFile.getName();
System.out.println("Processing file " + (count+1) + " : " + fileName);
String poemContent = "";
//Single Document with details
Doc doc = new Doc();
doc.docName = fileName;
//All terms of a single document
HashMap<String, Term> termMap = new HashMap<String, Term>();
BufferedReader br = null;
String sCurrentLine;
String poemName = "";
String poemAuthor = "";
try{
br = new BufferedReader(new FileReader(currentFile));
int lineNumber = 0;
while ((sCurrentLine = br.readLine()) != null) {
lineNumber++;
if(lineNumber == 1){
poemName = sCurrentLine;
}
if(lineNumber == 2){
poemAuthor = sCurrentLine;
}
if(lineNumber <= 9){
continue;
}
if(sCurrentLine.trim().equals("")){
continue;
}
if(sCurrentLine.split(" ").length == 1){
continue;
}
String processeLine = processLine(sCurrentLine);
poemContent = poemContent + " " + processeLine;
}
br.close();
br = null;
currentFile = null;
//System.out.println(poemContent);
ArrayList<String> strArr = getArrayListFromStr(poemContent);
for(int m=0;m<strArr.size();m++){
String word = strArr.get(m);
Term term;
if(termMap.containsKey(word)){
term = termMap.get(word);
term.count++;
}else{
term = new Term();
term.termName = word;
term.count = 1;
termMap.put(word, term);
}
//Check for Term to Document map for IDF calculation
if(termToDocMap.containsKey(word)){
termToDocMap.get(word).add(fileName);
}else{
Set<String> tmpSet = new HashSet<String>();
tmpSet.add(fileName);
termToDocMap.put(word, tmpSet);
}
}
//System.out.println(termMap);
doc.terms = termMap;
docList.add(doc);
//System.out.println();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
currentFile = null;
} catch (IOException ex) {
ex.printStackTrace();
}
}
//poemList.add(poem);
}
}
//System.out.println(poemList.size());
//printAllPoems();
//writeToFile("output/poem_output" + (loop+1) + ".txt");
}
children = null;
inpFolder = null;
}
public String processLine(String currentLine){
currentLine = currentLine.trim();
currentLine = currentLine.toLowerCase();
currentLine = handlePunctuation(currentLine);
String intermediateStr = cleanPrefix(currentLine);
String outLine = cleanSuffix(intermediateStr);
return outLine;
}
public String cleanPrefix(String currentWord){
String finalStr = currentWord;
int j=0;
for(j=0;j<currentWord.length();j++){
int asciiValue = currentWord.charAt(j);
if(((asciiValue>=48 && asciiValue<=57) || (asciiValue>=65 && asciiValue<=90) || (asciiValue>=97 && asciiValue<=122))){
break;
}else{
//System.out.println();
}
}
finalStr = currentWord.substring(j, currentWord.length());
return finalStr;
}
public static String cleanSuffix(String currentWord){
String finalStr = currentWord;
int j=0;
for(j=currentWord.length()-1;j>=0;j--){
int asciiValue = currentWord.charAt(j);
if(((asciiValue>=48 && asciiValue<=57) || (asciiValue>=65 && asciiValue<=90) || (asciiValue>=97 && asciiValue<=122))){
break;
}else{
//System.out.println();
}
}
finalStr = currentWord.substring(0, j+1);
return finalStr;
}
public ArrayList<String> getArrayListFromStr(String sCurrentLine){
ArrayList<String> outList = new ArrayList<String>();
String[] arr = sCurrentLine.split(" ");
for(int i=0;i<arr.length;i++){
if(arr[i].trim().equals("")){
continue;
}
outList.add(arr[i]);
}
return outList;
}
public String handlePunctuation(String inpStr){
//inpStr = "!!~~``%%^^&&**(())__--++==||\\[[]]{{}};;::\\\\''\"\",,..//<<>>";
String retStr = inpStr;
retStr = retStr.replaceAll("!", " ");
retStr = retStr.replaceAll("~", " ");
retStr = retStr.replaceAll("`", " ");
retStr = retStr.replaceAll("\\$", " ");
retStr = retStr.replaceAll("%", " ");
retStr = retStr.replaceAll("\\^", " ");
retStr = retStr.replaceAll("&", " ");
retStr = retStr.replaceAll("\\*", " ");
retStr = retStr.replaceAll("\\(", " ");
retStr = retStr.replaceAll("\\)", " ");
retStr = retStr.replaceAll("__", " ");
retStr = retStr.replaceAll("--", " ");
retStr = retStr.replaceAll("\\+", " ");
retStr = retStr.replaceAll("=", " ");
retStr = retStr.replaceAll("\\|", " ");
retStr = retStr.replaceAll("\\\\", " ");
retStr = retStr.replaceAll("\\[", " ");
retStr = retStr.replaceAll("]", " ");
retStr = retStr.replaceAll("\\{", " ");
retStr = retStr.replaceAll("}", " ");
retStr = retStr.replaceAll(";", " ");
retStr = retStr.replaceAll(":", " ");
retStr = retStr.replaceAll("\"", " ");
retStr = retStr.replaceAll("'", " ");
retStr = retStr.replaceAll(",", " ");
retStr = retStr.replaceAll("\\.", " ");
retStr = retStr.replaceAll("//", " ");
retStr = retStr.replaceAll("<", " ");
retStr = retStr.replaceAll(">", " ");
retStr = retStr.replaceAll("\\?", " ");
retStr = retStr.replaceAll("“", " ");
retStr = retStr.replaceAll("’", " ");
retStr = retStr.replaceAll("-", " ");
retStr = retStr.replaceAll(" ", " ");
return retStr;
}
}
class Term {
public String termID = "";
public String termName = "";
public Integer count = 0;
@Override
public String toString(){
return termName + ":" + count;
}
}
class Doc {
public String docID = "";
public String docName = "";
HashMap<String, Term> terms = new HashMap<String, Term>();
@Override
public String toString(){
return docName + ":" + terms.toString();
}
}
| true |
e16fd370eb0796fbb3ad600e65d41185f902aadb | Java | kiegroup/droolsjbpm-contributed-experiments | /machinelearning/4.0.x/experimental/drools-testing/src/org/drools/testing/core/utils/CollectionUtils.java | UTF-8 | 2,108 | 3.40625 | 3 | [
"Apache-2.0"
] | permissive | package org.drools.testing.core.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* A Collection of utilities that can be used modify collections. Many
* utilities are provided within the java.util.Collections class and
* should not be duplicated here.
* @see java.util.Collections
*/
public class CollectionUtils {
/**
* A method used to return a sub collection given an original, a to
* and from index. The subCollection is backed by a java.util.ArrayList. This method
* should be used when a subCollection is required to be passed as a
* Serializable object. For example, the method List.subList(int fromIndex, int toIndex)
* is not appropriate as it not Serializable.
* @param original The original collection
* @param fromIndex The starting index to inclusive add from
* @param toIndex The endIndex to inclusive add too
* @return Collection with 0 or more elements fom the original.
*/
public static Collection getSubCollection(Collection original, int fromIndex, int toIndex)
{
String methodName = "getSubCollection(Collection original, int fromIndex, int toIndex)";
ArrayList subCollection = new ArrayList();
Iterator originalIterator = original.iterator();
int count = 0;
while (originalIterator.hasNext())
{
Object nextObject = originalIterator.next();
if (count >= fromIndex && count <= toIndex)
{
subCollection.add(nextObject);
}
count++;
}
return subCollection;
}
/**
* Convert an Object array to a Collection
* @param objectArray
* @return
*/
public static Collection arrayToCollection(Object[] objectArray)
{
ArrayList conversion = new ArrayList();
for (int i = 0; i < objectArray.length; i++)
{
conversion.add(objectArray[i]);
}
return conversion;
}
public static Object getLastItem (Collection items) {
Object nextObject = new Object();
Iterator i = items.iterator();
while (i.hasNext()) {
nextObject = i.next();
}
return nextObject;
}
}
| true |
4a378aa1530892827a7e963f8b7f4d99ae0ab892 | Java | Ajinkya1993/WebServices-Task8- | /CFSWebServices/src/edu/cmu/service/BuyFund.java | UTF-8 | 1,059 | 2.3125 | 2 | [] | no_license | package edu.cmu.service;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.json.JSONException;
import org.json.JSONObject;
import edu.cmu.JSON.MessageJSON;
import edu.cmu.formbean.BuyFundFormBean;
import edu.cmu.model.Model;
import edu.cmu.resource.BuyFundAction;
@Path("/buyFund")
public class BuyFund {
@POST
@Produces(MediaType.APPLICATION_JSON)
public MessageJSON buyFund(@Context HttpServletRequest request, String jsonString)
throws ServletException, JSONException {
try {
JSONObject object = new JSONObject(jsonString);
BuyFundFormBean buyFundFormBean = new BuyFundFormBean(object.getString("symbol"),
object.getString("cashValue"));
return new BuyFundAction(buyFundFormBean).perform(request);
} catch (Exception e) {
MessageJSON message = new MessageJSON("The input you provided is not valid");
return message;
}
}
}
| true |
c4dc2bf15cd89e9fa67d7e7e5ee48ab68888f0d4 | Java | team5-funthing/funthing | /src/main/java/com/team5/funthing/common/controller/CKEditorFileUploadController.java | UTF-8 | 2,165 | 2.109375 | 2 | [] | no_license | package com.team5.funthing.common.controller;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.google.gson.JsonObject;
import com.team5.funthing.common.utils.uploadUtils.UploadUtil;
import com.team5.funthing.user.model.vo.ProjectStoryVO;
@Controller
public class CKEditorFileUploadController {
@Autowired
private UploadUtil uploadutil;
@Autowired
private ProjectStoryVO projectStory;
@RequestMapping(value = "/storyUpload.udo", method = RequestMethod.POST)
@ResponseBody
public String uploadUpload( HttpServletResponse response,
HttpSession session,
@RequestParam(name = "upload", required = false)MultipartFile upload) throws Exception {
JsonObject json = new JsonObject();
PrintWriter printWriter = null;
List<String> SettingPathList = new ArrayList<String>();
if(!upload.isEmpty()) {
List<MultipartFile> uploadList = new ArrayList<MultipartFile>();
List<String> toRemoveFilePath = new ArrayList<String>();
uploadList.add(upload);
toRemoveFilePath.add(projectStory.getProjectStoryImage());
String voName = projectStory.getClass().getSimpleName();
SettingPathList = uploadutil.upload(uploadList, voName, toRemoveFilePath);
}
String SettingPath = SettingPathList.get(0);
String uploadName = SettingPath.substring(SettingPath.lastIndexOf('/')+1);
printWriter = response.getWriter();
response.setContentType("text/html");
json.addProperty("uploaded", 1);
json.addProperty("uploadName", uploadName);
json.addProperty("url", SettingPath);
printWriter.println(json);
return null;
}
}
| true |
1f2596a7c12902c5deb7d7cf5bb308f696efacc8 | Java | prodigyoff/lab3 | /src/test/java/ua/lviv/ki/manager/DishManagerUtilsTest.java | UTF-8 | 1,662 | 2.546875 | 3 | [] | no_license | package ua.lviv.ki.manager;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import ua.lviv.ki.model.SortType;
public class DishManagerUtilsTest extends BaseDishesManagerTest {
@Test
public void testSortByPopularityDescending() {
DishManagerUtils.sortByPopularity(dishes, SortType.DESC);
assertEquals(9, dishes.get(0).getDishPopularityIndex());
assertEquals(8, dishes.get(1).getDishPopularityIndex());
assertEquals(7, dishes.get(2).getDishPopularityIndex());
}
@Test
public void testSortByPriceDescending() {
DishManagerUtils.sortByPrice(dishes, SortType.DESC);
assertEquals(125, dishes.get(0).getDishPriceInHryvnias());
assertEquals(120, dishes.get(1).getDishPriceInHryvnias());
assertEquals(70, dishes.get(2).getDishPriceInHryvnias());
}
@Test
public void testSortByPopularityAndPriceDescending() {
DishManagerUtils.sortByPopularityAndPrice(dishes, SortType.DESC);
assertEquals(125, dishes.get(0).getDishPriceInHryvnias());
assertEquals(9, dishes.get(0).getDishPopularityIndex());
assertEquals(120, dishes.get(1).getDishPriceInHryvnias());
assertEquals(8, dishes.get(1).getDishPopularityIndex());
assertEquals(18, dishes.get(2).getDishPriceInHryvnias());
assertEquals(7, dishes.get(2).getDishPopularityIndex());
}
@Test
public void testSortByCaloriesUsingLambdaAscending() {
DishManagerUtils.sortByCaloriesUsingLambda(dishes, SortType.ASC);
assertEquals(50, dishes.get(0).getCaloriesAmount());
assertEquals(120, dishes.get(1).getCaloriesAmount());
assertEquals(420, dishes.get(2).getCaloriesAmount());
}
}
| true |
3668eefbed31888fbf3d37051f7f84891f2884f4 | Java | Hydropumpon/catalogue-service | /src/main/java/com/example/catalogue/catalogueservice/service/impl/RabbitOrderResponseServiceImpl.java | UTF-8 | 1,138 | 2.0625 | 2 | [] | no_license | package com.example.catalogue.catalogueservice.service.impl;
import com.example.catalogue.catalogueservice.messages.OrderMessage;
import com.example.catalogue.catalogueservice.service.RabbitOrderResponseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class RabbitOrderResponseServiceImpl implements RabbitOrderResponseService {
@Value("${rabbitmq.exchanges.order_response}")
private String orderResponseExchange;
@Value("${rabbitmq.routing_key.order_response}")
private String orderResponseRoutingKey;
private RabbitTemplate rabbitTemplate;
@Autowired
public RabbitOrderResponseServiceImpl(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
@Override
public void processOrderMessage(OrderMessage orderMessage) {
rabbitTemplate.convertAndSend(orderResponseExchange, orderResponseRoutingKey, orderMessage);
}
}
| true |
59f71e8a605fd3cadec8b3c195a866bd4cb045e4 | Java | HarveyLuo91/KillBugTestCases | /test-case-src/src/main/java/java/Foo.java | UTF-8 | 106 | 1.953125 | 2 | [] | no_license | package java;
public class Foo {
static Class other;
static {
other = Bar.other;
}
}
| true |
2e818a793f34149c5546154d63cba7f4b3b06dba | Java | neosuniversity/javabasic | /src/org/neosuniversity/unidad2/math/MathApplication.java | UTF-8 | 335 | 2.8125 | 3 | [] | no_license | package org.neosuniversity.unidad2.math;
public class MathApplication {
public static void main(String[] args) {
Fraccion a = new Fraccion(1,4);
Fraccion b = new Fraccion(1,4);
System.out.println("c = " + a + " + " + b);
Fraccion c = a.suma(b);
System.out.println("c = " + c);
}
}
| true |
e2ca12ce40e3d4a8b2848eb6386814a2c023001c | Java | wangkk24/testgit | /20210809(ZJYD_v2.6.0)/app/src/main/java/com/pukka/ydepg/common/http/vss/node/PriceObject.java | UTF-8 | 1,032 | 1.84375 | 2 | [] | no_license | package com.pukka.ydepg.common.http.vss.node;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
public class PriceObject implements Serializable {
private static final long serialVersionUID = 3813691752866294040L;
/**
* 定价对象Id
*/
@SerializedName("id")
private String id;
/**
* 类型
*/
@SerializedName("type")
private String type;
/**
* 扩展字段
*/
@SerializedName("extensionInfo")
private List<NamedParameter> extensionInfo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<NamedParameter> getExtensionInfo() {
return extensionInfo;
}
public void setExtensionInfo(List<NamedParameter> extensionInfo) {
this.extensionInfo = extensionInfo;
}
}
| true |
bc449abafa58c4053acbdbe045c05eda5c6be03b | Java | BrittleFoot/tree-umph | /src/main/java/com/github/brittlefoot/treeumph/script/interfaces/IGreetingScript.java | UTF-8 | 224 | 2.015625 | 2 | [] | no_license | package com.github.brittlefoot.treeumph.script.interfaces;
import com.github.brittlefoot.treeumph.script.IScriptInterface;
public interface IGreetingScript extends IScriptInterface {
String greeting(String name);
}
| true |
02b48e868c26816b8db1b1dad8a7c2ae00ab9a66 | Java | adityamhatre/Viazene | /app/src/main/java/com/thelogicalcoder/viazene/Interfaces/onMatchSavedListener.java | UTF-8 | 182 | 1.679688 | 2 | [] | no_license | package com.thelogicalcoder.viazene.Interfaces;
/**
* Created by Aditya on 015, 15 July 2015.
*/
public interface onMatchSavedListener {
void onMatchSaved(String response);
}
| true |
26086a3de814a5b2639b1091cb44e61c59550a4e | Java | krystian50/csp | /src/algorithm/Backtracking.java | UTF-8 | 3,875 | 3.359375 | 3 | [] | no_license | package algorithm;
import models.CSPVertexPair;
import models.Graph;
import models.Tuple;
import java.util.LinkedList;
/**
* Created by Krystian on 2017-04-03.
*/
public class Backtracking {
Graph graph;
int[][] graphArray;
private LinkedList<CSPVertexPair> colors;
private static final int INVALID_STATE = -1;
public Backtracking() {
colors = new LinkedList<CSPVertexPair>();
}
public boolean solve(Graph graph) {
this.colors.clear();
this.graph = graph;
this.graphArray = graph.getGraph();
return nextState();
}
/**
* 1. find next vertice to color
* 2. for every color
* 3. check if can be colored
* 3a. color vertice
* 4. if cannot be colored
* 4a. remove color
* @return
*/
private boolean nextState() {
Tuple<Integer, Integer> uncoloredVertex = getFirstUncolored();
if (uncoloredVertex.first == -1
&& uncoloredVertex.second == -1) {
return true;
}
int uncoloredX = uncoloredVertex.first;
int uncoloredY = uncoloredVertex.second;
for (int i = 0; i < graph.getAvailableColors(); i++) {
if (canColorVertice(uncoloredX, uncoloredY, i)) {
graphArray[uncoloredX][uncoloredY] = i;
// System.out.println(graph);
if (nextState()) {
return true;
}else{
// System.out.println(uncoloredX + ", " + uncoloredY + " - Undoing, size before" + colors.size());
graphArray[uncoloredX][uncoloredY] = INVALID_STATE;
undoPairs(uncoloredX, uncoloredY);
// System.out.println("Undoing, size after" + colors.size());
}
}
}
return false;
}
private void undoPairs(int uncoloredX, int uncoloredY) {
if ((uncoloredX == 0) != (uncoloredY == 0)) {
colors.removeLast();
}else if (uncoloredX != 0 && uncoloredY != 0){
colors.removeLast();
colors.removeLast();
}
}
private Tuple<Integer, Integer> getFirstUncolored() {
int[][] graphArray = graph.getGraph();
for (int i = 0; i < graph.getSize(); i++){
for (int j = 0; j < graph.getSize(); j++) {
if (graphArray[i][j] == -1) {
return new Tuple<Integer, Integer>(i, j);
}
}
}
return new Tuple<Integer, Integer>(INVALID_STATE, INVALID_STATE);
}
private boolean canColorVertice(int x, int y, int color) {
int previousColor = graphArray[x][y];
graphArray[x][y] = color;
boolean result = graph.validateBackwards(x, y);
graphArray[x][y] = previousColor;
if (result) {
result = hasGraphOnlySingleColoredPair(x, y, color);
}
return result;
}
private boolean hasGraphOnlySingleColoredPair(int x, int y, int color) {
CSPVertexPair firstPair = null;
CSPVertexPair secondPair = null;
boolean hasFirstPair = false;
boolean hasSecondPair = false;
if (x == 0 && y == 0) {
return true;
}
if (x != 0) {
firstPair = new CSPVertexPair(graphArray[x-1][y], color);
hasFirstPair = colors.contains(firstPair);
}
if (y != 0) {
secondPair = new CSPVertexPair(graphArray[x][y-1], color);
hasSecondPair = colors.contains(secondPair);
}
if (hasFirstPair || hasSecondPair) {
return false;
}
if (firstPair != null && !hasFirstPair) {
colors.add(firstPair);
}
if (secondPair != null && !hasSecondPair) {
colors.add(secondPair);
}
return true;
}
}
| true |
67c17f678e8ebf48753a46971ab212c7957c0745 | Java | diegobetz/test-developer-sysone | /src/main/java/ar/com/bussiness/ventas/controller/FacturaVentaController.java | UTF-8 | 5,988 | 2.25 | 2 | [] | no_license | package ar.com.bussiness.ventas.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import ar.com.bussiness.ventas.controller.exception.ResourceNotFoundException;
import ar.com.bussiness.ventas.controller.exception.ValidationException;
import ar.com.bussiness.ventas.entity.FacturaVenta;
import ar.com.bussiness.ventas.request.FacturaVentaRequest;
import ar.com.bussiness.ventas.service.FacturaVentaServices;
import ar.com.bussiness.ventas.services.exception.AutomovilNotFoundException;
import ar.com.bussiness.ventas.services.exception.FacturaVentaNotFoundException;
import ar.com.bussiness.ventas.services.exception.InternalDataBaseException;
import ar.com.bussiness.ventas.services.exception.ValidationPrecioVentaException;
import ar.com.bussiness.ventas.services.exception.ValidationVentaAutoDisponibleException;
@RestController
@RequestMapping(path = "/bill")
public class FacturaVentaController {
@Autowired
private FacturaVentaServices facturaVentaServices;
/**
* Consulta de todas las facturas existentes
* @return todas las facturas
*/
@GetMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<FacturaVenta>> getAllFacturasVenta() {
List<FacturaVenta> bills = facturaVentaServices.getAllFacturasVentas();
return ResponseEntity.ok().body(bills);
}
/**
* Consulta factura por id
* @param id
* @return Factura
*/
@GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<FacturaVenta> getFacturaVenta(@PathVariable Long id) {
FacturaVenta factura = null;
try {
factura = facturaVentaServices.getFacturaVentaById(id);
} catch (FacturaVentaNotFoundException e) {
throw new ResourceNotFoundException("No se ha encontrado la factura solicitada",e);
}
return ResponseEntity.ok().body(factura);
}
/**
* Consulta de Facturas por parametros
* @param request
* @return
*/
@GetMapping(value = "/automovil/{idAutomovil}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<FacturaVenta>> getFacturasVentaPorAutomovil(@PathVariable Long idAutomovil) {
List<FacturaVenta> facturas = null;
try {
facturas = facturaVentaServices.getFacturaVentaByAutomovil(idAutomovil);
} catch (FacturaVentaNotFoundException e) {
throw new ResourceNotFoundException("No se ha encontrado la facturas para el automovil",e);
} catch (AutomovilNotFoundException e) {
throw new ResourceNotFoundException("No se ha encontrado el automovil solicitadoO",e);
}
return ResponseEntity.ok().body(facturas);
}
/**
* Alta de factura
* @param request
* @return resultado de la operacion
*/
@PostMapping(value = "/add", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> addFacturaVenta(@RequestBody FacturaVentaRequest request) {
ResponseEntity<Object> response = null;
try {
this.facturaVentaServices.addFacturaVenta(request);
response = ResponseEntity.ok("Se ingreso correctamente la factura de la venta realizada");
} catch (InternalDataBaseException e) {
throw new ResponseStatusException(
HttpStatus.INTERNAL_SERVER_ERROR, "Internal Error", e);
} catch (AutomovilNotFoundException e) {
throw new ResourceNotFoundException("No se ha encontrado el automovil solicitadoO",e);
} catch (ValidationPrecioVentaException e) {
throw new ValidationException("El valor del precio del automovil no se encuentra dentro del rango establecido",e);
} catch (ValidationVentaAutoDisponibleException e) {
throw new ValidationException("No existen unidades del automovil disponibles para la venta",e);
}
return response;
}
/**
* Eliminar factura
* @param request
* @return resultado de la operacion
*/
@DeleteMapping(value = "/delete/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> cancelarFactura(@PathVariable Long id) {
ResponseEntity<Object> response = null;
try {
this.facturaVentaServices.deleteFactura(id);
response = ResponseEntity.ok("Se elimno correctamente la factura");
} catch (FacturaVentaNotFoundException e) {
throw new ResourceNotFoundException("No es posible obtener la factura que desea eliminar",e);
}
return response;
}
/**
* Modificar datos de factura
* @param request
* @return resultado de la operacion
*/
@PostMapping(value = "/update/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> updateFactura(@RequestBody FacturaVentaRequest request) {
ResponseEntity<Object> response = null;
try {
this.facturaVentaServices.updateFacturaVenta(request);
response = ResponseEntity.ok("Se actualizo correctamente la factura de la venta realizada");
} catch (FacturaVentaNotFoundException e) {
throw new ResourceNotFoundException("No es posible obtener la factura que desea eliminar",e);
} catch (AutomovilNotFoundException e) {
throw new ResourceNotFoundException("No es posible obtener la factura que desea eliminar",e);
} catch (ValidationPrecioVentaException e) {
throw new ResourceNotFoundException("El precio de venta no se encuentra entre los rangos preestablecidos",e);
}
return response;
}
}
| true |
6e11c91e9548aa48d85a7d8f1add1cd65c32e5ae | Java | leandrocesar09/tutorials | /axon/src/main/java/com/baeldung/axon/aggregates/MessagesAggregate.java | UTF-8 | 1,037 | 2.4375 | 2 | [
"MIT"
] | permissive | package com.baeldung.axon.aggregates;
import com.baeldung.axon.commands.CreateMessageCommand;
import com.baeldung.axon.commands.MarkReadMessageCommand;
import com.baeldung.axon.events.MessageCreatedEvent;
import com.baeldung.axon.events.MessageReadEvent;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.model.AggregateIdentifier;
import org.axonframework.eventhandling.EventHandler;
import static org.axonframework.commandhandling.model.AggregateLifecycle.apply;
public class MessagesAggregate {
@AggregateIdentifier
private String id;
public MessagesAggregate() {
}
@CommandHandler
public MessagesAggregate(CreateMessageCommand command) {
apply(new MessageCreatedEvent(command.getId(), command.getText()));
}
@EventHandler
public void on(MessageCreatedEvent event) {
this.id = event.getId();
}
@CommandHandler
public void markRead(MarkReadMessageCommand command) {
apply(new MessageReadEvent(id));
}
} | true |
22d95c8b448a81fba2c922494dc87cdaac18c649 | Java | LONG89562566/BasicInfo | /admin/src/main/java/com/info/admin/service/FileAttrService.java | UTF-8 | 2,105 | 2.046875 | 2 | [] | no_license | package com.info.admin.service;
import com.info.admin.entity.FileAttr;
import com.info.admin.utils.PageUtil;
import java.util.List;
/**
* @author ysh
* @date 2018-11-14 23:45:42
* @describe 文件 Service
*/
public interface FileAttrService {
/**
*添加FileAttr对象
*@param entity 对象
*@author ysh
*@date 2018-11-14 23:45:42
*@updater or other
*@return int
*/
int insert(FileAttr entity);
/**
*批量添加FileAttr对象
*@param entity 对象
*@author ysh
*@date 2018-11-14 23:45:42
*@updater or other
*@return int
*/
int insertBatchFileAttr(FileAttr entity,List<String> pathList,List<String> nameList);
/**
*批量添加FileAttr对象
*@param fileAttrs 文件数组
*@author ysh
*@date 2018-11-14 23:45:42
*@updater or other
*@return int
*/
int insertBatchFileAttr(List<FileAttr> fileAttrs);
/**
*修改FileAttr对象
*@param entity 对象
*@author ysh
*@date 2018-11-14 23:45:42
*@updater or other
*@return int
*/
int update(FileAttr entity);
/**
*查询FileAttr对象
*@param entity 对象
*@author ysh
*@date 2018-11-14 23:45:42
*@updater or other
*@return List<FileAttr>
*/
List<FileAttr> query(FileAttr entity);
/**
*删除FileAttr对象
*@param entity 对象
*@author ysh
*@date 2018-11-14 23:45:42
*@updater or other
*@return int
*/
int delete(FileAttr entity);
/**
* 分页查询FileAttr对象
* @param entity 对象
* @param pageNum 页数
* @param pageSize 大小
* @author ysh
* @date 2018-11-14 23:45:42
* @updater or other
* @return PageUtil
*/
PageUtil pageQuery(FileAttr entity, int pageNum, int pageSize);
/**
* 根据 id获取 文件
* @author ysh
* @param fileId 主键id
* @date 2018-11-14 23:45:42
* @updater or other
* @return FileAttr
*/
public FileAttr getFileAttrById(String fileId);
}
| true |
562e8886d21124e7059bc00e13cfb273584f2917 | Java | mari-otus/2020-02-otus-spring-Tronina | /learn-otus-7/src/test/java/ru/otus/spring/repository/BookRepositoryTest.java | UTF-8 | 5,282 | 2.59375 | 3 | [] | no_license | package ru.otus.spring.repository;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.dao.EmptyResultDataAccessException;
import ru.otus.spring.domain.Author;
import ru.otus.spring.domain.Book;
import ru.otus.spring.domain.Genre;
import ru.otus.spring.repository.book.BookRepository;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Тестирование Repository JPA для работы с книгами.
*
* @author Mariya Tronina
*/
@DisplayName("BookRepository для работы с книгами должно")
@DataJpaTest
public class BookRepositoryTest {
public static final int EXPECTED_BOOK_COUNT = 8;
public static final long DEFAULT_BOOK_ID = 7L;
@Autowired
private BookRepository bookRepository;
@Autowired
private TestEntityManager em;
@DisplayName("добавлять книгу с авторами и жанрами в БД")
@Test
public void shouldInsertBookWithAuthorsAndGenres() {
Book newBook = Book.builder()
.name("Книга")
.yearEdition(1987)
.genres(Arrays.asList(
Genre.builder()
.name("Жанр1")
.build(),
Genre.builder()
.name("Роман")
.build()
).stream().collect(Collectors.toSet()))
.authors(Arrays.asList(
Author.builder()
.fio("Толстой Лев Николаевич")
.build(),
Author.builder()
.fio("Иванов Иван")
.build()
).stream().collect(Collectors.toSet()))
.build();
Book expectedBook = bookRepository.save(newBook);
Book actualBook = em.find(Book.class, expectedBook.getId());
assertThat(actualBook).isNotNull();
assertThat(actualBook.equals(expectedBook));
}
@DisplayName("возвращать ожидаемую книгу с авторами и жанрами по идентификатору из БД")
@Test
public void shouldGetBookByIdWithAuthorsAndGenres() {
Book expectedBook = Book.builder()
.id(DEFAULT_BOOK_ID)
.name("Улитка на склоне")
.yearEdition(2001)
.genres(Arrays.asList(
Genre.builder()
.name("Роман")
.build(),
Genre.builder()
.name("Фантастика")
.build()
).stream().collect(Collectors.toSet()))
.authors(Arrays.asList(
Author.builder()
.fio("Струкгацкий Аркадий Натанович")
.build(),
Author.builder()
.fio("Струкгацкий Борис Натанович")
.build()
).stream().collect(Collectors.toSet()))
.build();
Book actualBook = bookRepository.getOne(DEFAULT_BOOK_ID);
assertThat(actualBook).isNotNull();
assertThat(actualBook.equals(expectedBook));
}
@DisplayName("возвращать все книги из БД")
@Test
public void shouldGetAllBookWithAuthorsAndGenres() {
List<Book> actualBookList = bookRepository.findAll();
assertThat(actualBookList).isNotEmpty()
.hasSize(EXPECTED_BOOK_COUNT)
.allMatch(book -> Objects.nonNull(book));
}
@DisplayName("удалять существующую книгу из БД")
@Test
public void shouldDeleteExistsBook() {
assertThatCode(() -> {
bookRepository.deleteById(DEFAULT_BOOK_ID);
}).doesNotThrowAnyException();
}
@DisplayName("удалять не существующую книгу из БД")
@Test
public void shouldDeleteNotExistsBook() {
assertThatThrownBy(() -> {
bookRepository.deleteById(DEFAULT_BOOK_ID * 1000);
}).isInstanceOf(EmptyResultDataAccessException.class);
}
}
| true |
c7655e28893f625b4d05222c9e7fab26c3f3601b | Java | cgb-study/warpdb | /src/main/java/com/itranswarp/warpdb/ConfigurationException.java | UTF-8 | 515 | 2.28125 | 2 | [
"Apache-2.0"
] | permissive | package com.itranswarp.warpdb;
import javax.persistence.PersistenceException;
/**
* Thrown when invalid configuration found.
*
* @author liaoxuefeng
*/
public class ConfigurationException extends PersistenceException {
public ConfigurationException() {
super();
}
public ConfigurationException(String message, Throwable cause) {
super(message, cause);
}
public ConfigurationException(String message) {
super(message);
}
public ConfigurationException(Throwable cause) {
super(cause);
}
}
| true |
0bc739983387b45307a27cb694a6a4b49d9ec6d2 | Java | LogisticsImpactModel/LIMO | /view/src/main/java/nl/fontys/sofa/limo/view/wizard/leg/normal/ProceduresLegTypeWizard.java | UTF-8 | 1,828 | 2.3125 | 2 | [
"Apache-2.0"
] | permissive | package nl.fontys.sofa.limo.view.wizard.leg.normal;
import java.util.ArrayList;
import javax.swing.event.ChangeListener;
import nl.fontys.sofa.limo.domain.component.leg.Leg;
import nl.fontys.sofa.limo.view.custom.panel.ProceduresPanel;
import nl.fontys.sofa.limo.view.util.LIMOResourceBundle;
import org.openide.WizardDescriptor;
import org.openide.WizardValidationException;
import org.openide.util.HelpCtx;
/**
* Add Procedure to leg
*
* @author Pascal Lindner
*/
public class ProceduresLegTypeWizard implements WizardDescriptor.Panel<WizardDescriptor>, WizardDescriptor.ValidatingPanel<WizardDescriptor> {
private ProceduresPanel component;
private Leg leg;
public ProceduresLegTypeWizard() {
}
@Override
public ProceduresPanel getComponent() {
if (component == null) {
component = new ProceduresPanel();
}
return component;
}
@Override
public HelpCtx getHelp() {
return HelpCtx.DEFAULT_HELP;
}
@Override
public boolean isValid() {
return true;
}
@Override
public void addChangeListener(ChangeListener l) {
}
@Override
public void removeChangeListener(ChangeListener l) {
}
@Override
public void readSettings(WizardDescriptor wiz) {
leg = (Leg) wiz.getProperty("leg");
getComponent().update(new ArrayList(leg.getProcedures()));
}
@Override
public void storeSettings(WizardDescriptor wiz) {
leg.setProcedures(getComponent().getProcedures());
}
@Override
public void validate() throws WizardValidationException {
if (component.getProcedures().isEmpty()) {
throw new WizardValidationException(null, null, LIMOResourceBundle.getString("VALUE_NOT_SET2", LIMOResourceBundle.getString("PROCEDURES")));
}
}
}
| true |
cb55b9014fd954e9bea0ff37b2d4b16a3ec950ff | Java | hakat0m/Chessboxing | /com.gumtree.android.beta/java/com/gumtree/android/location/service/GeocoderLocationService$$Lambda$4.java | UTF-8 | 626 | 1.820313 | 2 | [] | no_license | package com.gumtree.android.location.service;
import android.location.Location;
import java.lang.invoke.LambdaForm.Hidden;
import rx.functions.Action1;
final /* synthetic */ class GeocoderLocationService$$Lambda$4 implements Action1 {
private static final GeocoderLocationService$$Lambda$4 instance = new GeocoderLocationService$$Lambda$4();
private GeocoderLocationService$$Lambda$4() {
}
public static Action1 lambdaFactory$() {
return instance;
}
@Hidden
public void call(Object obj) {
GeocoderLocationService.lambda$askForCurrentLocationPostcode$3((Location) obj);
}
}
| true |
b30b2d6b69722d40243b7e269d3a9d8869ca000b | Java | alexwoolford/streamsets-datacollector-marc-parser | /src/test/java/io/woolford/stage/processor/marcparser/TestMarcParserProcessor.java | UTF-8 | 16,480 | 1.976563 | 2 | [] | no_license | /*
* Copyright 2017 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.woolford.stage.processor.marcparser;
import com.streamsets.pipeline.api.Field;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.sdk.ProcessorRunner;
import com.streamsets.pipeline.sdk.RecordCreator;
import com.streamsets.pipeline.sdk.StageRunner;
import org.junit.Assert;
import org.junit.Test;
import org.marc4j.marc.DataField;
import org.marc4j.marc.Subfield;
import org.marc4j.marc.impl.DataFieldImpl;
import org.marc4j.marc.impl.SubfieldImpl;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
public class TestMarcParserProcessor {
@Test
@SuppressWarnings("unchecked")
public void testProcessor() throws StageException, IOException {
String marc = new String(Files.readAllBytes(Paths.get("src/test/resources/summerland.mrc")));
ProcessorRunner runner = new ProcessorRunner.Builder(MarcParserDProcessor.class)
.addConfiguration("config", "value")
.addOutputLane("output")
.build();
runner.runInit();
try {
Record record = RecordCreator.create();
Map<String, Field> fields = new HashMap<>();
fields.put("text", Field.create(marc));
record.set(Field.create(fields));
StageRunner.Output output = runner.runProcess(Arrays.asList(record));
assertEquals(1, output.getRecords().get("output").size());
Record record1 = output.getRecords().get("output").get(0);
assertEquals(Field.Type.LIST_MAP, record1.get().getType());
Field leader = record1.get("/leader");
assertEquals("00714cam a2200205 a 4500", leader.getValueAsString());
Field _001 = record1.get("/001");
assertEquals("12883376", _001.getValueAsString());
Field _005 = record1.get("/005");
assertEquals("20030616111422.0", _005.getValueAsString());
Field _008 = record1.get("/008");
assertEquals("020805s2002 nyu j 000 1 eng ", _008.getValueAsString());
// Fields 020
// 020 $a0786808772
// 020 $a0786816155 (pbk.)
Field _020 = record1.get("/020");
assertEquals(Field.Type.LIST, _020.getType());
List<Field> _020List = _020.getValueAsList();
assertEquals(2, _020List.size());
assertSame(record1.get("/020[0]"), _020List.get(0));
Field _020_0 = _020List.get(0);
assertEquals(Field.Type.LIST_MAP, _020_0.getType());
assertEquals(' ', record1.get("/020[0]/indicator1").getValueAsChar());
assertEquals(' ', record1.get("/020[0]/indicator2").getValueAsChar());
assertEquals(1, record1.get("/020[0]/a").getValueAsList().size());
assertEquals("0786808772", record1.get("/020[0]/a[0]").getValueAsString());
assertEquals(' ', record1.get("/020[1]/indicator1").getValueAsChar());
assertEquals(' ', record1.get("/020[1]/indicator2").getValueAsChar());
assertEquals("0786816155 (pbk.)", record1.get("/020[1]/a[0]").getValueAsString());
//Field 040
// 040 $aDLC$cDLC$dDLC
assertEquals(1, record1.get("/040").getValueAsList().size());
assertEquals(' ', record1.get("/040[0]/indicator1").getValueAsChar());
assertEquals(' ', record1.get("/040[0]/indicator2").getValueAsChar());
assertEquals(1, record1.get("/040[0]/a").getValueAsList().size());
assertEquals("DLC", record1.get("/040[0]/a[0]").getValueAsString());
assertEquals(1, record1.get("/040[0]/c").getValueAsList().size());
assertEquals("DLC", record1.get("/040[0]/c[0]").getValueAsString());
assertEquals(1, record1.get("/040[0]/d").getValueAsList().size());
assertEquals("DLC", record1.get("/040[0]/d[0]").getValueAsString());
//Field 100
//100 1 $aChabon, Michael.
assertEquals(1, record1.get("/100").getValueAsList().size());
assertEquals('1', record1.get("/100[0]/indicator1").getValueAsChar());
assertEquals(' ', record1.get("/100[0]/indicator2").getValueAsChar());
assertEquals(1, record1.get("/100[0]/a").getValueAsList().size());
assertEquals("Chabon, Michael.", record1.get("/100[0]/a[0]").getValueAsString());
//Field 245
// 245 10$aSummerland /$cMichael Chabon.
assertEquals(1, record1.get("/245").getValueAsList().size());
assertEquals('1', record1.get("/245[0]/indicator1").getValueAsChar());
assertEquals('0', record1.get("/245[0]/indicator2").getValueAsChar());
assertEquals(1, record1.get("/245[0]/a").getValueAsList().size());
assertEquals("Summerland /", record1.get("/245[0]/a[0]").getValueAsString());
assertEquals(1, record1.get("/245[0]/c").getValueAsList().size());
assertEquals("Michael Chabon.", record1.get("/245[0]/c[0]").getValueAsString());
//Fields 650
// 650 1$aFantasy.
// 650 1$aBaseball$vFiction.
// 650 1$aMagic$vFiction.
assertEquals(3, record1.get("/650").getValueAsList().size());
assertEquals(' ', record1.get("/650[0]/indicator1").getValueAsChar());
assertEquals('1', record1.get("/650[0]/indicator2").getValueAsChar());
assertEquals(1, record1.get("/650[0]/a").getValueAsList().size());
assertEquals("Fantasy.", record1.get("/650[0]/a[0]").getValueAsString());
assertEquals(' ', record1.get("/650[1]/indicator1").getValueAsChar());
assertEquals('1', record1.get("/650[1]/indicator2").getValueAsChar());
assertEquals(1, record1.get("/650[1]/a").getValueAsList().size());
assertEquals("Baseball", record1.get("/650[1]/a[0]").getValueAsString());
assertEquals(1, record1.get("/650[1]/v").getValueAsList().size());
assertEquals("Fiction.", record1.get("/650[1]/v[0]").getValueAsString());
assertEquals(' ', record1.get("/650[2]/indicator1").getValueAsChar());
assertEquals('1', record1.get("/650[2]/indicator2").getValueAsChar());
assertEquals(1, record1.get("/650[2]/a").getValueAsList().size());
assertEquals("Magic", record1.get("/650[2]/a[0]").getValueAsString());
assertEquals(1, record1.get("/650[2]/v").getValueAsList().size());
assertEquals("Fiction.", record1.get("/650[2]/v[0]").getValueAsString());
} finally {
runner.runDestroy();
}
}
@Test
public void testGetMapOfDataField() {
DataField field = new DataFieldImpl("650", ' ', '0');
Subfield a = new SubfieldImpl('a', "Theater");
field.addSubfield(a);
Subfield z = new SubfieldImpl('z', "United States");
field.addSubfield(z);
Subfield v0 = new SubfieldImpl('v', "Biography");
field.addSubfield(v0);
Subfield v1 = new SubfieldImpl('v', "Dictionaries.");
field.addSubfield(v1);
LinkedHashMap<String, Field> mapOfDataField = MarcParserProcessor.getMapOfDataField(field);
assertEquals(' ', mapOfDataField.get("indicator1").getValue());
assertEquals('0', mapOfDataField.get("indicator2").getValue());
assertEquals(Field.Type.LIST, mapOfDataField.get("a").getType());
List<Field> aSubfield = mapOfDataField.get("a").getValueAsList();
assertEquals(1, aSubfield.size());
assertEquals("Theater", aSubfield.get(0).getValueAsString());
List<Field> vSubfield = mapOfDataField.get("v").getValueAsList();
assertEquals(2, vSubfield.size());
assertEquals("Biography", vSubfield.get(0).getValueAsString());
assertEquals("Dictionaries.", vSubfield.get(1).getValueAsString());
}
@Test
public void testProcessMultiRecords() throws StageException, IOException {
String marc = new String(Files.readAllBytes(Paths.get("src/test/resources/chabon.mrc")));
ProcessorRunner runner = new ProcessorRunner.Builder(MarcParserDProcessor.class)
.addConfiguration("config", "value")
.addOutputLane("output")
.build();
runner.runInit();
//Not sure what groups or the labels are used for, but we should make sure we don't break tests
String groupLabel=Groups.MARC_PARSER.getLabel();
assertEquals("MARC Parser",groupLabel);
try {
Record record = RecordCreator.create();
Map<String, Field> fields = new HashMap<>();
fields.put("text", Field.create(marc));
record.set(Field.create(fields));
StageRunner.Output output = runner.runProcess(Arrays.asList(record));
assertEquals(2, output.getRecords().get("output").size());
Record record0 = output.getRecords().get("output").get(0);
assertEquals(Field.Type.LIST_MAP, record0.get().getType());
Field leader0 = record0.get("/leader");
assertEquals("00759cam a2200229 a 4500", leader0.getValueAsString());
Field _001 = record0.get("/001");
assertEquals("11939876", _001.getValueAsString());
Field _005 = record0.get("/005");
assertEquals("20041229190604.0", _005.getValueAsString());
Field _008 = record0.get("/008");
assertEquals("000313s2000 nyu 000 1 eng ", _008.getValueAsString());
assertEquals(' ', record0.get("/020[0]/indicator1").getValueAsChar());
assertEquals(' ', record0.get("/020[0]/indicator2").getValueAsChar());
assertEquals(1, record0.get("/020[0]/a").getValueAsList().size());
assertEquals("0679450041 (acid-free paper)", record0.get("/020[0]/a[0]").getValueAsString());
//Field 040
// 040 $aDLC$cDLC$dDLC
assertEquals(1, record0.get("/040").getValueAsList().size());
assertEquals(' ', record0.get("/040[0]/indicator1").getValueAsChar());
assertEquals(' ', record0.get("/040[0]/indicator2").getValueAsChar());
assertEquals(1, record0.get("/040[0]/a").getValueAsList().size());
assertEquals("DLC", record0.get("/040[0]/a[0]").getValueAsString());
assertEquals(1, record0.get("/040[0]/c").getValueAsList().size());
assertEquals("DLC", record0.get("/040[0]/c[0]").getValueAsString());
assertEquals(1, record0.get("/040[0]/d").getValueAsList().size());
assertEquals("DLC", record0.get("/040[0]/d[0]").getValueAsString());
//Field 100
//100 1 $aChabon, Michael.
assertEquals(1, record0.get("/100").getValueAsList().size());
assertEquals('1', record0.get("/100[0]/indicator1").getValueAsChar());
assertEquals(' ', record0.get("/100[0]/indicator2").getValueAsChar());
assertEquals(1, record0.get("/100[0]/a").getValueAsList().size());
assertEquals("Chabon, Michael.", record0.get("/100[0]/a[0]").getValueAsString());
//Field 245
// 245 10$aThe amazing adventures of Kavalier and Clay :$ba novel /$cMichael Chabon.
assertEquals(1, record0.get("/245").getValueAsList().size());
assertEquals('1', record0.get("/245[0]/indicator1").getValueAsChar());
assertEquals('4', record0.get("/245[0]/indicator2").getValueAsChar());
assertEquals(1, record0.get("/245[0]/a").getValueAsList().size());
assertEquals("The amazing adventures of Kavalier and Clay :", record0.get("/245[0]/a[0]").getValueAsString());
assertEquals(1, record0.get("/245[0]/b").getValueAsList().size());
assertEquals("a novel /", record0.get("/245[0]/b[0]").getValueAsString());
assertEquals(1, record0.get("/245[0]/c").getValueAsList().size());
assertEquals("Michael Chabon.", record0.get("/245[0]/c[0]").getValueAsString());
Record record1 = output.getRecords().get("output").get(1);
assertEquals(Field.Type.LIST_MAP, record1.get().getType());
Field leader = record1.get("/leader");
assertEquals("00714cam a2200205 a 4500", leader.getValueAsString());
_001 = record1.get("/001");
assertEquals("12883376", _001.getValueAsString());
_005 = record1.get("/005");
assertEquals("20030616111422.0", _005.getValueAsString());
_008 = record1.get("/008");
assertEquals("020805s2002 nyu j 000 1 eng ", _008.getValueAsString());
Field _020 = record1.get("/020");
assertEquals(Field.Type.LIST, _020.getType());
List<Field> _020List = _020.getValueAsList();
assertEquals(2, _020List.size());
assertSame(record1.get("/020[0]"), _020List.get(0));
Field _020_0 = _020List.get(0);
assertEquals(Field.Type.LIST_MAP, _020_0.getType());
assertEquals(' ', record1.get("/020[0]/indicator1").getValueAsChar());
assertEquals(' ', record1.get("/020[0]/indicator2").getValueAsChar());
assertEquals(1, record1.get("/020[0]/a").getValueAsList().size());
assertEquals("0786808772", record1.get("/020[0]/a[0]").getValueAsString());
assertEquals(' ', record1.get("/020[1]/indicator1").getValueAsChar());
assertEquals(' ', record1.get("/020[1]/indicator2").getValueAsChar());
assertEquals("0786816155 (pbk.)", record1.get("/020[1]/a[0]").getValueAsString());
//Field 040
// 040 $aDLC$cDLC$dDLC
assertEquals(1, record1.get("/040").getValueAsList().size());
assertEquals(' ', record1.get("/040[0]/indicator1").getValueAsChar());
assertEquals(' ', record1.get("/040[0]/indicator2").getValueAsChar());
assertEquals(1, record1.get("/040[0]/a").getValueAsList().size());
assertEquals("DLC", record1.get("/040[0]/a[0]").getValueAsString());
assertEquals(1, record1.get("/040[0]/c").getValueAsList().size());
assertEquals("DLC", record1.get("/040[0]/c[0]").getValueAsString());
assertEquals(1, record1.get("/040[0]/d").getValueAsList().size());
assertEquals("DLC", record1.get("/040[0]/d[0]").getValueAsString());
//Field 100
//100 1 $aChabon, Michael.
assertEquals(1, record1.get("/100").getValueAsList().size());
assertEquals('1', record1.get("/100[0]/indicator1").getValueAsChar());
assertEquals(' ', record1.get("/100[0]/indicator2").getValueAsChar());
assertEquals(1, record1.get("/100[0]/a").getValueAsList().size());
assertEquals("Chabon, Michael.", record1.get("/100[0]/a[0]").getValueAsString());
//Field 245
// 245 10$aSummerland /$cMichael Chabon.
assertEquals(1, record1.get("/245").getValueAsList().size());
assertEquals('1', record1.get("/245[0]/indicator1").getValueAsChar());
assertEquals('0', record1.get("/245[0]/indicator2").getValueAsChar());
assertEquals(1, record1.get("/245[0]/a").getValueAsList().size());
assertEquals("Summerland /", record1.get("/245[0]/a[0]").getValueAsString());
assertEquals(1, record1.get("/245[0]/c").getValueAsList().size());
assertEquals("Michael Chabon.", record1.get("/245[0]/c[0]").getValueAsString());
//Fields 650
// 650 1$aFantasy.
// 650 1$aBaseball$vFiction.
// 650 1$aMagic$vFiction.
assertEquals(3, record1.get("/650").getValueAsList().size());
assertEquals(' ', record1.get("/650[0]/indicator1").getValueAsChar());
assertEquals('1', record1.get("/650[0]/indicator2").getValueAsChar());
assertEquals(1, record1.get("/650[0]/a").getValueAsList().size());
assertEquals("Fantasy.", record1.get("/650[0]/a[0]").getValueAsString());
assertEquals(' ', record1.get("/650[1]/indicator1").getValueAsChar());
assertEquals('1', record1.get("/650[1]/indicator2").getValueAsChar());
assertEquals(1, record1.get("/650[1]/a").getValueAsList().size());
assertEquals("Baseball", record1.get("/650[1]/a[0]").getValueAsString());
assertEquals(1, record1.get("/650[1]/v").getValueAsList().size());
assertEquals("Fiction.", record1.get("/650[1]/v[0]").getValueAsString());
assertEquals(' ', record1.get("/650[2]/indicator1").getValueAsChar());
assertEquals('1', record1.get("/650[2]/indicator2").getValueAsChar());
assertEquals(1, record1.get("/650[2]/a").getValueAsList().size());
assertEquals("Magic", record1.get("/650[2]/a[0]").getValueAsString());
assertEquals(1, record1.get("/650[2]/v").getValueAsList().size());
assertEquals("Fiction.", record1.get("/650[2]/v[0]").getValueAsString());
} finally {
runner.runDestroy();
}
}
}
| true |
bc2de5db502a1bf566388787fdc76aa1ca64a2f4 | Java | EgbeEugene/calculator | /src/GPATest.java | UTF-8 | 529 | 2.3125 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Larry_Lite
*/
import javax.swing.JFrame;
public class GPATest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
GpaFrame TextFrame = new GpaFrame();
TextFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
TextFrame.setSize( 300, 300 );
TextFrame.setVisible(true);
// TODO code application logic here
}
}
| true |
abf2720322f390b7814b45c7042cb3020d6fe8ac | Java | MaximZaretsky/EPAM | /src/com/github/maximzaretsky/dev6/src/Components/Milliseconds.java | UTF-8 | 2,711 | 3.5625 | 4 | [] | no_license | package Components;
import java.util.Calendar;
/**
* Handles symbols, related to day
*/
public class Milliseconds extends FormatComponents{
private final String MILLISECONDS = "f";
private final String NOT_NULL_MILLISECONDS = "F";
private final int MAXIMAL_LENGTH = 3;
private String returnComponent;
/**
* Constructor of class, which transmit received data to defineMethodForExecution
* @param formatComponent string, received from factory
* @param calendar instance of java.util.Calendar
*/
public Milliseconds(String formatComponent, Calendar calendar){
defineMethodForExecution(formatComponent, calendar);
}
/**
* Define, which method will be called depending on the received string
* @param formatComponent string, received from constructor
* @param calendar calendar, received from constructor
*/
private void defineMethodForExecution(String formatComponent, Calendar calendar){
if (formatComponent.startsWith(MILLISECONDS)){
getMilliseconds(calendar, formatComponent);
} else if (formatComponent.startsWith(NOT_NULL_MILLISECONDS)){
getNotNullMilliseconds(calendar, formatComponent);
}
}
/**
* Define how many milliseconds needs to display
* @param calendar calendar, received from constructor
* @param formatComponent amount of numbers, which need to display
*/
private void getMilliseconds(Calendar calendar, String formatComponent){
if (formatComponent.length() <= MAXIMAL_LENGTH) {
returnComponent = (calendar.get(Calendar.MILLISECOND) + "").substring(0, formatComponent.length());
} else {
returnComponent = calendar.get(Calendar.MILLISECOND) + "";
for (int i = MAXIMAL_LENGTH; i < formatComponent.length(); i++) {
returnComponent += "0";
}
}
}
/**
* Define how many milliseconds needs to display, if value of milliseconds not equal 0
* @param calendar calendar, received from constructor
* @param formatComponent amount of numbers, which need to display
*/
private void getNotNullMilliseconds(Calendar calendar, String formatComponent){
if (calendar.get(Calendar.MILLISECOND) != 0) {
if (formatComponent.length() <= MAXIMAL_LENGTH) {
returnComponent = (calendar.get(Calendar.MILLISECOND) + "").substring(0, formatComponent.length());
} else {
returnComponent = calendar.get(Calendar.MILLISECOND) + "";
for (int i = MAXIMAL_LENGTH; i < formatComponent.length(); i++) {
returnComponent += "0";
}
}
} else {
returnComponent = "";
}
}
/**
*
* @return value of milled component
*/
public String getFormatComponent() {
return returnComponent;
}
}
| true |
13ad342a6519b6d27fc16f74103328e70ea64b85 | Java | flair2005/retail-scm-integrated | /WEB-INF/retail_scm_core_src/com/skynet/retailscm/receivingspace/ReceivingSpaceManager.java | UTF-8 | 1,866 | 1.804688 | 2 | [
"Apache-2.0"
] | permissive |
package com.skynet.retailscm.receivingspace;
import java.util.Date;
import com.skynet.retailscm.RetailScmUserContext;
public interface ReceivingSpaceManager{
public ReceivingSpace createReceivingSpace(RetailScmUserContext userContext, String location, String contactNumber, String description, String totalArea, String warehouseId, double latitude, double longitude
) throws Exception;
public ReceivingSpace updateReceivingSpace(RetailScmUserContext userContext,String receivingSpaceId, int receivingSpaceVersion, String property, String newValueExpr,String [] tokensExpr) throws Exception;
public ReceivingSpace transferToAnotherWarehouse(RetailScmUserContext userContext, String receivingSpaceId, String anotherWarehouseId) throws Exception;
public void delete(RetailScmUserContext userContext, String receivingSpaceId, int version) throws Exception;
public int deleteAll(RetailScmUserContext userContext, String secureCode ) throws Exception;
/*======================================================DATA MAINTENANCE===========================================================*/
public ReceivingSpace addGoods(RetailScmUserContext userContext, String receivingSpaceId, String name, String rfid, String uom, int maxPackage, Date expireTime, String skuId, String goodsAllocationId, String smartPalletId, String shippingSpaceId, String transportTaskId, String retailStoreId, String bizOrderId, String retailStoreOrderId ,String [] tokensExpr) throws Exception;
public ReceivingSpace removeGoods(RetailScmUserContext userContext, String receivingSpaceId, String goodsId, int goodsVersion,String [] tokensExpr) throws Exception;
public ReceivingSpace updateGoods(RetailScmUserContext userContext, String receivingSpaceId, String goodsId, int goodsVersion, String property, String newValueExpr,String [] tokensExpr) throws Exception;
}
| true |
8c269b8d188ba6dc2c1a63ccff870c5572883142 | Java | radhikayusuf/PBO6-10117909 | /pertemuan-5-(17-10-2018)/practice51/Practice51.java | UTF-8 | 1,585 | 2.984375 | 3 | [] | no_license | /*
*
* @author
* NAMA : Radhika Yusuf
* KELAS : PBO6
* NIM : 10117909
*
* Description : Program Gaji Karyawan
*
*/
public class Practice51 {
public static void main(String[] args) {
Scanner scannerText = new Scanner(System.in);
Scanner scannerNumber = new Scanner(System.in);
Manager m = new Manager();
System.out.println("====Program Perhitungan Gaji Karyawan====");
System.out.print("Masukkan NIK\t\t\t: ");m.setNik(scannerText.nextLine());
System.out.print("Masukkan Nama\t\t\t: ");m.setNama(scannerText.nextLine());
System.out.print("Masukkan Golongan\t\t: ");m.setGolongan(scannerNumber.nextInt());
System.out.print("Masukkan Jabatan\t\t: ");m.setJabatan(scannerText.nextLine());
System.out.print("Masukkan Jumlah Kehadiran\t: ");m.setKehadiran(scannerNumber.nextInt());
System.out.println("");
System.out.println("====Hasil Perhitungan====");
System.out.println("NIK\t\t\t: "+ m.getNik());
System.out.println("NAMA\t\t\t: "+ m.getNama());
System.out.println("GOLONGAN\t\t: "+ m.getGolongan());
System.out.println("JABATAN\t\t\t: " + m.getJabatan()); ;
System.out.println("\nTUNJANGAN GOLONGAN\t: " + m.tunjanganGolongan(m.getGolongan()));
System.out.println("TUNJANGAN JABATAN\t: " + m.tunjanganJabatan(m.getJabatan()));
System.out.println("TUNJANGAN KEHADIRAN\t: " + m.tunjanganKehadiran(m.getKehadiran()));
System.out.println("\nGAJI TOTAL\t\t: " + m.gajiTotal());
}
} | true |
eb8540b91e690f70d10148eb6268e638d5d0cce7 | Java | Jeorgius/JAX-RS_bankdemo | /src/test/java/jeorgius/WithdrawTest.java | UTF-8 | 2,482 | 2.453125 | 2 | [] | no_license | package jeorgius;
import jeorgius.DbAccess.DbAction;
import jeorgius.Validation.PreValidation;
import org.glassfish.grizzly.http.server.HttpServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class WithdrawTest {
private HttpServer server;
private WebTarget target;
private DbAction dbAction;
@Before
public void setUp() throws Exception {
server = Main.startServer();
Client c = ClientBuilder.newClient();
target = c.target(Main.BASE_URI);
this.dbAction = new DbAction();
dbAction.addAccount("00000");
dbAction.updateAccount("00000", 9000);
}
@After
public void tearDown() throws Exception {
dbAction.deleteAccount("00000");
server.stop();
}
@Test
public void testWithdraw() {
String e0 = "{\"account_number\":\"00000\",\"withdraw\":\"900\"}";
String e1 = "{\"account_number\":\"00000\",\"withdraw\":\"-9000\"}";
String e2 = "{\"account_number\":\"00000\",\"withdraw\":\"hhasd\"}";
String e3 = "{\"account_number\":\"00000\",\"withdraw\":\"9001\"}";
// Success!
String responseMsg0 = target.path("00000/withdraw").request().put(Entity.entity(e0,MediaType.APPLICATION_JSON_TYPE),String.class);
assertEquals("OK: Entered sum has been successfully withdrawn: 900\n" + "Current balance is: 8100", responseMsg0);
String responseMsg1 = target.path("00000/withdraw").request().put(Entity.entity(e1,MediaType.APPLICATION_JSON_TYPE),String.class);
assertEquals("Error: Deposit/Withdraw sum must be greater than null", responseMsg1);
String responseMsg2 = target.path("00000/withdraw").request().put(Entity.entity(e2,MediaType.APPLICATION_JSON_TYPE),String.class);
assertEquals("Error: Account/Entered data must be a 5-digit number, but contains characters", responseMsg2);
String responseMsg3 = target.path("00000/withdraw").request().put(Entity.entity(e3,MediaType.APPLICATION_JSON_TYPE),String.class);
assertEquals("Error: insufficient funds\n" + "Balance: 8100\n" + "Sum to withdraw: 9001", responseMsg3);
}
}
| true |
ebc423a2ba521d6733975f63abcff0e5dad226c7 | Java | webhash/test-1 | /src/tail/CircularBuffer.java | UTF-8 | 1,080 | 3.59375 | 4 | [] | no_license | package tail;
/*
* This class creates a circular buffer and keeps only the latest data.
*/
import java.util.ArrayList;
import java.util.List;
public class CircularBuffer {
private final int size;
private final String[] data;
private int counter;
public CircularBuffer(int size) {
if (size <=0 ) {
throw new IllegalArgumentException();
}
this.size = size;
this.data = new String[size];
this.counter = 0;
}
public void add(String line) {
data[this.counter % size] = line;
this.counter = (++this.counter) % size;
}
public List<String> data() {
List<String> l = new ArrayList<String>();
for(int i = this.counter; i < this.size ; i++ ) {
if(data[i] !=null) {
l.add(data[i]);
}
}
if(this.counter > 0) {
for(int i = 0; i < this.counter ; i++ ) {
l.add(data[i]);
}
}
return l;
}
}
| true |
08e0a35051b09cc851960f2cd66d9fe1dd828d99 | Java | inf112-v20/Todo | /src/test/java/inf112/core/movement/SpawnHandlerTest.java | UTF-8 | 4,295 | 2.828125 | 3 | [] | no_license | package inf112.core.movement;
import com.badlogic.gdx.math.Vector2;
import inf112.core.board.MapNames;
import inf112.core.game.MainGame;
import inf112.core.movement.util.SpawnHandler;
import inf112.core.player.Player;
import inf112.core.player.PlayerHandler;
import inf112.core.testingUtils.GdxTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(GdxTestRunner.class)
public class SpawnHandlerTest {
private MainGame game;
private Player player1, player2;
private List<Player> players;
private Vector2 flagPos, cornerPos;
private List<Vector2> availableAdjPosFromCentre, availableAdjPosFromCorner;
private SpawnHandler spawnHandler;
@Before
public void init() {
/*
* Initial situation is like this:
*
* player 1 has already visited the flag and moved away from both the flag and the adjacent positions
* pos (0,0)
*
* player 2 has just visited the flag
* (pos(2,2)
*
* i.e. both has their spawn on the flag
*/
PlayerHandler.playerCount = 0;
game = new MainGame(MapNames.SPAWN_TESTING);
game.getPlayerHandler().createPlayers(2);
game.getMovementHandler().moveAllToSpawn();
game.drawPlayers();
flagPos = new Vector2(2,2);
availableAdjPosFromCentre = new ArrayList<>();
availableAdjPosFromCentre.add(new Vector2(1,1));
availableAdjPosFromCentre.add(new Vector2(1,2));
availableAdjPosFromCentre.add(new Vector2(2,1));
availableAdjPosFromCentre.add(new Vector2(2,3));
availableAdjPosFromCentre.add(new Vector2(3,3));
cornerPos = new Vector2(0, 4);
availableAdjPosFromCorner = new ArrayList<>();
availableAdjPosFromCorner.add(new Vector2(0, 3));
availableAdjPosFromCorner.add(new Vector2(1, 4));
// simulate player 1 has previously visited flag and moved away
player1 = game.getPlayerById(1);
player1.setArchiveMarker((int) flagPos.x, (int) flagPos.y);
// simulate player 2 visits flag
player2 = game.getPlayerById(2);
player2.move(flagPos);
player2.setArchiveMarkerHere();
players = new ArrayList<>();
players.add(player1);
players.add(player2);
spawnHandler = new SpawnHandler(game);
}
@Test
public void isBackupAvailableReturnsFalseWhenBackupIsOccupied() {
assertFalse(spawnHandler.isBackupAvailable(player1));
}
@Test
public void isBackupAvailableReturnsTrueWhenBackupIsAvailable() {
player2.move(availableAdjPosFromCentre.get(0));
assertTrue(spawnHandler.isBackupAvailable(player1));
}
@Test
public void getAvailablePositionsReturnsTheCorrectPositionsWhenNoPlayerIsInTheSurroundingArea() {
List<Vector2> adjPosFromSpawnHandler = spawnHandler.getAvailableAdjPositions(flagPos);
for (Vector2 pos : availableAdjPosFromCentre)
assertTrue(adjPosFromSpawnHandler.contains(pos));
for (Vector2 pos : adjPosFromSpawnHandler)
assertTrue(availableAdjPosFromCentre.contains(pos));
}
@Test
public void getAvailablePositionsReturnsTheCorrectPositionsWhenOnePlayerIsInTheSurroundingArea() {
player2.move(availableAdjPosFromCentre.get(0));
availableAdjPosFromCentre.remove(0);
List<Vector2> adjPosFromSpawnHandler = spawnHandler.getAvailableAdjPositions(flagPos);
for (Vector2 pos : availableAdjPosFromCentre)
assertTrue(adjPosFromSpawnHandler.contains(pos));
for (Vector2 pos : adjPosFromSpawnHandler)
assertTrue(availableAdjPosFromCentre.contains(pos));
}
@Test
public void getAvailablePositionsReturnsTheCorrectPositionsWhenBackupIsAtCornerAndNoPlayerIsInTheSurroundings() {
List<Vector2> adjPosFromSpawnHandler = spawnHandler.getAvailableAdjPositions(cornerPos);
for (Vector2 pos : availableAdjPosFromCorner)
assertTrue(adjPosFromSpawnHandler.contains(pos));
for (Vector2 pos : adjPosFromSpawnHandler)
assertTrue(availableAdjPosFromCorner.contains(pos));
}
}
| true |
0eedb0e50accd3ac0c2549b50f773fa54d0227c1 | Java | clickear/jsaas | /src/main/java/com/redxun/sys/bo/entity/SysBoAttr.java | UTF-8 | 8,287 | 2.109375 | 2 | [] | no_license |
package com.redxun.sys.bo.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import com.alibaba.fastjson.JSONObject;
import com.redxun.core.annotion.table.FieldDefine;
import com.redxun.core.annotion.table.TableDefine;
import com.redxun.core.database.util.DbUtil;
import com.redxun.core.entity.BaseTenantEntity;
import com.redxun.core.util.StringUtil;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
/**
* <pre>
*
* 描述:BO属性表实体类定义
* 作者:ray
* 邮箱: ray@redxun.com
* 日期:2017-02-15 15:02:18
* 版权:广州红迅软件
* </pre>
*/
@Entity
@Table(name = "SYS_BO_ATTR")
@TableDefine(title = "BO属性表")
@XStreamAlias("sysBoAttr")
public class SysBoAttr extends BaseTenantEntity implements Cloneable{
@FieldDefine(title = "主键")
@Id
@Column(name = "ID_")
protected String id;
@FieldDefine(title = "名称")
@Column(name = "NAME_")
protected String name;
@FieldDefine(title = "字段名")
@Column(name = "FIELD_NAME_")
protected String fieldName;
@FieldDefine(title = "备注")
@Column(name = "COMMENT_")
protected String comment;
@FieldDefine(title = "字段类型")
@Column(name = "DATA_TYPE_")
protected String dataType;
@FieldDefine(title = "长度")
@Column(name = "LENGTH_")
protected Integer length;
@FieldDefine(title = "精度")
@Column(name = "DECIMAL_LENGTH_")
protected Integer decimalLength;
@FieldDefine(title = "控件类型")
@Column(name = "CONTROL_")
protected String control;
@FieldDefine(title = "扩展信息")
@Column(name = "EXT_JSON_")
protected String extJson;
/**
* 是否为单值属性,只存在一个字段。
*/
protected int isSingle=1;
@FieldDefine(title = "表单实体对象")
@ManyToOne
@JoinColumn(name = "ENT_ID_")
@XStreamOmitField
protected com.redxun.sys.bo.entity.SysBoEnt sysBoEnt;
@Transient
protected String status=SysBoDef.VERSION_NEW;
//不同的内容
@Transient
protected String diffConent="";
@Transient
protected JSONObject extJsonObj;
/**
* 是否包含,这个只在解析HTML的时候使用。
*/
@Transient
protected boolean isContain=false;
public SysBoAttr() {
}
/**
* Default Key Fields Constructor for class Orders
*/
public SysBoAttr(String in_id) {
this.setPkId(in_id);
}
@Override
public String getIdentifyLabel() {
return this.id;
}
@Override
public Serializable getPkId() {
return this.id;
}
@Override
public void setPkId(Serializable pkId) {
this.id = (String) pkId;
}
public String getId() {
return this.id;
}
public void setId(String aValue) {
this.id = aValue;
}
public void setName(String name) {
this.name = name;
}
/**
* 返回 名称
* @return
*/
public String getName() {
return this.name;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
/**
* 返回 字段名
* @return
*/
public String getFieldName() {
if(StringUtil.isEmpty(fieldName)){
String columnPre=DbUtil.getColumnPre();
return columnPre + this.getName();
}
return this.fieldName;
}
public void setComment(String comment) {
this.comment = comment;
}
/**
* 返回 备注
* @return
*/
public String getComment() {
if(StringUtil.isEmpty(this.comment)){
return this.name;
}
return this.comment;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
/**
* 返回 字段类型
* @return
*/
public String getDataType() {
return this.dataType;
}
public void setLength(Integer length) {
this.length = length;
}
/**
* 返回 长度
* @return
*/
public Integer getLength() {
return this.length;
}
public void setDecimalLength(Integer decimalLength) {
this.decimalLength = decimalLength;
}
/**
* 返回 精度
* @return
*/
public Integer getDecimalLength() {
return this.decimalLength;
}
public void setControl(String control) {
this.control = control;
}
/**
* 返回 控件类型
* @return
*/
public String getControl() {
return this.control;
}
public void setExtJson(String extJson) {
if(StringUtil.isNotEmpty(extJson)){
extJsonObj=JSONObject.parseObject(extJson);
}
this.extJson = extJson;
}
/**
* 返回 扩展信息
* @return
*/
public String getExtJson() {
if(StringUtil.isEmpty(this.extJson)){
return "{}";
}
return this.extJson;
}
public boolean getRequired(){
JSONObject json=JSONObject.parseObject(getExtJson());
String required=json.getString("required");
Boolean flag=false;
if("true".equals(required)){
flag=true;
}
return flag;
}
public String getPropByName(String name){
if(extJsonObj==null) return "";
if(extJsonObj.containsKey(name)){
return extJsonObj.getString(name);
}
return "";
}
public Integer getIntPropByName(String name){
if(extJsonObj==null) return -1;
if(extJsonObj.containsKey(name)){
return extJsonObj.getInteger(name);
}
return -1;
}
public com.redxun.sys.bo.entity.SysBoEnt getSysBoEnt() {
return sysBoEnt;
}
public void setSysBoEnt(com.redxun.sys.bo.entity.SysBoEnt in_sysBoEnt) {
this.sysBoEnt = in_sysBoEnt;
}
/**
* 外键
* @return String
*/
public String getEntId() {
return this.getSysBoEnt() == null ? null : this.getSysBoEnt().getId();
}
/**
* 设置 外键
*/
public void setEntId(String aValue) {
if (aValue == null) {
sysBoEnt = null;
} else if (sysBoEnt == null) {
sysBoEnt = new com.redxun.sys.bo.entity.SysBoEnt(aValue);
} else {
sysBoEnt.setId(aValue);
}
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDiffConent() {
return diffConent;
}
public void setDiffConent(String diffConent) {
this.diffConent = diffConent;
}
public int getIsSingle() {
return isSingle;
}
public boolean single() {
return isSingle==1;
}
public void setIsSingle(int isSingle) {
this.isSingle = isSingle;
}
public boolean isContain() {
return isContain;
}
public void setContain(boolean isContain) {
this.isContain = isContain;
}
/**
* @see java.lang.Object#equals(Object)
*/
public boolean equals(Object object) {
if (!(object instanceof SysBoAttr)) {
return false;
}
SysBoAttr rhs = (SysBoAttr) object;
boolean rtn= new EqualsBuilder()
.append(this.name.toLowerCase(), rhs.name.toLowerCase())
.append(this.dataType, rhs.dataType)
.append(this.control, rhs.control)
.isEquals();
if(!rtn) return rtn;
if(com.redxun.core.database.api.model.Column.COLUMN_TYPE_VARCHAR.equals(this.dataType)){
return this.length.equals( rhs.length);
}
if(com.redxun.core.database.api.model.Column.COLUMN_TYPE_NUMBER.equals(this.dataType)){
return this.length.equals(rhs.length) && this.decimalLength.equals(rhs.decimalLength);
}
return true;
}
/**
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return new HashCodeBuilder(-82280557, -700257973)
.append(this.id)
.append(this.name)
.append(this.fieldName)
.append(this.comment)
.append(this.dataType)
.append(this.length)
.append(this.decimalLength)
.append(this.control)
.append(this.extJson)
.toHashCode();
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
return new ToStringBuilder(this)
.append("id", this.id)
.append("name", this.name)
.append("fieldName", this.fieldName)
.append("comment", this.comment)
.append("dataType", this.dataType)
.append("length", this.length)
.append("decimalLength", this.decimalLength)
.append("control", this.control)
.append("extJson", this.extJson)
.toString();
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| true |
ec242152c27f918cb25d9d2a9a4e203b7bb72d8c | Java | Explorer1092/vox | /utopia-service/utopia-newhomework/utopia-newhomework-impl/src/main/java/com/voxlearning/utopia/service/newhomework/impl/service/internal/teacher/assignvacation/callback/PostAssignVacationHomeworkParentMessage.java | UTF-8 | 5,054 | 1.867188 | 2 | [] | no_license | package com.voxlearning.utopia.service.newhomework.impl.service.internal.teacher.assignvacation.callback;
import com.voxlearning.alps.annotation.meta.Subject;
import com.voxlearning.alps.calendar.DateUtils;
import com.voxlearning.alps.core.util.MapUtils;
import com.voxlearning.alps.core.util.StringUtils;
import com.voxlearning.alps.lang.convert.SafeConverter;
import com.voxlearning.alps.spi.queue.Message;
import com.voxlearning.alps.web.UrlUtils;
import com.voxlearning.utopia.mapper.ScoreCircleQueueCommand;
import com.voxlearning.utopia.service.newhomework.api.client.callback.PostAssignVacationHomework;
import com.voxlearning.utopia.service.newhomework.api.context.AssignVacationHomeworkContext;
import com.voxlearning.utopia.service.newhomework.api.entity.vacation.VacationHomeworkPackage;
import com.voxlearning.utopia.service.newhomework.impl.queue.NewHomeworkParentQueueProducer;
import com.voxlearning.utopia.service.newhomework.impl.support.NewHomeworkSpringBean;
import com.voxlearning.utopia.service.user.api.entities.extension.Teacher;
import com.voxlearning.utopia.service.user.api.mappers.ClazzGroup;
import com.voxlearning.utopia.service.vendor.api.constant.JpushUserTag;
import com.voxlearning.utopia.service.vendor.api.constant.ParentAppPushType;
import com.voxlearning.utopia.service.push.api.constant.AppMessageSource;
import javax.inject.Inject;
import javax.inject.Named;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by tanguohong on 2016/12/6.
*/
@Named
public class PostAssignVacationHomeworkParentMessage extends NewHomeworkSpringBean implements PostAssignVacationHomework {
@Inject private NewHomeworkParentQueueProducer newHomeworkParentQueueProducer;
private static final String CONTENT_PATTERN = "家长好,我布置了假期作业。作业开始时间:{0},请家长督促。";
@Override
public void afterVacationHomeworkAssigned(Teacher teacher, AssignVacationHomeworkContext context) {
Map<ClazzGroup, VacationHomeworkPackage> assignedHomeworks = context.getAssignedHomeworks();
if (MapUtils.isEmpty(assignedHomeworks)) {
return;
}
Long teacherId = teacher.getId();
String teacherName = teacher.fetchRealname();
//这里只是取发送人的ID
Long mainTeacherId = teacherLoaderClient.loadMainTeacherId(teacherId);
teacherId = mainTeacherId == null ? teacherId : mainTeacherId;
//这里才是取所有的学科
Set<Long> relTeacherIds = teacherLoaderClient.loadRelTeacherIds(teacherId);
List<Subject> subjectList = teacherLoaderClient.loadTeachers(relTeacherIds).values().stream().map(Teacher::getSubject).collect(Collectors.toList());
for (VacationHomeworkPackage vacationHomeworkPackage : context.getAssignedHomeworks().values()) {
Set<Long> groupIdSet = new HashSet<>();
groupIdSet.add(vacationHomeworkPackage.getClazzGroupId());
String startDate = DateUtils.dateToString(context.getHomeworkStartTime(), "M月d日");
Subject subject = vacationHomeworkPackage.getSubject();
String iMContent = MessageFormat.format(CONTENT_PATTERN, startDate);
//新的群组消息ScoreCircle
ScoreCircleQueueCommand circleQueueCommand = new ScoreCircleQueueCommand();
circleQueueCommand.setGroupId(vacationHomeworkPackage.getClazzGroupId());
circleQueueCommand.setCreateDate(new Date());
circleQueueCommand.setGroupCircleType("VACATION_HOMEWORK_NEW");
circleQueueCommand.setTypeId(vacationHomeworkPackage.getId());
circleQueueCommand.setImgUrl("");
circleQueueCommand.setLinkUrl(UrlUtils.buildUrlQuery("/view/mobile/activity/parent/vacation", MapUtils.m("subject", subject)));
circleQueueCommand.setContent(iMContent);
newHomeworkParentQueueProducer.getProducer().produce(Message.newMessage().writeObject(circleQueueCommand));
//新的极光push
Map<String, Object> jpushExtInfo = new HashMap<>();
jpushExtInfo.put("studentId", "");
jpushExtInfo.put("s", ParentAppPushType.HOMEWORK_ASSIGN.name());
jpushExtInfo.put("url", UrlUtils.buildUrlQuery("/view/mobile/activity/parent/vacation", MapUtils.m("subject", subject)));
List<String> groupTags = new LinkedList<>();
groupIdSet.forEach(p -> groupTags.add(JpushUserTag.CLAZZ_GROUP_REFACTOR.generateTag(SafeConverter.toString(p))));
String subjectsStr = "(" + StringUtils.join(subjectList.stream().sorted(Comparator.comparingInt(Subject::getId)).map(Subject::getValue).toArray(), ",") + ")";
String em_push_title = teacherName + subjectsStr + ":" + iMContent;
appMessageServiceClient.sendAppJpushMessageByTags(em_push_title,
AppMessageSource.PARENT,
groupTags,
null,
jpushExtInfo);
}
}
}
| true |
f3e8dbd5950e9af08854a7e86f910301f8bc12d7 | Java | SissiChenxy/Emergency-Medical-Service-Java-Application | /src/Interface/SystemAdminWorkArea/CreateDiseaseJPanel.java | UTF-8 | 14,328 | 2.421875 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Interface.SystemAdminWorkArea;
import Business.DiseaseAndTherapy.Disease;
import Business.DiseaseAndTherapy.Medicine;
import Business.DiseaseAndTherapy.Therapy;
import Business.EcoSystem;
import java.awt.CardLayout;
import java.awt.Component;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
*
* @author chenxinyun
*/
public class CreateDiseaseJPanel extends javax.swing.JPanel {
/**
* Creates new form CreateDiseaseJPanel
*/
private JPanel userProcessContainer;
private EcoSystem system;
public CreateDiseaseJPanel(JPanel userProcessContainer,EcoSystem system) {
initComponents();
this.system = system;
this.userProcessContainer = userProcessContainer;
populateMedicineCombo();
}
public void populateMedicineCombo(){
medicine1ComboBox.removeAllItems();
medicine2ComboBox.removeAllItems();
for (Medicine medicine : system.getMedicineCatalog().getMedicineList()){
medicine1ComboBox.addItem(medicine);
medicine2ComboBox.addItem(medicine);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
typeTextField = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
medicine1ComboBox = new javax.swing.JComboBox();
medicine2ComboBox = new javax.swing.JComboBox();
jLabel5 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
nameTextField = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
createButton = new javax.swing.JButton();
backButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
symptomTextArea = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
treatmentMethodsTextArea = new javax.swing.JTextArea();
jScrollPane3 = new javax.swing.JScrollPane();
selfcareMethodsTextArea = new javax.swing.JTextArea();
jLabel1.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
jLabel1.setText("Create Disease");
jLabel4.setText("Medicine:");
medicine1ComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
medicine2ComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel5.setText("Treatment Methods:");
jLabel2.setText("Name:");
nameTextField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
nameTextFieldKeyTyped(evt);
}
});
jLabel3.setText("Type:");
jLabel6.setText("Symptom:");
jLabel7.setText("Selfcare Methods:");
createButton.setText("Create");
createButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
createButtonActionPerformed(evt);
}
});
backButton.setText("<< Back");
backButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backButtonActionPerformed(evt);
}
});
symptomTextArea.setColumns(20);
symptomTextArea.setRows(5);
jScrollPane1.setViewportView(symptomTextArea);
treatmentMethodsTextArea.setColumns(20);
treatmentMethodsTextArea.setRows(5);
jScrollPane2.setViewportView(treatmentMethodsTextArea);
selfcareMethodsTextArea.setColumns(20);
selfcareMethodsTextArea.setRows(5);
jScrollPane3.setViewportView(selfcareMethodsTextArea);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(45, 45, 45)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(18, 18, 18))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(47, 47, 47)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(41, 41, 41))
.addComponent(jLabel4))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(medicine1ComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(medicine2ComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(typeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 287, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 287, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(backButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(createButton))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(0, 48, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(15, 15, 15)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(typeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(medicine1ComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(medicine2ComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(createButton)
.addComponent(backButton))
.addGap(86, 86, 86))
);
}// </editor-fold>//GEN-END:initComponents
private void nameTextFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nameTextFieldKeyTyped
// TODO add your handling code here:
}//GEN-LAST:event_nameTextFieldKeyTyped
private void createButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createButtonActionPerformed
// TODO add your handling code here:
Disease disease = new Disease();
disease.setName(nameTextField.getText());
disease.setSymptom(symptomTextArea.getText());
disease.setType(typeTextField.getText());
disease.addMedicine((Medicine)medicine1ComboBox.getSelectedItem());
disease.addMedicine((Medicine)medicine2ComboBox.getSelectedItem());
Therapy therapy = new Therapy();
therapy.setSelfcareMethods(selfcareMethodsTextArea.getText());
therapy.setAuxiliaryExamination(treatmentMethodsTextArea.getText());
disease.setTherapy(therapy);
system.getDiseaseCatalog().addDisease(disease);
JOptionPane.showMessageDialog(null, "disease has been created successfully!");
nameTextField.setText("");
}//GEN-LAST:event_createButtonActionPerformed
private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed
// TODO add your handling code here:
userProcessContainer.remove(this);
Component[] componentArray = userProcessContainer.getComponents();
Component component = componentArray[componentArray.length - 1];
ManageDiseaseCatalogJPanel mdcjp = (ManageDiseaseCatalogJPanel) component;
mdcjp.populateTable();
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.previous(userProcessContainer);
}//GEN-LAST:event_backButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton backButton;
private javax.swing.JButton createButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JComboBox medicine1ComboBox;
private javax.swing.JComboBox medicine2ComboBox;
private javax.swing.JTextField nameTextField;
private javax.swing.JTextArea selfcareMethodsTextArea;
private javax.swing.JTextArea symptomTextArea;
private javax.swing.JTextArea treatmentMethodsTextArea;
private javax.swing.JTextField typeTextField;
// End of variables declaration//GEN-END:variables
}
| true |
a4541a487e3a57abb9d5c2033e18d214ca48fc3d | Java | mgracy/Android | /Android/AndroidApps/iStudy-v1/src/com/tujk/istudy/adapter/BookNoteListAdapter.java | UTF-8 | 3,386 | 2.21875 | 2 | [] | no_license | /**
*
*/
package com.tujk.istudy.adapter;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.tujk.istudy.R;
import com.tujk.istudy.data.DemoData;
import com.tujk.istudy.ui.OpenPDFBook;
import com.tujk.istudy.ui.OpenVideo;
import com.tujk.istudy.vo.Book;
import com.tujk.istudy.vo.BookMarkValue;
/**
* title : MainBookListAdapter.java
* desc :
* author : tujiakuan
* QQ : 44822331
* email : jiakuantu@gmail.com
* date : 2013-5-27
*/
public class BookNoteListAdapter extends BaseAdapter {
private List<BookMarkValue> data = new ArrayList<BookMarkValue>();
LayoutInflater inflater = null;
Context context;
public BookNoteListAdapter(Context context,List<BookMarkValue> data){
this.data = data;
this.inflater = LayoutInflater.from(context);
this.context = context;
}
/* (non-Javadoc)
* @see android.widget.Adapter#getCount()
*/
@Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
/* (non-Javadoc)
* @see android.widget.Adapter#getItem(int)
*/
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data.get(position);
}
/* (non-Javadoc)
* @see android.widget.Adapter#getItemId(int)
*/
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
/* (non-Javadoc)
* @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
if(convertView==null){
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.book_note_list_item, null);
holder.name = (TextView)convertView.findViewById(R.id.book_note_listitem_text);
holder.imageButton = (ImageView)convertView.findViewById(R.id.book_note_listitem_button);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
final BookMarkValue bookMark = data.get(position);
if(data.get(position).getType()==1){//标签
holder.name.setText(context.getResources().getString(R.string.book_marker) + (position+1));
holder.imageButton.setBackgroundResource(R.drawable.play);
holder.imageButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Book book = DemoData.getBookById(bookMark.getBookId());
Intent intent = new Intent();
if(book.getType()==0){
intent.setClass(context, OpenVideo.class);
}else {
intent.setClass(context, OpenPDFBook.class);
}
intent.putExtra("bookId", book.getId());
intent.putExtra("numberOfPage", bookMark.getNumberOfPage());
context.startActivity(intent);
}
});
}else{//笔记
holder.name.setText(context.getResources().getString(R.string.book_note) + (position+1));
holder.imageButton.setBackgroundResource(R.drawable.detailbtn);
}
return convertView;
}
class ViewHolder{
public TextView name;
public ImageView imageButton;
}
}
| true |
cb07eb33d8e2e1fbaa0b48c181a0705b347fe6e9 | Java | DTStack/Taier | /taier-scheduler/src/main/java/com/dtstack/taier/scheduler/zookeeper/ZkConfig.java | UTF-8 | 2,113 | 1.929688 | 2 | [
"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 com.dtstack.taier.scheduler.zookeeper;
import com.alibaba.fastjson.JSONObject;
import com.dtstack.taier.common.util.AddressUtil;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;
/**
* company: www.dtstack.com
* author: toutian
* create: 2019/10/22
*/
public class ZkConfig {
private String nodeZkAddress;
private String localAddress;
private Map<String, String> security;
public String getNodeZkAddress() {
return nodeZkAddress;
}
public void setNodeZkAddress(String nodeZkAddress) {
this.nodeZkAddress = nodeZkAddress;
}
public String getLocalAddress() {
return localAddress;
}
public void setLocalAddress(String localAddress) {
if (StringUtils.isBlank(localAddress)) {
localAddress = String.format("%s:%s", AddressUtil.getOneIp(),"8090");
}
this.localAddress = localAddress;
}
public Map<String, String> getSecurity() {
return security;
}
public void setSecurity(String securityStr) {
if (StringUtils.isBlank(securityStr)) {
return;
}
this.security = JSONObject.parseObject(securityStr, Map.class);
}
public void setSecurity(Map<String, String> security) {
this.security = security;
}
}
| true |
e16e438fb230e1672ef36649d280af5d86eaaf6c | Java | wix-incubator/TreasureHunt | /TreasureHunt/android/app/src/main/java/com/treasurehunt/modules/HardWorkerModule.java | UTF-8 | 865 | 2.203125 | 2 | [] | no_license | package com.treasurehunt.modules;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
public class HardWorkerModule extends ReactContextBaseJavaModule {
@Override
public void initialize() {
super.initialize();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public HardWorkerModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "HardWorkerModule";
}
@ReactMethod
public void work(Promise promise) throws InterruptedException {
Thread.sleep(2000);
promise.resolve(true);
}
} | true |
7e8b848a18cbf446a4edd3fca058b3de764fce6d | Java | LuceteYang/SingleWenwo | /app/src/main/java/com/wenwoandroidnew/newsfeed/answercheck/AnswerCheckActivity.java | UTF-8 | 5,745 | 2 | 2 | [] | no_license | package com.wenwoandroidnew.newsfeed.answercheck;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Parcel;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.wenwoandroidnew.R;
import com.wenwoandroidnew.newsfeed.QuestionItem;
import com.wenwoandroidnew.newsfeed.answer.AnswerItem;
import com.wenwoandroidnew.system.common.CallResult;
import com.wenwoandroidnew.system.common.CallResultOnemore;
import com.wenwoandroidnew.system.model.ModelAnswerList;
import com.wenwoandroidnew.system.model.query.ModelAnswerPickQuery;
import com.wenwoandroidnew.system.module.ModelPicture;
import com.wenwoandroidnew.system.module.ModuleAnswer;
import java.util.ArrayList;
import java.util.List;
public class AnswerCheckActivity extends AppCompatActivity implements CallResult<ModelAnswerList>, CallResultOnemore<Boolean> {
ListView listView;
CheckAnswerAdapter mAdapter;
ActionBar actionBar;
private Dialog dialog;
private QuestionItem item;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_answer_check,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_answer_choice_complete :
finish();
return true;
case android.R.id.home :
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_answer_check);
actionBar =getSupportActionBar();
//홈아이콘 생성
actionBar.setDisplayHomeAsUpEnabled(true);
//홈아이콘 바꾸기
getSupportActionBar().setHomeAsUpIndicator(R.drawable.header_cancel_28x28);
actionBar.setDisplayShowTitleEnabled(false);
item = new QuestionItem(Parcel.obtain());
listView = (ListView)findViewById(R.id.answer_check_listView);
mAdapter = new CheckAnswerAdapter();
listView.setAdapter(mAdapter);
Intent i = getIntent();
item.status = i.getStringExtra("status");
item.qnum = i.getStringExtra("qnum");
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckAnswerView view2 = (CheckAnswerView)view;
final String anum=view2.AnswerInfo.getAnswernumber();
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(AnswerCheckActivity.this);
myAlertDialog.setTitle("답변 채택");
myAlertDialog.setMessage("이 답변을 채택하시겠습니까??");
myAlertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// Toast.makeText(getApplicationContext(),"ANSWER_NUMBER"+anum,Toast.LENGTH_SHORT).show();
ModelAnswerPickQuery a = new ModelAnswerPickQuery();
a.anum=anum;
ModuleAnswer.doAnswerPick(AnswerCheckActivity.this, a);
}});
myAlertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}});
myAlertDialog.show();
}
});
if(item.getStatus().equals("1")){
ModuleAnswer.getAnswerList(this, Integer.parseInt(item.qnum), 0);
}else if(item.getStatus().equals("0")){
ModuleAnswer.getAnswerList(this, Integer.parseInt(item.qnum), 1);
}
}
@Override
public void callResult(ModelAnswerList modelAnswerList) {
for (int i = 0; i < modelAnswerList.getData().size(); i++) {
ModelAnswerList.AnswerData mq = modelAnswerList.getData().get(i);
AnswerItem d = new AnswerItem();
ModelPicture tempPicture = null;
for(int k=0;k<mq.getProfileImage().size();k++){
List<ModelPicture> ProfileimageList = new ArrayList<>();
tempPicture = null;
tempPicture = new ModelPicture(
mq.getProfileImage().get(0).getOriginalPath() ,
mq.getProfileImage().get(0).getTh_path());
ProfileimageList.add(tempPicture); // 썸네일 이미지로 리스트 보여주기
d.setProfileList(ProfileimageList);
}
d.AnswerContent=mq.getText();
d.AnswerAccept="86%";
d.AnswerLevel="1";
d.AnswerName=mq.getNickname();
d.Answernumber=Integer.toString(mq.getAnum());
mAdapter.add(d);
}
}
@Override
public void CallResultOnemore(Boolean aBoolean) {
String message;
if( aBoolean.booleanValue() == Boolean.TRUE){
message = "답변채택완료`";
}
else{
message = "답변채택완료";
}
Toast.makeText(AnswerCheckActivity.this, message, Toast.LENGTH_SHORT).show();
finish();
}
}
| true |
22c9d76b2df0e384d0258c0cedd92821e0aeb7c4 | Java | shoxabbos/naft-android-app | /app/src/main/java/com/app/amento/worketic/Interface/Api.java | UTF-8 | 11,583 | 1.75 | 2 | [] | no_license | package uz.itmaker.naft.Interface;
import uz.itmaker.naft.Model.Category;
import uz.itmaker.naft.Model.Company.Employer;
import uz.itmaker.naft.Model.EmployerOfferProjects.Project;
import uz.itmaker.naft.Model.Latestjob.LatestJobModel;
import uz.itmaker.naft.Model.LoginResponce.RetrofitClientLogin;
import uz.itmaker.naft.Model.Provider.ProviderModel;
import uz.itmaker.naft.Model.TaxonomyListing.DurationList;
import uz.itmaker.naft.Model.TaxonomyListing.EnglishLevel;
import uz.itmaker.naft.Model.TaxonomyListing.FreelancerLevel;
import uz.itmaker.naft.Model.TaxonomyListing.Language;
import uz.itmaker.naft.Model.TaxonomyListing.Location;
import uz.itmaker.naft.Model.TaxonomyListing.NoOfEmploye;
import uz.itmaker.naft.Model.TaxonomyListing.ProjectCat;
import uz.itmaker.naft.Model.TaxonomyListing.ProjectType;
import uz.itmaker.naft.Model.TaxonomyListing.Projectlevel;
import uz.itmaker.naft.Model.TaxonomyListing.Rate;
import uz.itmaker.naft.Model.TaxonomyListing.Reason;
import uz.itmaker.naft.Model.TaxonomyListing.Skill;
import uz.itmaker.naft.Model.profileData;
import java.util.List;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.Query;
public interface Api {
String BASE_SITE = "http://naft.uz/";
String BASE_URL = BASE_SITE + "api/v1/";
@GET("list/get-categories")
Call<List<Category>> getTopCategories();
@FormUrlEncoded
@POST("user/do-login")
Call<RetrofitClientLogin> userLogin(
@Field("email") String email,
@Field("password") String password
);
@GET("listing/get-freelancers")
Call<List<ProviderModel>> getHomeFreelancer(
@Query("profile_id") String profile_id,
@Query("listing_type") String listing_type,
@Query("show_users") int show_users
);
@GET("listing/get-jobs")
Call<List<LatestJobModel>> getLatestjob(
@Query("profile_id") String profile_id,
@Query("listing_type") String listing_type,
@Query("show_users") int show_users
);
@GET("listing/get-jobs")
Call<List<LatestJobModel>> getjobbycategories(
@Query("listing_type") String listing_type,
@Query("category") String categroy
);
@GET("listing/get-jobs")
Call<List<LatestJobModel>> getCompleteLatestjob(
@Query("profile_id") String profile_id,
@Query("listing_type") String listing_type,
@Query("show_users") int show_users,
@Query("page_number") int page_number
);
@GET("listing/get-jobs")
Call<List<LatestJobModel>> getCompanyJobs(
@Query("listing_type") String listing_type,
@Query("company_id") String company_id
);
@GET("listing/get-freelancers")
Call<List<ProviderModel>> getCompleteFreelancer(
@Query("profile_id") String profile_id,
@Query("listing_type") String listing_type,
@Query("show_users") int show_users,
@Query("page_number") int page_number
);
@GET("listing/get-employers")
Call<List<Employer>> getCompanyListing(
@Query("profile_id") String profile_id,
@Query("listing_type") String listing_type,
@Query("show_users") int show_users,
@Query("page_number") int page_number
);
@GET("profile/setting")
Call<profileData> getUserProfile(@Query("id") String id );
@POST("user/do-logout")
Call<ResponseBody> logout(
@Query("user_id") String user_id
);
@GET("taxonomies/get-list")
Call<List<Rate>> getList(
@Query("list") String list
);
@GET("taxonomies/get-list")
Call<List<EnglishLevel>> getenglishlist(
@Query("list") String list
);
@GET("taxonomies/get-list")
Call<List<FreelancerLevel>> getFreelancerLevel(
@Query("list") String list
);
@GET("taxonomies/get-list")
Call<List<DurationList>> getduration(
@Query("list") String list
);
@GET("taxonomies/get-list")
Call<List<ProjectType>> getProjecttype(
@Query("list") String list
);
@GET("taxonomies/get-taxonomy")
Call<List<Language>> getlanguages(
@Query("taxonomy") String taxonomy
);
@GET("taxonomies/get-taxonomy")
Call<List<Skill>> getskill(
@Query("taxonomy") String taxonomy
);
@GET("taxonomies/get-taxonomy")
Call<List<Location>> getlocationlist(
@Query("taxonomy") String taxonomy
);
@GET("taxonomies/get-taxonomy")
Call<List<ProjectCat>> getProjectCategory(
@Query("taxonomy") String taxonomy
);
@GET("taxonomies/get-taxonomy")
Call<List<NoOfEmploye>> getnoOfemployee(
@Query("taxonomy") String taxonomy
);
@FormUrlEncoded
@POST("user/update-profile")
Call<ResponseBody> UpdateProfile(
@Query("user_id") String user_id,
@Field("first_name") String first_name,
@Field("last_name") String last_name,
@Field("user_type") String user_type,
@Field("longitude") String longitude,
@Field("latitude") String latitude,
@Field("hourly_rate") String hourly_rate,
@Field("location_id") int location_id,
@Field("employees") int employees,
@Field("counry") String country,
@Field("adress") String address,
@Field("tagline") String tagline,
@Field("gender") String gender
);
@GET("listing/get-freelancers")
Call<List<ProviderModel>> SearchFreelancer(
@Query("profile_id") String profile_id,
@Query("listing_type") String listing_type,
@Query("show_users") int show_users,
@Query("keyword") String keyword,
@Query("skills[]") String[] skills,
@Query("location[]") String[] location,
// @Query("hourly_rate") String hourly_rate,
@Query("type[]") String[] type,
@Query("english_level[]") String[] english_level,
@Query("language[]") String[] language
);
@GET("listing/get-freelancers")
Call<List<ProviderModel>> getFav_Freelancer(
@Query("profile_id") String profile_id,
@Query("listing_type") String listing_type
);
@GET("listing/get-jobs")
Call<List<LatestJobModel>> getFav_job(
@Query("profile_id") String profile_id,
@Query("listing_type") String listing_type
);
@GET("listing/get-employers")
Call<List<Employer>> getFav_company(
@Query("profile_id") String profile_id,
@Query("listing_type") String listing_type
);
@GET("listing/get-jobs")
Call<List<LatestJobModel>> SearchJob(
@Query("profile_id") String profile_id,
@Query("listing_type") String listing_type,
@Query("show_users") int show_users,
@Query("keyword") String keyword,
@Query("categories[]") String[] categories,
@Query("skills[]") String[] skills,
@Query("location[]") String[] location,
@Query("type[]") String[] type,
@Query("duration[]") String[] duration,
@Query("project_type[]") String[] project_type ,
@Query("language[]") String[] language
);
@GET("listing/get-employers")
Call<List<Employer>> SearchComapny(
@Query("profile_id") String profile_id,
@Query("listing_type") String listing_type,
@Query("show_users") int show_users,
@Query("keyword") String keyword,
@Query("location[]") String[] location,
@Query("employees[]") String[] employees
);
@POST("user/update-favourite")
Call<ResponseBody> UpdateFavourite(
@Query("id") String id,
@Query("favorite_id") int favorite_id,
@Query("type") String type
);
@Multipart
@POST("user/submit-proposal")
Call<ResponseBody> uploadMultiple(
@Query("user_id") String user_id,
@Query("project_id") String project_id,
@Part("proposed_amount") RequestBody proposed_amount,
@Part("proposed_time") RequestBody proposed_time,
@Part("proposed_content") RequestBody proposed_content,
@Part("size") RequestBody size,
@Part List<MultipartBody.Part> attachments);
@Multipart
@POST("media/upload-media")
Call<ResponseBody> uploadProfile(
@Part("id") RequestBody id,
@Part MultipartBody.Part profile_image
);
@Multipart
@POST("media/upload-media")
Call<ResponseBody> uploadbanner(
@Part("id") RequestBody id,
@Part MultipartBody.Part banner_image
);
@GET("taxonomies/get-list")
Call<List<Reason>> getReason(
@Query("list") String list
);
@FormUrlEncoded
@POST("user/reporting")
Call<ResponseBody> ReportUser(
@Query("user_id") String user_id,
@Query("id") int id,
@Field("reason") String reason,
@Field("description") String description
);
@FormUrlEncoded
@POST("user/send-offer")
Call<ResponseBody> Send_Employer_offer(
@Query("user_id") String user_id,
@Query("freelancer_id") int freelancer_id,
@Query("job_id") int job_id,
@Field("desc") String desc
);
@GET("employer-jobs")
Call<List<Project>> getoffer_project(
@Query("employer_id") String employer_id
);
@FormUrlEncoded
@POST("password/reset")
Call<ResponseBody> recoverPassword(@Field("email") String email);
@Multipart
@POST("listing/add-jobs")
Call<ResponseBody> Uploadjob(
@Query("user_id") String user_id,
@Part("title") RequestBody title,
@Part("project_level") RequestBody project_level,
@Part("project_duration") RequestBody project_duration,
@Part("freelancer_level") RequestBody freelancer_level,
@Part("english_level") RequestBody english_level,
@Part("project_cost") RequestBody project_cost,
@Part("description") RequestBody description,
@Part("country") RequestBody country,
@Part("address") RequestBody address,
@Part("longitude") RequestBody longitude,
@Part("latitude") RequestBody latitude,
@Part("is_featured") RequestBody is_featured,
@Part("show_attachments") RequestBody show_attachments,
@Query("categories[]") String[] categories,
@Query("skills[]") String[] skills,
@Query("languages[]") String[] languages,
@Part("size") RequestBody size,
@Part List<MultipartBody.Part> attachments
);
@GET("taxonomies/get-list")
Call<List<Projectlevel>> getProjectLevel(
@Query("list") String list
);
}
| true |
3044d0f322012239a3e596569886c9d47907d100 | Java | zhongxingyu/Seer | /Diff-Raw-Data/2/2_47be3ae930e63c9532c1a816704ad5bde7d71c05/FeatureTypeImporter/2_47be3ae930e63c9532c1a816704ad5bde7d71c05_FeatureTypeImporter_s.java | UTF-8 | 7,204 | 1.976563 | 2 | [] | no_license | /* Copyright (c) 2001 - 2008 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the GPL 2.0 license, available at the root
* application directory.
*/
package org.geoserver.importer;
import static org.geoserver.importer.ImportStatus.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.geoserver.catalog.Catalog;
import org.geoserver.catalog.CatalogBuilder;
import org.geoserver.catalog.DataStoreInfo;
import org.geoserver.catalog.FeatureTypeInfo;
import org.geoserver.catalog.LayerInfo;
import org.geoserver.catalog.NamespaceInfo;
import org.geoserver.catalog.ProjectionPolicy;
import org.geotools.data.DataAccess;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.util.logging.Logging;
import org.opengis.feature.type.Name;
/**
* <p>Tries to import all of the feature types in a datastore, provides the ability
* to observe the process and to stop it prematurely.</p>
* <p>It is advised to run it into its own thread</p>
*/
public class FeatureTypeImporter implements Runnable {
static final ReferencedEnvelope WORLD = new ReferencedEnvelope(-180, 180, -90, 90, DefaultGeographicCRS.WGS84);
static final Logger LOGGER = Logging.getLogger(FeatureTypeImporter.class);
DataStoreInfo storeInfo;
String defaultSRS;
Catalog catalog;
ImportSummary summary;
boolean cancelled;
Set<Name> resources;
/**
* Imports all the selected resources from the provided data store
* @param store The data store
* @param defaultSRS The default SRS to use when data have none
* @param resources The list of resources to import. Use {@code null} to import all available ones
* @param catalog The GeoServer catalog
* @param workspaceNew Marks the workspace as newly created and ready for rollback
* @param storeNew Marks the store as newly created and ready for rollback
*/
public FeatureTypeImporter(DataStoreInfo store, String defaultSRS, Set<Name> resources, Catalog catalog, boolean workspaceNew, boolean storeNew) {
this.storeInfo = store;
this.defaultSRS = defaultSRS;
this.catalog = catalog;
this.resources = resources;
this.summary = new ImportSummary(storeInfo.getName(), workspaceNew, storeNew);
}
public String getProject() {
return storeInfo.getName();
}
public void run() {
DataAccess da = null;
try {
NamespaceInfo namespace = catalog.getNamespaceByPrefix(storeInfo.getWorkspace().getName());
// prepare
CatalogBuilder builder = new CatalogBuilder(catalog);
da = storeInfo.getDataStore(null);
StyleGenerator styles = new StyleGenerator(catalog);
// cast necessary due to some classpath oddity/geoapi issue, the compiler
// complained about getNames() returning a List<Object>...
List<Name> names = new ArrayList<Name>(da.getNames());
// filter to the selected resources if necessary
if(resources != null)
names.retainAll(resources);
summary.setTotalLayers(names.size());
for (Name name : names) {
// start information
String layerName = name.getLocalPart();
summary.newLayer(layerName);
LayerInfo layer = null;
try {
builder.setStore(storeInfo);
FeatureTypeInfo featureType = builder.buildFeatureType(name);
boolean geometryless = featureType.getFeatureType().getGeometryDescriptor() == null;
if(geometryless) {
// geometryless case, fill in some random values just because we need them
featureType.setSRS("EPSG:4326");
featureType.setLatLonBoundingBox(WORLD);
} else {
builder.lookupSRS(featureType, true);
try {
builder.setupBounds(featureType);
} catch(Exception e) {
LOGGER.log(Level.FINE, "Could not compute the layer bbox", e);
}
}
layer = builder.buildLayer(featureType);
layer.setDefaultStyle(styles.getStyle(featureType));
ImportStatus status = SUCCESS;
if(cancelled)
return;
// if we have a default
if (layer.getResource().getSRS() == null && layer.getResource().getNativeCRS() != null
&& defaultSRS != null) {
layer.getResource().setSRS(defaultSRS);
layer.getResource().setProjectionPolicy(ProjectionPolicy.REPROJECT_TO_DECLARED);
status = DEFAULTED_SRS;
}
// handler common error conditions
if (catalog.getFeatureTypeByName(namespace, layerName) != null) {
status = DUPLICATE;
} else if (layer.getResource().getSRS() == null && defaultSRS == null && !geometryless) {
if(layer.getResource().getNativeCRS() == null)
status = MISSING_NATIVE_CRS;
else
status = NO_SRS_MATCH;
} else if (layer.getResource().getLatLonBoundingBox() == null) {
status = MISSING_BBOX;
} else {
// try to save the layer
catalog.add(featureType);
try {
catalog.add(layer);
} catch(Exception e) {
// will be caught by the external try/catch, here we just try to undo
// the feature type saving (transactions, where are you...)
catalog.remove(featureType);
throw e;
}
}
summary.completeLayer(layerName, layer, status);
} catch (Exception e) {
e.printStackTrace();
summary.completeLayer(layerName, layer, e);
}
if(cancelled)
return;
}
summary.end();
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Import process failed", e);
summary.end(e);
}
}
public ImportSummary getSummary() {
return summary;
}
public void cancel() {
this.cancelled = true;
}
}
| true |
8fce4f2cfccd14c87aa1e81550429cdf848c4bf5 | Java | sunwuliang/SlicingProject3.0 | /ClassModelSlicing/src/org/csu/slicing/main/SlicingMode.java | UTF-8 | 81 | 1.5625 | 2 | [] | no_license | package org.csu.slicing.main;
public enum SlicingMode {
Static, Dynamic
}
| true |
ba1382a00414d9f1df5a3a2db501c50dd8ef44e8 | Java | pangho/javageci | /javageci-docugen/src/test/java/javax0/geci/docugen/TestSnippetBuilder.java | UTF-8 | 812 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | package javax0.geci.docugen;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class TestSnippetBuilder {
@Test
@DisplayName("Test that ")
void testStringValues(){
final var sut = new SnippetBuilder("abrakadabra alma=\"Hungarian\" apple='English' manzana='Espa\\'nol'");
sut.add("first line");
sut.add("second line");
Assertions.assertEquals("abrakadabra",sut.snippetName());
final var snippet = sut.build();
Assertions.assertEquals(3,snippet.keys().size());
Assertions.assertEquals("Hungarian",snippet.param("alma"));
Assertions.assertEquals("English",snippet.param("apple"));
Assertions.assertEquals("Espa'nol",snippet.param("manzana"));
}
}
| true |
3b40dc39a50c3b1f6f9129f8fa3629423afb46f3 | Java | suknuk/DesignPatterns | /src/state/Girlfriend.java | UTF-8 | 380 | 2.984375 | 3 | [] | no_license | package state;
public class Girlfriend {
private State currentState;
public Girlfriend() {
this.currentState = new Neutral(this);
}
public void setNewState(State state) {
this.currentState = state;
}
public void talk() {
this.currentState.talk();
}
public void kiss() {
this.currentState.kiss();
}
public void annoy() {
this.currentState.annoy();
}
}
| true |
6f27d3af6ee70125ffef0ba75e8e04687bbafda9 | Java | jyccccc/addressbook | /app/src/main/java/com/jyc/addressbook/dao/Impl/MessageRecordDaoImpl.java | UTF-8 | 879 | 2.203125 | 2 | [] | no_license | package com.jyc.addressbook.dao.Impl;
import java.util.List;
import com.jyc.addressbook.dao.MessageRecordDao;
import com.jyc.addressbook.po.Contactor;
import com.jyc.addressbook.po.MessageRecord;
import org.litepal.crud.DataSupport;
public class MessageRecordDaoImpl implements MessageRecordDao {
@Override
public boolean addMessageRecord(MessageRecord messageRecord) {
return messageRecord.save();
}
@Override
public long deleteMessageRecord(MessageRecord messageRecord) {
return DataSupport.deleteAll(MessageRecord.class,
"id=?",messageRecord.getId().toString());
}
@Override
public List<MessageRecord> findRecordByContactor(Contactor contactor) {
List<MessageRecord> list = DataSupport.
where("phone=?",contactor.getPhone()).find(MessageRecord.class);
return null;
}
}
| true |
71c82d08ee8a53763331dca7d3aac250ebadb306 | Java | leeteng96/datong | /src/main/java/com/ifast/board/service/impl/BoardServiceImpl.java | UTF-8 | 2,147 | 1.984375 | 2 | [
"Apache-2.0"
] | permissive | package com.ifast.board.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ifast.board.dao.BoardDao;
import com.ifast.board.domain.BoardDO;
import com.ifast.board.service.BoardService;
import com.ifast.delivery.domain.ExpressDeliveryDO;
import com.ifast.sys.domain.RoleDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ifast.common.base.CoreServiceImpl;
import java.text.SimpleDateFormat;
import java.util.*;
/**
*
* <pre>
* 打板表
* </pre>
* <small> 2018-08-10 09:09:03 | Aron</small>
*/
@Service
public class BoardServiceImpl extends CoreServiceImpl<BoardDao, BoardDO> implements BoardService {
@Autowired
private BoardDao baseMapper;
@Override
public boolean createLadingBill(String[] boardId, String ladingBillNo) {
List list = new ArrayList();
for (int i = 0; i < boardId.length; i++) {
list.add(boardId[i]);
}
baseMapper.updateLadingBill(list,ladingBillNo);
return true;
}
@Override
public boolean insertBatch(String[] waybillNo, String boardId) {
List<String> wlist = new ArrayList<>();
List<String> strlist = new ArrayList<>();
//查询数据库waybillNo 是否与新增waybillNo重复 并剔除重复元素
for (int i = 0; i < waybillNo.length; i++) {
wlist.add(waybillNo[i]);
List<BoardDO> blist = baseMapper.selectBatchIds(wlist);
for (int j = 0; j < blist.size(); j++) {
strlist.add(blist.get(j).getWaybillNo());
}
wlist.removeAll(strlist);
}
for (int i = 0; i < wlist.size(); i++) {
baseMapper.insertBorad(wlist.get(i),boardId);
}
updateBoard(waybillNo);
return true;
}
@Override
public boolean updateBoard(String[] waybillNo) {
baseMapper.updateBoardStatus(waybillNo);
return true;
}
}
| true |
ae6874a2119c1fdcf223a582a1a2bebed92b56c8 | Java | ina3939/AcademyERP-Project | /src/main/java/com/example/demo/database/Mapper/ConsultMapper.java | UTF-8 | 335 | 1.882813 | 2 | [] | no_license | package com.example.demo.database.Mapper;
import java.util.HashMap;
import java.util.List;
import com.example.demo.database.DTO.ConsultDTO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ConsultMapper {
List<ConsultDTO> getList(HashMap<String,Object> map);
ConsultDTO getListDetail(long id);
}
| true |
d88075c10735047eff130e88cea32b379ab91436 | Java | budonglaoshi/airticket | /src/com/airticket/adapter/ServiceAdapter.java | UTF-8 | 1,490 | 2.375 | 2 | [] | no_license | package com.airticket.adapter;
//import org.dom4j.Document;
//import org.dom4j.DocumentException;
//import org.dom4j.DocumentHelper;
import org.apache.log4j.Logger;
import com.airticket.util.StaticData;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class ServiceAdapter {
public static Logger logger = Logger.getLogger(ServiceAdapter.class);
/**
* 将实体映射成xml
*
* @param obj
* @return
*/
public static String beanToXml(Object obj) {
XStream xStream = new XStream();
xStream.processAnnotations(obj.getClass());
return xStream.toXML(obj);
}
/**
* 将xml反转为实体
*
* @param xml
* @param clazz
* @return
*/
public static <T> T xmlToBean(String xml, Class<T> clazz) {
XStream xStream = new XStream(new DomDriver());
xStream.processAnnotations(clazz);
xStream.autodetectAnnotations(true);
return (T) xStream.fromXML(xml);
}
/**
* 获得响应xml主体
*
* @param xml
* @param rootName
* @return
*/
public static String getXmlBody(String xml, String rootName) {
String xmlBody = StaticData.EMPTY;
try {
String[] eles = xml.split(rootName);
xmlBody = StaticData.START_TAG + rootName + eles[1] + rootName + StaticData.END_TAG;
} catch (Exception e) {
logger.error(xmlBody+"响应数据异常!无法进行数据分割。");
e.printStackTrace();
}
return xmlBody;
}
}
| true |
ec378324b3ac401431c360ce26f106f88dffc4ab | Java | nickyhk4you/rpn-calculator | /src/test/java/com/demo/PlusMinusMultiplyDivideTest.java | UTF-8 | 1,494 | 2.6875 | 3 | [] | no_license | package com.demo;
import com.demo.lex.LexicalAnalyzer;
import com.demo.operator.RPNProcessor;
import org.junit.Test;
public class PlusMinusMultiplyDivideTest {
@Test
public void plusOperation() {
String plusInput = "5 2 +";
RPNProcessor processor = new RPNProcessor(plusInput);
try {
processor.execute();
LexicalAnalyzer.getNumberTokenStack().clear();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void minusOperation() {
String plusInput = "5 2 -";
RPNProcessor processor = new RPNProcessor(plusInput);
try {
processor.execute();
LexicalAnalyzer.getNumberTokenStack().clear();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void multiplyOperation() {
String plusInput = "5 2 *";
RPNProcessor processor = new RPNProcessor(plusInput);
try {
processor.execute();
LexicalAnalyzer.getNumberTokenStack().clear();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void divideOperation() {
String plusInput = "5 2 /";
RPNProcessor processor = new RPNProcessor(plusInput);
try {
processor.execute();
LexicalAnalyzer.getNumberTokenStack().clear();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
0118dcc968e03a28749a7aa77f40acdca9ab1569 | Java | DanilDidenko/ABSoftTest | /src/main/java/APIhandler.java | UTF-8 | 1,388 | 2.59375 | 3 | [] | no_license | package main.java;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.json.JSONObject;
public class APIhandler {
private APIhandler() {
}
private static String getJSONResponse(String url) throws UnirestException {
String response
= null;
response = Unirest.get(url)
.header("accept", "application/json")
.asString().getBody();
return response;
}
public static String getRandomCat() {
String res = null;
try {
res = new JSONObject(getJSONResponse("https://aws.random.cat/meow")).getString("file");
} catch (UnirestException e) {
e.printStackTrace();
}
return res;
}
public static String getRandomDog() {
String res = null;
try {
res = new JSONObject(getJSONResponse("https://random.dog/woof.json")).getString("url");
} catch (UnirestException e) {
e.printStackTrace();
}
return res;
}
public static String getRandomFox() {
String res = null;
try {
res = new JSONObject(getJSONResponse("https://randomfox.ca/floof/")).getString("image");
} catch (UnirestException e) {
e.printStackTrace();
}
return res;
}
}
| true |
6d7222b884a375da3cfffbbac6048b22f2b6945e | Java | XueyiGu/CS6650-DistributedSystems | /src/main/java/ccs/xueyi/mavenclient/MyClient.java | UTF-8 | 1,465 | 2.4375 | 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 ccs.xueyi.mavenclient;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
*
* @author ceres
*/
public class MyClient {
public String url;
private final Client client;
private final WebTarget webTarget;
public MyClient(String url){
this.url = url;
client = ClientBuilder.newClient();
webTarget =
// client.target("http://34.214.49.130:8080/MavenServer/").path("webapi/myresource");
client.target("http://" + url + "/MavenServer/").path("webapi/myresource");
}
public <T> T postText(Object requestEntity, Class<T> responseType) throws
ClientErrorException{
return webTarget.request(MediaType.TEXT_PLAIN)
.post(javax.ws.rs.client.Entity.entity(requestEntity,
javax.ws.rs.core.MediaType.TEXT_PLAIN),
responseType);
}
public String getStatus() throws ClientErrorException{
WebTarget resource = webTarget;
return resource.request(MediaType.TEXT_PLAIN).get(String.class);
}
}
| true |
91d3475f964c9a12615a4743a4c3120f9b828279 | Java | Terrakott/OurGroove | /src/Ventanas/Window.java | UTF-8 | 447 | 2.484375 | 2 | [] | no_license | package Ventanas;
import javax.swing.JFrame;
public class Window extends JFrame {
public static final int WIDTH=800,HEIGHT=600;
public Window(){
setTitle("OurGroove");
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new Window();
}
}
| true |
c9eddb1468094c71bf1624d7197b553522f7ef0c | Java | bkkim87/reciperoad | /Reciperoad2017_2b06/src/test/ParseIntTest.java | UTF-8 | 188 | 2.203125 | 2 | [] | no_license | package test;
public class ParseIntTest {
public static void main(String[] args) {
int groundSN=0;
groundSN=Integer.parseInt(null);
System.out.println(groundSN);
}
}
| true |
4736ff0645475b19af5db5473b9652fd1ba82b88 | Java | JetBrains/azure-tools-for-intellij | /Utils/azuretools-core/src/com/microsoft/azuretools/adauth/OAuthGrantType.java | UTF-8 | 779 | 1.84375 | 2 | [
"MIT"
] | permissive | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
package com.microsoft.azuretools.adauth;
class OAuthGrantType {
public final static String AuthorizationCode = "authorization_code";
public final static String RefreshToken = "refresh_token";
public final static String ClientCredentials = "client_credentials";
public final static String Saml11Bearer = "urn:ietf:params:oauth:grant-type:saml1_1-bearer";
public final static String Saml20Bearer = "urn:ietf:params:oauth:grant-type:saml2-bearer";
public final static String JwtBearer = "urn:ietf:params:oauth:grant-type:jwt-bearer";
public final static String Password = "password";
}
| true |
d28b80325decab695c493524cbdda66b616156d8 | Java | aksipal/Axpal | /src/main/java/com/biletdeneme/biletdeneme/service/RezervasyonService.java | UTF-8 | 1,136 | 2.125 | 2 | [] | no_license | package com.biletdeneme.biletdeneme.service;
import com.biletdeneme.biletdeneme.modal.Rezervasyon;
import com.biletdeneme.biletdeneme.repository.RezervasyonRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
@Slf4j
@Service
@Transactional
public class RezervasyonService {
@Autowired
private final RezervasyonRepository rezervasyonRepository;
public RezervasyonService(RezervasyonRepository rezervasyonRepository){this.rezervasyonRepository = rezervasyonRepository;}
public List<Rezervasyon> getAll() {
return rezervasyonRepository.findAll();
}
public Rezervasyon save(Rezervasyon rezervasyon) {
return rezervasyonRepository.save(rezervasyon);
}
public Rezervasyon update(Long rezervasyonId) {
return rezervasyonRepository.save( rezervasyonRepository.findById(rezervasyonId).get());
}
public Boolean delete(Long id) {
rezervasyonRepository.deleteById(id);
return true;
}
}
| true |
1e345d98f20274a882bc8c3df54161b1911f4c93 | Java | cszyx666/Android-NoiseReport | /app/src/main/java/com/noiselab/noisecomplain/utility/AppConfig.java | UTF-8 | 654 | 2.0625 | 2 | [] | no_license | package com.noiselab.noisecomplain.utility;
import android.content.Context;
import android.net.wifi.WifiManager;
/**
* Created by shawn on 30/3/2016.
*/
public class AppConfig {
public static final double DB_OFFSET = 4;
public static final int DB_INTERVAL = 100;
public static final String DATE_FORMAT = "yyyy-MM-dd-HH-mm-ss";
public static final String REQUEST_URL = "http://222.200.176.92:58080/ncpserver/api/complain";
public static String getMacAddress(Context context) {
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
return wm.getConnectionInfo().getMacAddress();
}
}
| true |
ac3292d7b0140f54405f9c090cffc178f76a3508 | Java | DivinerMH/Mybatisplus-ME | /common-test/src/main/java/com/menghuan/utils/ForAccessibleCycle.java | UTF-8 | 1,141 | 3.296875 | 3 | [] | no_license | package com.menghuan.utils;
import java.util.Date;
/**
* @Author:menghuan
* @Date:2019/12/26 17:15
*/
public class ForAccessibleCycle {
public static void main(String[] args) {
// 下面的for循环,只需输入100.fori按回车就可以出来
for (int i = 0; i < 100; i++) {
}
// 下面的for循环,只需输入50.fori按回车就可以出来
for (int i = 0; i < 50; i++) {
}
// 下面的for循环,只需输入2000.forr按回车就可以出来
for (int i = 2000; i > 0; i--) {
}
// new Date().sout
System.out.println(new Date());
System.out.println("usernmea is jone");//username拼写错误,单词下会出现波浪线
//按下alt+enter,出现Typo Change to...
//Intellij会给出一些建议的单词
fn1();
}
private static void fn1() {
}
void m(Object o) {
// o.nn
if (o != null) {
System.out.println("ture");
}
}
/* for (int i = 0; i < list.size(); i++) {
String item = list.get(i);
}*/
// List<T>
}
| true |
07a6d721a59098c367488dc92c54e45e0d73a8c1 | Java | yunjiChoe/zigme | /src/main/java/study/spring/zigme/service/ScheService.java | UTF-8 | 841 | 2.328125 | 2 | [] | no_license | package study.spring.zigme.service;
import java.util.List;
import study.spring.zigme.model.Scheduler;
public interface ScheService {
/**
* 캘린더의 일정을 등록한다.
* @param 일정 데이터를 담고 있는 Beans
* @return int
* @throws Exception
*/
public int addScheduler(Scheduler input) throws Exception;
/**
* 캘린더의 일정을 상세 조회한다.
* @param 일정 데이터를 담고 있는 Beans
* @return 조회된 데이터가 저장된 Beans
* @throws Exception
*/
public Scheduler getScheItem(Scheduler input) throws Exception;
public List<Scheduler> getScheList(Scheduler input) throws Exception;
public int getScheCount(Scheduler input) throws Exception;
public int deleteSche(Scheduler input) throws Exception;
public int editSche(Scheduler input) throws Exception;
}
| true |
9cc3e7ebcbca1841487f95ef7d266e7ddb687ab2 | Java | amitabhverma/jif-experimental | /jif-gui/src/main/java/edu/mbl/jif/gui/spatial/DirectionalXYController.java | UTF-8 | 808 | 2.3125 | 2 | [] | no_license | /*
* DirectionalXYController.java
*/
package edu.mbl.jif.gui.spatial;
/**
*
* @author GBH
*/
// Notes on JxInput
// NuLooq axis values range: 0 to 5000.
// Gamepad axis: 0 to 1.
public interface DirectionalXYController {
// attach AxisControllers, perhaps X & Y
public int goUp(int n);
public int goDown(int n);
public int goLeft(int n);
public int goRight(int n);
public int goCenter(int n);
public int goUpRight(int n); //pgUp
public int goDownRight(int n); //pgDn
public int goUpLeft(int n); // home
public int goDownLeft(int n); // end
public int goTop(int n);
public int goBottom(int n);
public int goLeftLimit(int n);
public int goRightLimit(int n);
// + Alt / Ctrl / Shift
}
| true |
54a2b0382839908e11b28f60935820bd035fea04 | Java | jweikai/carmanage | /src/main/java/com/ouyan/service/impl/CarInfoServiceImpl.java | UTF-8 | 381 | 1.617188 | 2 | [] | no_license | package com.ouyan.service.impl;
import org.springframework.stereotype.Service;
import com.ouyan.dao.BaseDaoImpl;
import com.ouyan.model.Caraccessinfo;
import com.ouyan.model.Deleteinfo;
import com.ouyan.service.CarInfoService;
import com.ouyan.service.DeleteInfoService;
@Service
public class CarInfoServiceImpl extends BaseDaoImpl<Caraccessinfo> implements CarInfoService{
}
| true |
b0903c3b60a0e940374f17c6f6b5825bca1ffb05 | Java | drunklurker/u_musicalstructure | /app/src/main/java/com/udacity/garyshem/musicalstructure/CurrentPlaybackActivity.java | UTF-8 | 373 | 1.929688 | 2 | [] | no_license | package com.udacity.garyshem.musicalstructure;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class CurrentPlaybackActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current_playback);
}
}
| true |
a550233611f578dd332d6b96cb809df8c1e421a8 | Java | salihaailhan/ObjectConcept | /src/com/compositepattern/UnaryExpressionNode.java | UTF-8 | 104 | 1.578125 | 2 | [] | no_license | package com.compositepattern;
public abstract class UnaryExpressionNode extends ExpressionNode {
}
| true |
1008fdfe7cd862dc2149840ea57c8b8b59e0c826 | Java | GoLangCJava/nkc-lesu | /nkangcloud/src/main/java/com/nkang/kxmoment/service/CoreService.java | UTF-8 | 24,861 | 1.828125 | 2 | [
"MIT"
] | permissive | package com.nkang.kxmoment.service;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.dom4j.Element;
import org.json.JSONArray;
import org.json.JSONObject;
import com.mongodb.DBObject;
import com.nkang.kxmoment.baseobject.ArticleMessage;
import com.nkang.kxmoment.baseobject.ClientMeta;
import com.nkang.kxmoment.baseobject.CongratulateHistory;
import com.nkang.kxmoment.baseobject.ExtendedOpportunity;
import com.nkang.kxmoment.baseobject.FaceObj;
import com.nkang.kxmoment.baseobject.GeoLocation;
import com.nkang.kxmoment.baseobject.WeChatUser;
import com.nkang.kxmoment.response.Article;
import com.nkang.kxmoment.response.NewsMessage;
import com.nkang.kxmoment.response.TextMessage;
import com.nkang.kxmoment.util.CommenJsonUtil;
import com.nkang.kxmoment.util.Constants;
import com.nkang.kxmoment.util.CronJob;
import com.nkang.kxmoment.util.FaceRecognition;
import com.nkang.kxmoment.util.MessageUtil;
import com.nkang.kxmoment.util.MongoDBBasic;
import com.nkang.kxmoment.util.RestUtils;
public class CoreService
{
private static Logger log = Logger.getLogger(CoreService.class);
private static Timer timer= new Timer();
public static String processRequest(HttpServletRequest request)
{
String respXml = null;
String respContent = "unknown request type.";
String AccessKey = MongoDBBasic.getValidAccessKey();
ClientMeta cm=MongoDBBasic.QueryClientMeta(Constants.clientCode);
String navPic = "http://leshu.bj.bcebos.com/standard/navigation.png";
try {
Element requestObject = MessageUtil.parseXml(request);
String fromUserName = requestObject.element("FromUserName").getText();
String toUserName = requestObject.element("ToUserName").getText();
String msgType = requestObject.element("MsgType").getText();
TextMessage textMessage = new TextMessage();
textMessage.setToUserName(fromUserName);
textMessage.setFromUserName(toUserName);
textMessage.setCreateTime(new Date().getTime());
textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
NewsMessage newsMessage = new NewsMessage();
newsMessage.setToUserName(fromUserName);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
List<Article> articleList = new ArrayList<Article>();
if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
String textContent = requestObject.element("Content").getText().trim();
String status="";
int realReceiver=0;
if ("cm".equals(textContent)) {
respContent = RestUtils.createMenu(AccessKey);
textMessage.setContent(respContent);
respXml = MessageUtil.textMessageToXml(textMessage);
}
else {
List<String> allUser = MongoDBBasic.getAllOpenIDByIsActivewithIsRegistered();
for(int i=0;i<allUser.size();i++){
if(fromUserName.equals(allUser.get(i))){
allUser.remove(i);
}
}
for(int i=0;i<allUser.size();i++){
status=RestUtils.sendTextMessageToUserOnlyByCustomInterface(textContent,allUser.get(i),fromUserName);
if(RestUtils.getValueFromJson(status,"errcode").equals("0")){
realReceiver++;
}
}
textMessage.setContent(realReceiver + " recevied");
respXml = MessageUtil.textMessageToXml(textMessage);
}
}
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
respContent = "LINK";
textMessage.setContent(respContent);
respXml = MessageUtil.textMessageToXml(textMessage);
}
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
respContent = "VOICE";
List<DBObject> results = MongoDBBasic.getDistinctSubjectArea("industrySegmentNames");
respContent = respContent + results.size() + "\n";
textMessage.setContent(respContent);
respXml = MessageUtil.textMessageToXml(textMessage);
}
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VIDEO)) {
respContent = "VIDEO";
textMessage.setContent(respContent);
respXml = MessageUtil.textMessageToXml(textMessage);
}
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
String eventType = requestObject.element("Event").getText();
if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
WeChatUser wcu = RestUtils.getWeChatUserInfo(AccessKey, fromUserName);
Boolean ret = false;
if(wcu.getOpenid() != "" || wcu.getOpenid() != null){
ret = MongoDBBasic.createUser(wcu);
}
articleList.clear();
Article article = new Article();
article.setTitle("【"+cm.getClientName()+"】欢迎您的到来,为了更好的为您提供服务,烦请注册。感谢一路有您");
article.setDescription("移动应用");
article.setPicUrl("https://c.ap1.content.force.com/servlet/servlet.ImageServer?id=0159000000EVjCT&oid=00D90000000pkXM");
article.setUrl("http://"+Constants.baehost+"/mdm/profile.jsp?UID=" + fromUserName);
articleList.add(article);
Article article4 = new Article();
article4.setTitle("在此注册");
article4.setDescription("在此注册");
article4.setPicUrl("https://c.ap1.content.force.com/servlet/servlet.ImageServer?id=0159000000EVjDC&oid=00D90000000pkXM");
article4.setUrl("http://"+Constants.baehost+"/mdm/profile.jsp?UID=" + fromUserName);
articleList.add(article4);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
respXml = MessageUtil.newsMessageToXml(newsMessage);
if(!ret){
respContent = "User Initialization Failed:\n";
textMessage.setContent(respContent);
respXml = MessageUtil.textMessageToXml(textMessage);
}
} else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
// Inactive the User - To-Be-Done
MongoDBBasic.removeUser(fromUserName);
} else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
String eventKey = requestObject.element("EventKey").getText();
if(eventKey.equals("MDLAKE")){ // Data Lake
articleList.clear();
Article article = new Article();
article.setTitle("欢迎参与乐数试听课程");
article.setDescription("欢迎参与乐数试听课程");
article.setPicUrl("http://leshu.bj.bcebos.com/standard/reservationBigPic.jpg");
article.setUrl("http://nkctech.duapp.com/at/yy/yy.jsp");
articleList.add(article);
Article article4 = new Article();
article4.setTitle("预约试听");
article4.setDescription("预约试听");
article4.setPicUrl("http://leshu.bj.bcebos.com/icon/ReservationICON.png");
article4.setUrl("http://nkctech.duapp.com/at/yy/yy.jsp");
articleList.add(article4);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
respXml = MessageUtil.newsMessageToXml(newsMessage);
}
else if(eventKey.equals("MYAPPS")){
articleList.clear();
Article article = new Article();
article.setTitle(cm.getClientName()+"|移动应用");
article.setDescription("移动应用");
article.setPicUrl("http://leshu.bj.bcebos.com/icon/myapplication.jpg");
article.setUrl("http://"+Constants.baehost+"/mdm/DQNavigate.jsp?UID=" + fromUserName);
articleList.add(article);
Article article2 = new Article();
article2.setTitle("乐数应用");
article2.setDescription("My Personal Applications");
article2.setPicUrl("http://leshu.bj.bcebos.com/icon/weiapp.png");
article2.setUrl("http://"+Constants.baehost+"/mdm/profile.jsp?UID=" + fromUserName);
articleList.add(article2);
String hardcodeUID = "oI3krwR_gGNsz38r1bdB1_SkcoNw";
String hardcodeUID2 = "oI3krwbSD3toGOnt_bhuhXQ0TVyo";
if(hardcodeUID2.equalsIgnoreCase(fromUserName)||hardcodeUID.equalsIgnoreCase(fromUserName)||MongoDBBasic.checkUserAuth(fromUserName, "isAdmin")){
Article article3 = new Article();
article3.setTitle("乐数管理");
article3.setDescription("Administration");
article3.setPicUrl("http://leshu.bj.bcebos.com/icon/weiadmin.png");
article3.setUrl("http://"+Constants.baehost+"/admin/index.jsp?UID=" + fromUserName);
articleList.add(article3);
}
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
respXml = MessageUtil.newsMessageToXml(newsMessage);
}
else if(eventKey.equals("MYRECOG")){
articleList.clear();
Article article = new Article();
article.setTitle("My Lasted Recognitions");
article.setDescription("My Lasted Recognition");
article.setPicUrl("http://"+Constants.baehost+"/MetroStyleFiles/RecognitionImage.jpg");
article.setUrl("http://"+Constants.baehost+"/mdm/DQNavigate.jsp?UID=" + fromUserName);
articleList.add(article);
// add article here
List<CongratulateHistory> myrecoghistList = MongoDBBasic.getRecognitionInfoByOpenID(fromUserName, "");
int myRecog = myrecoghistList.size();
if(myRecog > 6){
myRecog = 6;
}
Article myarticle;
CongratulateHistory congratulateHistory;
String icoURLPartnerFirst = "https://c.ap1.content.force.com/servlet/servlet.ImageServer?id=0159000000DkaRc&oid=00D90000000pkXM";
String icoURLBaisForAction = "https://c.ap1.content.force.com/servlet/servlet.ImageServer?id=0159000000DkaS6&oid=00D90000000pkXM";
String icoURLInnovator = "https://c.ap1.content.force.com/servlet/servlet.ImageServer?id=0159000000DkaSa&oid=00D90000000pkXM";
String icoURL = "http://"+Constants.baehost+"/MetroStyleFiles/RecognitionImage.jpg";
for(int i = myRecog; i >= 1; i--){
myarticle = new Article();
congratulateHistory = new CongratulateHistory();
congratulateHistory = myrecoghistList.get(i-1);
String type = congratulateHistory.getType();
String comments = congratulateHistory.getComments();
if(StringUtils.isEmpty(comments)){
comments = "You must done something amazaing";
}
else if(comments.length() >= 30){
comments = comments.trim();
comments = comments.substring(0, 30) + "...";
}
myarticle.setTitle(congratulateHistory.getComments() +"\n" + congratulateHistory.getCongratulateDate() + " | " + congratulateHistory.getFrom() + "\n" + type);
myarticle.setDescription("My Recognition");
if(type.equalsIgnoreCase("Bais For Action")){
icoURL = icoURLBaisForAction;
}
else if(type.equalsIgnoreCase("Innovators at Heart")){
icoURL = icoURLInnovator;
}
else{
icoURL = icoURLPartnerFirst;
}
myarticle.setPicUrl(icoURL);
myarticle.setUrl("http://"+Constants.baehost+"/mdm/RecognitionCenter.jsp?uid=" + fromUserName + "&num="+i);
articleList.add(myarticle);
}
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
respXml = MessageUtil.newsMessageToXml(newsMessage);
}
else if (eventKey.equals("nbcolleague")) {
GeoLocation geol = MongoDBBasic.getDBUserGeoInfo(fromUserName);
String lat = geol.getLAT();
String lng = geol.getLNG();
String addr = geol.getFAddr();
Article article = new Article();
Random rand = new Random();
int randNum = rand.nextInt(30);
article.setTitle("点击扫描您附近的同学");
article.setDescription("您当前所在位置:" + addr);
article.setPicUrl("https://c.ap1.content.force.com/servlet/servlet.ImageServer?id=0159000000E9rIB&oid=00D90000000pkXM");
article.setUrl("http://"+Constants.baehost+"/mdm/scan/scan.jsp?UID=" + fromUserName+"&num="+randNum);
articleList.add(article);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
respXml = MessageUtil.newsMessageToXml(newsMessage);
}else if (eventKey.equals("myPoints")) {//使劲戳我
Article article = new Article();
Random rand = new Random();
int randNum = rand.nextInt(30);
article.setTitle("点击开启你的幸运旅程-每日抽奖");
article.setPicUrl("https://c.ap1.content.force.com/servlet/servlet.ImageServer?id=0159000000E9rIB&oid=00D90000000pkXM");
//article.setUrl("http://"+Constants.baehost+"/mdm/scan/scan.jsp?UID=" + fromUserName+"&num="+randNum);
article.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+Constants.APP_ID+"&redirect_uri=http%3A%2F%2F"+Constants.baehost+"%2Fmdm%2FLucky.jsp&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
articleList.add(article);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
respXml = MessageUtil.newsMessageToXml(newsMessage);
/*HashMap<String, String> user = MongoDBBasic.getWeChatUserFromOpenID(fromUserName);
String respContent1 = "";
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateNowStr = sdf.format(d);
if(MongoDBBasic.checkUserPoint(fromUserName)){
java.util.Random random=new java.util.Random();// 定义随机类
int randomNum=random.nextInt(5)+1;// 返回[0,10)集合中的整数,注意不包括10
int pointSum=MongoDBBasic.updateUserPoint(fromUserName, randomNum);
respContent1 = "* * * * * * * * * * * * * * * * *\n"
+"* 欢迎您:"+user.get("NickName")+"\n"
+"* 今日积分:"+randomNum+"\n"
+"* 当前积分:"+pointSum+"\n"
+"*\n"
+"* =^_^=\n"
+"* 好感动,您今天又来了\n"
+"* 今日积分已入账,记得\n"
+"* 每天都来看我哦!\n";
}else{
int pointSum=MongoDBBasic.updateUserPoint(fromUserName, 0);
respContent1 = "* * * * * * * * * * * * * * * * *\n"
+"* 欢迎您:"+user.get("NickName")+"\n"
+"* 当前积分:"+pointSum+"\n"
+"* 时间:"+dateNowStr+"\n"
+"*\n"
+"* =^_^=\n"
+"* 好感动,您今天又来了\n"
+"* 但每天只有一次获取积\n"
+"* 分的机会哦!!\n";
}
respContent1=respContent1
+"* * * * * * * * * * * * * * * * *\n"
+"* 【温馨提示: 希望您能\n"
+"* 天天这里点一点逛一\n"
+"* 逛,这样才能收到我们\n"
+"* 高价值的消息推送,以\n"
+"* 便于我们为您提供更\n"
+"* 好的服务】\n"
+"* * * * * * * * * * * * * * * * *";
textMessage.setContent(respContent1);
respXml = MessageUtil.textMessageToXml(textMessage);*/
}else if (eventKey.equals("mysubscription")) {//我的订阅
Article article = new Article();
Random rand = new Random();
int randNum = rand.nextInt(30);
article.setTitle(cm.getClientName()+"| 点击查看我的课程订阅");
article.setDescription("乐数在线考试练习系统");
article.setPicUrl("https://c.ap1.content.force.com/servlet/servlet.ImageServer?id=0159000000E9mnn&oid=00D90000000pkXM");
// article.setUrl("http://"+Constants.baehost+"/mdm/RoleOfAreaMap.jsp?UID=" + fromUserName+"&num="+randNum);
article.setUrl("http://"+Constants.baehost+"/at/test.jsp?UID=" + fromUserName+"&num="+randNum);
articleList.add(article);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
respXml = MessageUtil.newsMessageToXml(newsMessage);
}
else if (eventKey.equals("opsmetric")) {//我的订阅
articleList.clear();
Article article = new Article();
article.setTitle(cm.getClientName()+"|乐数风采");
article.setDescription("您可查看实时更新的产品运维报表");
article.setPicUrl("http://leshu.bj.bcebos.com/standard/leshuslide2.JPG");
article.setUrl("http://leshu.bj.bcebos.com/standard/leshuslide2.JPG");
articleList.add(article);
Article article1 = new Article();
article1.setTitle("学员风采");
article1.setDescription("IM统计情况");
article1.setPicUrl("http://leshu.bj.bcebos.com/icon/student.png");
article1.setUrl("http://wxe542e71449270554.dodoca.com/164368/phonewebsitet/websitet?uid=164368&openid=FANS_ID&id=99846#mp.weixin.qq.com");
articleList.add(article1);
Article article2 = new Article();
article2.setTitle("师资风采");
article2.setDescription("生产环境智能监控");
article2.setPicUrl("http://leshu.bj.bcebos.com/icon/Teacher.png");
article2.setUrl("http://wxe542e71449270554.dodoca.com/164368/phonewebsitet/websitet?uid=164368&openid=FANS_ID&id=99846#mp.weixin.qq.com");
articleList.add(article2);
Article article3 = new Article();
article3.setTitle("家园共育");
article3.setDescription("家园共育");
article3.setPicUrl("http://leshu.bj.bcebos.com/icon/parenteacher.png");
article3.setUrl("http://mp.weixin.qq.com/s/EwgxfqfuzIuQgPss7jdNtQ");
articleList.add(article3);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
respXml = MessageUtil.newsMessageToXml(newsMessage);
}
else if (eventKey.equals("sitenavigator")){
articleList.clear();
Article article = new Article();
article.setTitle("乐数为您导航");
article.setDescription("乐数为您导航");
article.setPicUrl("http://leshu.bj.bcebos.com/standard/carnavigation.JPG");
article.setUrl("http://m.amap.com/search/view/keywords=%E5%8D%97%E5%9D%AA%E4%B8%87%E8%BE%BE%E5%B9%BF%E5%9C%BA2%E5%8F%B7%E5%86%99%E5%AD%97%E6%A5%BC11-6%20"); //http://map.baidu.com/mobile
articleList.add(article);
Article articlenav1 = new Article();
articlenav1.setTitle("南坪校区[TEL:023-62387134]\n南坪万达广场2号写字楼11-6"); //九龙坡区铁路村198号
articlenav1.setDescription("南坪校区[TEL:023-62387134]");
articlenav1.setPicUrl(navPic);
articlenav1.setUrl("http://m.amap.com/search/view/keywords=%E5%8D%97%E5%9D%AA%E4%B8%87%E8%BE%BE%E5%B9%BF%E5%9C%BA2%E5%8F%B7%E5%86%99%E5%AD%97%E6%A5%BC11-6%20");
articleList.add(articlenav1);
Article articlenav2 = new Article();
articlenav2.setTitle("江北观音桥校区[TEL:023-67616306]\n观音桥中信大厦25-10"); //港城工业园区C区
articlenav2.setDescription("江北校区[TEL:023-67616306]");
articlenav2.setPicUrl(navPic);
articlenav2.setUrl("http://m.amap.com/search/view/keywords=%E8%A7%82%E9%9F%B3%E6%A1%A5%E4%B8%AD%E4%BF%A1%E5%A4%A7%E5%8E%A625-10");
articleList.add(articlenav2);
Article articlenav4 = new Article();
articlenav4.setTitle("李家沱校区[TEL:023-67505761]\n李家沱都和广场A栋30-5"); //重庆沙坪坝区土主镇西部物流园区中石油仓储中心
articlenav4.setDescription("李家沱校区[TEL:023-67505761]");
articlenav4.setPicUrl(navPic);
articlenav4.setUrl("http://m.amap.com/search/view/keywords=%E6%9D%8E%E5%AE%B6%E6%B2%B1%E9%83%BD%E5%92%8C%E5%B9%BF%E5%9C%BAA%E6%A0%8B30-5");
articleList.add(articlenav4);
Article articlenav3 = new Article();
articlenav3.setTitle("杨家坪校区[TEL:13372680273]\n杨家坪步行街金州大厦16楼");
articlenav3.setDescription("杨家坪校区[TEL:13372680273]");
articlenav3.setPicUrl(navPic);
articlenav3.setUrl("http://m.amap.com/search/view/keywords=%E6%9D%A8%E5%AE%B6%E5%9D%AA%E6%AD%A5%E8%A1%8C%E8%A1%97%E9%87%91%E5%B7%9E%E5%A4%A7%E5%8E%A616%E6%A5%BC");
articleList.add(articlenav3);
Article articlenav6 = new Article();
articlenav6.setTitle("江北区青少年宫[TEL:13372680273]\n江北区青少年宫(石子山公园内)");
articlenav6.setDescription("石子山公园内");
articlenav6.setPicUrl(navPic);
articlenav6.setUrl("http://m.amap.com/search/mapview/keywords=%E7%9F%B3%E5%AD%90%E5%B1%B1%E4%BD%93%E8%82%B2%E5%85%AC%E5%9B%AD%E7%AF%AE%E7%90%83%E5%9C%BA&city=500105&poiid=B0FFH0QH92");
articleList.add(articlenav6);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
respXml = MessageUtil.newsMessageToXml(newsMessage);
}
else if (eventKey.equals("nboppt")) {// Partner
Article article = new Article();
article.setTitle(cm.getClientName()+"| 更多精彩尽乐数动态 ");
article.setDescription("更多精彩尽乐数动态 ");
article.setPicUrl("http://leshu.bj.bcebos.com/standard/leshuslide4.JPG");
article.setUrl("http://"+Constants.baehost+"/mdm/MesPushHistory.jsp?UID="+fromUserName);
articleList.add(article);
List<ArticleMessage> ams=MongoDBBasic.getArticleMessageByNum("");
int size=3;
if(ams.size()<3){
size=ams.size();
}
for(int i = 0; i < size ; i++){
Article articlevar = new Article();
articlevar.setTitle(ams.get(i).getTitle()+"\n"+ams.get(i).getTime());
articlevar.setDescription("");
if(ams.get(i).getPicture()!=null&&ams.get(i).getPicture()!=""){
articlevar.setPicUrl(ams.get(i).getPicture());
}
else{
articlevar.setPicUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1490602667276&di=5ff160cb3a889645ffaf2ba17b4f2071&imgtype=0&src=http%3A%2F%2Fpic.58pic.com%2F58pic%2F15%2F65%2F94%2F64B58PICiVp_1024.jpg");
}
articlevar.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+Constants.APP_ID+"&redirect_uri=http%3A%2F%2F"+Constants.baehost+"%2Fmdm%2FNotificationCenter.jsp?num="+ams.get(i).getNum()+"&response_type=code&scope=snsapi_userinfo&state="+fromUserName+"#wechat_redirect");
System.out.println("url======="+"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+Constants.APP_ID+"&redirect_uri=http%3A%2F%2F"+Constants.baehost+"%2Fmdm%2FNotificationCenter.jsp?num="+ams.get(i).getNum()+"&response_type=code&scope=snsapi_userinfo&state="+fromUserName+"#wechat_redirect");
articleList.add(articlevar);
}
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
respXml = MessageUtil.newsMessageToXml(newsMessage);
}
} else if (eventType.equals(MessageUtil.EVENT_TYPE_SCAN_TEXT)) {
String eventKey = requestObject.element("EventKey").getText();
if (eventKey.equals("C1")) {
respContent = requestObject.element("ScanCodeInfo").element("ScanResult").getText();
textMessage.setContent(respContent);
respXml = MessageUtil.textMessageToXml(textMessage);
}
} else if (eventType.equals(MessageUtil.EVENT_TYPE_SCAN_URL)) {
respContent = "scan url and redirect.";
textMessage.setContent(respContent);
respXml = MessageUtil.textMessageToXml(textMessage);
} else if (eventType.equals(MessageUtil.EVENT_TYPE_SCAN)) {
respContent = "scan qrcode.";
textMessage.setContent(respContent);
respXml = MessageUtil.textMessageToXml(textMessage);
} else if (eventType.equals(MessageUtil.EVENT_TYPE_LOCATION)) {
respContent = "upload location detail.";
textMessage.setContent(respContent);
WeChatUser wcu = RestUtils.getWeChatUserInfo(AccessKey, fromUserName);
MongoDBBasic.updateUser(fromUserName, requestObject.element("Latitude").getText(), requestObject.element("Longitude").getText(),wcu);
} else if (eventType.equals(MessageUtil.EVENT_TYPE_VIEW)) {
respContent = "page redirect.";
textMessage.setContent(respContent);
respXml = MessageUtil.textMessageToXml(textMessage);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return respXml;
}
}
| true |
cf3e90bb078cfe39fabc1522e5bc94d76649869f | Java | PlayWithAI101/WebNote | /0806/app4(쇼핑몰 완성. 선생님파일)/src/main/java/com/example/app2/model/product/Product.java | UTF-8 | 2,063 | 2.453125 | 2 | [] | no_license | package com.example.app2.model.product;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import com.example.app2.model.join.Shop_Member;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "product_sequence")
@SequenceGenerator(name = "product_sequence", sequenceName = "seq_product")
private Integer num;
private String name;
private Integer price;
private Integer amount;
private String info;
private String img;
@ManyToOne
@JoinColumn(name = "seller", nullable=false)
private Shop_Member seller;
public Product(){}
public Product(Integer num, String name, Integer price, Integer amount, String info, String img,
Shop_Member seller) {
super();
this.num = num;
this.name = name;
this.price = price;
this.amount = amount;
this.info = info;
this.img = img;
this.seller = seller;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public Shop_Member getSeller() {
return seller;
}
public void setSeller(Shop_Member seller) {
this.seller = seller;
}
@Override
public String toString() {
return "Product [num=" + num + ", name=" + name + ", price=" + price + ", amount=" + amount + ", info=" + info
+ ", img=" + img + ", seller=" + seller + "]";
}
}
| true |
4c382b7c80c720e9ddf7a6165120f9c40dce7264 | Java | Jonjic/GeolocationAPI | /demo/src/main/java/com/example/demo/action/Action.java | UTF-8 | 3,055 | 2.359375 | 2 | [] | no_license | package com.example.demo.action;
import com.example.demo.bus.Bus;
import com.example.demo.user.User;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
public class Action {
@Id
@SequenceGenerator(
name = "action_sequence_generator",
sequenceName = "action_sequence",
allocationSize = 1
)
@GeneratedValue(
strategy = GenerationType.IDENTITY,
generator = "action_sequence"
)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "bus_id")
private Bus bus;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
private double latitude;
private double longitude;
private LocalDateTime timestamp;
@Column(columnDefinition = "boolean default true")
private boolean entrance = true;
public Action()
{
}
public Action(Double latitude, Double longitude) {
this.latitude = latitude;
this.longitude = longitude;
this.timestamp = LocalDateTime.now();
}
public Action(Double latitude, Double longitude, boolean entrance) {
this.latitude = latitude;
this.longitude = longitude;
this.timestamp = LocalDateTime.now();
this.entrance = entrance;
}
public Action(Double latitude, Double longitude, LocalDateTime timestamp, boolean entrance) {
this.latitude = latitude;
this.longitude = longitude;
this.timestamp = timestamp;
this.entrance = entrance;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(float latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(LocalDateTime timestamp) {
this.timestamp = timestamp;
}
public boolean isEntrance() {
return entrance;
}
public void setEntrance(boolean entrance) {
this.entrance = entrance;
}
public Bus getBus() {
return bus;
}
public void setBus(Bus bus) {
this.bus = bus;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Action{" +
"id=" + id +
", latitude=" + latitude +
", longitude=" + longitude +
", timestamp=" + timestamp +
", entrance=" + entrance +
", bus=" + bus +
", user=" + user +
'}';
}
}
| true |
f2c742e782e1b09ab85e35512c83fe005ca305b9 | Java | lamichhaneBabita/BankProject | /src/com/vastika/bankproject/impl/AccountDaoImpl.java | UTF-8 | 848 | 2.5625 | 3 | [] | no_license | package com.vastika.bankproject.impl;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.vastika.bankproject.dao.AccountDao;
import com.vastika.bankproject.dbutil.*;
import com.vastika.bankproject.model.Account;
public class AccountDaoImpl implements AccountDao {
public static final String INSERT_SQL = "insert into account_info_tbl(account_name, address, mobile_no) values(?,?,?)";
@Override
public int openAccount(Account account) {
int saved =0;
try (PreparedStatement ps = DBUtil.getConnection().prepareStatement(INSERT_SQL)) {
ps.setString(1, account.getAccount_name());
ps.setString(2, account.getAddress());
ps.setInt(3, account.getMobile_no());
saved = ps.executeUpdate();
System.out.println("Data Inserted");
} catch (SQLException e) {
e.printStackTrace();
}
return saved;
}
} | true |
440545fff350eb9863309480053244f329ea6be8 | Java | ChanguBadshsh/MyIMS | /app/src/com/smart/webservice/SmartWebManager.java | UTF-8 | 33,149 | 1.804688 | 2 | [] | no_license | package com.smart.webservice;
import android.content.Context;
import android.support.design.widget.Snackbar;
import android.text.TextUtils;
import android.util.Log;
import com.volley.DefaultRetryPolicy;
import com.volley.RequestQueue;
import com.volley.Response;
import com.volley.VolleyError;
import com.volley.toolbox.Volley;
import com.smart.framework.Constants;
import com.smart.framework.SmartApplication;
import com.smart.framework.SmartUtils;
import org.json.JSONObject;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class SmartWebManager implements Constants {
private static final int TIMEOUT = 100000;
public enum REQUEST_METHOD_PARAMS {
CONTEXT, PARAMS, REQUEST_TYPES, TAG, URL, TABLE_NAME,
UN_NORMALIZED_FIELDS, RESPONSE_LISTENER, SHOW_SNACKBAR
}
;
public enum REQUEST_TYPE {JSON_OBJECT, JSON_ARRAY, IMAGE}
;
private static SmartWebManager mInstance;
private RequestQueue mRequestQueue;
private static Context mCtx;
private SmartWebManager(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
}
public static synchronized SmartWebManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SmartWebManager(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueueMultipart(final HashMap<REQUEST_METHOD_PARAMS, Object> requestParams, final String filePath,
final String message, final boolean isShowSnackbar) {
MultipartRequestMedia jsObjRequest = null;
JSONObject jsonRequest = ((JSONObject) requestParams.get(REQUEST_METHOD_PARAMS.PARAMS));
Log.v("@@@WsParams", jsonRequest.toString());
//appendLog("@@@WsParams::::::" + jsonRequest.toString());
if (requestParams.get(REQUEST_METHOD_PARAMS.REQUEST_TYPES) == REQUEST_TYPE.JSON_OBJECT) {
jsObjRequest = new MultipartRequestMedia((String) requestParams.get(REQUEST_METHOD_PARAMS.URL), jsonRequest, filePath, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.v("@@@@@WSResponse", response.toString());
//appendLog("@@@WSResponse::::::" + response.toString());
if (SmartUtils.isSessionExpire(response)) {
SmartUtils.removeCookie();
final HashMap<REQUEST_METHOD_PARAMS, Object> requestParamsForSession = new HashMap<>();
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.CONTEXT, requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.REQUEST_TYPES, SmartWebManager.REQUEST_TYPE.JSON_OBJECT);
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.TAG, Constants.WEB_AUTOLOGIN);
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.URL, SmartApplication.REF_SMART_APPLICATION.DOMAIN_NAME);
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.PARAMS, SmartUtils.getLoginParams());
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.RESPONSE_LISTENER, new SmartWebManager.OnResponseReceivedListener() {
@Override
public void onResponseReceived(final JSONObject response, boolean isValidResponse, int responseCode) {
if (responseCode == 200) {
addToRequestQueueMultipart(requestParams, filePath, message, isShowSnackbar);
} else {
//redirect to login page
SmartApplication.REF_SMART_APPLICATION.writeSharedPreferences(SP_ISLOGIN, true);
SmartApplication.REF_SMART_APPLICATION.writeSharedPreferences(SP_LOGIN_REQ_OBJECT, null);
// Intent loginIntent = new Intent((Activity) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT),
// IjoomerLoginActivity.class);
// SmartUtils.clearActivityStack((Activity) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT),
// loginIntent);
}
}
@Override
public void onResponseError() {
}
});
Log.v("@@@WsSessionParams", requestParamsForSession.toString());
SmartWebManager.getInstance((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT)).
addToRequestQueueMultipart(requestParamsForSession, null, filePath, false);
} else {
if (SmartUtils.getResponseCode(response) == 200) {
String errorMessage = SmartUtils.validateResponse((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), response, message);
SmartUtils.hideSoftKeyboard((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
if (isShowSnackbar && !TextUtils.isEmpty(errorMessage)) {
SmartUtils.showSnackBar((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), errorMessage, Snackbar.LENGTH_LONG);
}
((OnResponseReceivedListener) requestParams.get(REQUEST_METHOD_PARAMS.RESPONSE_LISTENER)).onResponseReceived(response, true, 200);
} else {
int responseCode = SmartUtils.getResponseCode(response);
String errorMessage = SmartUtils.validateResponse((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), response, message);
SmartUtils.hideSoftKeyboard((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
if (isShowSnackbar && !TextUtils.isEmpty(errorMessage)) {
SmartUtils.showSnackBar((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), errorMessage, Snackbar.LENGTH_LONG);
}
((OnResponseReceivedListener) requestParams.get(REQUEST_METHOD_PARAMS.RESPONSE_LISTENER)).onResponseReceived(response, false, responseCode);
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.v("@@@@@WSResponse", error.toString());
//appendLog("@@@WSResponse::::::" + error.toString());
SmartUtils.hideSoftKeyboard((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
String errorMessage = VolleyErrorHelper.getMessage(error, (Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
SmartUtils.showSnackBar((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), errorMessage, Snackbar.LENGTH_INDEFINITE);
((OnResponseReceivedListener) requestParams.get(REQUEST_METHOD_PARAMS.RESPONSE_LISTENER)).onResponseError();
}
});
}
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
TIMEOUT,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
jsObjRequest.setTag(requestParams.get(REQUEST_METHOD_PARAMS.TAG));
getRequestQueue().add(jsObjRequest);
}
public <T> void addToRequestQueueMultipartUpload(final HashMap<REQUEST_METHOD_PARAMS, Object> requestParams, final String[] filePath,
final String message, final boolean isShowSnackBar) {
MultipartRequestMedia jsObjRequest = null;
JSONObject jsonRequest = ((JSONObject) requestParams.get(REQUEST_METHOD_PARAMS.PARAMS));
Log.v("@@@WsParams", jsonRequest.toString());
//appendLog("@@@@@WsParams:::" + jsonRequest.toString());
if (requestParams.get(REQUEST_METHOD_PARAMS.REQUEST_TYPES) == REQUEST_TYPE.JSON_OBJECT) {
jsObjRequest = new MultipartRequestMedia((String) requestParams.get(REQUEST_METHOD_PARAMS.URL), jsonRequest, filePath, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.v("@@@@@WSResponse", response.toString());
//appendLog("@@@@@WSResponse:::" + response.toString());
if (SmartUtils.isSessionExpire(response)) {
SmartUtils.removeCookie();
final HashMap<REQUEST_METHOD_PARAMS, Object> requestParamsForSession = new HashMap<>();
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.CONTEXT, requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.REQUEST_TYPES, SmartWebManager.REQUEST_TYPE.JSON_OBJECT);
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.TAG, Constants.WEB_AUTOLOGIN);
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.URL, SmartApplication.REF_SMART_APPLICATION.DOMAIN_NAME);
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.PARAMS, SmartUtils.getLoginParams());
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.RESPONSE_LISTENER, new SmartWebManager.OnResponseReceivedListener() {
@Override
public void onResponseReceived(final JSONObject response, boolean isValidResponse, int responseCode) {
if (responseCode == 200) {
addToRequestQueueMultipartUpload(requestParams, filePath, message, isShowSnackBar);
}
}
@Override
public void onResponseError() {
}
});
SmartWebManager.getInstance((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT)).
addToRequestQueueMultipartUpload(requestParamsForSession, null, "", isShowSnackBar);
} else {
if (SmartUtils.getResponseCode(response) == 200) {
String errorMessage = SmartUtils.validateResponse((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), response, message);
SmartUtils.hideSoftKeyboard((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
if (isShowSnackBar && !TextUtils.isEmpty(errorMessage)) {
SmartUtils.showSnackBar((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), errorMessage, Snackbar.LENGTH_LONG);
}
((OnResponseReceivedListener) requestParams.get(REQUEST_METHOD_PARAMS.RESPONSE_LISTENER)).onResponseReceived(response, true, 200);
} else {
int responseCode = SmartUtils.getResponseCode(response);
String errorMessage = SmartUtils.validateResponse((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), response, message);
SmartUtils.hideSoftKeyboard((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
if (isShowSnackBar && !TextUtils.isEmpty(errorMessage)) {
SmartUtils.showSnackBar((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), errorMessage, Snackbar.LENGTH_LONG);
}
((OnResponseReceivedListener) requestParams.get(REQUEST_METHOD_PARAMS.RESPONSE_LISTENER)).onResponseReceived(response, false, responseCode);
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//appendLog("@@@@@WSResponse:::" + error.toString());
SmartUtils.hideSoftKeyboard((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
String errorMessage = VolleyErrorHelper.getMessage(error, (Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
SmartUtils.showSnackBar((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), errorMessage, Snackbar.LENGTH_INDEFINITE);
((OnResponseReceivedListener) requestParams.get(REQUEST_METHOD_PARAMS.RESPONSE_LISTENER)).onResponseError();
}
});
}
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
TIMEOUT,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
jsObjRequest.setTag(requestParams.get(REQUEST_METHOD_PARAMS.TAG));
getRequestQueue().add(jsObjRequest);
}
public <T> void addToRequestQueueMultipartFile(final HashMap<REQUEST_METHOD_PARAMS, Object> requestParams, final String filePath,
final String message, final boolean isShowSnackbar) {
MultipartRequestFile jsObjRequest = null;
JSONObject jsonRequest = ((JSONObject) requestParams.get(REQUEST_METHOD_PARAMS.PARAMS));
Log.v("@@@WsParams", jsonRequest.toString());
//appendLog("@@@WsParams::::::" + jsonRequest.toString());
if (requestParams.get(REQUEST_METHOD_PARAMS.REQUEST_TYPES) == REQUEST_TYPE.JSON_OBJECT) {
jsObjRequest = new MultipartRequestFile((String) requestParams.get(REQUEST_METHOD_PARAMS.URL), jsonRequest, filePath, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.v("@@@@@WSResponse", response.toString());
//appendLog("@@@WSResponse::::::" + response.toString());
if (SmartUtils.isSessionExpire(response)) {
SmartUtils.removeCookie();
final HashMap<REQUEST_METHOD_PARAMS, Object> requestParamsForSession = new HashMap<>();
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.CONTEXT, requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.REQUEST_TYPES, SmartWebManager.REQUEST_TYPE.JSON_OBJECT);
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.TAG, Constants.WEB_AUTOLOGIN);
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.URL, SmartApplication.REF_SMART_APPLICATION.DOMAIN_NAME);
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.PARAMS, SmartUtils.getLoginParams());
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.RESPONSE_LISTENER, new SmartWebManager.OnResponseReceivedListener() {
@Override
public void onResponseReceived(final JSONObject response, boolean isValidResponse, int responseCode) {
if (responseCode == 200) {
addToRequestQueueMultipartFile(requestParams, filePath, message, isShowSnackbar);
} else {
//redirect to login page
SmartApplication.REF_SMART_APPLICATION.writeSharedPreferences(SP_ISLOGIN, true);
SmartApplication.REF_SMART_APPLICATION.writeSharedPreferences(SP_LOGIN_REQ_OBJECT, null);
// Intent loginIntent = new Intent((Activity) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT),
// IjoomerLoginActivity.class);
// SmartUtils.clearActivityStack((Activity) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT),
// loginIntent);
}
}
@Override
public void onResponseError() {
}
});
Log.v("@@@WsSessionParams", requestParamsForSession.toString());
SmartWebManager.getInstance((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT)).
addToRequestQueueMultipartFile(requestParamsForSession, null, filePath, false);
} else {
if (SmartUtils.getResponseCode(response) == 200) {
String errorMessage = SmartUtils.validateResponse((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), response, message);
SmartUtils.hideSoftKeyboard((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
if (isShowSnackbar && !TextUtils.isEmpty(errorMessage)) {
SmartUtils.showSnackBar((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), errorMessage, Snackbar.LENGTH_LONG);
}
((OnResponseReceivedListener) requestParams.get(REQUEST_METHOD_PARAMS.RESPONSE_LISTENER)).onResponseReceived(response, true, 200);
} else {
int responseCode = SmartUtils.getResponseCode(response);
String errorMessage = SmartUtils.validateResponse((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), response, message);
SmartUtils.hideSoftKeyboard((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
if (isShowSnackbar && !TextUtils.isEmpty(errorMessage)) {
SmartUtils.showSnackBar((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), errorMessage, Snackbar.LENGTH_LONG);
}
((OnResponseReceivedListener) requestParams.get(REQUEST_METHOD_PARAMS.RESPONSE_LISTENER)).onResponseReceived(response, false, responseCode);
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.v("@@@@@WSResponse", error.toString());
//appendLog("@@@WSResponse::::::" + error.toString());
SmartUtils.hideSoftKeyboard((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
String errorMessage = VolleyErrorHelper.getMessage(error, (Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
SmartUtils.showSnackBar((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), errorMessage, Snackbar.LENGTH_INDEFINITE);
((OnResponseReceivedListener) requestParams.get(REQUEST_METHOD_PARAMS.RESPONSE_LISTENER)).onResponseError();
}
});
}
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
TIMEOUT,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
jsObjRequest.setTag(requestParams.get(REQUEST_METHOD_PARAMS.TAG));
getRequestQueue().add(jsObjRequest);
}
public <T> void addToRequestQueueMultipleFilesUpload(final HashMap<REQUEST_METHOD_PARAMS, Object> requestParams, final ArrayList<String> imagePath,
final ArrayList<String> filePath, final String message, final boolean isShowSnackBar) {
MultipartRequestMedia jsObjRequest = null;
JSONObject jsonRequest = ((JSONObject) requestParams.get(REQUEST_METHOD_PARAMS.PARAMS));
Log.v("@@@WsParams", jsonRequest.toString());
//appendLog("@@@@@WsParams:::" + jsonRequest.toString());
if (requestParams.get(REQUEST_METHOD_PARAMS.REQUEST_TYPES) == REQUEST_TYPE.JSON_OBJECT) {
jsObjRequest = new MultipartRequestMedia((String) requestParams.get(REQUEST_METHOD_PARAMS.URL), jsonRequest, imagePath,
filePath, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.v("@@@@@WSResponse", response.toString());
//appendLog("@@@@@WSResponse:::" + response.toString());
if (SmartUtils.isSessionExpire(response)) {
SmartUtils.removeCookie();
final HashMap<REQUEST_METHOD_PARAMS, Object> requestParamsForSession = new HashMap<>();
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.CONTEXT, requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.REQUEST_TYPES, SmartWebManager.REQUEST_TYPE.JSON_OBJECT);
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.TAG, Constants.WEB_AUTOLOGIN);
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.URL, SmartApplication.REF_SMART_APPLICATION.DOMAIN_NAME);
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.PARAMS, SmartUtils.getLoginParams());
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.RESPONSE_LISTENER, new SmartWebManager.OnResponseReceivedListener() {
@Override
public void onResponseReceived(final JSONObject response, boolean isValidResponse, int responseCode) {
if (responseCode == 200) {
addToRequestQueueMultipleFilesUpload(requestParams, imagePath, filePath, message, isShowSnackBar);
}
}
@Override
public void onResponseError() {
}
});
SmartWebManager.getInstance((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT)).
addToRequestQueueMultipleFilesUpload(requestParamsForSession, null, null, "", isShowSnackBar);
} else {
if (SmartUtils.getResponseCode(response) == 200) {
String errorMessage = SmartUtils.validateResponse((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), response, message);
SmartUtils.hideSoftKeyboard((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
if (isShowSnackBar && !TextUtils.isEmpty(errorMessage)) {
SmartUtils.showSnackBar((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), errorMessage, Snackbar.LENGTH_LONG);
}
((OnResponseReceivedListener) requestParams.get(REQUEST_METHOD_PARAMS.RESPONSE_LISTENER)).onResponseReceived(response, true, 200);
} else {
int responseCode = SmartUtils.getResponseCode(response);
String errorMessage = SmartUtils.validateResponse((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), response, message);
SmartUtils.hideSoftKeyboard((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
if (isShowSnackBar && !TextUtils.isEmpty(errorMessage)) {
SmartUtils.showSnackBar((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), errorMessage, Snackbar.LENGTH_LONG);
}
((OnResponseReceivedListener) requestParams.get(REQUEST_METHOD_PARAMS.RESPONSE_LISTENER)).onResponseReceived(response, false, responseCode);
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//appendLog("@@@@@WSResponse:::" + error.toString());
SmartUtils.hideSoftKeyboard((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
String errorMessage = VolleyErrorHelper.getMessage(error, (Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
SmartUtils.showSnackBar((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), errorMessage, Snackbar.LENGTH_INDEFINITE);
((OnResponseReceivedListener) requestParams.get(REQUEST_METHOD_PARAMS.RESPONSE_LISTENER)).onResponseError();
}
});
}
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
TIMEOUT,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
jsObjRequest.setTag(requestParams.get(REQUEST_METHOD_PARAMS.TAG));
getRequestQueue().add(jsObjRequest);
}
public <T> void addToRequestQueueFilesUploadWithTag(final HashMap<REQUEST_METHOD_PARAMS, Object> requestParams, final String filePath,
final String fileTag, final String message, final boolean isShowSnackBar) {
MultipartRequestMedia jsObjRequest = null;
JSONObject jsonRequest = ((JSONObject) requestParams.get(REQUEST_METHOD_PARAMS.PARAMS));
Log.v("@@@WsParams", jsonRequest.toString());
//appendLog("@@@@@WsParams:::" + jsonRequest.toString());
if (requestParams.get(REQUEST_METHOD_PARAMS.REQUEST_TYPES) == REQUEST_TYPE.JSON_OBJECT) {
jsObjRequest = new MultipartRequestMedia((String) requestParams.get(REQUEST_METHOD_PARAMS.URL), jsonRequest, filePath,
fileTag, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.v("@@@@@WSResponse", response.toString());
//appendLog("@@@@@WSResponse:::" + response.toString());
if (SmartUtils.isSessionExpire(response)) {
SmartUtils.removeCookie();
final HashMap<REQUEST_METHOD_PARAMS, Object> requestParamsForSession = new HashMap<>();
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.CONTEXT, requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.REQUEST_TYPES, SmartWebManager.REQUEST_TYPE.JSON_OBJECT);
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.TAG, Constants.WEB_AUTOLOGIN);
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.URL, SmartApplication.REF_SMART_APPLICATION.DOMAIN_NAME);
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.PARAMS, SmartUtils.getLoginParams());
requestParamsForSession.put(SmartWebManager.REQUEST_METHOD_PARAMS.RESPONSE_LISTENER, new SmartWebManager.OnResponseReceivedListener() {
@Override
public void onResponseReceived(final JSONObject response, boolean isValidResponse, int responseCode) {
if (responseCode == 200) {
addToRequestQueueFilesUploadWithTag(requestParams, filePath, fileTag, message, isShowSnackBar);
}
}
@Override
public void onResponseError() {
}
});
SmartWebManager.getInstance((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT)).
addToRequestQueueMultipleFilesUpload(requestParamsForSession, null, null, "", isShowSnackBar);
} else {
if (SmartUtils.getResponseCode(response) == 200) {
String errorMessage = SmartUtils.validateResponse((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), response, message);
SmartUtils.hideSoftKeyboard((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
if (isShowSnackBar && !TextUtils.isEmpty(errorMessage)) {
SmartUtils.showSnackBar((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), errorMessage, Snackbar.LENGTH_LONG);
}
((OnResponseReceivedListener) requestParams.get(REQUEST_METHOD_PARAMS.RESPONSE_LISTENER)).onResponseReceived(response, true, 200);
} else {
int responseCode = SmartUtils.getResponseCode(response);
String errorMessage = SmartUtils.validateResponse((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), response, message);
SmartUtils.hideSoftKeyboard((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
if (isShowSnackBar && !TextUtils.isEmpty(errorMessage)) {
SmartUtils.showSnackBar((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), errorMessage, Snackbar.LENGTH_LONG);
}
((OnResponseReceivedListener) requestParams.get(REQUEST_METHOD_PARAMS.RESPONSE_LISTENER)).onResponseReceived(response, false, responseCode);
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//appendLog("@@@@@WSResponse:::" + error.toString());
SmartUtils.hideSoftKeyboard((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
String errorMessage = VolleyErrorHelper.getMessage(error, (Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT));
SmartUtils.showSnackBar((Context) requestParams.get(REQUEST_METHOD_PARAMS.CONTEXT), errorMessage, Snackbar.LENGTH_INDEFINITE);
((OnResponseReceivedListener) requestParams.get(REQUEST_METHOD_PARAMS.RESPONSE_LISTENER)).onResponseError();
}
});
}
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
TIMEOUT,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
jsObjRequest.setTag(requestParams.get(REQUEST_METHOD_PARAMS.TAG));
getRequestQueue().add(jsObjRequest);
}
public interface OnResponseReceivedListener {
void onResponseReceived(JSONObject tableRows, boolean isValidResponse, int responseCode);
void onResponseError();
}
/**
* This method will write any text string to the log file generated by the
* SmartFramework.
*
* @param text = String text is the text which is to be written to the log
* file.
*/
private void appendLog(String text) {
File logFile = new File("sdcard/weweReqObject.txt");
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append("\n\n");
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} | true |
0199cd1dbfd45681f1f677aea3730febcaf2fb58 | Java | Mrmiffo/team-team-name | /GotoGothenburg/app/src/main/java/com/teamteamname/gotogothenburg/map/OnInfoWindowClickListener.java | UTF-8 | 2,682 | 2.53125 | 3 | [] | no_license | package com.teamteamname.gotogothenburg.map;
import android.content.Context;
import android.location.Location;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.teamteamname.gotogothenburg.api.ApiFactory;
import com.teamteamname.gotogothenburg.api.ErrorHandler;
import com.teamteamname.gotogothenburg.api.TripHandler;
import com.teamteamname.gotogothenburg.destination.Destination;
import com.teamteamname.gotogothenburg.destination.SavedDestinations;
/**
* Listener for deciding what should happen when the user clicks on a markers info window
* Created by patrick
*/
class OnInfoWindowClickListener implements GoogleMap.OnInfoWindowClickListener {
final private IMap map;
final private TripHandler tripHandler;
final private ErrorHandler errorHandler;
final private Context context;
/**
* Creates a new OnInfoWindowClick Listener
*
* @param map Map on which info window is shown
* @param tripHandler TripHandler to call should directions be requested
* @param errorHandler ErrorHandler should directions request go wrong
* @param context Context for displaying toasts
*/
public OnInfoWindowClickListener(IMap map, TripHandler tripHandler, ErrorHandler errorHandler, Context context) {
this.map = map;
this.tripHandler = tripHandler;
this.errorHandler = errorHandler;
this.context = context;
}
@Override
public void onInfoWindowClick(Marker marker) {
if (marker.equals(map.getUserMarker())) {
SavedDestinations.getInstance().addDestination(new Destination(marker.getTitle(), marker.getPosition().latitude, marker.getPosition().longitude));
marker.remove();
Toast.makeText(context, "Destination added", Toast.LENGTH_SHORT).show();
} else if("Directions".equalsIgnoreCase(marker.getSnippet())) {
final Location myLocation = ApiFactory.getInstance().createILocationServices().getLastKnownLocation();
if (myLocation != null) {
final LatLng originCoord = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
final LatLng destCoord = new LatLng(marker.getPosition().latitude, marker.getPosition().longitude);
ApiFactory.getInstance().createITrip().getTrip(
tripHandler, errorHandler, "Me", originCoord, marker.getTitle(), destCoord);
} else {
Toast.makeText(context,"Device Location not found",Toast.LENGTH_SHORT).show();
}
}
}
}
| true |
7075e6c3d58036464763fbfd48d328ce4cfd7be5 | Java | ghassane1991/libManagement | /lib(core)/src/subscribersManagement/AgeCategoryDAO.java | UTF-8 | 4,728 | 3 | 3 | [] | no_license | package subscribersManagement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;
import booksManagement.Book;
import exceptions.AgeCategoryExistsException;
import exceptions.AgeCategoryOverLapException;
import exceptions.BadParametersException;
import exceptions.BadStringException;
import exceptions.BookExistsException;
import exceptions.EmptyStringException;
import exceptions.SubscriberExistsException;
import jpaUtils.JPAUtil;
public class AgeCategoryDAO {
public boolean isEmpty() {
EntityManager entityManager = JPAUtil.getEntityManager();
if (entityManager.createNamedQuery("findAllAgeCategories")
.getResultList().isEmpty())
return true;
else
return false;
}
public List<AgeCategory> getContent() {
EntityManager entityManager = JPAUtil.getEntityManager();
return ((List<AgeCategory>) entityManager.createNamedQuery("findAllAgeCategories").getResultList());
}
public boolean add(AgeCategory ageCategory) throws AgeCategoryOverLapException, AgeCategoryExistsException{
EntityManager entityManager = JPAUtil.getEntityManager();
if(contains(ageCategory)){
throw new AgeCategoryExistsException(); //Verify if the book already exists in the database
}
//Make sure if there is no overlap
for (AgeCategory ag : getContent()){
if((ag.getMin() < ageCategory.getMax() && ageCategory.getMax() < ag.getMax()) || (ag.getMin() < ageCategory.getMin() && ageCategory.getMin() < ag.getMax()) ){
throw new AgeCategoryOverLapException();
}
}
try {
entityManager.persist(ageCategory);
} catch (Exception e) {
System.err.println("Problem when saving");
e.printStackTrace();
return false;
}
return true;
}
public String toString() {
EntityManager entityManager = JPAUtil.getEntityManager();
String result = "";
List<AgeCategory> theAgeCategories = (List<AgeCategory>) entityManager.createNamedQuery("findAllAgeCategories").getResultList();
for (AgeCategory ac : theAgeCategories)
result += ac.toString() + "\n";
return result;
}
// search for the age category by name
public AgeCategory get(String cat_name) throws AgeCategoryExistsException {
EntityManager entityManager = JPAUtil.getEntityManager();
AgeCategory ac = (AgeCategory) entityManager.find(AgeCategory.class, cat_name);
if (ac == null)
throw new AgeCategoryExistsException();
else
return ac;
}
/**
*/
public long size() {
EntityManager entityManager = JPAUtil.getEntityManager();
return (entityManager.createNamedQuery("findAllAgeCategories")
.getResultList().size());
}
/**
* @throws SubscriberExistsException
*/
public boolean remove(AgeCategory ageCategory) throws AgeCategoryExistsException, SubscriberExistsException {
EntityManager entityManager = JPAUtil.getEntityManager();
if (ageCategory == null)
throw new AgeCategoryExistsException();
else if(contains(ageCategory) == false) //Verify if the age category already exists
throw new AgeCategoryExistsException();
else if (ageCategory.getSubscribers().size() > 0){ //Verify if no subscribers in the age category
throw new SubscriberExistsException();
}
else
try {
entityManager.remove(ageCategory);
} catch (Exception pe) {
System.err.println("problem when deleting an entity ");
pe.printStackTrace();
return false;
}
return true;
}
public boolean contains(AgeCategory ageCategory) throws AgeCategoryExistsException {
EntityManager entityManager = JPAUtil.getEntityManager();
if (ageCategory == null)
throw new AgeCategoryExistsException();
AgeCategory ac = (AgeCategory) entityManager.find(AgeCategory.class,
ageCategory.getName());
if (ac == null)
return false;
else
return ac.equals(ageCategory);
}
// Modify an age category
public void modify(String name, int max,int min) throws AgeCategoryExistsException, AgeCategoryOverLapException, BadParametersException, EmptyStringException, BadStringException {
EntityManager entityManager=JPAUtil.getEntityManager();
AgeCategory ac = (AgeCategory) entityManager.find(AgeCategory.class, name);
if (ac == null)
throw new AgeCategoryExistsException();
if(max <= min){
throw new BadParametersException();
}
else {
//Make sure if there is no overlap
for (AgeCategory ag : getContent()){
if(ag.getMax() > min && max > ag.getMax()){
throw new AgeCategoryOverLapException();
}
}
ac.setName(name);
ac.setMax(max);
ac.setMin(min);
}
try{
entityManager.merge(ac);
} catch (Exception e) {
System.err.println("Problem when saving");
e.printStackTrace();
}
}
}
| true |
3b242ed45ae2f5065ede03e34f1a87413db051dd | Java | yaoguo00/java.code | /Practice12.java | UTF-8 | 1,366 | 3.796875 | 4 | [] | no_license | class Node{
public Node next;
public int value;
public Node(int value){
this.value=value;
}
}
public class Practice12{
//创造出一个链表
public static Node create(){
Node n1=new Node(1);
Node n2=new Node(2);
Node n3=new Node(3);
Node n4=new Node(4);
Node n5=new Node(5);
Node n6=new Node(6);
n1.next=n2;
n2.next=n3;
n3.next=n4;
n4.next=n5;
n5.next=n6;
n6.next=null;
return n1;
}
//找倒数第k个值
public static Node FindkthToTail(Node head,int k){
int length=0;
for(Node val=head;val!=null;val=val.next){
length++;
}
if (length < k) {
return null;
}
int n=length-k;
Node per=head;
for(int a=0;a<n;a++){
per=per.next;
}
return per;
}
public static Node FindkthToTail2(Node head,int k){
Node back=head;
Node front=head;
for(int n=0;n<k;n++){
if(front==null){
return null;
}
front=front.next;
}
while(front!=null){
front=front.next;
back=back.next;
}
return back;
}
public static void main(String [] args){
Node head=create();
head=FindkthToTail(head,2);
System.out.printf("这个数为倒数第k个,k为:");
System.out.println(head.value);
head=create();
head=FindkthToTail(head,3);
System.out.printf("这个数为倒数第k个,k为:");
System.out.println(head.value);
}
}
| true |
ddc4d873a452b4dbe541132867ed721e81a8437a | Java | gitssie/play-plugins2.6.x | /src/play-transport/app/play/libs/transport/dns/DNS.java | UTF-8 | 2,147 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | package play.libs.transport.dns;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* JVM为了提高效率,会将第一次的DNS结果缓存起来。而且你不重新启动JVM缓存永远不失效。
所以你的服务器一旦有了DNS更新的话,你只能重新启动服务来重新更新缓存。那么有没有什么办法可以设置一个缓存失效时间呢?JVM提供了两个启动参数:
设置解析成功的域名记录JVM中缓存的有效时间,这里修改为10秒钟有效,0表示禁止缓存,-1表示永远有效
-Dsun.net.inetaddr.ttl=10
设置解析失败的域名记录JVM中缓存的有效时间,这里修改为10秒钟有效,0表示禁止缓存,-1表示永远有效
-Dsun.net.inetaddr.negative.ttl=10
*/
public class DNS {
private static Logger LOGGER = LoggerFactory.getLogger(DNS.class);
private static final LoadingCache<String, InetAddress[]> ADDRS_CACHE = CacheBuilder.newBuilder()
.expireAfterWrite(10, TimeUnit.SECONDS)
.maximumSize(1000)
.build(new CacheLoader<String, InetAddress[]>() {
@Override
public InetAddress[] load(String host) throws Exception {
try{
return DNSLookup.getAllByName(host);
}catch (Exception e){
LOGGER.error("load ip address by host["+host+"] error",e);
throw e;
}
}
});
public static InetAddress[] getAllByName(String host) throws ExecutionException {
return ADDRS_CACHE.get(host);
}
}
| true |
5a8ffbb899fc18641cfdbb2db71e23ce6ca8b82f | Java | chigov2/FisherBook | /app/src/main/java/techmarket/uno/fisherbook/utils/customArrayAdapter.java | UTF-8 | 2,619 | 2.640625 | 3 | [] | no_license | package techmarket.uno.fisherbook.utils;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;
import techmarket.uno.fisherbook.R;
public class customArrayAdapter extends ArrayAdapter<listItemClass> {//созать конструктор
private LayoutInflater inflater; //создатель
// список может содержать объект класса
private List<listItemClass> listItemNew = new ArrayList<>();//////////////////// внешняя функция!!!!!
private Context context;
public customArrayAdapter(@NonNull Context context, int resource, List<listItemClass> listItemNew, LayoutInflater inflater) {
super(context, resource,listItemNew);
this.inflater = inflater;
this.listItemNew = listItemNew;
this.context = context;
}
// функция рисования отдельного элемента списка
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
ViewHolder viewHolder;
listItemClass listItemMain = listItemNew.get(position);
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_view_item_1, null, false);
viewHolder = new ViewHolder();
//viewHolder.image = convertView.findViewById(R.id.ivItem);
viewHolder.image = convertView.findViewById(R.id.ivItem);
viewHolder.secName = convertView.findViewById(R.id.tvSecondName);
viewHolder.name = convertView.findViewById(R.id.tvName);
convertView.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) convertView.getTag();///////////////?????
}
viewHolder.name.setText(listItemMain.getNamef());
viewHolder.secName.setText(listItemMain.getSecond_name());
//viewHolder.image.setImageResource(listItemMain.getImage_id());//??????
viewHolder.image.setImageResource(listItemMain.image_id);//??????
return convertView;//почему удалили - непонятно
}
//чтобы напрямую не работать с TextView, ImageView
private class ViewHolder{
TextView name;
TextView secName;
ImageView image;
}
}
| true |
6d07af44839f90e559d7f174a0f71be05a7f4247 | Java | MikhailNavitski/Task1 | /jwd-task01-template/src/main/java/by/tc/task01/dao/creator/RefrigeratorCreator.java | UTF-8 | 749 | 2.640625 | 3 | [] | no_license | package by.tc.task01.dao.creator;
import by.tc.task01.dao.command.Command;
import by.tc.task01.entity.Appliance;
import by.tc.task01.entity.Refrigerator;
public class RefrigeratorCreator implements Command {
public Appliance makeAppliance(String[] value) {
Refrigerator refrigerator = new Refrigerator();
refrigerator.setPowerConsumption(Integer.parseInt(value[2]));
refrigerator.setWeight(Integer.parseInt(value[3]));
refrigerator.setFreezerCapacity(Integer.parseInt(value[4]));
refrigerator.setOverallCapacity(Double.parseDouble(value[5]));
refrigerator.setHeight(Integer.parseInt(value[6]));
refrigerator.setWidth(Integer.parseInt(value[7]));
return refrigerator;
}
}
| true |
e508eba8f15baa335fa4b49be15da087f9f77d24 | Java | Kovboy56/SchedulerApplication | /SchoolScheduler/app/src/main/java/com/example/schoolscheduler/TermViewer.java | UTF-8 | 7,069 | 1.757813 | 2 | [] | no_license | package com.example.schoolscheduler;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.example.schoolscheduler.database.TermEntity;
import com.example.schoolscheduler.ui.TermAdapter;
import com.example.schoolscheduler.utilities.AlertReceiver;
import com.example.schoolscheduler.utilities.Constants;
import com.example.schoolscheduler.utilities.NotificationHelper;
import com.example.schoolscheduler.viewmodel.MainViewModel;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.NotificationCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.SystemClock;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class TermViewer extends AppCompatActivity {
@BindView(R.id.term_list)
RecyclerView mTermView;
@OnClick(R.id.fab)
void fabClickHandler() {
Intent intent = new Intent(this, TermViewActivity.class);
startActivity(intent);
}
private List<TermEntity> termsData = new ArrayList<>();
private TermAdapter mAdapter;
private MainViewModel mViewModel;
private NotificationHelper mNotificationHelper;
private Context myContext;
private AlarmManager mgrAlarms[];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mNotificationHelper = new NotificationHelper(this);
ButterKnife.bind(this);
initRecyclerView();
initViewModel();
setTitle("View of terms");
}
private void initViewModel() {
final Observer<List<TermEntity>> termsObserver =
new Observer<List<TermEntity>>() {
@Override
public void onChanged(List<TermEntity> termEntities) {
termsData.clear();
termsData.addAll(termEntities);
if (mAdapter == null) {
mAdapter = new TermAdapter(termsData,
TermViewer.this);
mTermView.setAdapter(mAdapter);
} else {
mAdapter.notifyDataSetChanged();
}
}
};
mViewModel = ViewModelProviders.of(this)
.get(MainViewModel.class);
mViewModel.mTerms.observe(this, termsObserver);
}
private void initRecyclerView() {
mTermView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mTermView.setLayoutManager(layoutManager);
DividerItemDecoration divider = new DividerItemDecoration(
mTermView.getContext(), layoutManager.getOrientation());
mTermView.addItemDecoration(divider);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_add_sample_data) {
addSampleData();
return true;
} else if (id == R.id.action_delete_all) {
deleteAllTerms();
return true;
} else if (id == R.id.action_add_test_alarms) {
triggerTestAlarms();
}
return super.onOptionsItemSelected(item);
}
public void triggerTestAlarms() {
//Trigger test alarms
myContext = getApplicationContext();
mgrAlarms = new AlarmManager[10];
Intent intents[] = new Intent[10];
for(int i = 1; i < 10; ++i)
{
System.out.println(Constants.intentArray.size());
intents[i] = new Intent(myContext, AlertReceiver.class);
// Loop counter `i` is used as a `requestCode`
PendingIntent pendingIntent = PendingIntent.getBroadcast(myContext,
Constants.intentArray.size()+500, intents[i], 0);
// Single alarms in 1, 2, ..., 10 minutes (in `i` minutes)
mgrAlarms[i] = (AlarmManager) myContext.getSystemService(ALARM_SERVICE);
mgrAlarms[i].setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + i*5000,
pendingIntent);
Constants.intentArray.add(pendingIntent);
}
//
}
private void deleteAllTerms() {
mViewModel.deleteAllTerms();
}
private void addSampleData() {
mViewModel.addSampleData();
}
private void addTestAlarms(){
Calendar c = Calendar.getInstance();
onTimeSet(c.HOUR_OF_DAY,c.MINUTE+1, 100);
onTimeSet(c.HOUR_OF_DAY,c.MINUTE+2, 101);
}
public void openNext(View view) {
Intent intent = new Intent(this, TermViewActivity.class);
startActivity(intent);
}
public void sendOnChannel1(String title, String message){
NotificationCompat.Builder nb = mNotificationHelper.getChannel1Notification(title,message);
mNotificationHelper.getManager().notify(1,nb.build());
}
public void sendOnChannel2(String title, String message){
NotificationCompat.Builder nb = mNotificationHelper.getChannel2Notification(title,message);
mNotificationHelper.getManager().notify(2,nb.build());
}
public void onTimeSet(int hour, int min, int rc){
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, min);
c.set(Calendar.SECOND, 0);
startAlarm(c,rc);
}
private void startAlarm(Calendar c, int rc) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, rc, intent, 0);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
}
}
| true |
fdfa41c4fb1e8cafa164a6426454ed513abed360 | Java | ThilakaVijayan/Design_Patterns | /src/com/thilaka/design/patterns/behavioural/command/head/first/complete/implementation/commands/TVOffCommand.java | UTF-8 | 564 | 2.703125 | 3 | [] | no_license | package com.thilaka.design.patterns.behavioural.command.head.first.complete.implementation.commands;
import com.thilaka.design.patterns.behavioural.command.head.first.complete.implementation.Command;
import com.thilaka.design.patterns.behavioural.command.head.first.complete.implementation.devices.TV;
public class TVOffCommand implements Command {
private TV tv;
public TVOffCommand(TV tv) {
this.tv = tv;
}
@Override
public void execute() {
tv.off();
}
@Override
public void undo() {
tv.on();
}
}
| true |
08108862bf532c5b810d9a0bf2098b228ca191d8 | Java | Christianhoej/FlexicuV2 | /app/src/main/java/com/example/chris/flexicuv2/opret_bruger/Opret_bruger_Presenter_Frag1.java | UTF-8 | 7,905 | 2.25 | 2 | [] | no_license | package com.example.chris.flexicuv2.opret_bruger;
/**
* @Author Gunn
*/
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.view.Gravity;
import android.widget.Toast;
import com.example.chris.flexicuv2.database.DBManager;
import com.example.chris.flexicuv2.model.Bruger;
import com.example.chris.flexicuv2.model.Singleton;
import java.util.Map;
public class Opret_bruger_Presenter_Frag1 {
private Opret_bruger_Presenter_Frag1.UpdateNewUser_Frag1 updateNewUser;
private final String ERRORMSGCVR = "CVRFEJL";
private final String ERRORVIRKSOMHEDSNAVN="VSHNAVNFEJL";
private final String ERRORADRESSE = "ADRESSEFEJL";
private final String ERRORBY = "BYFEJL";
private final String ERRORPOSTNR = "POSTNRFEJL";
private final String ERRORNAVN = "NAVENFEJL";
private final String ERRORTLFNR = "TELEFONNUMMER";
private final String ERRORTITEL = "TITELFEJL";
private DBManager dbManager;
private AsyncHentCVR async;
private String cvr;
private Map<String, String> map;
private CVR_Opslag cvr_opslag;
private Singleton singleton;
private Context mContext;
public Opret_bruger_Presenter_Frag1(Opret_bruger_Presenter_Frag1.UpdateNewUser_Frag1 updateNewUser, Context mContext){
this.updateNewUser = updateNewUser;
dbManager = new DBManager();
singleton = Singleton.getInstance();
this.mContext = mContext;
}
/**
* Metoden skal anvendes til at kontrollere at alle informationer er blevet tastet "tilstrækkeligt ind".
*
* @param CVR : virksomhedens cvr (8 cifre)
* @param virksomhedsnavn : virksomhedens navn
* @param adresse : virksomhedens adresse
* @param postNr : virksomhedens postnr
* @param by : Virksomhedens by (tilhørende adresse)
* @param brugerensNavn : Navnet på brugeren
* @param brugerensTlf : Brugerens tlf-nummer (8 cifre)
* @param brugerensTitel : brugerens titel (i virksomheden)
* @param context :
* @return boolean true hvis alle informationer er blevet tastet godt nok ind.
*/
boolean korrektudfyldtInformation(String CVR, String virksomhedsnavn, String adresse, String postNr,
String by,String brugerensNavn, String brugerensTlf,
String brugerensTitel, Context context) {
int errors = 0;
boolean CVROK = checkStringOnlyNumbersAndLength(CVR, 8);
if (!CVROK) {
updateNewUser.errorCVR(ERRORMSGCVR);
errors++;
}
boolean vshOK = !virksomhedsnavn.isEmpty();
if (!vshOK) {
updateNewUser.errorVirksomhedsnavn(ERRORVIRKSOMHEDSNAVN);
errors++;
}
boolean adresseOK = !adresse.isEmpty();
if (!adresseOK) {
updateNewUser.errorAdresse(ERRORADRESSE);
errors++;
}
boolean postNrOK = checkStringOnlyNumbersAndLength(postNr, 4);
if (!postNrOK){
updateNewUser.errorPostnr(ERRORPOSTNR);
errors++;
}
boolean byOK = !by.isEmpty();
if(!byOK) {
updateNewUser.errorBy(ERRORBY);
errors++;
}
boolean navnOK = brugerensNavn.length()>0;
if (!navnOK){
updateNewUser.errorNavn(ERRORNAVN);
errors++;
}
boolean brugerensTlfOK = checkStringOnlyNumbersAndLength(brugerensTlf, 8);
if(!brugerensTlfOK){
updateNewUser.errorTlf(ERRORTLFNR);
errors++;
}
boolean brugerTitelOK = brugerensTitel.length()>0;
if(!brugerTitelOK){
updateNewUser.errorTitel(ERRORTITEL);
}
if (errors > 0 )
return false;
else {
if(singleton.midlertidigBruger==null){
singleton.midlertidigBruger= new Bruger();
}
singleton.midlertidigBruger.setVirksomhedCVR(CVR);
singleton.midlertidigBruger.setVirksomhedsnavn(virksomhedsnavn);
singleton.midlertidigBruger.setAdresse(adresse);
singleton.midlertidigBruger.setPostnr(postNr);
singleton.midlertidigBruger.setBy(by);
singleton.midlertidigBruger.setBrugerensNavn(brugerensNavn);
singleton.midlertidigBruger.setTlfnr(brugerensTlf);
singleton.midlertidigBruger.setTitel(brugerensTitel);
return true;
}
}
private boolean checkStringOnlyNumbersAndLength(String cvr, int stringlength) {
if(cvr.length() == stringlength) {
int ammNumbers = 0;
for (int i = 0; i < stringlength; i++) {
if (cvr.charAt(i) <= '9' && cvr.charAt(i) >= '0') {
ammNumbers++;
}
}
if(ammNumbers == stringlength)
return true;
}
return false;
}
/**
* Metode til at oprette bruger
*/
void opretNyBruger(/*Indsæt alle oplysninger*/){
}
/**
* Metode til at opretteVirksomhed
*/
void opretVirksomhed(){
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/**
* Metode skal hente CVR oplysningerne, virksomhedsnavn, virksomhedsadresse, by og postnr.
* @param CVR: 8 cifret cvr string
*/
public void hentVirksomhedsoplysninger(String CVR) {
//TODO må ikke være i main thread
cvr = CVR;
System.out.println("Her kommer jeg"); //TODO
if(isNetworkAvailable()) {
async = new AsyncHentCVR();
async.execute();
}
else{
Toast toast = Toast.makeText(mContext, "Du har ingen internetforbindelse", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
private class AsyncHentCVR extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... param) {
try {
cvr_opslag = new CVR_Opslag();
System.out.println("her er jeg også!!!!!!!!!!!!!!!");//TODO
map = cvr_opslag.getResult(Opret_bruger_Presenter_Frag1.this.cvr);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
System.out.println(map.get(cvr_opslag.getAdresseString()) + "Jeg kan finde den!");
updateNewUser.updateAdresse(map.get(cvr_opslag.getAdresseString()));
updateNewUser.updateVirksomhedsNavn(map.get(cvr_opslag.getVirksomhedsNavnString()));
updateNewUser.updatePostNr(map.get(cvr_opslag.getPostNrString()));
updateNewUser.updateBy(map.get(cvr_opslag.getByString()));
}
}
/**
* Interfacet implementeres af NewUser_fragment_1 for at kunne opdatere viewet fra presenteren
*/
interface UpdateNewUser_Frag1{
void updateVirksomhedsNavn(String vsh_navn);
void updateAdresse(String adresse);
void updatePostNr(String postNr);
void updateBy(String by);
void errorCVR(String errorMsg);
void errorVirksomhedsnavn(String errorMsg);
void errorAdresse(String errorMsg);
void errorBy(String errorMsg);
void errorPostnr(String errorMsg);
void errorNavn(String errorMsg);
void errorTlf(String errorMsg);
void errorTitel(String errorMsg);
}
}
| true |
c1d1174b55379cc11e09c18f48f62188ff07a9f6 | Java | ManaliAundhkar/Problems-on-N-numbers-in-Java | /Demo7.java | UTF-8 | 1,222 | 3.6875 | 4 | [] | no_license | //Write java program which accept N numbers from user and accept one another number as NO , return index of last occurrence of that NO.
//Input : N : 6
//NO: 66
//Elements : 85 66 3 66 93 88
//Output : 3
//Input : N : 6
//NO: 93
//Elements : 85 66 3 66 93 88
//Output : 4
//Input : N : 6
//NO: 12
//Elements : 85 11 3 15 11 111
//Output : -1
import java.util.*;
class Array
{
public int ChkNo(int Arr[],int No)
{
int i=0,temp=0;
for(i=0;i<Arr.length;i++)
{
if(Arr[i]==No)
{
temp=i;
}
}
if(temp>0)
{
return temp;
}
else
{
return (temp-1);
}
}
}
class Demo7
{
public static void main(String arg[])
{
Scanner sobj=new Scanner(System.in);
System.out.println("Enter the no. of elements");
int iSize=sobj.nextInt();
int Arr[]=new int[iSize];//malloc
System.out.println("Enter the elements");
for(int i=0;i<iSize;i++)
{
Arr[i]=sobj.nextInt();
}
System.out.println("Enter the no to be found");
int No=sobj.nextInt();
Array mobj=new Array();
int iRet=mobj.ChkNo(Arr,No);
System.out.println("The last occurence is at index "+iRet);
}
}
| true |
ea7dc9a1c9feace155ec7cf88bc1c92145a4d980 | Java | itsSandeepMisal/Token-Based-Authentication-using-JWT | /src/main/java/com/example/demo/AuthenticationDemoApplication.java | UTF-8 | 941 | 2.15625 | 2 | [] | no_license | package com.example.demo;
import com.example.demo.entity.User;
import com.example.demo.repository.UserRepo;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AuthenticationDemoApplication {
@Autowired
private UserRepo userRepo;
@PostConstruct
public void initUsers() {
List<User> users = Stream.of(
new User(101, "sandeep", "123456", "sandeepmisal4@gmail.com"),
new User(102, "deepak", "102030", "deepakmisal4@gmail.com"),
new User(103, "prashant", "654321", "deepakmisal4@gmail.com")
).collect(Collectors.toList());
userRepo.saveAll(users);
}
public static void main(String[] args) {
SpringApplication.run(AuthenticationDemoApplication.class, args);
}
}
| true |
ca1e36a6b57ad985eec4dba5d38794bf17e64a76 | Java | haeinoh/java-live-study | /week14/src/bounded/BoundedTest.java | UTF-8 | 363 | 2.890625 | 3 | [] | no_license | package bounded;
public class BoundedTest {
public static void main(String[] args) {
int res1 = Util.compare(10, 20);
System.out.println(res1); // -1
int res2 = Util.compare(8.3, 6.2);
System.out.println(res2); // 1
// String res3 = Util.compare("20", "30");
// System.out.println(res3);
}
}
| true |
8aa449a7b61fe7d38cadf8477f556477db0dcf4c | Java | guilhermelange/Java-knowledge | /ByteBanc Herdado Conta/src/br/com/ByteBanc/Banco/Modelo/Conta.java | ISO-8859-1 | 2,591 | 3.359375 | 3 | [] | no_license | package br.com.ByteBanc.Banco.Modelo;
import java.io.Serializable;
/**
* Classe representa a moldura de uma conta;
* @author Guilherme
*
*/
public abstract class Conta implements Comparable<Conta>, Serializable{
// private double saldo;
protected double saldo;
private int agencia;
private int numero;
// Cliente titular = new Cliente();
private transient Cliente titular;
private static int total = 0;
public Conta(int agencia, int numero) {
total++;
this.agencia = agencia;
this.numero = numero;
}
public abstract void deposita(double valor);
// public void deposita(double valor) {
// this.saldo += valor;
// }
// public void saca(double valor) {
// if (this.saldo < valor) {
// throw new SaldoInsuficienteException("\nNo h saldo suficiente para esta operao. \nSaldo: " + this.saldo + "\nValor Sacar: " + valor);
// } else {
// this.saldo -= valor;
// }
// }
public void saca(double valor) throws SaldoInsuficienteException {
if (this.saldo < valor) {
throw new SaldoInsuficienteException(
"\nNo h saldo suficiente para esta operao. \nSaldo: " + this.saldo + "\nValor Sacar: " + valor);
} else {
this.saldo -= valor;
}
}
public void transfere(double valor, Conta destino) throws SaldoInsuficienteException {
this.saca(valor);
destino.deposita(valor);
}
public double getSaldo() {
return this.saldo;
}
public int getNumero() {
return this.numero;
}
public void setNumero(int numero) {
if (numero <= 0) {
System.out.println("No pode valor menor ou igual a 0.");
return;
}
this.numero = numero;
}
public int getAgencia() {
return this.agencia;
}
public void setAgencia(int agencia) {
if (agencia <= 0) {
System.out.println("No permitida agncia menor que 0.");
return;
}
this.agencia = agencia;
}
public void setTitular(Cliente titular) {
this.titular = titular;
}
public Cliente getTitular() {
return titular;
}
public static int getTotal() {
return total;
}
@Override
public String toString() {
return "Conta, nmero " + this.getNumero();
}
public boolean Igual(Conta conta) {
if (this.agencia != conta.agencia) {
return false;
}
if (this.numero != conta.numero) {
return false;
}
return true;
}
public boolean equals(Object ref) {
Conta conta = (Conta) ref;
if (this.agencia != conta.agencia) {
return false;
}
if (this.numero != conta.numero) {
return false;
}
return true;
}
@Override
public int compareTo(Conta c2) {
return Double.compare(this.saldo, c2.saldo);
}
} | true |
9d91e01647f4b1beecb2b8fc9b6ed6d66136f2e1 | Java | Vellyxenya/Nightmare_Gravity | /NightmareGravity/Energy.java | UTF-8 | 2,718 | 3.28125 | 3 | [] | no_license | import greenfoot.*;
import java.awt.Color;
/**
* Crée la barre d'énergie de tous les vaisseaux. Les méthodes sont les même que la classe Health,
* si ce n'est la couleur bleue...
*/
public class Energy extends Interface
{
public Energy()
{
drawEnergyBar();
}
public void drawEnergyBar()
{
GreenfootImage e= new GreenfootImage(getImage());
GreenfootImage energyBar = new GreenfootImage(e.getWidth(),20);
energyBar.setColor(Color.BLACK);
energyBar.fill();
switch(RightArrow.imageNumber)
{
case 0:
int energyPixels1 = (int)(200*Gear1.Henergy/Gear1.MAX_ENERGY);
if(energyPixels1 <= 0)
{
energyPixels1 = 1;
}
GreenfootImage filledEnergy = new GreenfootImage(energyPixels1,20);
filledEnergy.setColor(Color.BLUE);
filledEnergy.fill();
energyBar.drawImage(filledEnergy, 0, 0);
e.drawImage(energyBar,0,e.getHeight()-e.getHeight());
setImage(e);
break;
case 1:
int energyPixels2 = (int)(200*Gear2.Henergy/Gear2.MAX_ENERGY);
if(energyPixels2 <= 0)
{
energyPixels2 = 1;
}
GreenfootImage filledEnergy2 = new GreenfootImage(energyPixels2,20);
filledEnergy2.setColor(Color.BLUE);
filledEnergy2.fill();
energyBar.drawImage(filledEnergy2, 0, 0);
e.drawImage(energyBar,0,e.getHeight()-e.getHeight());
setImage(e);
break;
case 2:
int energyPixels3 = (int)(200*Gear3.Henergy/Gear3.MAX_ENERGY);
if(energyPixels3 <= 0)
{
energyPixels3 = 1;
}
GreenfootImage filledEnergy3 = new GreenfootImage(energyPixels3,20);
filledEnergy3.setColor(Color.BLUE);
filledEnergy3.fill();
energyBar.drawImage(filledEnergy3, 0, 0);
e.drawImage(energyBar,0,e.getHeight()-e.getHeight());
setImage(e);
break;
case 3:
int energyPixels4 = (int)(200*Gear4.Henergy/Gear4.MAX_ENERGY);
if(energyPixels4 <= 0)
{
energyPixels4 = 1;
}
GreenfootImage filledEnergy4 = new GreenfootImage(energyPixels4,20);
filledEnergy4.setColor(Color.BLUE);
filledEnergy4.fill();
energyBar.drawImage(filledEnergy4, 0, 0);
e.drawImage(energyBar,0,e.getHeight()-e.getHeight());
setImage(e);
break;
}
}
}
| true |
ba68a7c49178edea0b1a4277f434c40ef0ec8a6c | Java | dqhieuu/dictionary-application | /src/main/java/edu/uet/hieuhadict/dao/DatabaseConnection.java | UTF-8 | 3,769 | 2.609375 | 3 | [] | no_license | package edu.uet.hieuhadict.dao;
import org.sqlite.SQLiteConfig;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseConnection {
private static Connection conn = null;
private DatabaseConnection() {}
private static void connect(String location)
throws SQLException, ClassNotFoundException, IOException {
// Necessary for jar build. Returns class object from sqlite-jdbc interface
Class.forName("org.sqlite.JDBC");
SQLiteConfig config = new SQLiteConfig();
// Loading extension must be enabled
config.enableLoadExtension(true);
String url = "jdbc:sqlite::resource:" + DatabaseConnection.class.getResource(location);
conn = DriverManager.getConnection(url, config.toProperties());
System.out.println("Connection to SQLite has been established.");
// Loads the hieuspellfix1 extension
loadHieuSpellfix1Extension();
}
/**
* Spellfix1 is an extension for SQLite that enables the ability to fuzzy search thanks to a
* virtual table containing all the needed information based on Levenshtein distance algorithm.
*
* <p>This method loads the <b>HieuSpellfix(A|B).dll</b>, which is a precompiled, modified version
* of the extension that can be loaded on jdbc-sqlite.
*
* <p>There are 2 versions of the dll, ver A is for Win64, ver B is for Win32.
*
* <p>The dll must be outside of the .jar archive for the jdbc-sqlite to be able to load.
*
* <p>Thus, this method checks for the existence of the dll in the temp directory. If it can't
* find the file, it copies the precompiled dll corresponding to the Windows architecture to the
* temp folder, then executes the statement to load the dll.
*
* <p><i>Note that the jar doesn't include unix and mac dynamic lib, which means the application
* probably won't start on those OS, since this is one of the core functions of the
* application.</i>
*
* @throws SQLException exception
* @throws IOException exception
*/
private static void loadHieuSpellfix1Extension() throws SQLException, IOException {
String tempDir = System.getProperty("java.io.tmpdir");
String fileName;
// 64 or 32 bit
if (System.getProperty("sun.arch.data.model").equals("64")) {
fileName = "HieuSpellfixA.dll";
} else {
fileName = "HieuSpellfixB.dll";
}
Path dllPath = Paths.get(tempDir + fileName);
if (!Files.exists(dllPath)) {
Files.copy(
DatabaseConnection.class.getResourceAsStream("/dll/" + fileName),
dllPath,
StandardCopyOption.REPLACE_EXISTING);
System.out.println(fileName + " extension has been copied to temp folder.");
}
try (Statement stmt = conn.createStatement()) {
stmt.execute(
String.format("SELECT load_extension('%s');", dllPath.toAbsolutePath().normalize()));
}
System.out.println(fileName + " extension has been loaded.");
}
/**
* Executes {@code VACUUM;} statement, an effective command for optimizing disk space taken up by
* the database.
*
* @throws SQLException exception
*/
public static void optimize() throws SQLException {
if (conn == null) return;
try (Statement stmt = conn.createStatement()) {
stmt.execute("VACUUM;");
}
}
public static Connection getConnection() {
if (conn == null) {
try {
connect("/database/Dict.db");
} catch (SQLException | ClassNotFoundException | IOException throwables) {
throwables.printStackTrace();
}
}
return conn;
}
}
| true |
4a2eaed2e6122c803e2a7a51b77fdb8822dcc63b | Java | cody0117/LearnAndroid | /AndroidPOS/src/com/google/android/gms/internal/kg.java | UTF-8 | 6,148 | 1.539063 | 2 | [] | no_license | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.google.android.gms.internal;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.text.TextUtils;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
// Referenced classes of package com.google.android.gms.internal:
// jv, kw, fj, kn,
// fh, av, kl, bs,
// kj, me, kh, ku,
// ki, gs, kt, lq,
// kx, dn
public final class kg extends jv
{
private static final Object a = new Object();
private static kg b;
private final Context c;
private final kx d;
private final dn e;
private final bs f;
private kg(Context context, bs bs1, dn dn, kx kx)
{
c = context;
d = kx;
e = dn;
f = bs1;
}
private static fj a(Context context, bs bs1, fh fh1)
{
kn kn1;
kw kw1 = new kw(context);
if (kw1.l == -1)
{
return new fj(2);
}
kn1 = new kn(fh1.f.packageName);
if (fh1.c.c != null)
{
String s2 = fh1.c.c.getString("_ad");
if (s2 != null)
{
return kl.a(context, fh1, s2);
}
}
String s = bs1.a();
String s1 = kl.a(fh1, kw1, bs1.b(), bs1.c(), bs1.d());
if (s1 == null)
{
return new fj(0);
}
kj kj1 = new kj(s1);
me.a.post(new kh(context, fh1, kn1, kj1, s));
ku ku1 = (ku)kn1.a().get(10L, TimeUnit.SECONDS);
if (ku1 != null)
{
break MISSING_BLOCK_LABEL_237;
}
fj fj4 = new fj(0);
me.a.post(new ki(kn1));
return fj4;
Exception exception1;
exception1;
fj fj1 = new fj(0);
me.a.post(new ki(kn1));
return fj1;
fj fj2;
if (ku1.a() == -2)
{
break MISSING_BLOCK_LABEL_280;
}
fj2 = new fj(ku1.a());
me.a.post(new ki(kn1));
return fj2;
fj fj3;
if (ku1.f())
{
fh1.g.packageName;
}
fj3 = a(context, fh1.k.b, ku1.d(), ku1);
me.a.post(new ki(kn1));
return fj3;
Exception exception;
exception;
me.a.post(new ki(kn1));
throw exception;
}
public static fj a(Context context, String s, String s1, ku ku1)
{
HttpURLConnection httpurlconnection;
kt kt1;
URL url;
long l;
URL url1;
int i;
int j;
java.util.Map map;
fj fj1;
String s2;
fj fj2;
fj fj3;
fj fj4;
byte abyte0[];
BufferedOutputStream bufferedoutputstream;
try
{
kt1 = new kt();
(new StringBuilder("AdRequestServiceImpl: Sending request: ")).append(s1);
url = new URL(s1);
l = SystemClock.elapsedRealtime();
}
catch (IOException ioexception)
{
(new StringBuilder("Error while connecting to ad server: ")).append(ioexception.getMessage());
return new fj(2);
}
url1 = url;
i = 0;
httpurlconnection = (HttpURLConnection)url1.openConnection();
lq.a(context, s, false, httpurlconnection);
if (!TextUtils.isEmpty(null))
{
httpurlconnection.addRequestProperty("x-afma-drt-cookie", null);
}
if (ku1 == null)
{
break MISSING_BLOCK_LABEL_141;
}
if (!TextUtils.isEmpty(ku1.c()))
{
httpurlconnection.setDoOutput(true);
abyte0 = ku1.c().getBytes();
httpurlconnection.setFixedLengthStreamingMode(abyte0.length);
bufferedoutputstream = new BufferedOutputStream(httpurlconnection.getOutputStream());
bufferedoutputstream.write(abyte0);
bufferedoutputstream.close();
}
j = httpurlconnection.getResponseCode();
map = httpurlconnection.getHeaderFields();
if (j < 200 || j >= 300)
{
break MISSING_BLOCK_LABEL_215;
}
kt1.a(url1.toString(), map, lq.a(new InputStreamReader(httpurlconnection.getInputStream())));
fj4 = kt1.a(l);
httpurlconnection.disconnect();
return fj4;
if (j < 300 || j >= 400)
{
break MISSING_BLOCK_LABEL_305;
}
s2 = httpurlconnection.getHeaderField("Location");
if (!TextUtils.isEmpty(s2))
{
break MISSING_BLOCK_LABEL_267;
}
fj2 = new fj(0);
httpurlconnection.disconnect();
return fj2;
url1 = new URL(s2);
if (++i <= 5)
{
break MISSING_BLOCK_LABEL_339;
}
fj3 = new fj(0);
httpurlconnection.disconnect();
return fj3;
(new StringBuilder("Received error HTTP response code: ")).append(j);
fj1 = new fj(0);
httpurlconnection.disconnect();
return fj1;
kt1.a(map);
httpurlconnection.disconnect();
break MISSING_BLOCK_LABEL_45;
Exception exception;
exception;
httpurlconnection.disconnect();
throw exception;
}
public static kg a(Context context, bs bs1, dn dn, kx kx)
{
kg kg1;
synchronized (a)
{
if (b == null)
{
b = new kg(context.getApplicationContext(), bs1, dn, kx);
}
kg1 = b;
}
return kg1;
}
public final fj a(fh fh1)
{
Context context = c;
bs bs1 = f;
dn _tmp = e;
kx _tmp1 = d;
return a(context, bs1, fh1);
}
}
| true |
b6a8f74c6230a23590ce1d06bb62f0f87a16cba9 | Java | HoWi96/OGPProject | /OGP1516-Hillbillies/src/hillbillies/model/World.java | UTF-8 | 38,244 | 2.890625 | 3 | [] | no_license | package hillbillies.model;
import java.util.*;
import be.kuleuven.cs.som.annotate.*;
import hillbillies.model.helper.CubePosition;
import hillbillies.model.helper.Utils;
import hillbillies.part2.listener.TerrainChangeListener;
import hillbillies.util.ConnectedToBorder;
/**
* A class about the world of the game
*
* @author Holger Willems | 2e bach. ing. OOP
* @date 16/05/2016
* @Version 3.0
*
*/
/**
* A class representing the world of the game
*
* involving the following properties:
* terrainTypes, nbCubesX, nbCubesY, nbCubesZ
* involving the following associations:
* units, factions, items
*
*
* ATTRIBUTES
*
* @Invar The TerrainTypes of each world must be a valid TerrainTypes for any
* world.
* | isValidTerrainTypes(getTerrainTypes())
* @Invar Each world can have its nbCubesX as dimension.
* | canHaveAsDimension(this.getNbCubesX())
* @Invar Each world can have its nbCubesY as dimension.
* | canHaveAsDimension(this.getNbCubesY())
* @Invar Each world can have its nbCubesX as dimension.
* | canHaveAsDimension(this.getNbCubesZ())
*
* ASSOCIATIONS
*
* @Invar Each world must have proper units for that world
* | this.hasProperUnits()
* @Invar Each world must have proper factions for that world
* | hasProperFactions()
* @Invar Each world must have proper items for that world
* | hasProperItems()
*
*
*/
public class World implements ITerrainType {
/*___________________________________________________________________
* __________________________________________________________________
* -----------------------CONSTANTS---------------------------------
*___________________________________________________________________
*___________________________________________________________________*/
//PUBLIC
public static final int[] VALID_CUBE_TYPES = {TYPE_AIR,TYPE_ROCK,TYPE_TREE,TYPE_WORKSHOP};
public static final int MAX_UNITS_IN_WORLD = 100;
public static final int MAX_FACTIONS = 5;
/*___________________________________________________________________
* __________________________________________________________________
* -----------------------VARIABLES---------------------------------
*___________________________________________________________________
*___________________________________________________________________*/
/**
* Variable registering the TerrainTypes of this world.
*/
private int[][][] terrainTypes;
/**
* Variable registering the nbCubesX of this world.
*/
private final int nbCubesX;
/**
* Variable registering the nbCubesY of this world.
*/
private final int nbCubesY;
/**
* Variable registering the nbCubesZ of this world.
*/
private final int nbCubesZ;
/**
* Variable registering the TerrainChangeListener of this world.
*/
private final TerrainChangeListener modelListener;
/**
* Variable registering the ConnectedToBorder class storing information about this world
*/
private final ConnectedToBorder border;
/**
* Variable referencing a set collecting all the cubepositions of workshops
* of this world.
*
* @Invar The referenced set is effective.
* | workshops != null
* @Invar Each CubePosition registered in the referenced list is
* effective
* | for each CubePosition workshop in workshops:
* | (workshop != null)
*/
@Model
private final Set<CubePosition> workshops;
/*___________________________________________________________________
* __________________________________________________________________
* -----------------------CONSTRUCTOR--------------------------------
*___________________________________________________________________
*___________________________________________________________________*/
/**
* @param terraintypes
* The TerrainTypes for this new world.
* @param modelListener
* The TerrainChangeListener for this new world.
* ______________________________________________________
*
* @effect The TerrainTypes of this new world is set to
* the given TerrainTypes.
* | this.setTerrainTypes(terrainTypes)
*
* @post The nbCubesX of this new world is equal to terrainTypes.length
*
* @post The nbCubesY of this new world is equal to terrainTypes[0].length
*
* @post The nbCubesX of this new world is equal to terrainTypes[0][0].length
*
* @post The TerrainChangeListener of this new world is equal to the given
* TerrainChangeListener.
* | new.getTerrainChangeListener() == modelListener
*
* @post The connectedToBorder of this new world is equal to the given
* connectedToBorder.
* | new.getConnectedToBorder() == border
*
* @post No factions belong to this new world
* @post No units belong to this new world
*
* @post No items belong to this world, unless there are some spawned by
* | this.makeAllSolidsConnected();
* @effect Let all solids be connected to the border of the game world
* | this.makeAllSolidsConnected();
*/
public World(int[][][] terrainTypes, TerrainChangeListener modelListener) throws IllegalArgumentException {
//Connection with the GUI
if(modelListener==null)
throw new IllegalArgumentException();
this.modelListener = modelListener;
this.setTerrainTypes(terrainTypes);
//Initialize immutable attributes
this.nbCubesX = terrainTypes.length;
this.nbCubesY = terrainTypes[0].length;
this.nbCubesZ = terrainTypes[0][0].length;
this.workshops = new HashSet<CubePosition>();
//Initialize associations
this.units = new HashSet<Unit>(MAX_UNITS_IN_WORLD);
this.factions = new HashSet<Faction>(MAX_FACTIONS);
this.items = new HashSet<Item>();
//Connection to ConnectedToBorder
this.border = new ConnectedToBorder(this.getNbCubesX(),this.getNbCubesY(), this.getNbCubesZ());
this.makeAllSolidsConnected();
}
/*___________________________________________________________________
*___________________________________________________________________
* -----------------------METHODS--------------------------------
*___________________________________________________________________
*___________________________________________________________________*/
//------------------------GETTERS
/**
* Return the nbCubesX of this world.
*/
@Basic @Raw @Immutable
public int getNbCubesX() {
return this.nbCubesX;
}
/**
* Return the nbCubesY of this world.
*/
@Basic @Raw @Immutable
public int getNbCubesY() {
return this.nbCubesY;
}
/**
* Return the nbCubesZ of this world.
*/
@Basic @Raw @Immutable
public int getNbCubesZ() {
return this.nbCubesZ;
}
/**
* Return the TerrainTypes of this world.
*/
@Basic @Raw
public int[][][] getTerrainTypes() {
return this.terrainTypes.clone();
}
/**
* Get the cube type on a given position
*
* @param position
* the position where you want to know the cubeType of
* @return the cubeType
* @throws IllegalArgumentException
* if the position is out of bounds
*/
@Raw
public int getCubeType(int[] position) throws IllegalArgumentException {
if (!isValidPosition(position))
throw new IllegalArgumentException();
int X = position[0];
int Y = position[1];
int Z = position[2];
return this.getTerrainTypes()[X][Y][Z];
}
/**
* Return the TerrainChangeListener of this world.
*/
@Basic @Raw @Immutable
public TerrainChangeListener getTerrainChangeListener() {
return this.modelListener;
}
/**
* Return the connectedToBorder of this world.
*/
@Basic @Raw @Immutable
public ConnectedToBorder getConnectedToBorder() {
return this.border;
}
/**
* Return a set with all workshops in this world
*/
@Basic @Raw @Immutable
public Set<CubePosition> getAllWorkshops(){
return new HashSet<CubePosition>(workshops);
}
//------------------------SETTERS
/**
* Set the TerrainTypes of this world to the given TerrainTypes.
*
* @param terraintypes
* The new TerrainTypes for this world.
* @post The TerrainTypes of this new world is equal to
* the given TerrainTypes.
* | new.getTerrainTypes() == terrainTypes
* @throws IllegalArgmunetException
* The given TerrainTypes is not a valid TerrainTypes for any
* world.
* | ! isValidTerrainTypes(getTerrainTypes())
*/
@Raw @Model
private void setTerrainTypes(int[][][] terraintypes) throws IllegalArgumentException {
if (! isValidTerrainTypes(terraintypes))
throw new IllegalArgumentException();
this.terrainTypes = terraintypes;
}
/**
* Set the cubeType of this world to the given cubeType.
*
* @param cubeType
* The new cubeType for this world.
* @post The cubeType of this new world is equal to
* the given cubeType.
* | new.getcubeType(position) == cubeType
* @throws IllegalArgumentException
* The given cubeType is not a valid cubeType for any
* world. Or give position is out of bounds
*/
@Raw
public void setcubeType(int cubeType, int[] position) throws IllegalArgumentException {
if (! isValidCubeType(cubeType) || !isValidPosition(position))
throw new IllegalArgumentException();
int X = position[0];
int Y = position[1];
int Z = position[2];
//more efficient than changing the whole world
this.terrainTypes[X][Y][Z] = cubeType;
this.getTerrainChangeListener().notifyTerrainChanged(X,Y,Z);
}
//------------------------INSPECTORS
/**
* Check whether the given TerrainTypes is a valid TerrainTypes for
* any world.
*
* @param TerrainTypes
* The TerrainTypes to check.
* @return
* TerrainTypes may not be null.
* The dimensions must be nonzero and larger than 0.
* All elements part of TerrainType must be valid cube types.
*/
public static boolean isValidTerrainTypes(int[][][] terrainTypes) {
//terraintypes may not be null
if(terrainTypes == null)
return false;
//dimensions must be nonzero
if(!(terrainTypes.length>0 &&
terrainTypes[0].length>0 && terrainTypes[0][0].length>0))
return false;
// all elements need to be valid cube types;
for(int[][] outerArray: terrainTypes){
for( int[] innerArray: outerArray){
for(int cubeType: innerArray){
if(!isValidCubeType(cubeType))
return false;
}
}
}
return true;
}
/**
* Check whether the given cubeType is a valid cubeType for
* any world.
*
* @param cubeType
* The cubeType to check.
* @return
* whether the type of the cube is a valid cubeType
*/
private static boolean isValidCubeType(int cubeType) {
for(int validCubeType: VALID_CUBE_TYPES){
if(cubeType == validCubeType)
return true;
}
return false;
}
/**
*
* @param position
* the position to check
* @return
* whether the position is inside the game world
*/
@Raw
public boolean isValidPosition(int[] position) {
int X = position[0];
int Y = position[1];
int Z = position[2];
return 0<=X&&X<this.getNbCubesX()&&
0<=Y&&Y<this.getNbCubesY()&&
0<=Z&&Z<this.getNbCubesZ();
}
/**
* Returns whether the cube is solid or not
*
* @param position
* the position of the cube
* @return
* if the cube at the given position is rock or tree
*/
public boolean isSolidCube(int[] position){
int type = this.getCubeType(position);
return (type == TYPE_ROCK) || (type == TYPE_TREE);
}
/**
* Gives back all the adjacent cubes
* @param position
* The position of the cube
* @return
* a List<int[]> with all the locations of the surrounding cubes
*/
public List<int[]> getAdjacentCubes(int[] position){
List<int[]> adjacentCubes = new ArrayList<>();
int x = position[0];
int y = position[1];
int z = position[2];
for (int dx=-1; dx<=1;dx++){
for (int dy=-1; dy<=1;dy++){
for (int dz=-1; dz<=1;dz++){
int[] adjacentCube = new int[]{x+dx,y+dy,z+dz};
if(isValidPosition(adjacentCube) && !(dx==0&&dy==0&&dz==0)){
adjacentCubes.add(adjacentCube);
}
}
}
}
return adjacentCubes;
}
/**
* Checks whether there are solid cubes surrounding the given cube
* or the cube is positioned on ground level
*
* @param position
* The position
* @return
* whether there are solid cubes surrounding the given cube
* or the cube itself is positioned on ground level
*
*/
public boolean hasSolidAdjacents(int[] position){
int x = position[0];
int y = position[1];
int z = position[2];
if(z == 0)
return true;
for (int dx= -1; dx <=1;dx++){
for (int dy= -1; dy <=1;dy++){
for (int dz= -1; dz <=1;dz++){
int[] adjacentCube = new int[]{x+dx,y+dy,z+dz};
if(isValidPosition(adjacentCube) && !(dx==0&&dy==0&&dz==0) && isSolidCube(adjacentCube)){
return true ;
}
}
}
}
return false;
}
/**
* Checks whether the cube under the give position is solid
*
* @param position
* the given position
* @return
* whether the cube under the give position is solid
* with the level under z=0 considered as 0
*/
public boolean isSolidUnder(int[] position){
return position[2] == 0 ||
isSolidCube(Utils.getPositionUnder(position));
}
/**
* TODO find a more comprehensible piece of code (efficiency is okay!)
*
* Check if you can move directly from the given position to the other
* !!Only meant for adjacent cubes!!
*
* @param nextPosition
* @param currentPosition
* @return
* if you can move directly from the current position to the next
*/
@Raw
public boolean canMoveDirectly(int[] currentPosition, int dx, int dy, int dz) {
if(dx!=0 && dy !=0 && dz !=0){
// chance : 8/26
if(isSolidCube(new int[] {currentPosition[0],currentPosition[1], currentPosition[2]+dz})&&
isSolidCube(new int[]{currentPosition[0],currentPosition[1]+dy, currentPosition[2]}) &&
isSolidCube(new int[]{currentPosition[0]+dx,currentPosition[1], currentPosition[2]}))
return false;
} else if(dx!=0 && dy !=0 && dz ==0){
//chance : 4/26
if(isSolidCube(new int[] {currentPosition[0]+dx,currentPosition[1], currentPosition[2]})&&
isSolidCube(new int[]{currentPosition[0],currentPosition[1]+dy, currentPosition[2]}))
return false;
} else if(dx==0 && dy !=0 && dz !=0){
//chance : 4/26
if(isSolidCube(new int[] {currentPosition[0],currentPosition[1], currentPosition[2]+dz})&&
isSolidCube(new int[]{currentPosition[0],currentPosition[1]+dy, currentPosition[2]}))
return false;
}else if(dx!=0 && dy ==0 && dz !=0){
//chance : 4/26
if(isSolidCube(new int[] {currentPosition[0],currentPosition[1], currentPosition[2]+dz})&&
isSolidCube(new int[]{currentPosition[0]+dx,currentPosition[1], currentPosition[2]}))
return false;
}
return true;
}
/**
*
* Get a list with all positions
* Inside game world, non solid,directly movable to and not the same
*
* @param position
* @return
* a list with all positions Inside game world, non solid,directly movable to and not the same
*/
public List<int[]> findReachableAdjacents(int[] position){
List<int[]> adjacentCubes = new ArrayList<>(26);
int x = position[0];
int y = position[1];
int z = position[2];
for (int dx=-1; dx<=1;dx++){
for (int dy=-1; dy<=1;dy++){
for (int dz=-1; dz<=1;dz++){
int[] nextPos = new int[]{x+dx,y+dy,z+dz};
//Inside game world, non solid,directly movable to and not the same
//quick checks
if(isValidPosition(nextPos)&&!isSolidCube(nextPos)&&!(dx==0&&dy==0&&dz==0))
//longer checks
if(hasSolidAdjacents(nextPos) && canMoveDirectly(position,dx,dy,dz))
adjacentCubes.add(nextPos);
}
}
}
return adjacentCubes;
}
/**
* A quicker way to select proper adjacents moving only in one direction at a time
*
* @param position
* the position departing from
* @return
* the list with adjacents where is direct access to
*/
public List<int[]> quickFindReachableAdjacents(int[] position){
List<int[]> adjacentCubes = new ArrayList<>(6);
int x = position[0];
int y = position[1];
int z = position[2];
int[] di= new int[3];
for(int i=0; i<=2; i++){
for(int d=-1;d<=1;d+=2){
di[i] = d;
di[(i+1)%3] = 0;
di[(i+2)%3] = 0;
int[] nextPos = new int[]{x+di[0],y+di[1],z+di[2]};
if(isValidPosition(nextPos) && !isSolidCube(nextPos) && hasSolidAdjacents(nextPos)){
adjacentCubes.add(nextPos);
}
}
}
return adjacentCubes;
}
/*___________________________________________________________________
*___________________________________________________________________
* -----------------------TERRAIN CHANGES----------------------------
*___________________________________________________________________
*___________________________________________________________________*/
/**
* Cave in the world on the specific position and control if there
* are, due to this change, cubes not connected anymore to the border
*
* @param position
* The position where a cave in will happen
*
* @post The type of the position will be changed to TYPE_AIR
* @effect the ConnectedToBorder will change his content due to the change
* @effect The TerrainChangeListener will be notified
*
* @effect A boulder will be spawned
* @effect A log will be spawned
*
*/
public void caveIn(int[] position) throws IllegalArgumentException{
if(!isSolidCube(position) && !isValidPosition(position))
throw new IllegalArgumentException("The cube is not solid or is on an invalid location");
List<int[]> caveInList = this.getConnectedToBorder().changeSolidToPassable(
position[0], position[1], position[2]);
caveInList.add(position);
for(int[] caveInPosition: caveInList){
if(isSolidCube(caveInPosition)){
//REPLACE CUBE BY AIR
int type = this.getCubeType(caveInPosition);
this.setcubeType(TYPE_AIR, caveInPosition);
//SPAWN RAWMATERIAL
double probability = 0.25;
Random rand = new Random();
if (rand.nextDouble() <= probability){
if (type == TYPE_ROCK){
new Boulder(caveInPosition,this);
//System.out.println("spawn boulder");
}else if(type == TYPE_TREE){
new Log(caveInPosition,this);
//System.out.println("spawn log");
}
}
}
}
}
/**
* Makes all the solid cubes connected
*
* @effect the solid cubes in the world which are not connected will cave in
*
*/
@Raw @Model
private void makeAllSolidsConnected(){
for (int x=0; x<getNbCubesX(); x++) {
for (int y=0; y<getNbCubesY(); y++) {
for (int z=0; z<getNbCubesZ(); z++) {
int[] position = new int[] {x,y,z};
// non solid cubes have to be notified if they are not already updated
if(!isSolidCube(position)){
// make a set with all cubepositions of workshop
if(getCubeType(position)==TYPE_WORKSHOP)
this.workshops.add(new CubePosition(position));
if(this.getConnectedToBorder().isSolidConnectedToBorder(x, y, z)){
this.caveIn(position);
}
}
}
}
}
}
/*___________________________________________________________________
*___________________________________________________________________
* -----------------------ADVANCE TIME-------------------------------
*___________________________________________________________________
*___________________________________________________________________*/
/**
* Invokes the advanceTime method on all objects present in this World.
* This are all units and all items
*
* @param dt
* The time by which to advance, expressed in seconds.
*
* @effect The time will advance for all units
* @effect The time will advance for all items
*/
public void advanceTime(double dt) throws IllegalArgumentException, IllegalStateException{
if (!isValidDuration(dt))
throw new IllegalArgumentException();
//UNITS
for(Unit unit: this.units){
unit.advanceTime(dt);
}
//ITEMS
for(Item item: this.items){
item.advanceTime(dt);
}
}
/**
* @param dt
* the time to progress
* @return
* | (0.0<=dt && dt<=0.2)
*/
public static boolean isValidDuration(double dt) {
return (0.0<=dt && dt<=0.2);
}
/*___________________________________________________________________
*___________________________________________________________________
* -----------------------FACTIONS-----------------------------------
* -----------------UNIDIRECTIONAL----------------------------------
*___________________________________________________________________
*___________________________________________________________________
/**
* Variable referencing a set collecting all the factions
* of this world.
*
* @Invar The referenced set is effective.
* | factions != null
* @Invar Each faction registered in the referenced list is
* effective and not yet terminated.
* | for each faction in factions:
* | ( (faction != null) &&
* | (! faction.isTerminated()) )
*/
private Set<Faction> factions;
//------------------------GETTERS
/**
* Gives back the active factions of this world
*
* @return a new hashSet with all factions
*/
@Basic @Raw
public Set<Faction> getAllFactions(){
return new HashSet<>(factions);
}
/**
* @return the amount of factions in the world
*/
public int getNbFactions(){
return this.factions.size();
}
/**
* Returns the faction with the least amount of units
*
* @return the smallest faction
*
*/
@Raw @Model
private Faction getSmallestFaction(){
Faction smallestFaction = null;
int unitsInSmallest = Faction.MAX_UNITS_IN_FACTION;
for (Faction faction : this.getAllFactions()) {
if (faction.getNbUnits() < unitsInSmallest){
smallestFaction = faction;
unitsInSmallest = faction.getNbUnits();
}
}
return smallestFaction;
}
/**
*
* Adds a unit to a faction
*
* @param unit
* the unit who is needing a faction
*
* @return The new faction for the given unit
* @return The smallest faction is returned
*
*/
@Raw @Model
private Faction getFactionForUnit(Unit unit){
Faction faction;
if (this.getAllFactions().size()<MAX_FACTIONS){
//take the faction for the unit
faction = unit.getFaction();
}else{
//give unit a place in the smallest faction
faction = this.getSmallestFaction();
}
return faction;
}
//------------------------SETTERS
/**
*
* Add the given faction to the set of factions of this world.
*
* @param faction
* The faction to be added.
*
* @post This world has the given faction as one of its factions.
*
* @throws IllegalArgumentException
* |!canHaveAsFaction(faction) || this.factions.size()>=MAX_FACTIONS
*
*
*/
@Raw @Model
private void addAsFaction(@Raw Faction faction) throws IllegalArgumentException {
if(!canHaveAsFaction(faction) || this.factions.size()>=MAX_FACTIONS)
throw new IllegalArgumentException();
this.factions.add(faction);
}
/**
* Remove the given faction from the set of factions of this world.
*
* @param faction
* The faction to be removed.
*
* @post This world no longer has the given faction as
* one of its factions.
*
* @throws IllegalArgumentException
* |!this.hasAsFaction(faction)
*
*/
@Raw
public void removeFaction(@Raw Faction faction) throws IllegalArgumentException{
if(!this.hasAsFaction(faction))
throw new IllegalArgumentException();
factions.remove(faction);
}
//------------------------INSPECTORS
/**
* Check whether this world has the given faction as one of its
* factions.
*
* @param faction
* The faction to check.
*/
@Basic @Raw
public boolean hasAsFaction(@Raw Faction faction) {
return factions.contains(faction);
}
/**
* Check whether this world can have the given faction
* as one of its factions.
*
* @param faction
* The faction to check.
* @return True if and only if the given faction is effective
*/
@Raw
public boolean canHaveAsFaction(Faction faction) {
return faction != null;
}
/*___________________________________________________________________
*___________________________________________________________________
* -----------------------UNITS--------------------------------------
* -----------------CONTROLLING CLASS--------------------------------
*___________________________________________________________________
*___________________________________________________________________*/
/**
* Variable referencing a set collecting all the units
* of this world.
*
* @Invar The referenced set is effective.
* | units != null
* @Invar Each unit registered in the referenced list is
* effective and not yet terminated.
* | for each unit in units:
* | ( (unit != null) &&
* | (! unit.isTerminated()) )
*/
private Set<Unit> units;
//------------------------GETTERS
/**
* Gives back the units of the world
*/
@Basic @Raw
public Set<Unit> getAllUnits() {
Set<Unit> AllUnits = new HashSet<>(units);
return AllUnits;
}
/**
* @return the amount of units in the world
*/
public int getNbUnits(){
return this.units.size();
}
//------------------------SETTERS
/**
* Adds the unit to this world and gives the unit a faction
*
* @param unit
* a unit for this world
*
* @post the unit will belong now to this world
* @post the unit will belong now to his new faction
*
* @effect The world will have this unit as member
* @effect The unit will leave his old faction
* @effect The unit will have a new faction assigned
* @effect the world will have a new faction if it has not yet the faction assigned to this unit
*
* @throws IllegalArgumentException
* if the unit is dead or already belongs to a world
*/
public void addUnit(Unit unit) throws IllegalArgumentException{
if(!this.canHaveAsUnit(unit) || unit.getWorld() == this)
throw new IllegalArgumentException();
//INAPROPRIATE POSITION
if(!isValidPosition(Utils.getCubePosition(unit.getPosition()))
|| isSolidCube(Utils.getCubePosition(unit.getPosition())))
unit.setPosition(Utils.getCubeCenter(getRandomPositionForUnit()));
// SILENTLY REJECT UNIT
if(this.units.size() < MAX_UNITS_IN_WORLD){
//ADDING UNIT TO WORLD
this.units.add(unit);
unit.setWorld(this);
//ADDING UNIT TO FACTION
Faction faction = this.getFactionForUnit(unit);
if(!hasAsFaction(faction))
addAsFaction(faction);
unit.getFaction().removeUnit(unit);
faction.addUnit(unit);
//System.out.println("Succesfully added unit: " + unit.getName());
}
}
/**
* Handles the bidirectional association given Unit from the set of Units of this World.
*
* @param unit
* The Unit to be removed.
* @post This World no longer has the given Unit as
* one of its Units.
* | ! new.hasAsUnit(unit)
* @effect The unit has no longer this world as world
*
* @throws IllegalArgumentException
* |!this.hasAsUnit(unit) || !(unit.getWorld() == this)
*/
@Raw
public void removeUnit(Unit unit) throws IllegalArgumentException {
if(!this.hasAsUnit(unit) || !(unit.getWorld() == this))
throw new IllegalArgumentException("invalid unit to remove from this world");
units.remove(unit);
unit.setWorld(null);
}
//------------------------INSPECTORS
/**
* Check whether this World has the given Unit as one of its
* Units.
*
* @param unit
* The Unit to check.
*/
@Raw
public boolean hasAsUnit(@Raw Unit unit) {
return units.contains(unit);
}
/**
* Check whether this world can have the given unit
* as one of its units.
*
* @param Unit
* The unit to check.
* @return True if and only if the given unit is effective
* and if the unit is alive
*/
@Raw
public boolean canHaveAsUnit(Unit unit){
return unit != null && unit.isAlive();
}
/**
* Check whether this world has proper units attached to it.
*
* @return True if and only if this world can have each of the
* units attached to it as one of its units,
* and if each of these units references this faction as
* the faction to which they are attached.
* And if the amount of units does not exceed the max amount
*/
public boolean hasProperUnits() {
if (this.getNbUnits()>MAX_UNITS_IN_WORLD)
return false;
for (Unit unit : this.units) {
if (!canHaveAsUnit(unit) || unit.getWorld() != this)
return false;
}
return true;
}
/**
* Returns all units located on the cube, if any.
*
* @param position
* The position of the cube
*
* @return
* A new ArrayList of all units with positions located on the cube.
*/
@Raw
public List<Unit> getAllUnitsOnPosition(int[] position) throws IllegalArgumentException {
if (!isValidPosition(position)) {
throw new IllegalArgumentException("Given position is invalid");
}
List<Unit> AllUnits = new ArrayList<>();
for (Unit unit: this.units) {
if (Utils.equals(position, Utils.getCubePosition(unit.getPosition()))) {
AllUnits.add(unit);
}
}
return AllUnits;
}
//------------------------HELPERS
/**
* Gives back a random location for a unit
*
* @return a random position for a unit inside the game world
* The type where the unit is located is non solid
* The type where the unit is non solid or is ground level
*/
@Raw
public int[] getRandomPositionForUnit() {
int nbX = this.getNbCubesX();
int nbY = this.getNbCubesY();
int nbZ = this.getNbCubesZ();
int X = (int) (Math.random()*nbX);
int Y = (int) (Math.random()*nbY);
int Z = (int) (Math.random()*nbZ);
//get a random non solid location
while(isSolidCube(new int[]{X,Y,Z})){
X = (int) (Math.random()*nbX);
Y = (int) (Math.random()*nbY);
Z = (int) (Math.random()*nbZ);
};
// go down till you hit ground or level 0
while( Z != 0 && !isSolidCube(new int[]{X,Y,Z-1})){
Z= Z-1;
};
return new int[] {X, Y, Z};
}
/**
*
* @param enableDefaultBehavior
* whether the default behavior should be enabled or not
* @effect
* A random unit will be created with random properties
* @return
* The random unit
*
*/
public Unit createRandomUnit(boolean enableDefaultBehavior){
Random rand = new Random();
int MIN = 25;
int MAX = 100;
String name = "HillBilly"+(char)(this.getNbUnits()%26+'a');
int[] position = this.getRandomPositionForUnit();
int weight = rand.nextInt((MAX - MIN) + 1) + MIN;
int agility = rand.nextInt((MAX - MIN) + 1) + MIN;
int strength = rand.nextInt((MAX - MIN) + 1) + MIN;
int toughness = rand.nextInt((MAX - MIN) + 1) + MIN;
Unit unit = new Unit(name,position,weight,agility,strength,toughness, enableDefaultBehavior);
return unit;
}
/*___________________________________________________________________
*___________________________________________________________________
* -----------------------ITEMS--------------------------------------
* --------------------CONTROLLING CLASS-----------------------------
*___________________________________________________________________
*___________________________________________________________________*/
/**
* Variable referencing a set collecting all the Items
* of this World.
*
* @Invar The referenced set is effective.
* | items != null
* @Invar Each Item registered in the referenced list is
* effective and not yet terminated.
* | for each item in items:
* | ( (item != null) &&
* | (! item.isTerminated()) )
*/
private Set<Item> items;
/**
* Check whether this World has the given Item as one of its
* Items.
*
* @param item
* The Item to check.
*/
@Basic
@Raw
public boolean hasAsItem(@Raw Item item) {
return items.contains(item);
}
/**
* Check whether this World can have the given Item
* as one of its Items.
*
* @param item
* The Item to check.
* @return True if and only if the given Item is effective
* and that Item is a valid Item for this World.
* | result == (item != null) && (item.canHaveAsWorld(this))
*/
@Raw
public boolean canHaveAsItem(Item item) {
return (item != null) && (item.canHaveAsWorld(this));
}
/**
* Check whether this World has proper Items attached to it.
*
* @return True if and only if this World can have each of the
* items attached to it as one of its Items,
* and if each of these Items references this World as
* the World to which they are attached.
* | for each item in items:
* | if (hasAsItem(item))
* | then canHaveAsItem(item) &&
* | (item.getWorld() == this)
*/
public boolean hasProperItems() {
for (Item item : this.items) {
if (!canHaveAsItem(item) || item.getWorld() != this)
return false;
}
return true;
}
/**
* Return the number of Items associated with this World.
*
* @return The total number of Items collected in this World.
*/
public int getNbItems() {
return items.size();
}
/**
* Add the given Item to the set of Items of this World.
*
* @param item
* The Item to be added.
*
* @post This World has the given Item as one of its items.
* @effect the item has this world as its world
* @throws IllegalArgumentException
* The world can not have this item as item
* or the item does already reference this world
*
*/
@Raw
public void addItem(Item item) throws IllegalArgumentException {
if(!this.canHaveAsItem(item) || item.getWorld() == this)
throw new IllegalArgumentException();
items.add(item);
item.setWorld(this);
}
/**
* Remove the given Item from the set of Items of this World.
*
* @param item
* The Item to be removed.
* @post This World no longer has the given Item as
* one of its items.
* | ! new.hasAsItem(item)
*
* @throws IllegalArgumentException
* |!this.hasAsItem(item) || item.getWorld() != this
*/
@Raw
public void removeItem(Item item) throws IllegalArgumentException {
if(!this.hasAsItem(item) || item.getWorld() != this)
throw new IllegalArgumentException();
items.remove(item);
item.setWorld(null);
}
//---------------------ADDITIONAL INSPECTORS
/**
* get a clone of the set of Items that belong to this world
*
* @return a clone of the set of Items that belong to this world
*/
@Basic
public Set<Item> getAllItems(){
Set<Item> allItems = new HashSet<>(items);
return allItems;
}
/**
* Returns all items located on the cube, if any.
*
* @param position
* The position of the cube
*
* @return
* A new ArrayList of all items with positions located on the cube.
*/
@Raw
public List<Item> getAllItemsOnPosition(int[] position) throws IllegalArgumentException {
if (!isValidPosition(position)) {
throw new IllegalArgumentException("Given position is invalid");
}
List<Item> AllItems = new ArrayList<Item>();
for (Item item : this.items) {
if (Utils.equals(position, Utils.getCubePosition(item.getPosition()))) {
AllItems.add(item);
}
}
return AllItems;
}
/**
* Returns a random item on the give position or null
*
* @param position
* The position of the cube
*
* @return
* A random item or null
*
* @effect
* | getAllItemsOnPosition(position)
*/
@Raw
public Item getItemOnPosition(int[] position) throws IllegalArgumentException{
List<Item> AllItems = getAllItemsOnPosition(position);
if(AllItems.isEmpty())
return null;
else
return AllItems.get(0);
}
//-------------------BOULDERS
/**
* Gives back all Boulders in this World.
*
* @return
* A new HashSet of all Boulders in this World.
*/
public Set<Boulder> getAllBoulders() {
Set<Boulder> result = new HashSet<Boulder>();
for (Item item : this.items) {
if (item instanceof Boulder) {
result.add((Boulder)item);
}
}
return result;
}
//--------------------LOGS
/**
* Gives back all Logs in this World.
*
* @return
* A new HashSet of all Logs in this World.
*/
public Set<Log> getAllLogs() {
Set<Log> result = new HashSet<Log>();
for (Item item : this.items) {
if (item instanceof Log) {
result.add((Log)item);
}
}
return result;
}
}
| true |
7f6e5ed296492f2042e3a3bbc6ae38689620298a | Java | MarinaFF2/TiendaPeliculas | /src/vistas/Loggin.java | UTF-8 | 12,910 | 2.046875 | 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 vistas;
import vistas.admin.BienvenidoAdmin;
import vistas.user.BienvenidoUser;
import datos.ConectorBD;
import java.awt.Color;
import javax.swing.JOptionPane;
import modulos.Usuarios;
import org.apache.commons.codec.digest.DigestUtils;
/**
*
* @author ff_ma
*/
public class Loggin extends javax.swing.JFrame {
/**
* Creates new form Loggin
*/
public Loggin() {
initComponents();
setLocationRelativeTo(null);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanelInicioSesion = new javax.swing.JPanel();
TextFUsuario = new javax.swing.JTextField();
TextPassPwd = new javax.swing.JPasswordField();
jLabelUser = new javax.swing.JLabel();
jLabelPwd = new javax.swing.JLabel();
jButtonIncioSesion = new javax.swing.JButton();
jLabelRegistrarse = new javax.swing.JLabel();
jLabelFotoLogo = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Inicio de sesión");
jPanelInicioSesion.setToolTipText("");
TextFUsuario.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
TextFUsuarioFocusLost(evt);
}
});
TextPassPwd.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
TextPassPwdFocusLost(evt);
}
});
jLabelUser.setText("Usuario:");
jLabelPwd.setText("Contraseña:");
jButtonIncioSesion.setText("Iniciar Sesión");
jButtonIncioSesion.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonIncioSesionActionPerformed(evt);
}
});
jLabelRegistrarse.setText("Registrarse...");
jLabelRegistrarse.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelRegistrarseMouseClicked(evt);
}
});
jLabelFotoLogo.setBackground(new java.awt.Color(51, 51, 255));
javax.swing.GroupLayout jPanelInicioSesionLayout = new javax.swing.GroupLayout(jPanelInicioSesion);
jPanelInicioSesion.setLayout(jPanelInicioSesionLayout);
jPanelInicioSesionLayout.setHorizontalGroup(
jPanelInicioSesionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelInicioSesionLayout.createSequentialGroup()
.addGap(125, 125, 125)
.addComponent(jButtonIncioSesion)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelInicioSesionLayout.createSequentialGroup()
.addContainerGap(47, Short.MAX_VALUE)
.addGroup(jPanelInicioSesionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelInicioSesionLayout.createSequentialGroup()
.addComponent(jLabelFotoLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelInicioSesionLayout.createSequentialGroup()
.addGroup(jPanelInicioSesionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelUser)
.addComponent(jLabelPwd)
.addComponent(jLabelRegistrarse))
.addGap(66, 66, 66)
.addGroup(jPanelInicioSesionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(TextPassPwd, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE)
.addComponent(TextFUsuario))
.addGap(81, 81, 81))))
);
jPanelInicioSesionLayout.setVerticalGroup(
jPanelInicioSesionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelInicioSesionLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelFotoLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27)
.addGroup(jPanelInicioSesionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(TextFUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelUser))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanelInicioSesionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(TextPassPwd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelPwd))
.addGap(19, 19, 19)
.addComponent(jLabelRegistrarse)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonIncioSesion)
.addContainerGap(39, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelInicioSesion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelInicioSesion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButtonIncioSesionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonIncioSesionActionPerformed
//comprobamos que ningún campo este vacío
if (TextPassPwd.getText().length() != 0 && TextFUsuario.getText().length() != 0) {
if (TextFUsuario.getText().contains("@") && TextFUsuario.getText().contains(".")) {
confirmar();
} else {
JOptionPane.showMessageDialog(null, "Error en el campo usuario, hay que introducir un correo", "Error al introducir el correo", JOptionPane.CLOSED_OPTION);
}
} else {
JOptionPane.showMessageDialog(null, "Error algún campo está vacío", "Error de campo vacío", JOptionPane.CLOSED_OPTION);
}
}//GEN-LAST:event_jButtonIncioSesionActionPerformed
private void jLabelRegistrarseMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelRegistrarseMouseClicked
JDialogRegistrarse regis = new JDialogRegistrarse(this, true);
regis.setLocationRelativeTo(null);
regis.setSize(400, 400);
regis.setVisible(true);
}//GEN-LAST:event_jLabelRegistrarseMouseClicked
private void TextPassPwdFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_TextPassPwdFocusLost
if (TextPassPwd.getText().length() == 0) {
TextPassPwd.setBackground(Color.red);
TextPassPwd.setForeground(Color.white);
} else {
TextPassPwd.setForeground(Color.black);
TextPassPwd.setBackground(Color.white);
}
}//GEN-LAST:event_TextPassPwdFocusLost
private void TextFUsuarioFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_TextFUsuarioFocusLost
if (TextFUsuario.getText().length() == 0 && !TextFUsuario.getText().contains("@") && !TextFUsuario.getText().contains(".")) {
TextFUsuario.setBackground(Color.red);
TextFUsuario.setForeground(Color.white);
}
if (TextFUsuario.getText().length() != 0 && TextFUsuario.getText().contains("@") && TextFUsuario.getText().contains(".")) {
TextFUsuario.setForeground(Color.black);
TextFUsuario.setBackground(Color.white);
}
}//GEN-LAST:event_TextFUsuarioFocusLost
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Loggin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Loggin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Loggin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Loggin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Loggin().setVisible(true);
}
});
}
private void confirmar() {
ConectorBD conectBD = new ConectorBD();
String usu = this.TextFUsuario.getText();
//contraseña codificada
String pwdmd5Hex = DigestUtils.md5Hex(TextPassPwd.getText());
conectBD.openBD();
Usuarios usuario = conectBD.existeUsuario(usu, pwdmd5Hex);
conectBD.closeBD();
if (usuario != null) {
if (usuario.getIdRol() == 1 && usuario.getActivo( )== 1) { //es usuario normal
//volvemos invisible esta venta
dispose();
//Redirigmos a BienvenidoUser
BienvenidoUser t = new BienvenidoUser(usuario);
t.setLocationRelativeTo(null);
t.setVisible(true);
} else if (usuario.getIdRol() == 2 && usuario.getActivo() == 1) { //es un admin
//volvemos invisible esta venta
dispose();
//Redirigmos a BienvenidoAdmin
BienvenidoAdmin t = new BienvenidoAdmin(usuario);
t.setLocationRelativeTo(null);
t.setVisible(true);
} else { // no tiene rol asigando o no está activado
JOptionPane.showMessageDialog(null, "Te tienen que activar el usuario", "Error de activación", JOptionPane.CLOSED_OPTION);
}
} else {
JOptionPane.showMessageDialog(null, "Error en el correo o la contraseña", "Error de autentificacion", JOptionPane.CLOSED_OPTION);
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField TextFUsuario;
private javax.swing.JPasswordField TextPassPwd;
private javax.swing.JButton jButtonIncioSesion;
private javax.swing.JLabel jLabelFotoLogo;
private javax.swing.JLabel jLabelPwd;
private javax.swing.JLabel jLabelRegistrarse;
private javax.swing.JLabel jLabelUser;
private javax.swing.JPanel jPanelInicioSesion;
// End of variables declaration//GEN-END:variables
}
| true |
c08f7918f6e35fcfcad85a7f3f6592b0ebe956b3 | Java | tischi/fiji-plugin-morphometry | /src/main/java/de/embl/cba/morphometry/microglia/MicrogliaMorphometrySettings.java | UTF-8 | 464 | 1.554688 | 2 | [] | no_license | package de.embl.cba.morphometry.microglia;
import net.imagej.ops.OpService;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.type.NativeType;
import net.imglib2.type.numeric.RealType;
import java.io.File;
public class MicrogliaMorphometrySettings<T extends RealType<T> & NativeType< T > >
{
public OpService opService;
public long labelMapChannelIndex = 2;
public double[] inputCalibration;
public boolean showIntermediateResults = false;
}
| true |
62b7396cabde875e40b1147c51fd0c1e91fc5c72 | Java | lz2003/Greenfoot-Tower-Defence | /LegendOfJayJay/Sprite.java | UTF-8 | 21,426 | 2.9375 | 3 | [] | no_license | import greenfoot.*;
import java.awt.image.BufferedImage;
import java.awt.geom.AffineTransform;
/**
* Sprites that will be rendered to the canvas
*
* @author Young Chen
* @author Lucy Zhao
* @version 2021-01-26
*/
public abstract class Sprite extends Updated{
private static Canvas globalCanvas;
static void setGlobalCanvas(Canvas c) {
globalCanvas = c;
}
private double xLoc, yLoc;
private int xLocInt, yLocInt;
private int zIndex = -1;
private Canvas canvas;
private BufferedImage image;
private double rot = 0;
private int width, height;
private int apparentWidth, apparentHeight;
private int layer = 0;
private double scaleX, scaleY;
private double alpha;
private boolean removed = false;
private Animation animation;
private float animationTimer = 0, animationDur = 1;
private int animFrame = 0;
/**
* Creates a sprite
* @param x x location
* @param y y location
* @param image image
*/
public Sprite(double x, double y, GreenfootImage image) {
if(globalCanvas == null) throw new Error("Global canvas has not been set. If no global " +
"canvas is to be desired, use alternate constructor of new Sprite(canvas, xLoc, yLoc, image)");
xLoc = x;
yLoc = y;
xLocInt = (int) (x + .5f);
yLocInt = (int) (y + .5f);
this.layer = layer;
globalCanvas.addSprite(this, layer);
canvas = globalCanvas;
initImage(image);
}
/**
* Creates a sprite
* @param x x location
* @param y y location
* @param image image
* @param layer draw layer; must be positive or zero integer
*/
public Sprite(double x, double y, GreenfootImage image, int layer) {
if(globalCanvas == null) throw new Error("Global canvas has not been set. If no global " +
"canvas is to be desired, use alternate constructor of new Sprite(canvas, xLoc, yLoc, image)");
xLoc = x;
yLoc = y;
xLocInt = (int) (x + .5f);
yLocInt = (int) (y + .5f);
this.layer = layer;
globalCanvas.addSprite(this, layer);
canvas = globalCanvas;
initImage(image);
}
/**
* Creates a sprite in a certain canvas
* @param c canvas
* @param x x location
* @param y y location
* @param image image
*/
public Sprite(Canvas c, double x, double y, GreenfootImage image) {
xLoc = x;
yLoc = y;
xLocInt = (int) (x + .5f);
yLocInt = (int) (y + .5f);
this.layer = layer;
c.addSprite(this, layer);
canvas = c;
initImage(image);
}
/**
* Creates a sprite in a certain canvas
* @param c canvas
* @param x x location
* @param y y location
* @param image image
* @param layer draw layer
*/
public Sprite(Canvas c, double x, double y, GreenfootImage image, int layer) {
xLoc = x;
yLoc = y;
xLocInt = (int) (x + .5f);
yLocInt = (int) (y + .5f);
this.layer = layer;
c.addSprite(this, layer);
canvas = c;
initImage(image);
}
/**
* Creates a sprite in a certain canvas
* @param c canvas
* @param x x location
* @param y y location
* @param image image
* @param height height
* @param width width
*/
public Sprite(Canvas c, double x, double y, GreenfootImage image, int width, int height) {
xLoc = x;
yLoc = y;
xLocInt = (int) (x + .5f);
yLocInt = (int) (y + .5f);
this.layer = layer;
c.addSprite(this, layer);
canvas = c;
initImage(image);
setWidth(width);
setHeight(height);
}
/**
* Creates a sprite in a certain canvas
* @param c canvas
* @param x x location
* @param y y location
* @param image image
* @param height height
* @param width width
* @param layer draw layer
*/
public Sprite(Canvas c, double x, double y, GreenfootImage image, int width, int height, int layer) {
xLoc = x;
yLoc = y;
xLocInt = (int) (x + .5f);
yLocInt = (int) (y + .5f);
this.layer = layer;
c.addSprite(this, layer);
canvas = c;
initImage(image);
setWidth(width);
setHeight(height);
}
/**
* Creates a sprite
* @param x x location
* @param y y location
* @param image image
* @param height height
* @param width width
*/
public Sprite(double x, double y, GreenfootImage image, int width, int height) {
if(globalCanvas == null) throw new Error("Global canvas has not been set. If no global " +
"canvas is to be desired, use alternate constructor of new Sprite(canvas, xLoc, yLoc, image)");
xLoc = x;
yLoc = y;
xLocInt = (int) (x + .5f);
yLocInt = (int) (y + .5f);
canvas = globalCanvas;
this.layer = layer;
canvas.addSprite(this, layer);
initImage(image);
setWidth(width);
setHeight(height);
}
/**
* Creates a sprite
* @param x x location
* @param y y location
* @param image image
* @param height height
* @param width width
* @param layer draw layer
*/
public Sprite(double x, double y, GreenfootImage image, int width, int height, int layer) {
if(globalCanvas == null) throw new Error("Global canvas has not been set. If no global " +
"canvas is to be desired, use alternate constructor of new Sprite(canvas, xLoc, yLoc, image)");
xLoc = x;
yLoc = y;
xLocInt = (int) (x + .5f);
yLocInt = (int) (y + .5f);
canvas = globalCanvas;
this.layer = layer;
canvas.addSprite(this, layer);
initImage(image);
setWidth(width);
setHeight(height);
}
/**
* Creates a sprite
* @param x x location
* @param y y location
* @param image image
* @param layer draw layer
*/
public Sprite(double x, double y, BufferedImage image, int layer) {
if(globalCanvas == null) throw new Error("Global canvas has not been set. If no global " +
"canvas is to be desired, use alternate constructor of new Sprite(canvas, xLoc, yLoc, image)");
xLoc = x;
yLoc = y;
xLocInt = (int) (x + .5f);
yLocInt = (int) (y + .5f);
this.layer = layer;
globalCanvas.addSprite(this, layer);
canvas = globalCanvas;
initImage(image);
}
/**
* Creates a sprite in a certain canvas
* @param c canvas
* @param x x location
* @param y y location
* @param image image
*/
public Sprite(Canvas c, double x, double y, BufferedImage image) {
xLoc = x;
yLoc = y;
xLocInt = (int) (x + .5f);
yLocInt = (int) (y + .5f);
this.layer = layer;
c.addSprite(this, layer);
canvas = c;
initImage(image);
}
/**
* Creates a sprite in a certain canvas
* @param c canvas
* @param x x location
* @param y y location
* @param image image
* @param layer draw layer
*/
public Sprite(Canvas c, double x, double y, BufferedImage image, int layer) {
xLoc = x;
yLoc = y;
xLocInt = (int) (x + .5f);
yLocInt = (int) (y + .5f);
this.layer = layer;
c.addSprite(this, layer);
canvas = c;
initImage(image);
}
/**
* Creates a sprite in a certain canvas
* @param c canvas
* @param x x location
* @param y y location
* @param image image
* @param height height
* @param width width
*/
public Sprite(Canvas c, double x, double y, BufferedImage image, int width, int height) {
xLoc = x;
yLoc = y;
xLocInt = (int) (x + .5f);
yLocInt = (int) (y + .5f);
this.layer = layer;
c.addSprite(this, layer);
canvas = c;
initImage(image);
setWidth(width);
setHeight(height);
}
/**
* Creates a sprite in a certain canvas
* @param c canvas
* @param x x location
* @param y y location
* @param image image
* @param height height
* @param width width
* @param layer draw layer
*/
public Sprite(Canvas c, double x, double y, BufferedImage image, int width, int height, int layer) {
xLoc = x;
yLoc = y;
xLocInt = (int) (x + .5f);
yLocInt = (int) (y + .5f);
this.layer = layer;
c.addSprite(this, layer);
canvas = c;
initImage(image);
setWidth(width);
setHeight(height);
}
/**
* Creates a sprite
* @param x x location
* @param y y location
* @param image image
* @param height height
* @param width width
*/
public Sprite(double x, double y, BufferedImage image, int width, int height) {
if(globalCanvas == null) throw new Error("Global canvas has not been set. If no global " +
"canvas is to be desired, use alternate constructor of new Sprite(canvas, xLoc, yLoc, image)");
xLoc = x;
yLoc = y;
xLocInt = (int) (x + .5f);
yLocInt = (int) (y + .5f);
canvas = globalCanvas;
this.layer = layer;
canvas.addSprite(this, layer);
initImage(image);
setWidth(width);
setHeight(height);
}
/**
* Creates a sprite
* @param x x location
* @param y y location
* @param image image
* @param height height
* @param width width
* @param layer draw layer
*/
public Sprite(double x, double y, BufferedImage image, int width, int height, int layer) {
if(globalCanvas == null) throw new Error("Global canvas has not been set. If no global " +
"canvas is to be desired, use alternate constructor of new Sprite(canvas, xLoc, yLoc, image)");
xLoc = x;
yLoc = y;
xLocInt = (int) (x + .5f);
yLocInt = (int) (y + .5f);
canvas = globalCanvas;
this.layer = layer;
canvas.addSprite(this, layer);
initImage(image);
setWidth(width);
setHeight(height);
}
/**
* Sets the sprite's location
* @param x x location
* @param y y location
*/
public void setLocation(double x, double y) {
canvas.removeSprite(this, layer);
xLoc = x;
yLoc = y;
xLocInt = (int) (x + .5f);
yLocInt = (int) (y + .5f);
canvas.addSprite(this, layer);
}
/**
* Sets the sprite's x location
* @param x x location
*/
public void setX(double x) {
setLocation(x, getY());
}
/**
* Sets the sprite's y location
* @param y y location
*/
public void setY(double y) {
setLocation(getX(), y);
}
/**
* Initialise the image
* @param image image
*/
private void initImage(GreenfootImage image) {
this.image = image.getAwtImage();
width = image.getWidth();
height = image.getHeight();
apparentWidth = width;
apparentHeight = height;
scaleX = 1;
scaleY = 1;
alpha = 1;
}
/**
* Initialise the image
* @param image image
*/
private void initImage(BufferedImage image) {
this.image = image;
width = image.getWidth();
height = image.getHeight();
apparentWidth = width;
apparentHeight = height;
scaleX = 1;
scaleY = 1;
alpha = 1;
}
/**
* Move in direction of rotation
* @param dist distance
*/
public void move(double dist) {
setLocation(getX() + Math.cos(rot) * dist, getY() + Math.sin(rot) * dist);
}
/**
* Move forward
* @param dist distance
* @param angle angle
*/
public void move(double dist, double angle) {
setLocation(getX() + Math.cos(angle) * dist, getY() + Math.sin(angle) * dist);
}
/**
* Get x location
* @return x location
*/
public double getX() {
return xLoc;
}
/**
* Get y location
* @return y location
*/
public double getY() {
return yLoc;
}
/**
* Get x location as an integer
* @return x location
*/
public int getIntX() {
return xLocInt;
}
/**
* Get y location as an integer
* @return y location
*/
public int getIntY() {
return yLocInt;
}
/**
* Get the image of the sprite
* @return image
*/
public BufferedImage getImage() {
return image;
}
/**
* Stores the z index value of the sprite. Does not change the layer or order it is drawn in.
*
* @param z z index
*/
public void setZ(int z) {
zIndex = z;
}
/**
* Get the z index
* @return z index
*/
public int getZ() {
return zIndex;
}
/**
* Sets the rotation
* @param rot angle
*/
public void setRotation(double rot) {
this.rot = rot;
}
/**
* Gets the rotation
* @return angle
*/
public double getRotation() {
return this.rot;
}
/**
* Turn towards a point
* @param x x location of point
* @param y y location of point
*/
public void turnTowards(double x, double y) {
this.setRotation(
Math.atan2((y - getY()), (x - getX()))
);
}
/**
* Move towards a point
* @param x x location of point
* @param y y location of point
* @param step distance to travel
*/
public void moveTowards(double x, double y, double step) {
double rotation = (
Math.atan2((y - getY()), (x - getX()))
);
move(step, rotation);
}
/**
* Get width of sprite
* @return width
*/
public int getWidth() {
return apparentWidth;
}
/**
* Get height of sprite
* @return height of sprite
*/
public int getHeight() {
return apparentHeight;
}
/**
* Set the scale of the sprite
* @param scale scale
*/
public void setScale(double scale) {
this.scaleX = scale;
this.scaleY = scale;
}
/**
* Set the width of the sprite
* @param width width
*/
public void setWidth(int width) {
scaleX = (double) width / (double) this.width;
this.apparentWidth = width;
}
/**
* Set the height of the sprite
* @param height height
*/
public void setHeight(int height) {
scaleY = (double) height / (double) this.height;
this.apparentHeight = height;
}
/**
* Gets whether or not a point is inside the sprite
* @param x x location of point
* @param y y location of point
* @return whether or not the point intersects
*/
public boolean isInsideImage(int x, int y){
return (getX() - apparentWidth/2) <=x && x <= (getX() + apparentWidth/2) && (getY() - apparentHeight/2) <= y && y <= (getY() + apparentHeight/2);
}
/**
* Set the dimensions of the sprite
* @param width width of sprite
* @param height height of sprite
*/
public void setDimensions(int width, int height) {
setWidth(width);
setHeight(height);
}
/**
* Set the dimensions of the sprite
* For compatability with the Greenfoot Actor class
*
* @param width width of sprite
* @param height height of sprite
*/
public void scale(int width, int height) {
setDimensions(width, height);
}
/**
* Sets the sprite's image
* @param image new image
*/
public void setImage(GreenfootImage image) {
this.image = image.getAwtImage();
width = image.getWidth();
height = image.getHeight();
setDimensions(apparentWidth, apparentHeight);
}
/**
* Sets the sprite's image
* @param image new image
* @param keepPreviousState whether to keep previous dimensions
*/
public void setImage(GreenfootImage image, boolean keepPreviousState) {
if(keepPreviousState) setImage(image);
else initImage(image);
}
/**
* Set the sprite's image
* @param image new image
*/
public void setImage(BufferedImage image) {
this.image = image;
width = image.getWidth();
height = image.getHeight();
setDimensions(apparentWidth, apparentHeight);
}
/**
* Sets the sprite's image
* @param image new image
* @param keepPreviousState whether to keep previous dimensions
*/
public void setImage(BufferedImage image, boolean keepPreviousState) {
if(keepPreviousState) setImage(image);
else initImage(image);
}
/**
* Change width
* @param delta amount to change by
*/
public void changeWidth(int delta) {
setWidth(getWidth() + delta);
}
/**
* Change height
* @param delta amount to change by
*/
public void changeHeight(int delta) {
setHeight(getHeight() + delta);
}
/**
* Get width of image
* @return width
*/
public int getImageWidth() {
return width;
}
/**
* Get height of image
* @return height
*/
public int getImageHeight() {
return height;
}
/**
* Get sprite horizontal image scale
* @return scale
*/
public double getScaleX() {
return scaleX;
}
/**
* Get sprite vertical image scale
* @return scale
*/
public double getScaleY() {
return scaleY;
}
/**
* Set the sprite's alpha
* @param alpha new alpha
*/
public void setTransparency(double alpha) {
this.alpha = alpha;
}
/**
* Gets the sprite's alpha
* @return alpha
*/
public double getTransparency() {
return alpha;
}
/**
* Removes the sprite from the canvas
*/
public void removeSprite() {
canvas.removeSprite(this, layer);
removed = true;
}
/**
* Whether or not the sprite has been removed
* @return Whether or not the sprite has been removed
*/
public boolean isRemoved() {
return removed;
}
/**
* Sets the sprite's animation
* @param animation animation
*/
public void setAnimation(Animation animation) {
this.animation = animation;
}
/**
* Sets the sprite's animation
* @param animation animation
* @param time time between frames
*/
public void setAnimation(Animation animation, float time) {
this.animation = animation;
setAnimationFrameTime(time);
}
/**
* Sets the time between animation frames
* @param time time between frames
*/
public void setAnimationFrameTime(float time) {
animationDur = time;
}
/**
* Animates the sprite
* @param delta change in time since last update
*/
public void animate(float delta) {
animationTimer += delta;
if(animationTimer > animationDur) {
animationTimer = 0;
nextFrameLooped();
}
}
/**
* Set the current frame's index
* @param frame index
*/
public void setFrameIndex(int frame) {
animFrame = frame;
}
/**
* Get the current frame's index
* @return index
*/
public int getFrameIndex() {
return animFrame;
}
/**
* Get total number of frames
* @return number of frames
*/
public int getFrameCount() {
return animation.getFrameCount();
}
/**
* Change to next frame
*/
public void nextFrame() {
setImage(animation.getFrame(++this.animFrame));
}
/**
* Change to next frame and loop back to first frame when it has reached the last frame
*/
public void nextFrameLooped() {
if(animation != null) {
animFrame++;
if(animFrame >= animation.getFrameCount()) animFrame = 0;
setImage(animation.getFrame(this.animFrame));
}
}
}
/**
* Class to contain animations
*
* @author Young Chen
* @version 2021-01-26
*/
class Animation {
private BufferedImage[] frames;
/**
* Creates an animation object
* @param frames animation frames
*/
public Animation(GreenfootImage[] frames) {
this.frames = new BufferedImage[frames.length];
for(int i = 0; i < frames.length; i++) {
this.frames[i] = frames[i].getAwtImage();
}
}
/**
* Creates an animation object
* @param frames animation frames
*/
public Animation(BufferedImage[] frames) {
this.frames = frames;
}
/**
* Gets a frame at the indicated index
* @param index index
* @return frame
*/
public BufferedImage getFrame(int index) {
return this.frames[index];
}
/**
* Get total number of frames
* @return frames
*/
public int getFrameCount() {
return frames.length;
}
}
| true |
b5ae25bd6c9d02fa6c7811ec80f762219619923a | Java | kimsjzzz/team2 | /src/main/java/dev/mvc/paydescript/PaydescriptVO.java | UHC | 4,219 | 2.1875 | 2 | [] | no_license | package dev.mvc.paydescript;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class PaydescriptVO {
/* paydescriptno NUMBER(10) NOT NULL,
employeeno NUMBER(10) NOT NULL,
employee_name VARCHAR(10) NOT NULL,
department_name VARCHAR(10) NOT NULL,
pay NUMBER(10) NOT NULL,
insentive NUMBER(10) NOT NULL,
team_pay NUMBER(10) NOT NULL,
perfect_pay NUMBER(10) NOT NULL,
total NUMBER(10) NOT NULL,
insurance NUMBER(10) NOT NULL,
incometax NUMBER(10) NOT NULL,
real_pay NUMBER(10) NOT NULL,
month VARCHAR(10) NOT NULL,
payment_day VARCHAR(10) NOT NULL,
*/
/** ȣ */
private int paydescriptno;
/** ȣ */
private int employeeno;
/** ̸ */
private String employee_name;
/** μ̸ */
private String department_name;
/** ⺻ */
private int pay;
/** */
private int insentive;
/** */
private int team_pay;
/** ٺ */
private int perfect_pay;
/** ѱݾ */
private int total;
/** 4뺸(4%) */
private int insurance;
/** ռҵ漼(10%) */
private int incometax;
/** Ǽɾ */
private int real_pay;
/** */
private String month;
/** */
private String payment_day;
/** ̹ */
private String file1= "";
/**
Spring Framework ڵ ԵǴ ε ü,
DBMS ÷ ʰ ӽ .
*/
private MultipartFile file1MF;
public int getPaydescriptno() {
return paydescriptno;
}
public void setPaydescriptno(int paydescriptno) {
this.paydescriptno = paydescriptno;
}
public int getEmployeeno() {
return employeeno;
}
public void setEmployeeno(int employeeno) {
this.employeeno = employeeno;
}
public String getEmployee_name() {
return employee_name;
}
public void setEmployee_name(String employee_name) {
this.employee_name = employee_name;
}
public String getDepartment_name() {
return department_name;
}
public void setDepartment_name(String department_name) {
this.department_name = department_name;
}
public int getPay() {
return pay;
}
public void setPay(int pay) {
this.pay = pay;
}
public int getInsentive() {
return insentive;
}
public void setInsentive(int insentive) {
this.insentive = insentive;
}
public int getTeam_pay() {
return team_pay;
}
public void setTeam_pay(int team_pay) {
this.team_pay = team_pay;
}
public int getPerfect_pay() {
return perfect_pay;
}
public void setPerfect_pay(int perfect_pay) {
this.perfect_pay = perfect_pay;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getInsurance() {
return insurance;
}
public void setInsurance(int insurance) {
this.insurance = insurance;
}
public int getIncometax() {
return incometax;
}
public void setIncometax(int incometax) {
this.incometax = incometax;
}
public int getReal_pay() {
return real_pay;
}
public void setReal_pay(int real_pay) {
this.real_pay = real_pay;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public String getPayment_day() {
return payment_day;
}
public void setPayment_day(String payment_day) {
this.payment_day = payment_day;
}
public String getFile1() {
return file1;
}
public void setFile1(String file1) {
this.file1 = file1;
}
public MultipartFile getFile1MF() {
return file1MF;
}
public void setFile1MF(MultipartFile file1mf) {
file1MF = file1mf;
}
}
| true |
201673075d2626a8b307ad76b7b1236ab6b589cd | Java | FedericoCoppo/JavaProcessing | /myProject/LocationTester.java | UTF-8 | 675 | 3.421875 | 3 | [] | no_license | package myProject;
public class LocationTester
{
public static void main(String []args)
{
System.out.println("Hello World!");
SimpleLocation champoluc = new SimpleLocation(45.8316 , 7.7263);
SimpleLocation cervinia = new SimpleLocation(45.937, 7.6297);
System.out.println("Distance between champoluc and cervinia " + champoluc.distance(cervinia) + "Km");
double[] coords = {50.0, 0.0};
ArrayLocation accra = new ArrayLocation(coords);
coords[0] = 25; // you are allowed to change the value of accra obj outside the obj!
System.out.println(accra.GetCoord().clone()[0]);
System.out.println("End of the program");
}
}
| true |
f7ba005474ec6b0c0aa7a4e5c6de318e3778acc5 | Java | GYiyouth/ECollaboration | /src/bean/domain/MessageBean.java | UTF-8 | 1,314 | 2.140625 | 2 | [] | no_license | package bean.domain;
public class MessageBean {
private Integer id;
private String title;
private String content;
private String createTime;
private Integer senderId;
private Integer readFlag;//是否收件人都阅读了
private String deadDate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public Integer getSenderId() {
return senderId;
}
public void setSenderId(Integer senderId) {
this.senderId = senderId;
}
public Integer getReadFlag() {
return readFlag;
}
public void setReadFlag(Integer readFlag) {
this.readFlag = readFlag;
}
public String getDeadDate() {
return deadDate;
}
public void setDeadDate(String deadDate) {
this.deadDate = deadDate;
}
}
| true |
2446dde565f476c7a182d95722ff796cae0e3a65 | Java | chdtu-fitis/deanoffice-backend | /src/main/java/ua/edu/chdtu/deanoffice/service/datasync/edebo/student/EdeboStudentDataSynchronizationServiceImpl.java | UTF-8 | 32,257 | 1.890625 | 2 | [] | no_license | package ua.edu.chdtu.deanoffice.service.datasync.edebo.student;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import ua.edu.chdtu.deanoffice.entity.*;
import ua.edu.chdtu.deanoffice.entity.superclasses.Sex;
import ua.edu.chdtu.deanoffice.service.DegreeService;
import ua.edu.chdtu.deanoffice.service.FacultyService;
import ua.edu.chdtu.deanoffice.service.SpecialityService;
import ua.edu.chdtu.deanoffice.service.SpecializationService;
import ua.edu.chdtu.deanoffice.service.StudentDegreeService;
import ua.edu.chdtu.deanoffice.service.StudentService;
import ua.edu.chdtu.deanoffice.service.datasync.edebo.student.beans.StudentDegreePrimaryDataBean;
import ua.edu.chdtu.deanoffice.service.datasync.edebo.student.beans.MissingPrimaryDataRedMessageBean;
import ua.edu.chdtu.deanoffice.service.datasync.edebo.student.beans.StudentDegreePrimaryDataWithGroupBean;
import ua.edu.chdtu.deanoffice.service.document.DocumentIOService;
import ua.edu.chdtu.deanoffice.util.FacultyUtil;
import ua.edu.chdtu.deanoffice.util.comparators.EntityUtil;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public abstract class EdeboStudentDataSynchronizationServiceImpl implements EdeboStudentDataSyncronizationService {
private static final String SPECIALIZATION_REGEXP = "([\\d]+\\.[\\d]+)\\s([\\w\\W]+)";
private static final String SPECIALITY_REGEXP_OLD = "([\\d]\\.[\\d]+)\\s([\\w\\W]+)";
private static final String SPECIALITY_REGEXP_NEW = "([\\d]{3})\\s([\\w\\W]+)";
private static final String ADMISSION_REGEXP = "Номер[\\s]+наказу[\\s:]+([\\w\\W]+);[\\W\\w]+Дата[\\s]+наказу[\\s:]*([0-9]{2}.[0-9]{2}.[0-9]{4})";
private static final String EXPEL_DATE_REGEXP = "[\\W\\w]+Дата[\\s]+відрахування[\\s:]*([0-9]{2}.[0-9]{2}.[0-9]{4})";
private static final String STUDENT_PREVIOUS_UNIVERSITY_FIELDS_TO_COMPARE[] = {"universityName", "studyStartDate", "studyEndDate"};
private static final String SECONDARY_STUDENT_DEGREE_FIELDS_TO_COMPARE[] = {"payment", "tuitionForm", "citizenship", "previousDiplomaNumber", "previousDiplomaDate",
"previousDiplomaType", "previousDiplomaIssuedBy", "edeboId", "admissionDate", "admissionOrderNumber", "admissionOrderDate"};
private static final String SECONDARY_STUDENT_FIELDS_TO_COMPARE[] = {
"surnameEng", "nameEng", "sex"};
protected static Logger log = LoggerFactory.getLogger(EdeboStudentDataSynchronizationServiceImpl.class);
protected final DocumentIOService documentIOService;
private final StudentService studentService;
private final StudentDegreeService studentDegreeService;
private final DegreeService degreeService;
private final FacultyService facultyService;
private final SpecialityService specialityService;
private final SpecializationService specializationService;
@Autowired
public EdeboStudentDataSynchronizationServiceImpl(DocumentIOService documentIOService, StudentService studentService, StudentDegreeService studentDegreeService,
DegreeService degreeService, SpecialityService specialityService, SpecializationService specializationService,
FacultyService facultyService) {
this.documentIOService = documentIOService;
this.studentService = studentService;
this.studentDegreeService = studentDegreeService;
this.degreeService = degreeService;
this.specialityService = specialityService;
this.specializationService = specializationService;
this.facultyService = facultyService;
}
protected abstract List<ImportedData> getStudentDegreesFromStream(InputStream inputStream) throws IOException;
@Override
public EdeboStudentDataSynchronizationReport getEdeboDataSynchronizationReport(InputStream inputStream, int facultyId, Map<String, String> selectionParams) throws Exception {
if (inputStream == null)
throw new Exception("Помилка читання файлу");
try {
List<ImportedData> importedData = getStudentDegreesFromStream(inputStream);
Objects.requireNonNull(importedData);
EdeboStudentDataSynchronizationReport edeboDataSyncronizationReport = new EdeboStudentDataSynchronizationReport();
for (ImportedData data : importedData) {
addSynchronizationReportForImportedData(data, edeboDataSyncronizationReport, facultyId, selectionParams);
}
getAllIdForAbsentInFileStudentDegrees(edeboDataSyncronizationReport, selectionParams, facultyId);
sortingSyncohronizedDegreeGreen(edeboDataSyncronizationReport);
sortingAbsentInFileStudentDegreeYellow(edeboDataSyncronizationReport);
sortingMissingPrimaryDataRed(edeboDataSyncronizationReport);
sortingNoSuchStudentOrStudentDegreeInDbOrange(edeboDataSyncronizationReport);
return edeboDataSyncronizationReport;
} catch (IOException e) {
e.printStackTrace();
throw new Exception("Помилка читання файлу");
} finally {
inputStream.close();
}
}
@Override
public boolean isCriticalDataAvailable(StudentDegree studentDegree) throws RuntimeException {
List<String> necessaryNotEmptyStudentDegreeData = new ArrayList<>();
Specialization specialization = studentDegree.getSpecialization();
Student student = studentDegree.getStudent();
String specialityName = specialization.getSpeciality().getName();
necessaryNotEmptyStudentDegreeData.add(student.getSurname());
necessaryNotEmptyStudentDegreeData.add(student.getName());
necessaryNotEmptyStudentDegreeData.add(specialization.getDegree().getName());
necessaryNotEmptyStudentDegreeData.add(specialization.getFaculty().getName());
for (String s : necessaryNotEmptyStudentDegreeData) {
if (Strings.isNullOrEmpty(s)) {
return false;
}
}
if (student.getBirthDate() == null || Strings.isNullOrEmpty(specialityName) ||
studentDegree.getSpecialization().getDegree() == null) {
return false;
}
return true;
}
private boolean isSpecialityPatternMatch(ImportedData importedData) {
String specialityName = importedData.getFullSpecialityName();
Pattern specialityPattern = Pattern.compile(SPECIALITY_REGEXP_NEW);
Matcher specialityMatcher = specialityPattern.matcher(specialityName);
if (specialityMatcher.matches()) {
return true;
} else {
return false;
}
}
@Override
public Student getStudentFromData(ImportedData data) {
Student student = new Student();
Date birthDate = parseDate(data.getBirthday());
student.setBirthDate(birthDate);
student.setName(data.getFirstName());
student.setSurname(data.getLastName());
student.setPatronimic(data.getMiddleName());
student.setNameEng(data.getFirstNameEn());
student.setSurnameEng(data.getLastNameEn());
student.setSex("Чоловіча".equals(data.getPersonsSexName()) ? Sex.MALE : Sex.FEMALE);
return student;
}
@Override
public Speciality getSpecialityFromData(ImportedData data) {
Speciality speciality = new Speciality();
String specialityNameWithCode = data.getFullSpecialityName();
String specialityCode = "";
String specialityName = "";
Pattern specialityPattern;
if (specialityNameWithCode.matches(SPECIALITY_REGEXP_OLD)) {
specialityPattern = Pattern.compile(SPECIALITY_REGEXP_OLD);
} else {
specialityPattern = Pattern.compile(SPECIALITY_REGEXP_NEW);
}
Matcher matcher = specialityPattern.matcher(specialityNameWithCode);
if (matcher.matches() && matcher.groupCount() > 1) {
specialityCode = matcher.group(1).trim();
specialityName = matcher.group(2).trim();
}
speciality.setCode(specialityCode);
speciality.setName(specialityName);
return speciality;
}
@Override
public Specialization getSpecializationFromData(ImportedData data) {
Specialization specialization = new Specialization();
specialization.setName("");
specialization.setCode("");
Speciality speciality = getSpecialityFromData(data);
specialization.setSpeciality(speciality);
Faculty faculty = new Faculty();
if ((speciality.getCode() + " " + speciality.getName()).matches(SPECIALITY_REGEXP_NEW)) {
specialization.setName(data.getProgramName());
}
specialization.setDegree(DegreeEnum.getDegreeFromEnumByName(data.getQualificationGroupName()));
faculty.setName(data.getFacultyName());
specialization.setFaculty(faculty);
return specialization;
}
@Override
public StudentPreviousUniversity getStudentPreviousUniversityFromData(ImportedData data) {
StudentPreviousUniversity studentPreviousUniversity = null;
if (!Strings.isNullOrEmpty(data.getUniversityFrom()) && !Strings.isNullOrEmpty(data.getEduFromInfo())) {
studentPreviousUniversity = new StudentPreviousUniversity();
studentPreviousUniversity.setUniversityName(data.getUniversityFrom());
studentPreviousUniversity.setStudyStartDate(parseDate(data.getEducationDateBegin()));
studentPreviousUniversity.setStudyEndDate(getExpelDateFromPreviousUniversity(data.getEduFromInfo()));
}
return studentPreviousUniversity;
}
private Date getExpelDateFromPreviousUniversity(String eduFromInfo) {
Date deductionDateFromPreviousUniversity = null;
DateFormat deductionDateFormatter = new SimpleDateFormat("dd.MM.yyyy");
Pattern pattern = Pattern.compile(EXPEL_DATE_REGEXP);
Matcher matcher = pattern.matcher(eduFromInfo);
try {
if (matcher.find()) {
deductionDateFromPreviousUniversity = matcher.groupCount() > 0 ? deductionDateFormatter.parse(matcher.group(1)) : null;
}
} catch (ParseException e) {
log.debug(e.getMessage());
}
return deductionDateFromPreviousUniversity;
}
@Override
public StudentDegree getStudentDegreeFromData(ImportedData data) {
Student student = getStudentFromData(data);
Specialization specialization = getSpecializationFromData(data); //getSpeciality inside
StudentDegree studentDegree = new StudentDegree();
studentDegree.setActive(true);
studentDegree.setStudent(student);
studentDegree.setSpecialization(specialization);
if (getStudentPreviousUniversityFromData(data) != null) {
Set<StudentPreviousUniversity> studentPreviousUniversities = new HashSet<>();
studentPreviousUniversities.add(getStudentPreviousUniversityFromData(data));
studentDegree.setStudentPreviousUniversities(studentPreviousUniversities);
}
studentDegree.setEdeboId(data.getEducationId());
studentDegree.setPayment(Payment.getPaymentFromUkrName(data.getPersonEducationPaymentTypeName()));
studentDegree.setTuitionForm(TuitionForm.getTuitionFormFromUkrName(data.getEducationFormName()));
if (data.getIsShortened().toUpperCase().equals("ТАК"))
studentDegree.setTuitionTerm(TuitionTerm.SHORTENED);//(evaluateTuitionTermGuess(data.getEducationDateBegin(), data.getEducationDateEnd()));
else
studentDegree.setTuitionTerm(TuitionTerm.REGULAR);
String previousEducationInfo[] = data.getEduDocInfo().split(";");
for (int i = 0; i < previousEducationInfo.length; i++) previousEducationInfo[i] = previousEducationInfo[i].trim();
if (previousEducationInfo.length > 0) {
if (previousEducationInfo[0].indexOf('(') > 0)
previousEducationInfo[0] = previousEducationInfo[0].substring(0, previousEducationInfo[0].indexOf('(')).trim();
studentDegree.setPreviousDiplomaType(EducationDocument.getEducationDocumentByName(previousEducationInfo[0]));
}
if (previousEducationInfo.length > 1 && !previousEducationInfo[1].equals("")) {
String number[] = previousEducationInfo[1].split(" ");
if (number.length > 1)
studentDegree.setPreviousDiplomaNumber(number[0] + " № " + number[1]);
else
studentDegree.setPreviousDiplomaNumber(number[0]);
}
try {
studentDegree.setPreviousDiplomaDate(new SimpleDateFormat("dd.MM.yyyy").parse(previousEducationInfo[2]));
} catch(Exception e) {}
if (previousEducationInfo.length > 3) {
String parts[] = previousEducationInfo[3].split(":");
if (parts[1] != null) studentDegree.setPreviousDiplomaIssuedBy(parts[1].trim());
}
studentDegree.setAdmissionDate(parseDate(data.getEducationDateBegin()));
Map<String, Object> admissionOrderNumberAndDate = getAdmissionOrderNumberAndDate(data.getRefillInfo());
studentDegree.setAdmissionOrderNumber((String) admissionOrderNumberAndDate.get("admissionOrderNumber"));
studentDegree.setAdmissionOrderDate((Date) admissionOrderNumberAndDate.get("admissionOrderDate"));
if (!data.getCountry().equals(""))
studentDegree.setCitizenship(Citizenship.getCitizenshipByCountryUkrName(data.getCountry()));
else
studentDegree.setCitizenship(Citizenship.UKR);
return studentDegree;
}
private int getYearFromDateStringInImportedFile(String date) {
int i = date.lastIndexOf('/');
return Integer.parseInt(date.substring(i+1, i+3));
}
private TuitionTerm evaluateTuitionTermGuess(String educationBeginDate, String educationEndDate) {
int educationDuration = getYearFromDateStringInImportedFile(educationEndDate) - getYearFromDateStringInImportedFile(educationBeginDate);
if (educationDuration <= 3)
return TuitionTerm.SHORTENED;
else
return TuitionTerm.REGULAR;
}
public Map<String, Object> getAdmissionOrderNumberAndDate(String refillInfo) {
Map<String, Object> admissionOrderNumberAndDate = new HashMap<>();
DateFormat admissionOrderDateFormatter = new SimpleDateFormat("dd.MM.yyyy");
Pattern admissionPattern = Pattern.compile(ADMISSION_REGEXP);
try {
Matcher matcher = admissionPattern.matcher(refillInfo);
if (matcher.find()) {
admissionOrderNumberAndDate.put("admissionOrderNumber", matcher.groupCount() > 0 ? matcher.group(1).trim() : "");
Date admissionOrderDate = matcher.groupCount() > 1 ? admissionOrderDateFormatter.parse(matcher.group(2).trim()) : null;
admissionOrderNumberAndDate.put("admissionOrderDate", admissionOrderDate);
return admissionOrderNumberAndDate;
}
} catch (ParseException e) {
log.debug(e.getMessage());
} catch (IllegalStateException e) {
log.debug(e.getMessage());
}
return admissionOrderNumberAndDate;
}
@Override
public void addSynchronizationReportForImportedData(ImportedData importedData, EdeboStudentDataSynchronizationReport edeboDataSyncronizationReport, int facultyId, Map<String, String> selectionParams) {
if ((!(selectionParams.get("faculty").toUpperCase().equals(importedData.getFacultyName().toUpperCase())) && FacultyUtil.getUserFacultyIdInt()!=12)
|| !(selectionParams.get("degree") == null || selectionParams.get("degree").toUpperCase().equals(importedData.getQualificationGroupName().toUpperCase()))
|| !(selectionParams.get("speciality") == null || selectionParams.get("speciality").toUpperCase().equals(importedData.getFullSpecialityName().toUpperCase()))
)
return;
StudentDegree studentDegreeFromData;
if (isSpecialityPatternMatch(importedData)) {
studentDegreeFromData = getStudentDegreeFromData(importedData);
if (!isCriticalDataAvailable(studentDegreeFromData)) {
String message = "Недостатньо інформації для синхронізації";
edeboDataSyncronizationReport.addMissingPrimaryDataRed(new MissingPrimaryDataRedMessageBean(message, new StudentDegreePrimaryDataBean(importedData)));
return;
}
} else {
String message = "Неправильна освітня програма";
edeboDataSyncronizationReport.addMissingPrimaryDataRed(new MissingPrimaryDataRedMessageBean(message, new StudentDegreePrimaryDataBean(importedData)));
return;
}
Specialization specializationFromData = studentDegreeFromData.getSpecialization();
Faculty facultyFromDb = facultyService.getByName(specializationFromData.getFaculty().getName());
if (facultyFromDb == null) {
String message = "Даний факультет відсутній";
edeboDataSyncronizationReport.addMissingPrimaryDataRed(new MissingPrimaryDataRedMessageBean(message, new StudentDegreePrimaryDataBean(importedData)));
return;
}
Speciality specialityFromDb = specialityService.findSpecialityByCodeAndName(specializationFromData.getSpeciality().getCode(),
specializationFromData.getSpeciality().getName());
if (specialityFromDb == null) {
String message = "Дана спеціальність відсутня";
edeboDataSyncronizationReport.addMissingPrimaryDataRed(new MissingPrimaryDataRedMessageBean(message, new StudentDegreePrimaryDataBean(importedData)));
return;
}
Specialization specializationFromDB = specializationService.getByNameAndDegreeAndSpecialityAndFaculty(
specializationFromData.getName(),
specializationFromData.getDegree().getId(),
specialityFromDb.getId(),
facultyFromDb.getId());
if (specializationFromDB == null) {
if (Strings.isNullOrEmpty(specializationFromData.getName()) && specialityFromDb.getCode().length() == 3) {
List<Specialization> specialitySpecializations = specializationService.getAllActiveBySpecialityAndDegree(specialityFromDb.getId(), facultyId, specializationFromData.getDegree().getId());
if (specialitySpecializations.size() >= 0) {
specializationFromDB = specialitySpecializations.get(0);
}
}
}
if (specializationFromDB == null) {
String message = "Дана освітня програма відсутня";
edeboDataSyncronizationReport.addMissingPrimaryDataRed(new MissingPrimaryDataRedMessageBean(message, new StudentDegreePrimaryDataBean(importedData)));
return;
}
studentDegreeFromData.setSpecialization(specializationFromDB);
Set<StudentPreviousUniversity> studentPreviousUniversityFromData = studentDegreeFromData.getStudentPreviousUniversities();
if (studentPreviousUniversityFromData.size() != 0) {
Iterator<StudentPreviousUniversity> iterator = studentPreviousUniversityFromData.iterator();
StudentPreviousUniversity studentPreviousUniversity = iterator.next();
if (studentPreviousUniversity.getStudyStartDate() == null) {
String message = "Відсутня дата початку навчання в попередньому ВНЗ";
edeboDataSyncronizationReport.addMissingPrimaryDataRed(new MissingPrimaryDataRedMessageBean(
message,
new StudentDegreePrimaryDataBean(importedData))
);
return;
}
if (studentPreviousUniversity.getStudyEndDate() == null) {
String message = "Відсутня дата закінчення навчання попереднього ВНЗ";
edeboDataSyncronizationReport.addMissingPrimaryDataRed(new MissingPrimaryDataRedMessageBean(
message,
new StudentDegreePrimaryDataBean(importedData))
);
return;
}
if (Strings.isNullOrEmpty(studentPreviousUniversity.getUniversityName())) {
String message = "Відсутня назва попереднього ВНЗ";
edeboDataSyncronizationReport.addMissingPrimaryDataRed(new MissingPrimaryDataRedMessageBean(
message,
new StudentDegreePrimaryDataBean(importedData))
);
return;
}
}
Student studentFromData = studentDegreeFromData.getStudent();
Student studentFromDB = studentService.searchByFullNameAndBirthDate(
studentFromData.getName(),
studentFromData.getSurname(),
studentFromData.getPatronimic(),
studentFromData.getBirthDate()
);
if (studentFromDB == null) {
edeboDataSyncronizationReport.addNoSuchStudentOrStudentDegreeInDbOrange(studentDegreeFromData);
return;
}
studentDegreeFromData.getStudent().setId(studentFromDB.getId());
StudentDegree studentDegreeFromDb = studentDegreeService.getByStudentIdAndSpecializationId(true, studentFromDB.getId(), specializationFromDB.getId());
if (studentDegreeFromDb == null) {
edeboDataSyncronizationReport.addNoSuchStudentOrStudentDegreeInDbOrange(studentDegreeFromData);
return;
}
if (isSecondaryFieldsMatch(studentDegreeFromData, studentDegreeFromDb) &&
isPreviousUniversityFieldsMatch(studentDegreeFromData.getStudentPreviousUniversities(), studentDegreeFromDb.getStudentPreviousUniversities())) {
edeboDataSyncronizationReport.addSyncohronizedDegreeGreen(new StudentDegreePrimaryDataWithGroupBean(studentDegreeFromDb));
} else {
edeboDataSyncronizationReport.addUnmatchedSecondaryDataStudentDegreeBlue(studentDegreeFromData, studentDegreeFromDb);
}
}
public boolean isSecondaryFieldsMatch(StudentDegree studentDegreeFromFile, StudentDegree studentDegreeFromDb) {
return (EntityUtil.isValuesOfFieldsReturnedByGettersMatch(studentDegreeFromFile, studentDegreeFromDb, SECONDARY_STUDENT_DEGREE_FIELDS_TO_COMPARE) &&
EntityUtil.isValuesOfFieldsReturnedByGettersMatch(studentDegreeFromFile.getStudent(), studentDegreeFromDb.getStudent(), SECONDARY_STUDENT_FIELDS_TO_COMPARE));
}
private boolean isPreviousUniversityFieldsMatch(Set<StudentPreviousUniversity> studentPreviousUniversityFromFile,
Set<StudentPreviousUniversity> studentPreviousUniversityFromDb) {
if (studentPreviousUniversityFromDb.size() == 0 && studentPreviousUniversityFromFile.size() == 0) {
return true;
}
for (StudentPreviousUniversity universityFromFile : studentPreviousUniversityFromFile) {
for (StudentPreviousUniversity universityFromDb : studentPreviousUniversityFromDb) {
if (EntityUtil.isValuesOfFieldsReturnedByGettersMatch(universityFromFile, universityFromDb, STUDENT_PREVIOUS_UNIVERSITY_FIELDS_TO_COMPARE)) {
return true;
}
}
}
return false;
}
private void getAllIdForAbsentInFileStudentDegrees(EdeboStudentDataSynchronizationReport edeboDataSyncronizationReport,
Map<String, String> selectionParams,
int facultyId) {
List<Integer> idNotForAbsentInFileStudentDegrees = edeboDataSyncronizationReport.getSynchronizedStudentDegreesGreen().stream().
map(studentDegree -> studentDegree.getId()).collect(Collectors.toList());
idNotForAbsentInFileStudentDegrees.addAll(edeboDataSyncronizationReport.getUnmatchedSecondaryDataStudentDegreesBlue().stream().
map(studentDegree -> studentDegree.getStudentDegreeFromDb().getId()).collect(Collectors.toList()));
int degreeId = 0;
if (selectionParams.get("degree") != null) {
degreeId = degreeService.getByName(selectionParams.get("degree")).getId();
}
int specialityId = 0;
if (selectionParams.get("speciality") != null) {
String code = "", name = "";
String specialityParts[] = selectionParams.get("speciality").split(" ", 2);
if (specialityParts.length == 2) {
code = specialityParts[0];
name = specialityParts[1];
specialityId = specialityService.findSpecialityByCodeAndName(code, name).getId();
}
}
List<StudentDegree> studentDegrees = studentDegreeService.getAllNotInImportData(idNotForAbsentInFileStudentDegrees, facultyId, degreeId, specialityId);
for (StudentDegree studentDegree : studentDegrees) {
edeboDataSyncronizationReport.addAbsentInFileStudentDegreeYellow(new StudentDegreePrimaryDataWithGroupBean(studentDegree));
}
}
private Date parseDate(String fileDate) {
try {
DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
formatter.setTimeZone(TimeZone.getTimeZone("EET"));
return formatter.parse(fileDate);
} catch (ParseException e) {
log.debug(e.getMessage());
}
return null;
}
private void sortingSyncohronizedDegreeGreen(EdeboStudentDataSynchronizationReport edeboDataSyncronizationReport) {
edeboDataSyncronizationReport.setSynchronizedStudentDegreesGreen(
edeboDataSyncronizationReport.getSynchronizedStudentDegreesGreen()
.stream().sorted((sd1, sd2) -> (
sd1.getDegreeName() + " "
+ sd1.getFullSpecialityName() + " "
+ sd1.getFullSpecializationName() + " "
+ sd1.getGroupName() + " "
+ sd1.getLastName() + " "
+ sd1.getFirstName() + " "
+ sd1.getMiddleName())
.compareTo(
sd2.getDegreeName() + " "
+ sd2.getFullSpecialityName() + " "
+ sd2.getFullSpecializationName() + " "
+ sd2.getGroupName() + " "
+ sd2.getLastName() + " "
+ sd2.getFirstName() + " "
+ sd2.getMiddleName()))
.collect(Collectors.toList())
);
}
private void sortingMissingPrimaryDataRed(EdeboStudentDataSynchronizationReport edeboDataSyncronizationReport) {
edeboDataSyncronizationReport.setMissingPrimaryDataRed(
edeboDataSyncronizationReport.getMissingPrimaryDataRed()
.stream().sorted((sd1, sd2) -> (
sd1.getStudentDegreePrimaryData().getDegreeName() + " "
+ sd1.getStudentDegreePrimaryData().getFullSpecialityName() + " "
+ sd1.getStudentDegreePrimaryData().getFullSpecializationName() + " "
+ sd1.getStudentDegreePrimaryData().getLastName() + " "
+ sd1.getStudentDegreePrimaryData().getFirstName() + " "
+ sd1.getStudentDegreePrimaryData().getMiddleName())
.compareTo(
sd2.getStudentDegreePrimaryData().getDegreeName() + " "
+ sd2.getStudentDegreePrimaryData().getFullSpecialityName() + " "
+ sd2.getStudentDegreePrimaryData().getFullSpecializationName() + " "
+ sd2.getStudentDegreePrimaryData().getLastName() + " "
+ sd2.getStudentDegreePrimaryData().getFirstName() + " "
+ sd2.getStudentDegreePrimaryData().getMiddleName()))
.collect(Collectors.toList())
);
}
private void sortingAbsentInFileStudentDegreeYellow(EdeboStudentDataSynchronizationReport edeboDataSyncronizationReport) {
edeboDataSyncronizationReport.setAbsentInFileStudentDegreesYellow(
edeboDataSyncronizationReport.getAbsentInFileStudentDegreesYellow()
.stream().sorted((sd1, sd2) -> (
sd1.getDegreeName() + " "
+ sd1.getFullSpecialityName() + " "
+ sd1.getFullSpecializationName() + " "
+ sd1.getGroupName() + " "
+ sd1.getLastName() + " "
+ sd1.getFirstName() + " "
+ sd1.getMiddleName())
.compareTo(
sd2.getDegreeName() + " "
+ sd2.getFullSpecialityName() + " "
+ sd2.getFullSpecializationName() + " "
+ sd2.getGroupName() + " "
+ sd2.getLastName() + " "
+ sd2.getFirstName() + " "
+ sd2.getMiddleName()))
.collect(Collectors.toList())
);
}
private void sortingNoSuchStudentOrStudentDegreeInDbOrange(EdeboStudentDataSynchronizationReport edeboDataSyncronizationReport) {
edeboDataSyncronizationReport.setNoSuchStudentOrSuchStudentDegreeInDbOrange(
edeboDataSyncronizationReport.getNoSuchStudentOrSuchStudentDegreeInDbOrange()
.stream().sorted((sd1, sd2) ->
(sd1.getSpecialization().getDegree().getName() + " "
+ sd1.getSpecialization().getSpeciality().getCode() + " "
+ sd1.getSpecialization().getSpeciality().getName() + " "
+ sd1.getSpecialization().getName() + " "
+ sd1.getPreviousDiplomaType() + " "
+ sd1.getStudent().getSurname() + " "
+ sd1.getStudent().getName() + " "
+ sd1.getStudent().getPatronimic())
.compareTo(sd2.getSpecialization().getDegree().getName() + " "
+ sd2.getSpecialization().getSpeciality().getCode() + " "
+ sd2.getSpecialization().getSpeciality().getName() + " "
+ sd2.getSpecialization().getName() + " "
+ sd2.getPreviousDiplomaType() + " "
+ sd2.getStudent().getSurname() + " "
+ sd2.getStudent().getName() + " "
+ sd2.getStudent().getPatronimic()))
.collect(Collectors.toList())
);
}
}
| true |
74fcf55b715b9b75b712f00cdfe49f166eecba1e | Java | juandiegov16/trivia-game | /ProyectoMejoramiento/src/aplicacion/Principal.java | UTF-8 | 1,705 | 2.921875 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aplicacion;
import static datos.Almacenamiento.cargarPreguntas;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
import javafx.scene.Scene;
import pantallas.Menu;
/**
* @author Juandi
*/
public class Principal extends Application{
/**
*El stage donde mostraremos todas las posibles pantallas del juego.
*/
public static Stage sPrimario;
/**
* El espinazo de la ejecución del juego.
* @param args
*/
public static void main(String[] args) {
//Aquí lee el archivo y agrega su contenido al programa
cargarPreguntas("PreguntasJava1.txt");
launch(args);
//Descomentar para hacer pruebas forzando cierre después de ciertos procesos(NO REMOVER IMPORT!)
//Platform.exit();
}
/**
* Override requerido al extender Application;
* Ejecuta lo correspondiente a JavaFX.
* @param primaryStage
* @throws Exception
*/
@Override
public void start(Stage primaryStage) throws Exception {
sPrimario = primaryStage;
//Nos muestra la pantalla Menu, para comenzar.
Scene s = new Scene(new Menu().getRoot());
sPrimario.setTitle("Quién quiere pasar POO?");
sPrimario.setOnCloseRequest((event -> { // Cierra el programa totalmente.
Platform.exit();
System.exit(0);
}));
sPrimario.setScene(s);
sPrimario.show();
}
//TODO: Dibujar UML
}
| true |
28b00e33eea517aa3bf0b268a66595b88bb257d7 | Java | xsren/AndroidReverseNotes | /docs/weixin_7.0.4_source/反编译源码/反混淆后/src/main/java/com/tencent/p177mm/model/C32776be.java | UTF-8 | 10,171 | 1.648438 | 2 | [] | no_license | package com.tencent.p177mm.model;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.p177mm.model.p1207a.C26407g;
import com.tencent.p177mm.sdk.platformtools.C4990ab;
import com.tencent.tmassistantsdk.downloadservice.Downloads;
import java.util.ArrayList;
import java.util.List;
/* renamed from: com.tencent.mm.model.be */
public class C32776be {
private static C32776be fmd;
public C32778b fmc;
/* renamed from: com.tencent.mm.model.be$a */
public enum C32777a {
NO_INIT,
SET_MOBILE,
SUCC,
SUCC_UNLOAD;
static {
AppMethodBeat.m2505o(16329);
}
}
/* renamed from: com.tencent.mm.model.be$b */
public interface C32778b {
/* renamed from: ZZ */
void mo31111ZZ();
}
/* renamed from: ZV */
public static C32776be m53537ZV() {
AppMethodBeat.m2504i(16330);
synchronized (C32776be.class) {
try {
if (fmd == null) {
fmd = new C32776be();
}
} finally {
while (true) {
}
AppMethodBeat.m2505o(16330);
}
}
C32776be c32776be = fmd;
return c32776be;
}
private C32776be() {
}
/* renamed from: ZW */
public static C37903bd m53538ZW() {
AppMethodBeat.m2504i(16332);
C9638aw.m17190ZK();
SharedPreferences lK = C18628c.m29106lK("banner");
if (lK == null) {
AppMethodBeat.m2505o(16332);
return null;
}
int i = lK.getInt("CurrentType", -1);
int i2 = lK.getInt("CurrentShowType", -1);
String string = lK.getString("CurrentData", "");
if (i != -1) {
switch (i) {
case 1:
C32777a ZY = C32776be.m53540ZY();
if (ZY == C32777a.SUCC || ZY == C32777a.SUCC_UNLOAD || C26407g.aaK().aaI()) {
if (C26407g.aaK().aaI()) {
C4990ab.m7416i("MicorMsg.MainFrameBannerStorage", "has abtest case. ignore bind bind contacts banner.");
} else {
C4990ab.m7416i("MicorMsg.MainFrameBannerStorage", "already Bind the Mobile");
}
AppMethodBeat.m2505o(16332);
return null;
}
case 2:
if (C32776be.m53540ZY() == C32777a.SUCC || C26407g.aaK().aaI()) {
if (C26407g.aaK().aaI()) {
C4990ab.m7416i("MicorMsg.MainFrameBannerStorage", "has abtest case. ignore bind upload contacts banner.");
} else {
C4990ab.m7416i("MicorMsg.MainFrameBannerStorage", "already upload the contacts");
}
AppMethodBeat.m2505o(16332);
return null;
}
case 3:
C4990ab.m7416i("MicorMsg.MainFrameBannerStorage", "avatar already existed");
AppMethodBeat.m2505o(16332);
return null;
case 11:
AppMethodBeat.m2505o(16332);
return null;
case Downloads.MIN_WAIT_FOR_NETWORK /*10000*/:
case 57005:
AppMethodBeat.m2505o(16332);
return null;
}
C37903bd c37903bd = new C37903bd(i, i2, string);
AppMethodBeat.m2505o(16332);
return c37903bd;
}
AppMethodBeat.m2505o(16332);
return null;
}
/* renamed from: co */
public final void mo53322co(int i, int i2) {
AppMethodBeat.m2504i(16333);
C9638aw.m17190ZK();
SharedPreferences lK = C18628c.m29106lK("banner");
if (lK == null) {
AppMethodBeat.m2505o(16333);
return;
}
Editor edit = lK.edit();
switch (i2) {
case 1:
edit.remove("CurrentType").remove("CurrentShowType").remove("CurrentData").commit();
break;
case 2:
edit.remove("CurrentType").remove("CurrentShowType").remove("CurrentData").commit();
List ov = C32776be.m53543ov("HistoryInfo");
if (!ov.contains(Integer.valueOf(i))) {
ov.add(Integer.valueOf(i));
}
C32776be.m53542f("HistoryInfo", ov);
break;
case 3:
if (i == 3) {
edit.remove("CurrentType").remove("CurrentShowType").remove("CurrentData").commit();
break;
}
break;
}
if (this.fmc != null) {
this.fmc.mo31111ZZ();
}
AppMethodBeat.m2505o(16333);
}
/* renamed from: ZX */
private static boolean m53539ZX() {
AppMethodBeat.m2504i(16334);
C9638aw.m17190ZK();
SharedPreferences lK = C18628c.m29106lK("banner");
if (lK == null || !lK.edit().clear().commit()) {
AppMethodBeat.m2505o(16334);
return false;
}
AppMethodBeat.m2505o(16334);
return true;
}
/* renamed from: b */
private static boolean m53541b(C37903bd c37903bd) {
AppMethodBeat.m2504i(16335);
boolean contains = C32776be.m53543ov("HistoryInfo").contains(Integer.valueOf(c37903bd.type));
AppMethodBeat.m2505o(16335);
return contains;
}
/* renamed from: f */
private static boolean m53542f(String str, List<Integer> list) {
boolean z = false;
AppMethodBeat.m2504i(16336);
C9638aw.m17190ZK();
SharedPreferences lK = C18628c.m29106lK("banner");
if (lK == null) {
AppMethodBeat.m2505o(16336);
return false;
}
Editor edit = lK.edit();
edit.putInt(str + "ArraySize", list.size());
while (true) {
boolean z2 = z;
if (z2 < list.size()) {
edit.putInt(str + z2, ((Integer) list.get(z2)).intValue());
z = z2 + 1;
} else {
z = edit.commit();
AppMethodBeat.m2505o(16336);
return z;
}
}
}
/* renamed from: ov */
private static List<Integer> m53543ov(String str) {
AppMethodBeat.m2504i(16337);
C9638aw.m17190ZK();
SharedPreferences lK = C18628c.m29106lK("banner");
if (lK == null) {
AppMethodBeat.m2505o(16337);
return null;
}
int i = lK.getInt(str + "ArraySize", 0);
List<Integer> arrayList = new ArrayList(i);
for (int i2 = 0; i2 < i; i2++) {
arrayList.add(Integer.valueOf(lK.getInt(str + i2, 0)));
}
AppMethodBeat.m2505o(16337);
return arrayList;
}
/* renamed from: ZY */
public static C32777a m53540ZY() {
AppMethodBeat.m2504i(16338);
C32777a c32777a;
try {
C9638aw.m17190ZK();
String str = (String) C18628c.m29072Ry().get(4097, (Object) "");
C9638aw.m17190ZK();
String str2 = (String) C18628c.m29072Ry().get(6, (Object) "");
boolean Zc = C1853r.m3849Zc();
C4990ab.m7410d("MicorMsg.MainFrameBannerStorage", "isUpload " + Zc + " stat " + C1853r.m3822YD());
if (str == null || str.length() <= 0) {
str = null;
}
if (str2 == null || str2.length() <= 0) {
str2 = null;
}
if (str == null && str2 == null) {
c32777a = C32777a.NO_INIT;
AppMethodBeat.m2505o(16338);
return c32777a;
} else if (str != null && str2 == null) {
c32777a = C32777a.SET_MOBILE;
AppMethodBeat.m2505o(16338);
return c32777a;
} else if (Zc) {
c32777a = C32777a.SUCC;
AppMethodBeat.m2505o(16338);
return c32777a;
} else {
c32777a = C32777a.SUCC_UNLOAD;
AppMethodBeat.m2505o(16338);
return c32777a;
}
} catch (Exception e) {
c32777a = C32777a.NO_INIT;
AppMethodBeat.m2505o(16338);
return c32777a;
}
}
/* renamed from: a */
public final boolean mo53321a(C37903bd c37903bd) {
boolean z = true;
AppMethodBeat.m2504i(16331);
if (c37903bd.type == Downloads.MIN_WAIT_FOR_NETWORK) {
C32776be.m53539ZX();
if (this.fmc != null) {
this.fmc.mo31111ZZ();
}
AppMethodBeat.m2505o(16331);
return true;
} else if (c37903bd.type == 57005) {
AppMethodBeat.m2505o(16331);
return false;
} else {
C9638aw.m17190ZK();
SharedPreferences lK = C18628c.m29106lK("banner");
if (lK == null) {
AppMethodBeat.m2505o(16331);
return false;
}
Editor edit = lK.edit();
C37903bd ZW = C32776be.m53538ZW();
if (C32776be.m53541b(c37903bd)) {
z = false;
}
if (ZW != null && ZW.showType == 2) {
List ov = C32776be.m53543ov("HistoryInfo");
if (!ov.contains(Integer.valueOf(ZW.type))) {
ov.add(Integer.valueOf(ZW.type));
}
C32776be.m53542f("HistoryInfo", ov);
}
if (z) {
edit.putInt("CurrentType", c37903bd.type).putInt("CurrentShowType", c37903bd.showType).putString("CurrentData", c37903bd.data).commit();
}
if (this.fmc != null) {
this.fmc.mo31111ZZ();
}
AppMethodBeat.m2505o(16331);
return z;
}
}
}
| true |
574c2ca7aa7cc090657b2fce268ebb01dc94939b | Java | arifyaman/clearTheScreen-game | /core/src/com/xlip/threedtemp/Menu/Effects/Defaults/DefaultMenuFinisher.java | UTF-8 | 1,492 | 2.484375 | 2 | [] | no_license | package com.xlip.threedtemp.Menu.Effects.Defaults;
import com.badlogic.gdx.math.Matrix4;
import com.xlip.threedtemp.Utils.Lerp;
import com.xlip.threedtemp.Menu.Effects.MenuEffect;
/**
* Created by Arif on 23.07.2017.
*/
public class DefaultMenuFinisher extends MenuEffect {
Lerp fx,fy;
private float xdif,ydif;
private float endX, endY;
public DefaultMenuFinisher(float interpolation) {
super(interpolation);
this.xdif = 0.0005f;
this.ydif = 0.0002f;
this.endX = 0;
this.endY = 0;
}
@Override
public void setTransformMatrix(Matrix4 transformMatrix) {
super.setTransformMatrix(transformMatrix);
float xdif = this.xdif;
float ydif = this.ydif;
fx = new Lerp(viewScale.x, viewScale.x + xdif, interpolation) {
@Override
public void onFinished() {
DefaultMenuFinisher.this.onFinished();
super.onFinished();
}
}.combineWith(endX,interpolation);
fy = new Lerp(viewScale.y, viewScale.y + ydif, interpolation).combineWith(endY,interpolation);
}
@Override
public void onFinished() {
super.onFinished();
if(menuEffectCallbacks != null) {
menuEffectCallbacks.finishParentMenu();
}
}
@Override
public void tick(float delta) {
transformMatrix.setToScaling(fx.getValue(delta),fy.getValue(delta),0);
super.tick(delta);
}
}
| true |
2eab5cf8addea81428874f31f851e58dbdb905ca | Java | TheRoyalFlush/TheResuseR | /app/src/main/java/com/example/theresuser/DonateStuff.java | UTF-8 | 16,313 | 1.992188 | 2 | [] | no_license | package com.example.theresuser;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.NavOptions;
import androidx.navigation.Navigation;
//Cass populating the options for users to selcet the item to be posted
public class DonateStuff extends Fragment {
View view;
Spinner colorSpinner,itemSpinner,yearSpinner;
Button proceed,addMore;
JSONArray colorArray,itemArray,yearArray;
ListView itemListView;
List<String[]> currentItemsList;
TextView heading;
Boolean edit = false;
int pos = 0;
Item itemObject;
JSONArray finalPostArray;
String finalArray ="";
List<Integer> postIdList = new ArrayList<>();
Context con;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
view = inflater.inflate(R.layout.fragment_donate_stuff, container, false);
itemListView =(ListView) view.findViewById(R.id.item_list_view);
addMore = (Button) view.findViewById(R.id.addMore);
itemSpinner =(Spinner) view.findViewById(R.id.itemSpinner);
colorSpinner =(Spinner) view.findViewById(R.id.colorSpinner);
heading = (TextView)view.findViewById(R.id.headding);
yearSpinner =(Spinner) view.findViewById(R.id.yearSpinner);
proceed = (Button)view.findViewById(R.id.proceed);
currentItemsList = new ArrayList<String[]>();
final ListViewCustomAdapter adapter = new ListViewCustomAdapter(con,R.layout.custom_list_view, (ArrayList<String[]>) currentItemsList);
itemListView.setAdapter(adapter);
finalPostArray = new JSONArray();
ItemDataAsyncTaks itemDataAsyncTaks = new ItemDataAsyncTaks();
itemDataAsyncTaks.execute();
itemListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
heading.setText(getString(R.string.edit));
addMore.setText(getString(R.string.save1));
pos = position;
edit = true;
try {
for (int i = 0; i<= itemArray.length()-1;i++){
if (currentItemsList.get(position)[0].equals(itemArray.getJSONObject(i).getString("item_name"))){
itemSpinner.setSelection(i);
}
}
for (int i = 0; i<= colorArray.length()-1;i++){
if (currentItemsList.get(position)[1].equals(colorArray.getJSONObject(i).getString("color_name"))){
colorSpinner.setSelection(i);
}
}
for (int i = 0; i<= yearArray.length()-1;i++){
if (currentItemsList.get(position)[2].equals(yearArray.getJSONObject(i).getString("year_range"))){
yearSpinner.setSelection(i);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
});
addMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (!edit) {
currentItemsList.add(new String[]{itemArray.getJSONObject(itemSpinner.getSelectedItemPosition()).getString("item_name"),
colorArray.getJSONObject(colorSpinner.getSelectedItemPosition()).getString("color_name"),
yearArray.getJSONObject(yearSpinner.getSelectedItemPosition()).getString("year_range")});
adapter.notifyDataSetChanged();
} else {
currentItemsList.set(pos,new String[]{itemArray.getJSONObject(itemSpinner.getSelectedItemPosition()).getString("item_name"),
colorArray.getJSONObject(colorSpinner.getSelectedItemPosition()).getString("color_name"),
yearArray.getJSONObject(yearSpinner.getSelectedItemPosition()).getString("year_range")});
heading.setText(getString(R.string.selectitem));
addMore.setText("ADD MORE");
edit = false;
adapter.notifyDataSetChanged();
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
});
proceed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentItemsList.size() == 0) {
Toast.makeText(getActivity(), getString(R.string.noitem), Toast.LENGTH_LONG).show();
} else {
final NavController navController = Navigation.findNavController(view);
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(con);
if (account == null) {
navController.navigate(R.id.action_donateStuff_to_login);
} else {
if (edit) {
Toast.makeText(con, getString(R.string.save), Toast.LENGTH_LONG).show();
} else {
try {
Toast.makeText(getActivity(),getString(R.string.posted),Toast.LENGTH_LONG).show();
SharedPreferences sharedPreferences = con.getSharedPreferences("post_data", Context.MODE_PRIVATE);
float latitude = sharedPreferences.getFloat("latitude", 0);
float longitude = sharedPreferences.getFloat("longitude", 0);
int postId = sharedPreferences.getInt("post_id", 0);
int itemId = 0;
int colorId = 0;
int yearId = 0;
int count = 0;
for (int i = 0; i <= currentItemsList.size() - 1; i++) {
for (int j = 0; j <= itemArray.length() - 1; j++) {
if (currentItemsList.get(i)[0].equals(itemArray.getJSONObject(j).getString("item_name"))) {
itemId = Integer.parseInt(itemArray.getJSONObject(j).getString("item_id"));
}
}
for (int j = 0; j <= colorArray.length() - 1; j++) {
if (currentItemsList.get(i)[1].equals(colorArray.getJSONObject(j).getString("color_name"))) {
colorId = Integer.parseInt(colorArray.getJSONObject(j).getString("color_id"));
}
}
for (int j = 0; j <= yearArray.length() - 1; j++) {
if (currentItemsList.get(i)[2].equals(yearArray.getJSONObject(j).getString("year_range"))) {
yearId = Integer.parseInt(yearArray.getJSONObject(j).getString("year_id"));
}
}
if (count > 0) {
postId = postId + 1;
}
itemObject = new Item(postId, colorId, itemId, yearId, latitude, longitude);
postIdList.add(postId);
count = count + 1;
Gson gson = new GsonBuilder().create();
String stringJson = gson.toJson(itemObject);
System.out.println(stringJson);
if (i != currentItemsList.size() - 1) {
finalArray = finalArray + stringJson + ",";
} else {
finalArray = finalArray + stringJson;
}
JSONObject newObject = new JSONObject(stringJson);
finalPostArray.put(newObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
finalArray = "[" + finalArray + "]";
SendDataAysnc sendDataAysnc = new SendDataAysnc();
sendDataAysnc.execute();
Toast.makeText(getActivity(),getString(R.string.greener),Toast.LENGTH_SHORT).show();
NavOptions navOptions = new NavOptions.Builder().setPopUpTo(R.id.findStuff, true).build();
navController.navigate(R.id.action_donateStuff_to_locationConfirmation2, null, navOptions);
}
}
}
}
});
//Sending the user to the landing page when back button is pressed
view.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK){
return true;
}
return false;
}
});
return view;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
con = context;
}
public class SendDataAysnc extends AsyncTask<String,Void,String> {
@Override
protected String doInBackground(String... strings) {
AsyncTaskData.postItem(finalArray);
return null;
}
@Override
protected void onPostExecute(String s) {
RecordActivity recordActivity = new RecordActivity();
recordActivity.execute();
}
}
public class RecordActivity extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... strings) {
String recordData = AsyncTaskData.RecordId();
return recordData;
}
@Override
protected void onPostExecute(String s) {
int counter = 0;
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(con);
Date date = new Date();
System.out.println(date);
String activityAraay = "";
try {
JSONArray arrayData = new JSONArray(s);
for(int i = 0; i <= arrayData.length()-1; i++){
System.out.println(Integer.valueOf(arrayData.getJSONObject(i).getString("record_id")));
if(Integer.valueOf(arrayData.getJSONObject(i).getString("record_id")) > counter){
counter = Integer.valueOf(arrayData.getJSONObject(i).getString("record_id"));
}
}
counter += 1;
for (int j = 0; j <= postIdList.size()-1; j++){
if(j>0){
counter = counter + 1;
}
UserActivity userActivity = new UserActivity(account.getEmail(),counter,postIdList.get(j),1,date);
Gson gson = new GsonBuilder().create();
String stringJson = gson.toJson(userActivity);
if (j != postIdList.size() - 1) {
activityAraay = activityAraay + stringJson + ",";
} else {
activityAraay = activityAraay + stringJson;
}
}
} catch (Exception e) {
e.printStackTrace();
}
activityAraay = "["+activityAraay+"]";
System.out.println(activityAraay);
UpdateActivity updateActivity = new UpdateActivity();
updateActivity.execute(activityAraay);
}
}
public class UpdateActivity extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... strings) {
AsyncTaskData.postActivity(strings[0]);
return null;
}
}
//Populating all the options for the items to be posted
public class ItemDataAsyncTaks extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... strings) {
String spinnerData = AsyncTaskData.PopulateSpinner("items");
return spinnerData;
}
@Override
protected void onPostExecute(String s) {
try {
//Populating the drop down menues for the user to select the item to be posted
JSONObject mainObject = new JSONObject(s);
colorArray = new JSONArray(mainObject.getString("Color"));
itemArray = new JSONArray(mainObject.getString("Item"));
yearArray = new JSONArray(mainObject.getString("Year"));
List colorList = new ArrayList();
List itemList = new ArrayList();
List yearList = new ArrayList();
for (int i = 0; i <= colorArray.length() - 1;i++ ){
colorList.add(colorArray.getJSONObject(i).get("color_name"));
}
for(int i = 0; i<= itemArray.length() - 1;i++){
itemList.add(itemArray.getJSONObject(i).get("item_name"));
}
for(int i = 0; i<= yearArray.length() - 1;i++){
yearList.add(yearArray.getJSONObject(i).get("year_range"));
}
final ArrayAdapter<String> colorSpinnerAdapter = new ArrayAdapter<String>(con,android.R.layout.simple_spinner_item, colorList);
colorSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_expandable_list_item_1);
final ArrayAdapter<String> itemSpinnerAdapter = new ArrayAdapter<String>(con,android.R.layout.simple_spinner_item, itemList);
colorSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_expandable_list_item_1);
final ArrayAdapter<String> yearSpinnerAdapter = new ArrayAdapter<String>(con,android.R.layout.simple_spinner_item, yearList);
colorSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_expandable_list_item_1);
colorSpinner.setAdapter(colorSpinnerAdapter);
itemSpinner.setAdapter(itemSpinnerAdapter);
yearSpinner.setAdapter(yearSpinnerAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
| true |
7be17df2d7d8f3e97abb95451682e3ec69e667f6 | Java | anujji1999/weather-app-akashvani | /app/src/main/java/com/firefinch/akashvani/db/tables/LocationTable.java | UTF-8 | 3,005 | 2.46875 | 2 | [] | no_license | package com.firefinch.akashvani.db.tables;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.firefinch.akashvani.models.Location;
import com.firefinch.akashvani.utils.Consts;
import java.util.ArrayList;
import static com.firefinch.akashvani.utils.Consts.*;
/**
* Created by Nitin on 10/6/2017.
*/
public class LocationTable {
public static final String TABLE_NAME = Consts.LOCATION_TABLE_NAME;
public interface Columns {
String ID = "id";
String NAME = "name";
String LATITUDE = "latitude";
String LONGITUDE = "longitude";
}
public static final String CMD_CREATE =
CMD_CREATE_TABLE_INE + TABLE_NAME +
LBR +
Columns.ID + TYPE_INT + TYPE_PK + TYPE_AI + COMMA +
Columns.NAME + TYPE_TEXT + COMMA +
Columns.LATITUDE + TYPE_DOUBLE + COMMA +
Columns.LONGITUDE + TYPE_DOUBLE +
RBR +
SEMI;
public static ArrayList<Location> getAllLocations(SQLiteDatabase db) {
ArrayList<Location> locations = new ArrayList<>();
Cursor c = db.query(
TABLE_NAME,
new String[]{Columns.ID, Columns.NAME, Columns.LATITUDE, Columns.LONGITUDE},
null,
null,
null,
null,
null
);
int colForId = c.getColumnIndex(Columns.ID);
int colForName = c.getColumnIndex(Columns.NAME);
int colForLatitude = c.getColumnIndex(Columns.LATITUDE);
int colForLongitude = c.getColumnIndex(Columns.LONGITUDE);
while (c.moveToNext()) {
locations.add(
new Location(
c.getInt(colForId),
c.getString(colForName),
c.getDouble(colForLatitude),
c.getDouble(colForLongitude)
)
);
}
return locations;
}
public static long insertLocation(SQLiteDatabase db, Location location) {
ContentValues locationData = new ContentValues();
locationData.put(Columns.NAME, location.getName());
locationData.put(Columns.LATITUDE, location.getLatitude());
locationData.put(Columns.LONGITUDE, location.getLongitude());
return db.insert(
TABLE_NAME,
null,
locationData
);
}
public static void deleteLocation(SQLiteDatabase db, int locationId) {
db.delete(TABLE_NAME, Columns.ID + " = ?", new String[]{String.valueOf(locationId)});
}
public static int getCount(SQLiteDatabase db) {
String count = "SELECT count(*) FROM " + TABLE_NAME;
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
return icount;
}
}
| true |
ed68c7a05559dca1a4eb34b5d10a4e876cce595f | Java | LongerChen/myandroid | /src/myandroid/dialog/ImageDialog.java | UTF-8 | 2,157 | 2.328125 | 2 | [] | no_license | package myandroid.dialog;
import myandroid.layout.RelativeLayout;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.view.WindowManager.LayoutParams;
public class ImageDialog extends Dialog implements
android.view.View.OnClickListener {
protected ImageLayout layout;
public ImageDialog(Context context, Bitmap ad, int resourceIdOfClose) {
super(context);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
setCancelable(false);
setContentView(layout = new ImageLayout(context), new LayoutParams(
android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.MATCH_PARENT));
layout.setCloseImage(resourceIdOfClose);
layout.setAdImage(ad);
layout.closeImage.setOnClickListener(this);
layout.adImage.setOnClickListener(this);
Window window = getWindow();
LayoutParams params = window.getAttributes();
params.width = android.view.ViewGroup.LayoutParams.MATCH_PARENT;
params.height = android.view.ViewGroup.LayoutParams.MATCH_PARENT;
window.setAttributes(params);
}
@Override
public void onClick(View v) {
if (v == layout.closeImage)
onCloseClick();
if (v == layout.adImage)
onImageClick();
}
protected void onImageClick() {
}
protected void onCloseClick() {
dismiss();
}
class ImageLayout extends RelativeLayout {
ImageView adImage;
ImageView closeImage;
public ImageLayout(Context context) {
super(context);
adImage = addView(new ImageView(context), M, M, new int[] {});
closeImage = addView(new ImageView(context), 10, 10,
new int[] { ALIGN_PARENT_RIGHT });
setMargin(adImage, 5, 5, 5, 5);
}
public void setCloseImage(int resourceIdOfClose) {
closeImage.setImageResource(resourceIdOfClose);
}
public void setAdImage(Bitmap ad) {
adImage.setImageBitmap(ad);
}
}
}
| true |
eac07f5d5ee47adc59fd493427a7df3dd017cf10 | Java | mos8502/viewdecorator | /viewdecorator/src/main/java/hu/nemi/appcompat/view/ViewFactoryV11.java | UTF-8 | 1,368 | 2.375 | 2 | [] | no_license | package hu.nemi.appcompat.view;
import android.annotation.TargetApi;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import java.lang.reflect.Method;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
class ViewFactoryV11 implements ViewFactory {
private Method method;
private LayoutInflater layoutInflater;
public ViewFactoryV11(LayoutInflater layoutInflater) {
this.layoutInflater = layoutInflater;
this.method = getOnCreateViewMethod();
}
@Override
public View createView(View parent, String name, AttributeSet attrs) {
if(method != null) {
return onCreateView(parent, name, attrs);
}
return null;
}
private View onCreateView(View parent, String name, AttributeSet attrs){
try {
return (View) method.invoke(layoutInflater, parent, name, attrs);
} catch (Exception e) {
return null;
}
}
private static Method getOnCreateViewMethod() {
try {
Method method = LayoutInflater.class.getDeclaredMethod("onCreateView",
View.class, String.class, AttributeSet.class);
method.setAccessible(true);
return method;
} catch (NoSuchMethodException e) {
return null;
}
}
}
| true |
2194b32c324f4a7804cabcd5aebd253fab4aba1b | Java | pavithratg/OCA | /src/com/oca/revision/demos/classesNInterfaces/AbstractClassDemo.java | UTF-8 | 750 | 3.671875 | 4 | [] | no_license | package com.oca.revision.demos.classesNInterfaces;
// abstract classes cannot be instantiated.
public abstract class AbstractClassDemo {
public abstract void printState();
public void print() {
System.out.println("printing...");
}
public static void main(String[] args) {
new SubSubClassDemo().printState();
}
}
abstract class SubClassDemo extends AbstractClassDemo {
@Override
public void print() {
System.out.println("Printing subclass...");
}
public int getInt() {
return 10;
}
public abstract float getFloat();
}
class SubSubClassDemo extends SubClassDemo {
@Override
public void printState() {
System.out.println("Printing concrete state...");
}
@Override
public float getFloat() {
return 10.98f;
}
}
| true |
910fb8b69a1614e60ffd7fe3ea33cadb82ba53d0 | Java | oranie/AndroidStudy | /androidday3listviewexpand/src/com/example/androidday3listviewexpand/MainActivity.java | SHIFT_JIS | 2,716 | 2.46875 | 2 | [] | no_license | package com.example.androidday3listviewexpand;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TwoLineListItem;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] g_titles = {"","؊",""};
String[][][] c_titles = {
{{"gybg","g"},{"g{[","g"},{"`[o","`["}},
{{"Nlbg","N"},{"t@Sbg","t@"},{"I[{G","I["}},
{{"oCI","oC"},{"rI","rI"},{"`F","`F"}},
};
ExpandableListView elv = (ExpandableListView)findViewById(R.id.elv);
ArrayList<Map<String, String>> g_list = new ArrayList<Map<String, String>>();
ArrayList<List<Map<String, String>>> c_list = new ArrayList<List<Map<String, String>>>();
for (int i = 0; i < g_titles.length; i++) {
HashMap<String, String> group = new HashMap<String,String>();
group.put("group_title", g_titles[i]);
g_list.add(group);
ArrayList<Map<String,String>> childs = new ArrayList<Map<String,String>>();
for (int j = 0; j < c_titles.length; j++) {
HashMap<String, String> child = new HashMap<String,String>();
child.put("child_title", c_titles[i][j][0]);
child.put("child_text", c_titles[i][j][1]);
childs.add(child);
}
c_list.add(childs);
}
SimpleExpandableListAdapter adapter = new SimpleExpandableListAdapter(
this,
g_list,
android.R.layout.simple_expandable_list_item_1,
new String []{"group_title"},
new int []{android.R.id.text1},
c_list,
android.R.layout.simple_expandable_list_item_2,
new String []{"child_title","child_text"},
new int []{android.R.id.text1,android.R.id.text2}
);
elv.setAdapter(adapter);
elv.setOnChildClickListener(
new OnChildClickListener(){
public boolean onChildClick(
ExpandableListView parent,
View v,
int groupPosition,
int childPosition,
long id){
TextView txt = (TextView)((TwoLineListItem)v).findViewById(android.R.id.text1);
//Toast.makeText(ExpandableListView.this, txt.getText(),Toast.LENGTH_LONG).show();
return false;
}
});
}
} | true |
2a72b45a9cbbc4d80ce26dae13a543abc12476da | Java | AndreyAMolkov/ProgramModelBank | /src/main/java/demo/model/Account.java | UTF-8 | 3,714 | 2.328125 | 2 | [] | no_license | package demo.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import demo.constant.Constants;
@Entity(name = "Account")
@Table(name = "accounts")
public class Account {
private static Logger log = LoggerFactory.getLogger("demo.model.Account");
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long number;
private Long data;
@Transient
private List<Story> sortList;
private Long sum;
@Autowired
@javax.persistence.Transient
private Story story;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "accounts_id")
private List<Story> histories;
public Account() {
setHistories(histories);
this.sum = 0L;
}
public Long getData() {
return data;
}
public void setData(Long data) {
this.data = data;
}
public Long getNumber() {
return number;
}
public void setNumber(Long numberOfaccount) {
this.number = numberOfaccount;
}
public Long getSum() {
if (sum == null)
this.sum = 0L;
return sum;
}
private void setSum(Long sum) {
this.sum = getSum() + sum;
}
public String getHistoriesSize() {
String nameMethod = "getHistoriesSize";
if (histories == null) {
return "empty";
}
int result = 0;
try {
result = getHistories().size();
} catch (IllegalStateException e) {
log.debug(nameMethod + Constants.ONE_PARAMETERS, "error load for getHistories().size()", "true");
}
return String.valueOf(result);
}
public List<Story> getHistories() {
if (histories == null) {
this.histories = new ArrayList<>();
}
return histories;
}
public List<Story> getSortHistories() {
return sortHistoriesLastDateFirst(getCopy());
}
private List<Story> getCopy() {
return getHistories().stream().map(Story::storyForSort).collect(Collectors.toList());
}
public List<Story> sortHistoriesLastDateFirst(List<Story> historiesOld) {
Collections.sort(historiesOld, (story1, story2) -> story2.getDate().compareTo(story1.getDate()));
return historiesOld;
}
public void setHistories(List<Story> historiesNew) {
if (this.histories == null)
this.histories = new ArrayList<>(5);
if (historiesNew == null) {
historiesNew = new ArrayList<>(5);
}
historiesNew.stream().forEach(this::setHistories);
}
private boolean validateStory(Story story) {
Long sumOfStory = story.getSum();
Boolean flag = false;
if ((Constants.OUTPUT_AMOUNT).equals(story.getOperation())) {
flag = (sumOfStory < 0);
}
if ((Constants.INPUT_AMOUNT).equals(story.getOperation())) {
flag = (sumOfStory > 0);
}
return flag;
}
public void setHistories(Story story) {
String nameMethod = "setHistories";
Long sumOfStory = story.getSum();
if (validateStory(story)) {
setSum(sumOfStory);
story.setAccount(getNumber());
this.histories.add(story);
return;
}
log.warn(nameMethod + Constants.FOUR_PARAMETERS, "error load story", "true", "operation", story.getOperation(),
"exemples of operations", Constants.INPUT_AMOUNT + ", " + Constants.OUTPUT_AMOUNT,
"sumOfStory", sumOfStory);
}
@Override
public String toString() {
return "[" + "number=" + number + ", sum=" + sum + "]";
}
}
| true |
34c6214fdcc41dd6adba11bb22298e0c28153c8a | Java | oblac/jodd-util | /src/main/java/jodd/io/NetUtil.java | UTF-8 | 6,106 | 2.34375 | 2 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | // Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package jodd.io;
import jodd.util.StringUtil;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.StandardOpenOption;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Network utilities.
*/
public class NetUtil {
public static final String LOCAL_HOST = "localhost";
public static final String LOCAL_IP = "127.0.0.1";
public static final String DEFAULT_MASK = "255.255.255.0";
public static final int INT_VALUE_127_0_0_1 = 0x7f000001;
/**
* Resolves IP address from a hostname.
*/
public static String resolveIpAddress(final String hostname) {
try {
final InetAddress netAddress;
if (hostname == null || hostname.equalsIgnoreCase(LOCAL_HOST)) {
netAddress = InetAddress.getLocalHost();
} else {
netAddress = Inet4Address.getByName(hostname);
}
return netAddress.getHostAddress();
} catch (final UnknownHostException ignore) {
return null;
}
}
/**
* Returns IP address as integer.
*/
public static int getIpAsInt(final String ipAddress) {
int ipIntValue = 0;
final String[] tokens = StringUtil.splitc(ipAddress, '.');
for (final String token : tokens) {
if (ipIntValue > 0) {
ipIntValue <<= 8;
}
ipIntValue += Integer.parseInt(token);
}
return ipIntValue;
}
public static int getMaskAsInt(String mask) {
if (!validateIPv4(mask)) {
mask = DEFAULT_MASK;
}
return getIpAsInt(mask);
}
public static boolean isSocketAccessAllowed(final int localIp, final int socketIp, final int mask) {
boolean _retVal = false;
if (socketIp == INT_VALUE_127_0_0_1 || (localIp & mask) == (socketIp & mask)) {
_retVal = true;
}
return _retVal;
}
private static final Pattern ip4RegExp = Pattern.compile("^((?:1?[1-9]?\\d|2(?:[0-4]\\d|5[0-5]))\\.){4}$");
/**
* Checks given string against IP address v4 format.
*
* @param input an ip address - may be null
* @return <tt>true</tt> if param has a valid ip v4 format <tt>false</tt> otherwise
* @see <a href="https://en.wikipedia.org/wiki/IP_address#IPv4_addresses">ip address v4</a>
*/
public static boolean validateIPv4(final String input) {
final Matcher m = ip4RegExp.matcher(input + '.');
return m.matches();
}
/**
* Resolves host name from IP address bytes.
*/
public static String resolveHostName(final byte[] ip) {
try {
final InetAddress address = InetAddress.getByAddress(ip);
return address.getHostName();
} catch (final UnknownHostException ignore) {
return null;
}
}
// ---------------------------------------------------------------- download
/**
* Downloads resource as byte array.
*/
public static byte[] downloadBytes(final String url) throws IOException {
try (final InputStream inputStream = new URL(url).openStream()) {
return IOUtil.readBytes(inputStream);
}
}
/**
* Downloads resource as String.
*/
public static String downloadString(final String url, final Charset encoding) throws IOException {
try (final InputStream inputStream = new URL(url).openStream()) {
return new String(IOUtil.readChars(inputStream, encoding));
}
}
/**
* Downloads resource as String.
*/
public static String downloadString(final String url) throws IOException {
try (final InputStream inputStream = new URL(url).openStream()) {
return new String(IOUtil.readChars(inputStream));
}
}
/**
* Downloads resource to a file, potentially very efficiently.
*/
public static void downloadFile(final String url, final File file) throws IOException {
try (
final InputStream inputStream = new URL(url).openStream();
final ReadableByteChannel rbc = Channels.newChannel(inputStream);
final FileChannel fileChannel = FileChannel.open(
file.toPath(),
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING,
StandardOpenOption.WRITE)
) {
fileChannel.transferFrom(rbc, 0, Long.MAX_VALUE);
}
}
/**
* Get remote file size. Returns -1 if the content length is unknown
*
* @param url remote file url
* @return file size
* @throws IOException JDK-IOException
*/
public static long getRemoteFileSize(final String url) throws IOException {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(url).openConnection();
return connection.getContentLengthLong();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
| true |
f3006bfe52bc9bc292ac4166860185074bf37b7b | Java | fekete20/DBMSc | /myBatis_Dolgozo/src/main/java/myBatis/Dolgozo.java | UTF-8 | 587 | 2.03125 | 2 | [] | no_license | package myBatis;
public class Dolgozo {
private int did;
private String dnev;
private String beosztas;
private int fizetes;
public int getDid() {
return did;
}
public void setDid(int did) {
this.did = did;
}
public String getDnev() {
return dnev;
}
public void setDnev(String dnev) {
this.dnev = dnev;
}
public String getBeosztas() {
return beosztas;
}
public void setBeosztas(String beosztas) {
this.beosztas = beosztas;
}
public int getFizetes() {
return fizetes;
}
public void setFizetes(int fizetes) {
this.fizetes = fizetes;
}
}
| true |