blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
sequence | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
sequence | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
950ae3ed0f9f138fc77dc6b5288862b78133d366 | 14,783,277,501,438 | 0d22154e8348f42f2546022a29ae500540312195 | /Array/src/Students.java | f6443e0ae178442febe81bb64033a2e9f3b87519 | [] | no_license | mehedimithu/Java-Programing | https://github.com/mehedimithu/Java-Programing | c8ab70abc46f8009d1ad2e1512ea0906286b30a2 | d036aae035b1172441e0c27a45de5e39937364c8 | refs/heads/main | 2023-06-06T06:58:41.795000 | 2022-08-30T10:02:26 | 2022-08-30T10:02:26 | 379,607,357 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Students {
public int roll;
public String name;
Students(int roll, String name) {
this.name = name;
this.roll = roll;
}
}
| UTF-8 | Java | 170 | java | Students.java | Java | [] | null | [] | public class Students {
public int roll;
public String name;
Students(int roll, String name) {
this.name = name;
this.roll = roll;
}
}
| 170 | 0.570588 | 0.570588 | 11 | 14.454545 | 12.808829 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 1 |
ae3614b200e4ae403bb907b91c42dbeecaadc9fe | 16,844,861,794,421 | ab856d03e4a3d32fa27b13374558c5bc8340aad5 | /presentation/src/main/java/cn/canlnac/onlinecourse/presentation/internal/di/components/DeleteMessageComponent.java | 67bbe71834ed895d883b0472481dbcba1479f2fe | [
"MIT"
] | permissive | CecilJxSu/Online-Course-Android | https://github.com/CecilJxSu/Online-Course-Android | f895dc2979c5a54fb3433051fac9d79d40f250c3 | aaee8757acc78721e9ffa91d18cd96939c020057 | refs/heads/master | 2021-01-19T10:03:21.299000 | 2017-04-06T02:46:22 | 2017-04-06T02:46:22 | 71,952,463 | 0 | 0 | null | false | 2017-04-06T02:46:23 | 2016-10-26T01:05:48 | 2017-02-27T05:34:59 | 2017-04-06T02:46:23 | 6,191 | 0 | 0 | 0 | null | null | null | package cn.canlnac.onlinecourse.presentation.internal.di.components;
import cn.canlnac.onlinecourse.presentation.internal.di.PerActivity;
import cn.canlnac.onlinecourse.presentation.internal.di.modules.ActivityModule;
import cn.canlnac.onlinecourse.presentation.internal.di.modules.DeleteMessageModule;
import cn.canlnac.onlinecourse.presentation.ui.adapter.MessageViewHolder;
import dagger.Component;
@PerActivity
@Component(dependencies = ApplicationComponent.class, modules = {ActivityModule.class, DeleteMessageModule.class})
public interface DeleteMessageComponent extends ActivityComponent {
void inject(MessageViewHolder messageViewHolder);
}
| UTF-8 | Java | 656 | java | DeleteMessageComponent.java | Java | [] | null | [] | package cn.canlnac.onlinecourse.presentation.internal.di.components;
import cn.canlnac.onlinecourse.presentation.internal.di.PerActivity;
import cn.canlnac.onlinecourse.presentation.internal.di.modules.ActivityModule;
import cn.canlnac.onlinecourse.presentation.internal.di.modules.DeleteMessageModule;
import cn.canlnac.onlinecourse.presentation.ui.adapter.MessageViewHolder;
import dagger.Component;
@PerActivity
@Component(dependencies = ApplicationComponent.class, modules = {ActivityModule.class, DeleteMessageModule.class})
public interface DeleteMessageComponent extends ActivityComponent {
void inject(MessageViewHolder messageViewHolder);
}
| 656 | 0.858232 | 0.858232 | 13 | 49.46154 | 36.252567 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false | 1 |
8d8538f7a24b8adac8a23ed34f1e0a3564882124 | 3,298,534,942,999 | 074cb451d1c2ac987c31712fc8c494d4a604200e | /wselsfk/src/main/java/com/example/wselsfk/controller/handler/ExceptionHandler.java | 8d18a776ac5cce136725bd4be3ccc1ef99fa42a0 | [] | no_license | Anyzm/onlineTetris | https://github.com/Anyzm/onlineTetris | 6b9edb973877952d891e5a6afdc37ae20de59007 | 1315e5bc152ac2ce2064a85e3344402f6403d111 | refs/heads/master | 2020-03-19T12:10:48.078000 | 2018-06-07T17:50:44 | 2018-06-07T17:50:44 | 136,501,593 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.wselsfk.controller.handler;
import com.example.wselsfk.dto.ReturnResult;
import com.example.wselsfk.exception.GameException;
import com.example.wselsfk.exception.UserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by ZhaoLai Huang on 2018/4/13.
*/
@ControllerAdvice
public class ExceptionHandler {
private final static Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);
@ResponseBody
@org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
public ReturnResult handle(Exception e) {
if (e instanceof GameException) {
GameException gameException = (GameException) e;
return new ReturnResult(gameException.getCodeMessage());
}if(e instanceof UserException){
UserException userException = (UserException) e;
return new ReturnResult(userException.getCodeMessage());
}else {
logger.error("【系统异常】{}", e);
return new ReturnResult(ReturnResult.CodeMessage.INNER_ERROR);
}
}
}
| UTF-8 | Java | 1,233 | java | ExceptionHandler.java | Java | [
{
"context": "b.bind.annotation.ResponseBody;\n\n/**\n * Created by ZhaoLai Huang on 2018/4/13.\n */\n\n@ControllerAdvice\npublic class",
"end": 413,
"score": 0.9998429417610168,
"start": 400,
"tag": "NAME",
"value": "ZhaoLai Huang"
}
] | null | [] | package com.example.wselsfk.controller.handler;
import com.example.wselsfk.dto.ReturnResult;
import com.example.wselsfk.exception.GameException;
import com.example.wselsfk.exception.UserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by <NAME> on 2018/4/13.
*/
@ControllerAdvice
public class ExceptionHandler {
private final static Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);
@ResponseBody
@org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
public ReturnResult handle(Exception e) {
if (e instanceof GameException) {
GameException gameException = (GameException) e;
return new ReturnResult(gameException.getCodeMessage());
}if(e instanceof UserException){
UserException userException = (UserException) e;
return new ReturnResult(userException.getCodeMessage());
}else {
logger.error("【系统异常】{}", e);
return new ReturnResult(ReturnResult.CodeMessage.INNER_ERROR);
}
}
}
| 1,226 | 0.728911 | 0.72154 | 36 | 32.916668 | 27.533188 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 1 |
cc5e529d05b97d924cdf035c70b0e7a85d33f636 | 33,062,658,264,825 | 726bf30be2e07e7e0d7cdf99e68e157ee9c6cc34 | /src/main/java/edu/upc/bip/Tests/CSVtoHBASE.java | ff14d4b73031283a9fc80db08f45d663bd6019ca | [] | no_license | anasalba/crohavior-batch | https://github.com/anasalba/crohavior-batch | 58cce5c4c61bf402185c7f4905946397e44426bd | f5e7bb16a82f7a7d29c12bdf5b633e08e4407325 | refs/heads/master | 2021-01-12T04:46:41.406000 | 2017-01-08T22:58:19 | 2017-01-08T22:58:19 | 77,794,496 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.upc.bip.Tests;
import edu.upc.bip.utils.HBaseUtils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
/**
* Created by osboxes on 03/01/17.
*/
public class CSVtoHBASE {
private static List<Path> files = new ArrayList<>();
public static void main(String[] args) throws Exception {
try {
Path dir = Paths.get("/home/osboxes/data_beiging_4hours");
listFiles(dir);
BufferedReader br = null;
HBaseUtils.deleteTable("csvtohbase");
HBaseUtils.creatTable("csvtohbase",new String[]{"data"});
int lineNmb = 0;
//files.size()
for (int i = 0; i < files.size(); i++) {
Path pltFile = files.get(i);
br = new BufferedReader(new FileReader(pltFile.toFile()));
int internalLineNmb = 0;
String line = br.readLine();
while (line != null) {
if (!line.contains("lat") && !line.contains("id")) {
String[] words = line.split(";");
String rowKey = words[4]+words[7];
String payload= words[0]+";"+words[1]+";"+words[4]+";"+words[7];
HBaseUtils.addRecord("csvtohbase",rowKey,"data","",payload);
System.out.println(lineNmb++);
}
line = br.readLine();
}
}
} catch (Throwable throwable) {
System.out.printf("%s", throwable.getStackTrace());
} finally {
}
}
static void listFiles(Path path) throws IOException {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
for (Path entry : stream) {
if (Files.isDirectory(entry)) {
listFiles(entry);
}
if(entry.getFileName().toString().contains(".csv")) {
files.add(entry);
}
}
}
}
}
| UTF-8 | Java | 2,266 | java | CSVtoHBASE.java | Java | [
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by osboxes on 03/01/17.\n */\npublic class CSVtoHBASE {\n\n p",
"end": 378,
"score": 0.9995418787002563,
"start": 371,
"tag": "USERNAME",
"value": "osboxes"
}
] | null | [] | package edu.upc.bip.Tests;
import edu.upc.bip.utils.HBaseUtils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
/**
* Created by osboxes on 03/01/17.
*/
public class CSVtoHBASE {
private static List<Path> files = new ArrayList<>();
public static void main(String[] args) throws Exception {
try {
Path dir = Paths.get("/home/osboxes/data_beiging_4hours");
listFiles(dir);
BufferedReader br = null;
HBaseUtils.deleteTable("csvtohbase");
HBaseUtils.creatTable("csvtohbase",new String[]{"data"});
int lineNmb = 0;
//files.size()
for (int i = 0; i < files.size(); i++) {
Path pltFile = files.get(i);
br = new BufferedReader(new FileReader(pltFile.toFile()));
int internalLineNmb = 0;
String line = br.readLine();
while (line != null) {
if (!line.contains("lat") && !line.contains("id")) {
String[] words = line.split(";");
String rowKey = words[4]+words[7];
String payload= words[0]+";"+words[1]+";"+words[4]+";"+words[7];
HBaseUtils.addRecord("csvtohbase",rowKey,"data","",payload);
System.out.println(lineNmb++);
}
line = br.readLine();
}
}
} catch (Throwable throwable) {
System.out.printf("%s", throwable.getStackTrace());
} finally {
}
}
static void listFiles(Path path) throws IOException {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
for (Path entry : stream) {
if (Files.isDirectory(entry)) {
listFiles(entry);
}
if(entry.getFileName().toString().contains(".csv")) {
files.add(entry);
}
}
}
}
}
| 2,266 | 0.523389 | 0.516328 | 70 | 31.371429 | 23.809465 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.628571 | false | false | 1 |
22c9505ebf82689eac1643c4c3928df000323098 | 5,016,521,817,919 | 56373b970e848188b2a285964731a94fc5cd2a7a | /catering/src/businesslogic/kitchenTask/KitchenTaskEventReceiver.java | 5ae05cbb374d2c6aa4deee32c47ec1fe5fec5890 | [] | no_license | palfag/catering | https://github.com/palfag/catering | 61d04116a9a2579f50dcb85dfc0dd0bf1260327e | efab14af162b080282e35170faedb7d81144d254 | refs/heads/master | 2023-03-08T09:56:50.051000 | 2021-02-25T16:48:10 | 2021-02-25T16:48:10 | 338,080,947 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package businesslogic.kitchenTask;
public interface KitchenTaskEventReceiver {
void updateSheetCreated(SummarySheet currentSheet);
void updateSheetOpened(SummarySheet currentSheet);
void updateSheetDeleted(SummarySheet currentSheet);
void updateTaskCreated(SummarySheet currentSheet, Task task);
void updateTaskRemoved(SummarySheet currentSheet, Task task);
void updateTaskRearranged(SummarySheet currentSheet);
void updateTaskModified(SummarySheet currentSheet, Task task);
void updateTimeAdded(SummarySheet currentSheet, Task selectedTask);
void updateQuantityAdded(SummarySheet currentSheet, Task selectedTask);
void updateTaskAssigned(SummarySheet currentSheet, Task selectedTask);
void updateAssignmentNullified(SummarySheet currentSheet, Task selectedTask);
}
| UTF-8 | Java | 801 | java | KitchenTaskEventReceiver.java | Java | [] | null | [] | package businesslogic.kitchenTask;
public interface KitchenTaskEventReceiver {
void updateSheetCreated(SummarySheet currentSheet);
void updateSheetOpened(SummarySheet currentSheet);
void updateSheetDeleted(SummarySheet currentSheet);
void updateTaskCreated(SummarySheet currentSheet, Task task);
void updateTaskRemoved(SummarySheet currentSheet, Task task);
void updateTaskRearranged(SummarySheet currentSheet);
void updateTaskModified(SummarySheet currentSheet, Task task);
void updateTimeAdded(SummarySheet currentSheet, Task selectedTask);
void updateQuantityAdded(SummarySheet currentSheet, Task selectedTask);
void updateTaskAssigned(SummarySheet currentSheet, Task selectedTask);
void updateAssignmentNullified(SummarySheet currentSheet, Task selectedTask);
}
| 801 | 0.833958 | 0.833958 | 26 | 29.807692 | 31.011189 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 1 |
1d3bef5f436c90dac604d6d741e0db83a3a6d6b2 | 16,647,293,288,317 | 03489b8d72e486f0f77c9a966101d9686f0aade9 | /src/matz/basics/network/StaticCNNNetwork.java | 1e1c992aebdbeb5710bd250a7483e9800ef73257 | [] | no_license | ymtszw/SilentMajority | https://github.com/ymtszw/SilentMajority | 3fc1cd0675aaf16d3b18eeded4f4427a2212e2d0 | 7b1fe1d14ccb61902fea06ffd4ee4cc103fb9985 | refs/heads/master | 2020-12-31T06:23:05.443000 | 2015-02-13T07:36:38 | 2015-02-13T07:36:38 | 15,672,788 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package matz.basics.network;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* VazquezのCNNモデルに基づき、現実やSNSでの友人関係に近いネットワークを生成するクラス。<br>
* 確率p_nnで「友人の友人」という関係(潜在リンク)をランダムに選んで接続する操作、<br>
* 確率1-p_nnで新しいエージェントをランダムに追加する操作を行うアルゴリズム。<br>
* p_nnはパラメータであるが、与えられていない場合はデフォルト値{@value #P_NN_DEFAULT}を用いる。<br>
* アルゴリズムから、確率1-p_nnでエージェント数が1増え、次数の総和が2増える一方、<br>
* p_nnで次数の総和だけが2増えることがわかる。<br>
* 従って特定の次数degreeに漸近するネットワークにしたい場合は、{@code p_nn = 1 - 2/(degree)}とすれば良い。<br>
* ただし、エージェント数が十分に大きくない場合は必ずしも良い近似とならない。
*
* @author Yu
*
*/
public class StaticCNNNetwork extends StaticNetwork {
private double p_nn;
private static final double P_NN_DEFAULT = 0.666667;
//private static final double P_NN_DEFAULT = 0.75;
// private List<Integer[]> potentialLinks = new ArrayList<Integer[]>();
// private List<Edge> potentialLinks = new ArrayList<Edge>();
// private Set<Integer[]> potentialLinks = new HashSet<Integer[]>();
private Set<Edge> potentialLinks = new HashSet<Edge>();
private int numNodes = 0;
private int numEdges = 0;
@Override
public void build() {
//test
// Edge test1 = new Edge(0, 1);
// Edge test2 = new Edge(0, 1);
// System.out.println((test1.equals(test2))? "true" : "false");
// HashSet<Edge> testSet = new HashSet<StaticNetwork.Edge>();
// System.out.println((testSet.add(test1))? "added" : "not");
// System.out.println((testSet.add(test2))? "added" : "not");
//とりあえず無向グラフ. CNNは有向グラフを作るのが難しい.
if (this.getOrientation() == UNDIRECTED) {
//ネットワークの種を作る
this.constructLink(0, 2);
this.constructLink(1, 2);
this.numNodes = 3;
this.numEdges = 2;
//指定された数のエージェントからなるネットワークが出来るまでイテレート
while(this.numNodes < this.getnAgents()) {
double roll = this.localRNG.nextDouble();
if (roll < this.p_nn) {
this.connectPotential();
} else {
this.addNode();
}
}
}
}
/**
* ポテンシャルリンクをリンクにする。
*/
private void connectPotential() {
int listSize = this.potentialLinks.size();
if (listSize == 0) return;
// Collections.shuffle(this.potentialLinks);
// int roll = this.localRNG.nextInt(listSize);
// Integer[] pLink = this.potentialLinks.get(roll);
// Edge pLink = this.potentialLinks.get(roll);
// Edge pLink = this.potentialLinks.get(0);
// this.potentialLinks.remove(roll); //rollでランダムなポテンシャルリンクを選び出して,リストから除去
// ArrayList<Integer[]> asList = new ArrayList<Integer[]>(this.potentialLinks); //サンプリングするために,SetをListに
ArrayList<Edge> asList = new ArrayList<Edge>(this.potentialLinks); //サンプリングするために,SetをListに.→ここが多分くっそ遅い?
Collections.shuffle(asList);
Edge pLink = asList.get(0); //shuffleして順番をランダムにし,最初の1つを取得.
// Edge pLink = asList.get(roll); //shuffleして順番をランダムにし,最初の1つを取得.
// Edge pLink = null;
// for (int i = 0; i <= roll; i++) {
// pLink = this.potentialLinks.iterator().next();
// }
this.potentialLinks.remove(pLink);
this.constructLink(pLink.littleEnd, pLink.bigEnd); //それをエッジに変換
asList.clear();
}
/**
* 新規エージェントをランダムに加える。
*/
private void addNode() {
int target = this.localRNG.nextInt(this.numNodes);
int newcomer = this.numNodes++;
this.constructLink(newcomer, target);
System.out.println(this.numNodes + " " + this.numEdges);
}
/**
* subjectとobjectの間にリンクを張り、生じるポテンシャルリンクを登録する。<br>
* 二重登録がないように細かくチェックする<br>
* 互いを互いのリストに漏れ無く登録するので、引数を逆にしてこのメソッドを2回呼ぶ必要はない
* @param subject
* @param object
*/
private void constructLink(int subject, int object) {
this.appendToUndirectedListOf(subject, object);
this.appendToUndirectedListOf(object, subject);
this.numEdges++;
this.safeAppendPotentialLink(subject, object);
this.safeAppendPotentialLink(object, subject);
}
/**
* 重複なきよう確認しながらポテンシャルリンクを追加。<br>
* subjectから見た場合と、objectから見た場合、両方のポテンシャルリンクを登録するために、<br>
* 引数を逆にして2回呼ぶ必要がある。
* @param subject
* @param object
*/
private void safeAppendPotentialLink(int subject, int object) {
for(int pIndex : this.getUndirectedListOf(object)) {
if (pIndex != subject &&
!this.getUndirectedListOf(subject).contains(pIndex)) {
// Integer[] pLink = {pIndex, subject};
// Integer[] rLink = {subject, pIndex};
Edge pLink = new Edge(pIndex, subject);
// boolean isNew = true;
// for(Integer[] link : this.potentialLinks) {
// if (Arrays.equals(pLink, link) ||
// Arrays.equals(rLink, link)) { //両方向ないことを確認し、
// isNew = false;
// break;
// }
// }
// if (isNew) this.potentialLinks.add(pLink); //一方向だけ登録。
this.potentialLinks.add(pLink);
/*potentialLinksがSet系Collectionなら,単にaddしていい.重複はない.
* List系なら,重複判定しなければならない.
* 一般に,HashSetなどのSetはHash値に基づく階層型の格納構造を持っているので,
* List系よりも重複判定は高速である.
*/
}
}
}
/**
* 操作の選択率を与える基本コンストラクタ。
* @param nAgents -エージェント数
* @param p_nn -ポテンシャルリンク接続の選択率
* @param orientation -指向性
*/
public StaticCNNNetwork(int nAgents, boolean orientation, double p_nn) {
super("CNN", nAgents, orientation, null);
this.p_nn = p_nn;
this.build();
}
/**
* 目標平均次数を与える基本コンストラクタ。
* @param nAgents
* @param orientation
* @param degree
*/
public StaticCNNNetwork(int nAgents, boolean orientation, Double degree) {
super("CNN", nAgents, orientation, degree);
this.p_nn = 1.0 - 2.0 / (this.getGivenDegree());
this.build();
}
/**
* デフォルトのp_nnを用いるコンストラクタ。
* @param nAgents
* @param orientation
*/
public StaticCNNNetwork(int nAgents, boolean orientation) {
this(nAgents, orientation, P_NN_DEFAULT);
}
/**
* エージェント数と平均次数を与えるコンストラクタ.無向グラフ.p_nnは平均次数がdegreeに漸近するよう設定される.
* @param nAgents
* @param degree
*/
public StaticCNNNetwork(int nAgents, Double degree) {
this(nAgents, UNDIRECTED, degree);
}
/**
* エージェント数を与えて無向グラフを作るコンストラクタ。
* @param nAgents
*/
public StaticCNNNetwork(int nAgents) {
this(nAgents, UNDIRECTED);
}
}
| UTF-8 | Java | 7,632 | java | StaticCNNNetwork.java | Java | [
{
"context": "し、エージェント数が十分に大きくない場合は必ずしも良い近似とならない。\n * \n * @author Yu\n *\n */\npublic class StaticCNNNetwork extends Stat",
"end": 581,
"score": 0.9954885244369507,
"start": 579,
"tag": "NAME",
"value": "Yu"
}
] | null | [] | package matz.basics.network;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* VazquezのCNNモデルに基づき、現実やSNSでの友人関係に近いネットワークを生成するクラス。<br>
* 確率p_nnで「友人の友人」という関係(潜在リンク)をランダムに選んで接続する操作、<br>
* 確率1-p_nnで新しいエージェントをランダムに追加する操作を行うアルゴリズム。<br>
* p_nnはパラメータであるが、与えられていない場合はデフォルト値{@value #P_NN_DEFAULT}を用いる。<br>
* アルゴリズムから、確率1-p_nnでエージェント数が1増え、次数の総和が2増える一方、<br>
* p_nnで次数の総和だけが2増えることがわかる。<br>
* 従って特定の次数degreeに漸近するネットワークにしたい場合は、{@code p_nn = 1 - 2/(degree)}とすれば良い。<br>
* ただし、エージェント数が十分に大きくない場合は必ずしも良い近似とならない。
*
* @author Yu
*
*/
public class StaticCNNNetwork extends StaticNetwork {
private double p_nn;
private static final double P_NN_DEFAULT = 0.666667;
//private static final double P_NN_DEFAULT = 0.75;
// private List<Integer[]> potentialLinks = new ArrayList<Integer[]>();
// private List<Edge> potentialLinks = new ArrayList<Edge>();
// private Set<Integer[]> potentialLinks = new HashSet<Integer[]>();
private Set<Edge> potentialLinks = new HashSet<Edge>();
private int numNodes = 0;
private int numEdges = 0;
@Override
public void build() {
//test
// Edge test1 = new Edge(0, 1);
// Edge test2 = new Edge(0, 1);
// System.out.println((test1.equals(test2))? "true" : "false");
// HashSet<Edge> testSet = new HashSet<StaticNetwork.Edge>();
// System.out.println((testSet.add(test1))? "added" : "not");
// System.out.println((testSet.add(test2))? "added" : "not");
//とりあえず無向グラフ. CNNは有向グラフを作るのが難しい.
if (this.getOrientation() == UNDIRECTED) {
//ネットワークの種を作る
this.constructLink(0, 2);
this.constructLink(1, 2);
this.numNodes = 3;
this.numEdges = 2;
//指定された数のエージェントからなるネットワークが出来るまでイテレート
while(this.numNodes < this.getnAgents()) {
double roll = this.localRNG.nextDouble();
if (roll < this.p_nn) {
this.connectPotential();
} else {
this.addNode();
}
}
}
}
/**
* ポテンシャルリンクをリンクにする。
*/
private void connectPotential() {
int listSize = this.potentialLinks.size();
if (listSize == 0) return;
// Collections.shuffle(this.potentialLinks);
// int roll = this.localRNG.nextInt(listSize);
// Integer[] pLink = this.potentialLinks.get(roll);
// Edge pLink = this.potentialLinks.get(roll);
// Edge pLink = this.potentialLinks.get(0);
// this.potentialLinks.remove(roll); //rollでランダムなポテンシャルリンクを選び出して,リストから除去
// ArrayList<Integer[]> asList = new ArrayList<Integer[]>(this.potentialLinks); //サンプリングするために,SetをListに
ArrayList<Edge> asList = new ArrayList<Edge>(this.potentialLinks); //サンプリングするために,SetをListに.→ここが多分くっそ遅い?
Collections.shuffle(asList);
Edge pLink = asList.get(0); //shuffleして順番をランダムにし,最初の1つを取得.
// Edge pLink = asList.get(roll); //shuffleして順番をランダムにし,最初の1つを取得.
// Edge pLink = null;
// for (int i = 0; i <= roll; i++) {
// pLink = this.potentialLinks.iterator().next();
// }
this.potentialLinks.remove(pLink);
this.constructLink(pLink.littleEnd, pLink.bigEnd); //それをエッジに変換
asList.clear();
}
/**
* 新規エージェントをランダムに加える。
*/
private void addNode() {
int target = this.localRNG.nextInt(this.numNodes);
int newcomer = this.numNodes++;
this.constructLink(newcomer, target);
System.out.println(this.numNodes + " " + this.numEdges);
}
/**
* subjectとobjectの間にリンクを張り、生じるポテンシャルリンクを登録する。<br>
* 二重登録がないように細かくチェックする<br>
* 互いを互いのリストに漏れ無く登録するので、引数を逆にしてこのメソッドを2回呼ぶ必要はない
* @param subject
* @param object
*/
private void constructLink(int subject, int object) {
this.appendToUndirectedListOf(subject, object);
this.appendToUndirectedListOf(object, subject);
this.numEdges++;
this.safeAppendPotentialLink(subject, object);
this.safeAppendPotentialLink(object, subject);
}
/**
* 重複なきよう確認しながらポテンシャルリンクを追加。<br>
* subjectから見た場合と、objectから見た場合、両方のポテンシャルリンクを登録するために、<br>
* 引数を逆にして2回呼ぶ必要がある。
* @param subject
* @param object
*/
private void safeAppendPotentialLink(int subject, int object) {
for(int pIndex : this.getUndirectedListOf(object)) {
if (pIndex != subject &&
!this.getUndirectedListOf(subject).contains(pIndex)) {
// Integer[] pLink = {pIndex, subject};
// Integer[] rLink = {subject, pIndex};
Edge pLink = new Edge(pIndex, subject);
// boolean isNew = true;
// for(Integer[] link : this.potentialLinks) {
// if (Arrays.equals(pLink, link) ||
// Arrays.equals(rLink, link)) { //両方向ないことを確認し、
// isNew = false;
// break;
// }
// }
// if (isNew) this.potentialLinks.add(pLink); //一方向だけ登録。
this.potentialLinks.add(pLink);
/*potentialLinksがSet系Collectionなら,単にaddしていい.重複はない.
* List系なら,重複判定しなければならない.
* 一般に,HashSetなどのSetはHash値に基づく階層型の格納構造を持っているので,
* List系よりも重複判定は高速である.
*/
}
}
}
/**
* 操作の選択率を与える基本コンストラクタ。
* @param nAgents -エージェント数
* @param p_nn -ポテンシャルリンク接続の選択率
* @param orientation -指向性
*/
public StaticCNNNetwork(int nAgents, boolean orientation, double p_nn) {
super("CNN", nAgents, orientation, null);
this.p_nn = p_nn;
this.build();
}
/**
* 目標平均次数を与える基本コンストラクタ。
* @param nAgents
* @param orientation
* @param degree
*/
public StaticCNNNetwork(int nAgents, boolean orientation, Double degree) {
super("CNN", nAgents, orientation, degree);
this.p_nn = 1.0 - 2.0 / (this.getGivenDegree());
this.build();
}
/**
* デフォルトのp_nnを用いるコンストラクタ。
* @param nAgents
* @param orientation
*/
public StaticCNNNetwork(int nAgents, boolean orientation) {
this(nAgents, orientation, P_NN_DEFAULT);
}
/**
* エージェント数と平均次数を与えるコンストラクタ.無向グラフ.p_nnは平均次数がdegreeに漸近するよう設定される.
* @param nAgents
* @param degree
*/
public StaticCNNNetwork(int nAgents, Double degree) {
this(nAgents, UNDIRECTED, degree);
}
/**
* エージェント数を与えて無向グラフを作るコンストラクタ。
* @param nAgents
*/
public StaticCNNNetwork(int nAgents) {
this(nAgents, UNDIRECTED);
}
}
| 7,632 | 0.687802 | 0.679704 | 202 | 27.732674 | 22.789562 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.282178 | false | false | 1 |
ca0bbaeb669805cb5f37a5e7e85005e77eef2f0c | 962,072,674,709 | 2081a6ef2af1c00ca3f08b6f1095aebbd6e19b83 | /src/main/java/org/wooddog/domain/Stock.java | 682c1db3674d9e37a1291aa8d47c952557bb7ab5 | [] | no_license | claus437/feed-analyser | https://github.com/claus437/feed-analyser | 2263a9e5222b75c7a67a8c60ba838473f37f8501 | cbd93d2dfe3982b6bea086a0c549d9ea37362867 | refs/heads/master | 2016-09-16T15:31:36.554000 | 2011-08-29T05:47:02 | 2011-08-29T05:47:02 | 1,987,249 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.wooddog.domain;
import java.util.Date;
/**
* Created by IntelliJ IDEA.
* User: DENCBR
* Date: 15-08-11
* Time: 18:49
* To change this template use File | Settings | File Templates.
*/
public class Stock {
private int id;
private String company;
private String value;
private String diff;
private Date date;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDiff() {
return diff;
}
public void setDiff(String diff) {
this.diff = diff;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "Stock{" +
"company='" + company + '\'' +
", value='" + value + '\'' +
", diff='" + diff + '\'' +
'}';
}
}
| UTF-8 | Java | 1,296 | java | Stock.java | Java | [
{
"context": "Date;\r\n\r\n/**\r\n* Created by IntelliJ IDEA.\r\n* User: DENCBR\r\n* Date: 15-08-11\r\n* Time: 18:49\r\n* To change thi",
"end": 105,
"score": 0.9996712803840637,
"start": 99,
"tag": "USERNAME",
"value": "DENCBR"
}
] | null | [] | package org.wooddog.domain;
import java.util.Date;
/**
* Created by IntelliJ IDEA.
* User: DENCBR
* Date: 15-08-11
* Time: 18:49
* To change this template use File | Settings | File Templates.
*/
public class Stock {
private int id;
private String company;
private String value;
private String diff;
private Date date;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDiff() {
return diff;
}
public void setDiff(String diff) {
this.diff = diff;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "Stock{" +
"company='" + company + '\'' +
", value='" + value + '\'' +
", diff='" + diff + '\'' +
'}';
}
}
| 1,296 | 0.500772 | 0.493056 | 67 | 17.343283 | 14.728947 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.328358 | false | false | 4 |
ab48d098f3e78a097ab3c7b6ef4273490d3af0ba | 27,230,092,682,085 | db913543eafe3d79436c736403b6709daf360bc4 | /src/main/java/com/demo/service/mapper/TestMapper.java | db3e7e3456ab2afd0646f54b904b37f039113970 | [] | no_license | h-virtualspace/service | https://github.com/h-virtualspace/service | be0d2c7c9272fcb16aebadddc9d05bce10625998 | 7548a3ba914dadf07cbd2a00b294498d15998dd6 | refs/heads/master | 2021-01-19T18:44:35.828000 | 2017-07-02T10:13:04 | 2017-07-02T10:13:04 | 101,160,933 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.demo.service.mapper;
import java.util.List;
import java.util.Map;
/**
* 测试mapper
* @author koujp
*
*/
public interface TestMapper {
public List<Map<String,String>> getAll();
public boolean add(Map<String,String> map);
}
| UTF-8 | Java | 243 | java | TestMapper.java | Java | [
{
"context": ";\nimport java.util.Map;\n/**\n * 测试mapper\n * @author koujp\n *\n */\npublic interface TestMapper {\n\tpublic List",
"end": 111,
"score": 0.9995460510253906,
"start": 106,
"tag": "USERNAME",
"value": "koujp"
}
] | null | [] | package com.demo.service.mapper;
import java.util.List;
import java.util.Map;
/**
* 测试mapper
* @author koujp
*
*/
public interface TestMapper {
public List<Map<String,String>> getAll();
public boolean add(Map<String,String> map);
}
| 243 | 0.715481 | 0.715481 | 13 | 17.384615 | 15.092221 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false | 4 |
748eba4f2e92f059ae8c5bc36048f57629cac95f | 27,298,812,192,915 | 2c52479061527f368ce0a33d43506cc54bc2e372 | /src/com/internousdev/miyako/dto/test/PaginationDTOTest.java | d677b6b05ffd16354fe8f33331146dcaa8927ee6 | [] | no_license | yoneyama829/miyako | https://github.com/yoneyama829/miyako | f95836d9e33c8eaa4e7313fd18e79db7fcdee78f | 2daee125f71702ec574bb4c3488406479e218d9d | refs/heads/master | 2021-03-29T08:34:19.729000 | 2020-03-17T10:15:07 | 2020-03-17T10:15:07 | 139,176,726 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.internousdev.miyako.dto.test;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import com.internousdev.miyako.dto.PaginationDTO;
import com.internousdev.miyako.dto.ProductInfoDTO;
public class PaginationDTOTest {
@Test
public void testGetTotalPageSize1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}
@Test
public void testSetTotalPageSize1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}
@Test
public void testGetTotalPageSize2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}
@Test
public void testSetTotalPageSize2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}
@Test
public void testGetTotalPageSize3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}
@Test
public void testSetTotalPageSize3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}
//最大値以上
@Test
public void testGetTotalPageSize4() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setTotalPageSize(expected);
int actual= dto.getTotalPageSize();
assertEquals(expected, actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetTotalPageSize4() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
//最小値以下
@Test
public void testGetTotalPageSize5() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testSetTotalPageSize5() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testGetCurrentPageNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetCurrentPageNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected, actual);
}
@Test
public void testGetCurrentPageNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetCurrentPageNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected, actual);
}
@Test
public void testGetCurrentPageNo3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetCurrentPageNo3(){
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected,actual);
}
//最大値以上
@Test
public void testGetCurrentPageNo4() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected, actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetCurrentPageNo4(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected, actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
//最小値以下
@Test
public void testSetCurrentPageNo5(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected, actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testGetCurrentPageNo5(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setCurrentPageNo(expected);
assertEquals(expected, dto.getCurrentPageNo());
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testGetTotalRecordSize1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected,actual);
}
@Test
public void testSetTotalRecordSize1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected, actual);
}
@Test
public void testGetTotalRecordSize2(){
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected,actual);
}
@Test
public void testSetTotalRecordSize2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected, actual);
}
@Test
public void testGetTotalRecordSize3(){
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected,actual);
}
@Test
public void testSetTotalRecordSize3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected, actual);
}
@Test
public void testGetTotalRecordSize4(){
PaginationDTO dto = new PaginationDTO();
try {
int expected = Integer.parseInt("2147483648");
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected,actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetTotalRecordSize4(){
PaginationDTO dto = new PaginationDTO();
try {
int expected = Integer.parseInt("2147483648");
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected,actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testGetTotalRecordSize5(){
PaginationDTO dto = new PaginationDTO();
try {
int expected = Integer.parseInt("-2147483649");
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected,actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testSetTotalRecordSize5(){
PaginationDTO dto = new PaginationDTO();
try {
int expected = Integer.parseInt("-2147483649");
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected,actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testGetStartRecordNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}
@Test
public void testSetStartRecordNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}
@Test
public void testGetStartRecordNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}
@Test
public void testSetStartRecordNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}
@Test
public void testGetStartRecordNo3(){
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}
@Test
public void testSetStartRecordNo3(){
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}
@Test
public void testGetStartRecordNo4(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetStartRecordNo4(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testGetStartRecordNo5(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testSetStartRecordNo5(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setStartRecordNo(expected);
int actual =dto.getStartRecordNo();
assertEquals(expected, actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testGetEndRecordNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected,actual);
}
@Test
public void testSetEndRecordNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected, actual);
}
@Test
public void testGetEndRecordNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setEndRecordNo(expected);
int actual =dto.getEndRecordNo();
assertEquals(expected,actual);
}
@Test
public void testSetEndRecordNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected, actual);
}
@Test
public void testGetEndRecordNo3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected , actual);
}
@Test
public void testSetEndRecordNo3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected, actual);
}
@Test
public void testGetEndRecordNo4() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetEndRecordNo4() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected, actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testGetEndRecordNo5() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected, actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testSetEndRecordNo5() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testGetPageNumberList1() {
PaginationDTO dto = new PaginationDTO();
Integer [] expected = {0};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in ,actual);
}
@Test
public void testSetPageNumberList1() {
PaginationDTO dto = new PaginationDTO();
Integer [] expected = {0};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in ,actual);
}
@Test
public void testGetPageNumberList2() {
PaginationDTO dto = new PaginationDTO();
Integer [] expected = {2147483647};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in ,actual);
}
@Test
public void testSetPageNumberList2() {
PaginationDTO dto = new PaginationDTO();
Integer [] expected = {2147483647};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in ,actual);
}
@Test
public void testGetPageNumberList3() {
PaginationDTO dto = new PaginationDTO();
Integer [] expected = {-2147483648};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in ,actual);
}
@Test
public void testSetPageNumberList3() {
PaginationDTO dto = new PaginationDTO();
Integer [] expected = {-2147483648};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in ,actual);
}
@Test
public void testGetPageNumberList4(){
PaginationDTO dto = new PaginationDTO();
try{
Integer [] expected = {Integer.parseInt("2147483648")};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetPageNumberList4(){
PaginationDTO dto = new PaginationDTO();
try{
Integer [] expected = {Integer.parseInt("2147483648")};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testGetPageNumberList5(){
PaginationDTO dto = new PaginationDTO();
try{
Integer [] expected = {Integer.parseInt("-2147483649")};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testSetPageNumberList5(){
PaginationDTO dto = new PaginationDTO();
try{
Integer [] expected = {Integer.parseInt("-2147483649")};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in.get(0) , actual.get(0));
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testGetCurrentProductInfoPage1() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
int expected = 0;
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}
@Test
public void testSetCurrentProductInfoPage1() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
int expected = 0;
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}
@Test
public void testGetCurrentProductInfoPage2() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
int expected = 2147483647;
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}
@Test
public void testSetCurrentProductInfoPage2() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
int expected = 2147483647;
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}
@Test
public void testGetCurrentProductInfoPage3() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
int expected = -2147483648;
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}
@Test
public void testSetCurrentProductInfoPage3() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
int expected = -2147483648;
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}
@Test
public void testGetCurrentProductInfoPage4() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
try{
int expected = Integer.parseInt("2147483648");
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetCurrentProductInfoPage4() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
try{
int expected = Integer.parseInt("2147483648");
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testGetCurrentProductInfoPage5() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
try{
int expected = Integer.parseInt("-2147483649");
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testSetCurrentProductInfoPage5() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
try{
int expected = Integer.parseInt("-2147483649");
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testHasNextPage1() {
PaginationDTO dto = new PaginationDTO();
Boolean expected = true;
dto.setHasNextPage(expected);
Boolean actual = dto.getHasNextPage();
assertEquals(expected,actual);
}
@Test
public void testSetNextPage1() {
PaginationDTO dto = new PaginationDTO();
Boolean expected = true;
dto.setHasNextPage(expected);
Boolean actual = dto.getHasNextPage();
assertEquals(expected,actual);
}
@Test
public void testHasNextPage2() {
PaginationDTO dto = new PaginationDTO();
Boolean expected = false;
dto.setHasNextPage(expected);
Boolean actual = dto.getHasNextPage();
assertEquals(expected,actual);
}
@Test
public void testSetNextPage2() {
PaginationDTO dto = new PaginationDTO();
Boolean expected = false;
dto.setHasNextPage(expected);
Boolean actual = dto.getHasNextPage();
assertEquals(expected,actual);
}
@Test
public void testHasPreviousPage1() {
PaginationDTO dto = new PaginationDTO();
Boolean expected = true;
dto.setHasPreviousPage(expected);
Boolean actual = dto.getHasPreviousPage();
assertEquals(expected, actual);
}
@Test
public void testSetPreviousPage1() {
PaginationDTO dto = new PaginationDTO();
Boolean expected = true;
dto.setHasPreviousPage(expected);
Boolean actual = dto.getHasPreviousPage();
assertEquals(expected,actual);
}
@Test
public void testHasPreviousPage2() {
PaginationDTO dto = new PaginationDTO();
Boolean expected = false;
dto.setHasPreviousPage(expected);
Boolean actual = dto.getHasPreviousPage();
assertEquals(expected, actual);
}
@Test
public void testSetPreviousPage2() {
PaginationDTO dto = new PaginationDTO();
Boolean expected = false;
dto.setHasPreviousPage(expected);
Boolean actual = dto.getHasPreviousPage();
assertEquals(expected,actual);
}
@Test
public void testGetNextPageNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetNextPageNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected, actual);
}
@Test
public void testGetNextPageNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetNextPageNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected, actual);
}
@Test
public void testGetNextPageNo3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetNextPageNo3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected, actual);
}
@Test
public void testGetNextPageNo4(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetNextPageNo4(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testGetNextPageNo5(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testSetNextPageNo5(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testGetPreviousPageNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetPreviousPageNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected , actual);
}
@Test
public void testGetPreviousPageNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetPreviousPageNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected , actual);
}
@Test
public void testGetPreviousPageNo3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetPreviousPageNo3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected , actual);
}
@Test
public void testGetPreviousPageNo4(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected, actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetPreviousPageNo4(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected, actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testGetPreviousPageNo5(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected, actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testSetPreviousPageNo5(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected, actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
}
| UTF-8 | Java | 30,003 | java | PaginationDTOTest.java | Java | [] | null | [] | package com.internousdev.miyako.dto.test;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import com.internousdev.miyako.dto.PaginationDTO;
import com.internousdev.miyako.dto.ProductInfoDTO;
public class PaginationDTOTest {
@Test
public void testGetTotalPageSize1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}
@Test
public void testSetTotalPageSize1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}
@Test
public void testGetTotalPageSize2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}
@Test
public void testSetTotalPageSize2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}
@Test
public void testGetTotalPageSize3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}
@Test
public void testSetTotalPageSize3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}
//最大値以上
@Test
public void testGetTotalPageSize4() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setTotalPageSize(expected);
int actual= dto.getTotalPageSize();
assertEquals(expected, actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetTotalPageSize4() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
//最小値以下
@Test
public void testGetTotalPageSize5() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testSetTotalPageSize5() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setTotalPageSize(expected);
int actual = dto.getTotalPageSize();
assertEquals(expected, actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testGetCurrentPageNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetCurrentPageNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected, actual);
}
@Test
public void testGetCurrentPageNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetCurrentPageNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected, actual);
}
@Test
public void testGetCurrentPageNo3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetCurrentPageNo3(){
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected,actual);
}
//最大値以上
@Test
public void testGetCurrentPageNo4() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected, actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetCurrentPageNo4(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected, actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
//最小値以下
@Test
public void testSetCurrentPageNo5(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setCurrentPageNo(expected);
int actual = dto.getCurrentPageNo();
assertEquals(expected, actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testGetCurrentPageNo5(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setCurrentPageNo(expected);
assertEquals(expected, dto.getCurrentPageNo());
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testGetTotalRecordSize1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected,actual);
}
@Test
public void testSetTotalRecordSize1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected, actual);
}
@Test
public void testGetTotalRecordSize2(){
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected,actual);
}
@Test
public void testSetTotalRecordSize2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected, actual);
}
@Test
public void testGetTotalRecordSize3(){
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected,actual);
}
@Test
public void testSetTotalRecordSize3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected, actual);
}
@Test
public void testGetTotalRecordSize4(){
PaginationDTO dto = new PaginationDTO();
try {
int expected = Integer.parseInt("2147483648");
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected,actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetTotalRecordSize4(){
PaginationDTO dto = new PaginationDTO();
try {
int expected = Integer.parseInt("2147483648");
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected,actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testGetTotalRecordSize5(){
PaginationDTO dto = new PaginationDTO();
try {
int expected = Integer.parseInt("-2147483649");
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected,actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testSetTotalRecordSize5(){
PaginationDTO dto = new PaginationDTO();
try {
int expected = Integer.parseInt("-2147483649");
dto.setTotalRecordSize(expected);
int actual = dto.getTotalRecordSize();
assertEquals(expected,actual);
}catch (RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testGetStartRecordNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}
@Test
public void testSetStartRecordNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}
@Test
public void testGetStartRecordNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}
@Test
public void testSetStartRecordNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}
@Test
public void testGetStartRecordNo3(){
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}
@Test
public void testSetStartRecordNo3(){
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}
@Test
public void testGetStartRecordNo4(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetStartRecordNo4(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testGetStartRecordNo5(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setStartRecordNo(expected);
int actual = dto.getStartRecordNo();
assertEquals(expected,actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testSetStartRecordNo5(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setStartRecordNo(expected);
int actual =dto.getStartRecordNo();
assertEquals(expected, actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testGetEndRecordNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected,actual);
}
@Test
public void testSetEndRecordNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected, actual);
}
@Test
public void testGetEndRecordNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setEndRecordNo(expected);
int actual =dto.getEndRecordNo();
assertEquals(expected,actual);
}
@Test
public void testSetEndRecordNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected, actual);
}
@Test
public void testGetEndRecordNo3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected , actual);
}
@Test
public void testSetEndRecordNo3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected, actual);
}
@Test
public void testGetEndRecordNo4() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetEndRecordNo4() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected, actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testGetEndRecordNo5() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected, actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testSetEndRecordNo5() {
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setEndRecordNo(expected);
int actual = dto.getEndRecordNo();
assertEquals(expected , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testGetPageNumberList1() {
PaginationDTO dto = new PaginationDTO();
Integer [] expected = {0};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in ,actual);
}
@Test
public void testSetPageNumberList1() {
PaginationDTO dto = new PaginationDTO();
Integer [] expected = {0};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in ,actual);
}
@Test
public void testGetPageNumberList2() {
PaginationDTO dto = new PaginationDTO();
Integer [] expected = {2147483647};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in ,actual);
}
@Test
public void testSetPageNumberList2() {
PaginationDTO dto = new PaginationDTO();
Integer [] expected = {2147483647};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in ,actual);
}
@Test
public void testGetPageNumberList3() {
PaginationDTO dto = new PaginationDTO();
Integer [] expected = {-2147483648};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in ,actual);
}
@Test
public void testSetPageNumberList3() {
PaginationDTO dto = new PaginationDTO();
Integer [] expected = {-2147483648};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in ,actual);
}
@Test
public void testGetPageNumberList4(){
PaginationDTO dto = new PaginationDTO();
try{
Integer [] expected = {Integer.parseInt("2147483648")};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetPageNumberList4(){
PaginationDTO dto = new PaginationDTO();
try{
Integer [] expected = {Integer.parseInt("2147483648")};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testGetPageNumberList5(){
PaginationDTO dto = new PaginationDTO();
try{
Integer [] expected = {Integer.parseInt("-2147483649")};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testSetPageNumberList5(){
PaginationDTO dto = new PaginationDTO();
try{
Integer [] expected = {Integer.parseInt("-2147483649")};
List<Integer> in = Arrays.asList(expected);
dto.setPageNumberList(in);
List<Integer> actual = dto.getPageNumberList();
assertEquals(in.get(0) , actual.get(0));
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testGetCurrentProductInfoPage1() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
int expected = 0;
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}
@Test
public void testSetCurrentProductInfoPage1() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
int expected = 0;
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}
@Test
public void testGetCurrentProductInfoPage2() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
int expected = 2147483647;
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}
@Test
public void testSetCurrentProductInfoPage2() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
int expected = 2147483647;
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}
@Test
public void testGetCurrentProductInfoPage3() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
int expected = -2147483648;
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}
@Test
public void testSetCurrentProductInfoPage3() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
int expected = -2147483648;
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}
@Test
public void testGetCurrentProductInfoPage4() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
try{
int expected = Integer.parseInt("2147483648");
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetCurrentProductInfoPage4() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
try{
int expected = Integer.parseInt("2147483648");
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testGetCurrentProductInfoPage5() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
try{
int expected = Integer.parseInt("-2147483649");
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testSetCurrentProductInfoPage5() {
PaginationDTO dto = new PaginationDTO();
ProductInfoDTO product = new ProductInfoDTO();
try{
int expected = Integer.parseInt("-2147483649");
product.setId(expected);
List<ProductInfoDTO> list = Arrays.asList(product);
dto.setCurrentProductInfoPage(list);
List<ProductInfoDTO> actual = dto.getCurrentProductInfoPage();
assertEquals(expected, actual.get(0).getId());
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testHasNextPage1() {
PaginationDTO dto = new PaginationDTO();
Boolean expected = true;
dto.setHasNextPage(expected);
Boolean actual = dto.getHasNextPage();
assertEquals(expected,actual);
}
@Test
public void testSetNextPage1() {
PaginationDTO dto = new PaginationDTO();
Boolean expected = true;
dto.setHasNextPage(expected);
Boolean actual = dto.getHasNextPage();
assertEquals(expected,actual);
}
@Test
public void testHasNextPage2() {
PaginationDTO dto = new PaginationDTO();
Boolean expected = false;
dto.setHasNextPage(expected);
Boolean actual = dto.getHasNextPage();
assertEquals(expected,actual);
}
@Test
public void testSetNextPage2() {
PaginationDTO dto = new PaginationDTO();
Boolean expected = false;
dto.setHasNextPage(expected);
Boolean actual = dto.getHasNextPage();
assertEquals(expected,actual);
}
@Test
public void testHasPreviousPage1() {
PaginationDTO dto = new PaginationDTO();
Boolean expected = true;
dto.setHasPreviousPage(expected);
Boolean actual = dto.getHasPreviousPage();
assertEquals(expected, actual);
}
@Test
public void testSetPreviousPage1() {
PaginationDTO dto = new PaginationDTO();
Boolean expected = true;
dto.setHasPreviousPage(expected);
Boolean actual = dto.getHasPreviousPage();
assertEquals(expected,actual);
}
@Test
public void testHasPreviousPage2() {
PaginationDTO dto = new PaginationDTO();
Boolean expected = false;
dto.setHasPreviousPage(expected);
Boolean actual = dto.getHasPreviousPage();
assertEquals(expected, actual);
}
@Test
public void testSetPreviousPage2() {
PaginationDTO dto = new PaginationDTO();
Boolean expected = false;
dto.setHasPreviousPage(expected);
Boolean actual = dto.getHasPreviousPage();
assertEquals(expected,actual);
}
@Test
public void testGetNextPageNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetNextPageNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected, actual);
}
@Test
public void testGetNextPageNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetNextPageNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected, actual);
}
@Test
public void testGetNextPageNo3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetNextPageNo3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected, actual);
}
@Test
public void testGetNextPageNo4(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetNextPageNo4(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testGetNextPageNo5(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testSetNextPageNo5(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setNextPageNo(expected);
int actual = dto.getNextPageNo();
assertEquals(expected , actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testGetPreviousPageNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetPreviousPageNo1() {
PaginationDTO dto = new PaginationDTO();
int expected = 0;
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected , actual);
}
@Test
public void testGetPreviousPageNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetPreviousPageNo2() {
PaginationDTO dto = new PaginationDTO();
int expected = 2147483647;
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected , actual);
}
@Test
public void testGetPreviousPageNo3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected, actual);
}
@Test
public void testSetPreviousPageNo3() {
PaginationDTO dto = new PaginationDTO();
int expected = -2147483648;
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected , actual);
}
@Test
public void testGetPreviousPageNo4(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected, actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testSetPreviousPageNo4(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("2147483648");
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected, actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"2147483648\"");
}
}
@Test
public void testGetPreviousPageNo5(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected, actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
@Test
public void testSetPreviousPageNo5(){
PaginationDTO dto = new PaginationDTO();
try{
int expected = Integer.parseInt("-2147483649");
dto.setPreviousPageNo(expected);
int actual = dto.getPreviousPageNo();
assertEquals(expected, actual);
}catch(RuntimeException e){
assertEquals(e.getMessage(), "For input string: \"-2147483649\"");
}
}
}
| 30,003 | 0.718653 | 0.678337 | 1,231 | 23.340374 | 19.869974 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.03818 | false | false | 4 |
21f7f47a26014718faafd1177ba174cac386125c | 25,512,105,800,325 | c1e94f2606fbb48bc2cb7089f7738db3f1310ca5 | /src/main/java/quantitymeasurement/UnitMeasurementSystem.java | 3c99f96229633ae9ce33f3acad1abd7ddef82435 | [] | no_license | SakshiShetty641/QuantityMeasurement | https://github.com/SakshiShetty641/QuantityMeasurement | 7cf1a2c89ca3e0f06b941c635f6e492ec2a15bbe | 6e75f344a447f51b1ea96b2a441e735af507f912 | refs/heads/main | 2023-08-11T17:24:55.323000 | 2021-09-24T01:39:46 | 2021-09-24T01:39:46 | 408,348,934 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package quantitymeasurement;
public class UnitMeasurementSystem {
public double value;
public MeasurementUnits unit;
public UnitMeasurementSystem(MeasurementUnits unit, double value) {
this.value = value;
this.unit = unit;
}
public boolean compare(UnitMeasurementSystem that) {
if (this.unit.equals(that.unit))
return this.equals(that);
return Double.compare(this.unit.convertToBaseUnit(this), that.unit.convertToBaseUnit(that)) == 0;
}
public UnitMeasurementSystem addition(UnitMeasurementSystem that, MeasurementUnits requiredUnit) {
double sumOfInput = this.unit.convertToBaseUnit(this) + that.unit.convertToBaseUnit(that);
return new UnitMeasurementSystem(requiredUnit, sumOfInput);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UnitMeasurementSystem quantity = (UnitMeasurementSystem) o;
return Double.compare(quantity.value, value) == 0 && unit == quantity.unit;
}
}
| UTF-8 | Java | 1,102 | java | UnitMeasurementSystem.java | Java | [] | null | [] | package quantitymeasurement;
public class UnitMeasurementSystem {
public double value;
public MeasurementUnits unit;
public UnitMeasurementSystem(MeasurementUnits unit, double value) {
this.value = value;
this.unit = unit;
}
public boolean compare(UnitMeasurementSystem that) {
if (this.unit.equals(that.unit))
return this.equals(that);
return Double.compare(this.unit.convertToBaseUnit(this), that.unit.convertToBaseUnit(that)) == 0;
}
public UnitMeasurementSystem addition(UnitMeasurementSystem that, MeasurementUnits requiredUnit) {
double sumOfInput = this.unit.convertToBaseUnit(this) + that.unit.convertToBaseUnit(that);
return new UnitMeasurementSystem(requiredUnit, sumOfInput);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UnitMeasurementSystem quantity = (UnitMeasurementSystem) o;
return Double.compare(quantity.value, value) == 0 && unit == quantity.unit;
}
}
| 1,102 | 0.686933 | 0.685118 | 31 | 34.548386 | 32.806213 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.645161 | false | false | 4 |
44ad509102b4683e17a165712436e0f05494e215 | 11,613,591,621,369 | 187b7b8d168f25115042332179343edd1da7c696 | /src/main/java/model/entities/employees/LoginData.java | e59bc94fea5f4e6779ac4a24f3a2044b243f430c | [] | no_license | Andrfas/SCPI | https://github.com/Andrfas/SCPI | cfa9584bc81dc04750b1b42559322c4052eac7bc | 55b69dc8fbfc0c57812a310574b4f53869d2a565 | refs/heads/master | 2021-03-12T20:44:20.217000 | 2015-03-22T03:10:35 | 2015-03-22T03:10:35 | 28,803,869 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package model.entities.employees;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import javax.persistence.*;
import java.io.Serializable;
/**
* Created by Andrey on 28.02.2015.
*/
@Entity
@Table(name = "login_data")
public class LoginData implements Serializable {
private Integer employeeId;
private Employee employee;
private String login;
private String password;
public LoginData() {
}
public LoginData(String login, String pass, Employee empl) {
this.employee = empl;
this.login = login;
this.password = pass;
}
@GenericGenerator(name = "generator", strategy = "foreign",
parameters = @Parameter(name = "property", value = "employee"))
@Id
@GeneratedValue(generator = "generator")
@Column(name = "employee_id", nullable = false)
public Integer getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
@Column(name = "login", nullable = false)
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
@Column(name = "password", nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| UTF-8 | Java | 1,653 | java | LoginData.java | Java | [
{
"context": "*;\nimport java.io.Serializable;\n\n/**\n * Created by Andrey on 28.02.2015.\n */\n@Entity\n@Table(name = \"login_d",
"end": 215,
"score": 0.9962002038955688,
"start": 209,
"tag": "NAME",
"value": "Andrey"
}
] | null | [] | package model.entities.employees;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import javax.persistence.*;
import java.io.Serializable;
/**
* Created by Andrey on 28.02.2015.
*/
@Entity
@Table(name = "login_data")
public class LoginData implements Serializable {
private Integer employeeId;
private Employee employee;
private String login;
private String password;
public LoginData() {
}
public LoginData(String login, String pass, Employee empl) {
this.employee = empl;
this.login = login;
this.password = pass;
}
@GenericGenerator(name = "generator", strategy = "foreign",
parameters = @Parameter(name = "property", value = "employee"))
@Id
@GeneratedValue(generator = "generator")
@Column(name = "employee_id", nullable = false)
public Integer getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
@Column(name = "login", nullable = false)
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
@Column(name = "password", nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| 1,653 | 0.648518 | 0.643678 | 72 | 21.958334 | 19.487488 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false | 4 |
c9dcdedd635cd6f0bc09bdc684980eb9b6a594ef | 14,740,327,784,285 | 36bb8d9a32dea713c052172f5e8d9bec679fc4d2 | /src/main/java/ru/engineeroid/model/Reservation.java | b4a8e2b8c053871ceb8dc88e2fe0a70911d1fe59 | [] | no_license | ForLearningAtJob4J/MeetingRooms | https://github.com/ForLearningAtJob4J/MeetingRooms | cb29bd0277c49fe45f1f3c9454b8e38c4b0ffac5 | 35e4de1db03cf0332e23fc2299122d88a44d4be8 | refs/heads/master | 2023-06-10T02:22:03.672000 | 2021-07-05T20:32:27 | 2021-07-05T20:32:27 | 383,165,341 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.engineeroid.model;
import org.hibernate.annotations.CreationTimestamp;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "reservation")
public class Reservation implements IdOwner {
@Id
@GeneratedValue()
private int id;
@Column(name = "name")
private String name;
@ManyToOne
@JoinColumn(name = "creator_id")
private User creator;
@Column(name = "creation_date")
@CreationTimestamp
private Timestamp creationDate;
@ManyToMany
private List<User> participants;
@ManyToOne
@JoinColumn(name = "room_id")
private Room room;
@Column(name = "begin_date")
private Timestamp beginDate;
@Column(name = "end_date")
private Timestamp endDate;
@Override
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void addParticipant(User u) {
this.participants.add(u);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getCreator() {
return creator;
}
public void setCreator(User creator) {
this.creator = creator;
}
public Timestamp getCreationDate() {
return creationDate;
}
public void setCreationDate(Timestamp creationDate) {
this.creationDate = creationDate;
}
public Room getRoom() {
return room;
}
public void setRoom(Room room) {
this.room = room;
}
public Timestamp getBeginDate() {
return beginDate;
}
public void setBeginDate(Timestamp begin) {
this.beginDate = begin;
}
public Timestamp getEndDate() {
return endDate;
}
public void setEndDate(Timestamp end) {
this.endDate = end;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Reservation that = (Reservation) o;
return id == that.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Reservation{"
+ "id=" + id
+ ", name='" + name + '\''
+ ", creator=" + creator
+ ", creationDate=" + creationDate
+ ", room=" + room
+ ", begin=" + beginDate
+ ", end=" + endDate
+ '}';
}
}
| UTF-8 | Java | 2,652 | java | Reservation.java | Java | [
{
"context": " + \"id=\" + id\n + \", name='\" + name + '\\''\n + \", creator=\" + creator\n ",
"end": 2408,
"score": 0.9688084125518799,
"start": 2404,
"tag": "NAME",
"value": "name"
}
] | null | [] | package ru.engineeroid.model;
import org.hibernate.annotations.CreationTimestamp;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "reservation")
public class Reservation implements IdOwner {
@Id
@GeneratedValue()
private int id;
@Column(name = "name")
private String name;
@ManyToOne
@JoinColumn(name = "creator_id")
private User creator;
@Column(name = "creation_date")
@CreationTimestamp
private Timestamp creationDate;
@ManyToMany
private List<User> participants;
@ManyToOne
@JoinColumn(name = "room_id")
private Room room;
@Column(name = "begin_date")
private Timestamp beginDate;
@Column(name = "end_date")
private Timestamp endDate;
@Override
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void addParticipant(User u) {
this.participants.add(u);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getCreator() {
return creator;
}
public void setCreator(User creator) {
this.creator = creator;
}
public Timestamp getCreationDate() {
return creationDate;
}
public void setCreationDate(Timestamp creationDate) {
this.creationDate = creationDate;
}
public Room getRoom() {
return room;
}
public void setRoom(Room room) {
this.room = room;
}
public Timestamp getBeginDate() {
return beginDate;
}
public void setBeginDate(Timestamp begin) {
this.beginDate = begin;
}
public Timestamp getEndDate() {
return endDate;
}
public void setEndDate(Timestamp end) {
this.endDate = end;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Reservation that = (Reservation) o;
return id == that.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Reservation{"
+ "id=" + id
+ ", name='" + name + '\''
+ ", creator=" + creator
+ ", creationDate=" + creationDate
+ ", room=" + room
+ ", begin=" + beginDate
+ ", end=" + endDate
+ '}';
}
}
| 2,652 | 0.558446 | 0.558446 | 130 | 19.4 | 15.495211 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.330769 | false | false | 4 |
a16a0f9318d701444133639b9575603b89d7f6ed | 26,113,401,229,586 | 0658d5e002b838ea4031cb579fc05d2b44cf4de4 | /PhanTichSoDungFor.java | 4303f7a37ae2072874bbb5afc579896b6ead3594 | [] | no_license | congdanh97/Sample_java | https://github.com/congdanh97/Sample_java | a6e707fcb307dbd2c18392faf0dee902578b2a41 | 141c422c4de11455bd8889962623f1753c27171e | refs/heads/master | 2021-09-10T14:04:54.185000 | 2018-03-27T13:31:54 | 2018-03-27T13:31:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package PhanTichSo;
import java.lang.*;
public class PhanTichSoDungFor {
public static void main(String[] args) {
int a = 25684 ;
int tong = 0;
int du = 0;
int sochuso;
sochuso = (int) Math.log10(a) ;
int dem = (sochuso +1);
for(int i=0 ;i < dem;i++) {
du = a % 10;
a = (a - du) / 10;
tong = tong + du;
}
/* for(int i=0 ;;i++) {
du = a % 10;
a = (a - du) / 10;
tong = tong + du;
if ( a == 0 ) {break;}
*/
System.out.print(tong);
}
}
| UTF-8 | Java | 509 | java | PhanTichSoDungFor.java | Java | [] | null | [] | package PhanTichSo;
import java.lang.*;
public class PhanTichSoDungFor {
public static void main(String[] args) {
int a = 25684 ;
int tong = 0;
int du = 0;
int sochuso;
sochuso = (int) Math.log10(a) ;
int dem = (sochuso +1);
for(int i=0 ;i < dem;i++) {
du = a % 10;
a = (a - du) / 10;
tong = tong + du;
}
/* for(int i=0 ;;i++) {
du = a % 10;
a = (a - du) / 10;
tong = tong + du;
if ( a == 0 ) {break;}
*/
System.out.print(tong);
}
}
| 509 | 0.485265 | 0.444008 | 30 | 15.966666 | 11.50792 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.566667 | false | false | 4 |
5f919a6c5365ba4b611b982931208fe5392f4eb6 | 17,059,610,115,676 | f5a1b7f86073ca95982cbbd6e530c81f0db4463f | /Logica/src/main/java/es/ucm/gdv/logica/Flechas.java | f61eed28dcd5aabe6a3f1572e1d761b6fbba2e0d | [] | no_license | daquinte/Practica1_SwitchDash | https://github.com/daquinte/Practica1_SwitchDash | adcf26c4fc9e84dde0047519eb24f37c34c65288 | c46d6a67dc3379eeba01cc33918e9d4ed72e451b | refs/heads/master | 2021-08-07T22:39:25.742000 | 2020-09-08T16:56:32 | 2020-09-08T16:56:32 | 217,104,636 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package es.ucm.gdv.logica;
import es.ucm.gdv.interfaces.Graphics;
import es.ucm.gdv.interfaces.Image;
public class Flechas {
private Sprite sprite;
private double posY;
private int startPosition;
private int velFlechas;
Flechas(ResourceManager res) {
Image flechasimg = res.getImage(ResourceManager.GameSprites.ARROWS);
posY = startPosition = - flechasimg.getHeight() / 5;
velFlechas = 0;
sprite = new Sprite(flechasimg, 0, 0, flechasimg.getWidth(), flechasimg.getHeight());
}
public void tick(double elapsedTime) {
posY = posY >= 0? startPosition : posY + ((384 + velFlechas) * elapsedTime);
}
public void render(Graphics graphics) {
sprite.drawImage(graphics, 1080/2 - sprite.getImage().getWidth() / 2,
(int)posY, sprite.getSpriteWidth(), sprite.getSpriteHeight(), 50, true);
}
void aumentaVelocidad() {
velFlechas += 90;
}
void resetVelocidad() {
velFlechas = 0;
}
Sprite getSprite() {
return sprite;
}
}
| UTF-8 | Java | 1,071 | java | Flechas.java | Java | [] | null | [] | package es.ucm.gdv.logica;
import es.ucm.gdv.interfaces.Graphics;
import es.ucm.gdv.interfaces.Image;
public class Flechas {
private Sprite sprite;
private double posY;
private int startPosition;
private int velFlechas;
Flechas(ResourceManager res) {
Image flechasimg = res.getImage(ResourceManager.GameSprites.ARROWS);
posY = startPosition = - flechasimg.getHeight() / 5;
velFlechas = 0;
sprite = new Sprite(flechasimg, 0, 0, flechasimg.getWidth(), flechasimg.getHeight());
}
public void tick(double elapsedTime) {
posY = posY >= 0? startPosition : posY + ((384 + velFlechas) * elapsedTime);
}
public void render(Graphics graphics) {
sprite.drawImage(graphics, 1080/2 - sprite.getImage().getWidth() / 2,
(int)posY, sprite.getSpriteWidth(), sprite.getSpriteHeight(), 50, true);
}
void aumentaVelocidad() {
velFlechas += 90;
}
void resetVelocidad() {
velFlechas = 0;
}
Sprite getSprite() {
return sprite;
}
}
| 1,071 | 0.634921 | 0.61718 | 42 | 24.5 | 26.496407 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.619048 | false | false | 4 |
c71927c3f6e6667ab8a3064f917e0c825257875e | 5,712,306,521,633 | 2641daad99422dd2fa275c1da413812a8b627afe | /garage-18-master/src/main/java/com/everis/alicante/courses/beca/garage/domain/Invoice.java | 0621e16326df7d5b4cae46b39012417d65b639e0 | [] | no_license | igarcia10/garage_JDBC | https://github.com/igarcia10/garage_JDBC | 7184a73013447bbac369f6d3614e248584e698f8 | ef6801fbafeadfcb6894137fa100820c96c9f537 | refs/heads/master | 2020-03-22T08:34:27.433000 | 2018-07-05T11:06:03 | 2018-07-05T11:06:03 | 139,775,294 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.everis.alicante.courses.beca.garage.domain;
import lombok.Getter;
@Getter
@Table(tableName="invoice", id="idinvoice")
public class Invoice implements GarageEntity {
int idinvoice;
String number;
Double price;
public Invoice(int idinvoice, String number, Double price) {
super();
this.idinvoice = idinvoice;
this.number = number;
this.price = price;
}
@Override
public String toString() {
return "Invoice [idinvoice=" + idinvoice + ", number=" + number + ", price=" + price + "]\n";
}
}
| UTF-8 | Java | 547 | java | Invoice.java | Java | [] | null | [] | package com.everis.alicante.courses.beca.garage.domain;
import lombok.Getter;
@Getter
@Table(tableName="invoice", id="idinvoice")
public class Invoice implements GarageEntity {
int idinvoice;
String number;
Double price;
public Invoice(int idinvoice, String number, Double price) {
super();
this.idinvoice = idinvoice;
this.number = number;
this.price = price;
}
@Override
public String toString() {
return "Invoice [idinvoice=" + idinvoice + ", number=" + number + ", price=" + price + "]\n";
}
}
| 547 | 0.667276 | 0.667276 | 24 | 20.791666 | 23.494644 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.458333 | false | false | 4 |
e91d7af1c9f35da54960462994da94e853763077 | 1,529,008,363,501 | 70fac9f57ee95ef37310b16e2ac5cf41ec54abd6 | /kurtgeiger/src/test/java/stefdef/CheckOutStepDef.java | 6c28e9699a087448049569db10cd1dd3548f4b0f | [] | no_license | hirenh/es.kurtgeiger | https://github.com/hirenh/es.kurtgeiger | 0fe67f67996aa27aa00f284bcfef779b3c435704 | 8f3a765f9360148cd68ea05bf171674c636e09e2 | refs/heads/master | 2020-03-19T01:35:35.465000 | 2018-05-31T09:14:47 | 2018-05-31T09:14:47 | 135,556,661 | 0 | 0 | null | false | 2018-05-31T09:49:26 | 2018-05-31T08:40:51 | 2018-05-31T09:16:06 | 2018-05-31T09:47:45 | 0 | 0 | 0 | 1 | Java | false | null | package stefdef;
import cucumber.api.PendingException;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import pageobject.CheckOutPage;
import pageobject.HomePage;
import pageobject.PdpPage;
import utils.Utils;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class CheckOutStepDef {
Utils utils = new Utils();
HomePage homePage = new HomePage();
PdpPage pdpPage = new PdpPage();
CheckOutPage checkOutPage = new CheckOutPage();
@Given("^I select men category from the header$")
public void i_select_men_category_from_the_header() {
}
@Given("^I am on PDP$")
public void i_am_on_PDP() {
pdpPage.iAmOnPDPpage();
assertThat(pdpPage.iAmOnPDPpage(), is(true));
}
@When("^I add the product to the bag$")
public void i_add_the_product_to_the_bag() throws InterruptedException {
pdpPage.goToBag();
}
@Then("^I can see the bag with single item$")
public void i_can_see_the_bag_with_single_item() {
pdpPage.totalItemsInBag();
assertThat(pdpPage.totalItemsInBag(), containsString("MY BAG (1 ITEM)"));
}
@And("^I click 'Proceed to Checkout'$")
public void i_click_Proceed_to_Checkout() {
pdpPage.clickToProceedToCheckOut();
}
@Then("^I should be on checkout page$")
public void i_should_be_on_checkout_page() {
pdpPage.confirmedCheckOutPage();
assertThat(pdpPage.confirmedCheckOutPage(), containsString("CHECKOUT / Welcome"));
}
@When("^I select colour \"([^\"]*)\" and size \"([^\"]*)\" for the chosen men category$")
public void iSelectColourAndSizeForTheChosenMenCategory(String colour, String size) {
pdpPage.colours(colour);
pdpPage.size(size);
pdpPage.addProduct();
}
@Given("^I checkout as a guest$")
public void iCheckoutAsAGuest() {
checkOutPage.loginAsAGuest();
}
@When("^I enter all the billing and delivery details$")
public void iEnterAllTheBillingAndDeliveryDetails() {
checkOutPage.dropDownTitleByPassingValue();
}
@And("^I click 'Continue to Payment'$")
public void iClickContinueToPayment() {
checkOutPage.contiuneToPayment();
}
@Then("^I should be on the payment summary page$")
public void iShouldBeOnThePaymentSummaryPage() {
pdpPage.confirmedCheckOutPage();
assertThat(pdpPage.confirmedCheckOutPage(), containsString("CHECKOUT / Delivery & Billing"));
}
@When("^I select to pay by card$")
public void iSelectToPayByCard() throws Throwable {
checkOutPage.selectPaymentMethod();
}
@And("^I enter credit card \"([^\"]*)\" with \"([^\"]*)\" expiry date$")
public void iEnterCreditCardWithExpiryDate(String arg0, String arg1) throws Throwable {
checkOutPage.enterCreditCardAndExpiryDetails(arg0, arg1);
}
@And("^I enter \"([^\"]*)\" CVC code$")
public void iEnterCVCCode(String arg0) {
checkOutPage.cvcDetails(arg0);
checkOutPage.cardDetails();
}
@Then("^I should see \"Your card number has failed our validity checks and appears to be incorrect Please check and re-enter”$")
public void iShouldSeeYourCardNumberHasFailedOurValidityChecksAndAppearsToBeIncorrectPleaseCheckAndReEnter() throws Throwable {
checkOutPage.cardValidityChecks();
assertThat(checkOutPage.cardValidityChecks(), containsString("The Card Range not supported by the system."));
}
}
| UTF-8 | Java | 3,659 | java | CheckOutStepDef.java | Java | [] | null | [] | package stefdef;
import cucumber.api.PendingException;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import pageobject.CheckOutPage;
import pageobject.HomePage;
import pageobject.PdpPage;
import utils.Utils;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class CheckOutStepDef {
Utils utils = new Utils();
HomePage homePage = new HomePage();
PdpPage pdpPage = new PdpPage();
CheckOutPage checkOutPage = new CheckOutPage();
@Given("^I select men category from the header$")
public void i_select_men_category_from_the_header() {
}
@Given("^I am on PDP$")
public void i_am_on_PDP() {
pdpPage.iAmOnPDPpage();
assertThat(pdpPage.iAmOnPDPpage(), is(true));
}
@When("^I add the product to the bag$")
public void i_add_the_product_to_the_bag() throws InterruptedException {
pdpPage.goToBag();
}
@Then("^I can see the bag with single item$")
public void i_can_see_the_bag_with_single_item() {
pdpPage.totalItemsInBag();
assertThat(pdpPage.totalItemsInBag(), containsString("MY BAG (1 ITEM)"));
}
@And("^I click 'Proceed to Checkout'$")
public void i_click_Proceed_to_Checkout() {
pdpPage.clickToProceedToCheckOut();
}
@Then("^I should be on checkout page$")
public void i_should_be_on_checkout_page() {
pdpPage.confirmedCheckOutPage();
assertThat(pdpPage.confirmedCheckOutPage(), containsString("CHECKOUT / Welcome"));
}
@When("^I select colour \"([^\"]*)\" and size \"([^\"]*)\" for the chosen men category$")
public void iSelectColourAndSizeForTheChosenMenCategory(String colour, String size) {
pdpPage.colours(colour);
pdpPage.size(size);
pdpPage.addProduct();
}
@Given("^I checkout as a guest$")
public void iCheckoutAsAGuest() {
checkOutPage.loginAsAGuest();
}
@When("^I enter all the billing and delivery details$")
public void iEnterAllTheBillingAndDeliveryDetails() {
checkOutPage.dropDownTitleByPassingValue();
}
@And("^I click 'Continue to Payment'$")
public void iClickContinueToPayment() {
checkOutPage.contiuneToPayment();
}
@Then("^I should be on the payment summary page$")
public void iShouldBeOnThePaymentSummaryPage() {
pdpPage.confirmedCheckOutPage();
assertThat(pdpPage.confirmedCheckOutPage(), containsString("CHECKOUT / Delivery & Billing"));
}
@When("^I select to pay by card$")
public void iSelectToPayByCard() throws Throwable {
checkOutPage.selectPaymentMethod();
}
@And("^I enter credit card \"([^\"]*)\" with \"([^\"]*)\" expiry date$")
public void iEnterCreditCardWithExpiryDate(String arg0, String arg1) throws Throwable {
checkOutPage.enterCreditCardAndExpiryDetails(arg0, arg1);
}
@And("^I enter \"([^\"]*)\" CVC code$")
public void iEnterCVCCode(String arg0) {
checkOutPage.cvcDetails(arg0);
checkOutPage.cardDetails();
}
@Then("^I should see \"Your card number has failed our validity checks and appears to be incorrect Please check and re-enter”$")
public void iShouldSeeYourCardNumberHasFailedOurValidityChecksAndAppearsToBeIncorrectPleaseCheckAndReEnter() throws Throwable {
checkOutPage.cardValidityChecks();
assertThat(checkOutPage.cardValidityChecks(), containsString("The Card Range not supported by the system."));
}
}
| 3,659 | 0.682527 | 0.680613 | 116 | 30.525862 | 30.071312 | 132 | false | false | 0 | 0 | 0 | 0 | 94 | 0.025704 | 0.405172 | false | false | 4 |
5102c02d091aac790e8235f9a4c973c6f1799cf1 | 30,502,857,751,249 | dfbe91f6044e4bf663000bc5fdd0f7cd3604589a | /micro-business/provider-cloud-uac/src/main/java/com/pupilary/provider/service/impl/ClientDetailServiceImpl.java | e614787fc0a318233dab8ea7dd5b23c24c12c37b | [] | no_license | pupilary/spring-cloud-master | https://github.com/pupilary/spring-cloud-master | 1ee68f0a28224e924cbfc59b6ccdae3706a3bd9f | 1cc8ed93b7c4919357807006642662ba4a384f97 | refs/heads/master | 2023-06-05T19:19:25.050000 | 2021-06-30T13:21:41 | 2021-06-30T13:21:41 | 363,426,732 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pupilary.provider.service.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pupilary.provider.mapper.OauthClientDetailsMapper;
import com.pupilary.provider.model.domain.OauthClientDetails;
import com.pupilary.provider.service.ClientDetailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Map;
/**
* @author takesi
*/
@Service
public class ClientDetailServiceImpl implements ClientDetailService {
private static final Logger logger = LoggerFactory.getLogger(ClientDetailService.class);
@Autowired
private OauthClientDetailsMapper oauthClientDetailsMapper;
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
OauthClientDetails result = oauthClientDetailsMapper.queryClientDetailsFromClientId(clientId);
BaseClientDetails details = new BaseClientDetails(result.getClientId(), result.getResourceIds(), result.getScope(),
result.getAuthorizedGrantTypes(), result.getAuthorities(), result.getWebServerRedirectUri());
details.setClientSecret(result.getClientSecret());
details.setAccessTokenValiditySeconds(result.getAccessTokenValidity());
details.setRefreshTokenValiditySeconds(result.getRefreshTokenValidity());
String json = result.getAdditionalInformation();
if (json != null) {
final ObjectMapper mapper = new ObjectMapper();
try {
@SuppressWarnings("unchecked")
Map<String, Object> additionalInformation = mapper.readValue(json, Map.class);
details.setAdditionalInformation(additionalInformation);
} catch (Exception e) {
logger.warn("Could not decode JSON for additional information: " + details, e);
}
}
String scopes = result.getScope();
if (scopes != null) {
details.setAutoApproveScopes(StringUtils.commaDelimitedListToSet(scopes));
}
return details;
}
}
| UTF-8 | Java | 2,430 | java | ClientDetailServiceImpl.java | Java | [
{
"context": "tringUtils;\n\nimport java.util.Map;\n\n/**\n * @author takesi\n */\n@Service\npublic class ClientDetailServiceImpl",
"end": 762,
"score": 0.8830078840255737,
"start": 756,
"tag": "USERNAME",
"value": "takesi"
}
] | null | [] | package com.pupilary.provider.service.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pupilary.provider.mapper.OauthClientDetailsMapper;
import com.pupilary.provider.model.domain.OauthClientDetails;
import com.pupilary.provider.service.ClientDetailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Map;
/**
* @author takesi
*/
@Service
public class ClientDetailServiceImpl implements ClientDetailService {
private static final Logger logger = LoggerFactory.getLogger(ClientDetailService.class);
@Autowired
private OauthClientDetailsMapper oauthClientDetailsMapper;
@Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
OauthClientDetails result = oauthClientDetailsMapper.queryClientDetailsFromClientId(clientId);
BaseClientDetails details = new BaseClientDetails(result.getClientId(), result.getResourceIds(), result.getScope(),
result.getAuthorizedGrantTypes(), result.getAuthorities(), result.getWebServerRedirectUri());
details.setClientSecret(result.getClientSecret());
details.setAccessTokenValiditySeconds(result.getAccessTokenValidity());
details.setRefreshTokenValiditySeconds(result.getRefreshTokenValidity());
String json = result.getAdditionalInformation();
if (json != null) {
final ObjectMapper mapper = new ObjectMapper();
try {
@SuppressWarnings("unchecked")
Map<String, Object> additionalInformation = mapper.readValue(json, Map.class);
details.setAdditionalInformation(additionalInformation);
} catch (Exception e) {
logger.warn("Could not decode JSON for additional information: " + details, e);
}
}
String scopes = result.getScope();
if (scopes != null) {
details.setAutoApproveScopes(StringUtils.commaDelimitedListToSet(scopes));
}
return details;
}
}
| 2,430 | 0.746502 | 0.744444 | 56 | 42.392857 | 34.62899 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.660714 | false | false | 4 |
b88336e20f92785dbe7e7d248596b4e8285f1d52 | 11,407,433,166,112 | 6dee6a22e0b473ab44ad1bb80a7d3983f5d7ac20 | /netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadTransaction.java | ed972c1d5d3689cdbeed2203102a9448424be0d9 | [] | no_license | zhanghuafei/netconf | https://github.com/zhanghuafei/netconf | 297f86837f0689de38f0991621940f02831e9875 | afe54f7a2675f971ccf6e12defa54a71f24a49be | refs/heads/ut-fluorine-sr2 | 2021-06-06T00:38:34.309000 | 2020-03-20T05:52:45 | 2020-03-20T05:52:45 | 110,987,096 | 2 | 1 | null | true | 2020-03-31T09:03:24 | 2017-11-16T15:17:30 | 2020-03-20T05:52:53 | 2020-03-31T09:03:23 | 18,084 | 0 | 1 | 1 | Java | false | false | /*
* Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.netconf.topology.singleton.impl.tx;
import akka.actor.ActorRef;
import akka.util.Timeout;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import scala.concurrent.ExecutionContext;
import scala.concurrent.Future;
/**
* ProxyReadTransaction uses provided {@link ActorRef} to delegate method calls to master
* {@link org.opendaylight.netconf.topology.singleton.impl.actors.ReadTransactionActor}.
*/
public class ProxyReadTransaction extends ProxyReadWriteTransaction implements DOMDataReadOnlyTransaction {
public ProxyReadTransaction(final RemoteDeviceId id, final Future<Object> masterTxActorFuture,
final ExecutionContext executionContext, final Timeout askTimeout) {
super(id, masterTxActorFuture, executionContext, askTimeout);
}
@Override
public void close() {
// noop
}
}
| UTF-8 | Java | 1,269 | java | ProxyReadTransaction.java | Java | [] | null | [] | /*
* Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.netconf.topology.singleton.impl.tx;
import akka.actor.ActorRef;
import akka.util.Timeout;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
import scala.concurrent.ExecutionContext;
import scala.concurrent.Future;
/**
* ProxyReadTransaction uses provided {@link ActorRef} to delegate method calls to master
* {@link org.opendaylight.netconf.topology.singleton.impl.actors.ReadTransactionActor}.
*/
public class ProxyReadTransaction extends ProxyReadWriteTransaction implements DOMDataReadOnlyTransaction {
public ProxyReadTransaction(final RemoteDeviceId id, final Future<Object> masterTxActorFuture,
final ExecutionContext executionContext, final Timeout askTimeout) {
super(id, masterTxActorFuture, executionContext, askTimeout);
}
@Override
public void close() {
// noop
}
}
| 1,269 | 0.778566 | 0.772262 | 33 | 37.454544 | 36.301842 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 4 |
15ce680f212e94e1c9ae441750ff325cacdce94c | 2,035,814,506,776 | dea3d126d4dd6e666086c798c47376caf7f7cc46 | /src/test/java/Logiikka/PelaajaTest.java | 7d898c9ded26f2c6aa17155d4a6887e39877c313 | [] | no_license | Tupsu-jy/Ristinolla | https://github.com/Tupsu-jy/Ristinolla | d132390033d615825d72348436132f33072c27ee | 8ad0f3d7a1ede1b28542d062211c7aba3f90ae45 | refs/heads/master | 2022-04-04T17:26:22.093000 | 2020-02-13T13:56:46 | 2020-02-13T13:56:46 | 240,272,857 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 Logiikka;
import Logiikka.Pelaaja;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author jayl@cs
*/
public class PelaajaTest {
public PelaajaTest() {
}
Pelaaja p1;
@Before
public void setUp() {
p1 = new Pelaaja(1, "Juntti");
}
@Test
public void TestKonstruktori(){
Pelaaja p2=new Pelaaja(2, "Hintti");
assertEquals(2, p2.haekumpi());
}
@Test
public void Testvoitin(){
assertEquals(false, p1.haevoitto());
p1.voitin();
assertEquals(true, p1.haevoitto());
}
@Test
public void Testhaekumpi(){
assertEquals(1, p1.kumpi);
}
@Test
public void Testhaevoitto(){
assertEquals(false, p1.haevoitto());
}
}
| UTF-8 | Java | 1,125 | java | PelaajaTest.java | Java | [
{
"context": "port static org.junit.Assert.*;\n\n/**\n *\n * @author jayl@cs\n */\npublic class PelaajaTest {\n \n public Pe",
"end": 421,
"score": 0.9944518804550171,
"start": 414,
"tag": "EMAIL",
"value": "jayl@cs"
},
{
"context": "ublic void setUp() {\n p1 = new Pelaaja(1, \"Juntti\");\n }\n\n @Test\n public void TestKonstru",
"end": 587,
"score": 0.6079370975494385,
"start": 583,
"tag": "NAME",
"value": "Junt"
},
{
"context": "ri(){\n \n Pelaaja p2=new Pelaaja(2, \"Hintti\");\n \n assertEquals(2, p2.haekumpi()",
"end": 696,
"score": 0.5440104007720947,
"start": 690,
"tag": "NAME",
"value": "Hintti"
}
] | null | [] | /*
* 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 Logiikka;
import Logiikka.Pelaaja;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author <EMAIL>
*/
public class PelaajaTest {
public PelaajaTest() {
}
Pelaaja p1;
@Before
public void setUp() {
p1 = new Pelaaja(1, "Juntti");
}
@Test
public void TestKonstruktori(){
Pelaaja p2=new Pelaaja(2, "Hintti");
assertEquals(2, p2.haekumpi());
}
@Test
public void Testvoitin(){
assertEquals(false, p1.haevoitto());
p1.voitin();
assertEquals(true, p1.haevoitto());
}
@Test
public void Testhaekumpi(){
assertEquals(1, p1.kumpi);
}
@Test
public void Testhaevoitto(){
assertEquals(false, p1.haevoitto());
}
}
| 1,125 | 0.597333 | 0.585778 | 59 | 18.067797 | 17.065044 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.457627 | false | false | 4 |
3993c99126bcf3ee9a8b351469fe50d70b21fcc8 | 30,545,807,411,730 | 98c412a2a9b66563cc17e6bc61eb2552daa69da8 | /src/main/java/gyromite/scene/AnimatedSprite.java | 45d19e4d9b9d656068cd85a340614a61fc176074 | [] | no_license | theodoreguillet/Gyromite | https://github.com/theodoreguillet/Gyromite | 49f7a4932c3fc8f23cf2b86614f4ded8d9b5e6b9 | 40dc7567e623d773d8d8ec608cc636cf0fb27d4c | refs/heads/master | 2023-04-22T07:54:53.285000 | 2021-05-07T19:19:51 | 2021-05-07T19:19:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gyromite.scene;
import gyromite.core.MainLoop;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.HashMap;
/**
* A sprite node that can use multiple image for animations.
* Animations are created using {@link SpriteFrames}.
* Each animation is associated to an id.
*/
public class AnimatedSprite extends SpriteBase {
private final HashMap<String, SpriteFrames> animations = new HashMap<>();
boolean playing = false;
boolean playBackwards = false;
String currentAnimation = "";
int currentAnimationFrame = 0;
private long frameTime = 0;
private double speedScale = 1.0;
public AnimatedSprite() {
super();
}
/**
* @param id The id of the animation.
* @return <code>true</code> If the animation with the given id exists.
*/
public boolean hasAnimation(String id) {
return animations.containsKey(id);
}
/**
* @param id The id of the animation.
* @return The animation with the given id or null if the animation does not exist.
*/
public SpriteFrames animation(String id) {
return animations.get(id);
}
/**
* @return Return if an animation is playing.
*/
public boolean isPlaying() {
return playing;
}
/**
* @return Return if the current animation is playing backwards.
*/
public boolean isPlayingBackwards() {
return playing && playBackwards;
}
/**
* @return The index of the current animation.
*/
public String currentAnimation() {
return currentAnimation;
}
/**
* @return The position of the current frame of the current animation.
*/
public int currentFrame() {
return currentAnimationFrame;
}
/**
* @return The speed scale of animations. The animations speed will be multiplied by this value.
*/
public double speedScale() {
return speedScale;
}
/**
* Set the speed scale of animations.
* The animations speed will be multiplied by this value.
*/
public void setSpeedScale(double speedScale) {
this.speedScale = speedScale;
}
/**
* Add an animation with the given id.
* @param id The id of the animation.
* @return The animation frames resources. See {@link SpriteFrames}.
*/
public SpriteFrames addAnimation(String id) {
SpriteFrames a = new SpriteFrames(id, this);
animations.put(id, a);
return a;
}
/**
* Play the given animation.
* @param id The id of the animation.
*/
public void play(String id) {
play(id, false);
}
/**
* Play the given animation.
* @param id The id of the animation.
* @param backwards If <code>true</code> the animation will be played backward.
*/
public void play(String id, boolean backwards) {
if(hasAnimation(id)) {
if(isPlaying()) {
stop();
}
if(!id.equals(currentAnimation)) {
currentAnimation = id;
if(backwards) {
currentAnimationFrame = animation(id).frameCount() - 1;
} else {
currentAnimationFrame = 0;
}
}
frameTime = 0;
playBackwards = backwards;
playing = true;
}
}
/**
* Stop the current animation without resetting the frame counter.
* The animation can be resumed by calling {@link AnimatedSprite#play(String)}.
*/
public void stop() {
playing = false;
}
/**
* Stop the current animation and reset the frame counter.
*/
public void reset() {
currentAnimation = "";
currentAnimationFrame = 0;
frameTime = 0;
playing = false;
}
@Override
protected void update() {
super.update();
if(!isPlaying()) {
return;
}
SpriteFrames anim = animation(currentAnimation);
if(anim == null) {
return;
}
frameTime += MainLoop.NANOS_PER_TICK;
if(frameTime > MainLoop.NANOSECOND / (anim.speed() * speedScale)) {
if(playBackwards) {
currentAnimationFrame--;
} else {
currentAnimationFrame++;
}
boolean looped = false;
if(currentAnimationFrame >= anim.frameCount()) {
currentAnimationFrame = 0;
looped = true;
} else if(currentAnimationFrame < 0) {
currentAnimationFrame = anim.frameCount() - 1;
looped = true;
}
if(looped && !anim.isLoop()) {
stop();
}
frameTime = 0;
}
}
@Override
protected void render(Graphics2D g) {
super.render(g);
if(currentAnimation == null) {
return;
}
SpriteFrames anim = animation(currentAnimation);
if(anim == null || currentAnimationFrame < 0 || currentAnimationFrame >= anim.frameCount()) {
return;
}
BufferedImage image = anim.getFrame(currentAnimationFrame);
g.translate(-size().width / 2.0, -size().height / 2.0);
g.scale(size().width / (double)image.getWidth(), size().height / (double)image.getHeight());
g.drawImage(image, 0, 0, null);
}
}
| UTF-8 | Java | 5,444 | java | AnimatedSprite.java | Java | [] | null | [] | package gyromite.scene;
import gyromite.core.MainLoop;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.HashMap;
/**
* A sprite node that can use multiple image for animations.
* Animations are created using {@link SpriteFrames}.
* Each animation is associated to an id.
*/
public class AnimatedSprite extends SpriteBase {
private final HashMap<String, SpriteFrames> animations = new HashMap<>();
boolean playing = false;
boolean playBackwards = false;
String currentAnimation = "";
int currentAnimationFrame = 0;
private long frameTime = 0;
private double speedScale = 1.0;
public AnimatedSprite() {
super();
}
/**
* @param id The id of the animation.
* @return <code>true</code> If the animation with the given id exists.
*/
public boolean hasAnimation(String id) {
return animations.containsKey(id);
}
/**
* @param id The id of the animation.
* @return The animation with the given id or null if the animation does not exist.
*/
public SpriteFrames animation(String id) {
return animations.get(id);
}
/**
* @return Return if an animation is playing.
*/
public boolean isPlaying() {
return playing;
}
/**
* @return Return if the current animation is playing backwards.
*/
public boolean isPlayingBackwards() {
return playing && playBackwards;
}
/**
* @return The index of the current animation.
*/
public String currentAnimation() {
return currentAnimation;
}
/**
* @return The position of the current frame of the current animation.
*/
public int currentFrame() {
return currentAnimationFrame;
}
/**
* @return The speed scale of animations. The animations speed will be multiplied by this value.
*/
public double speedScale() {
return speedScale;
}
/**
* Set the speed scale of animations.
* The animations speed will be multiplied by this value.
*/
public void setSpeedScale(double speedScale) {
this.speedScale = speedScale;
}
/**
* Add an animation with the given id.
* @param id The id of the animation.
* @return The animation frames resources. See {@link SpriteFrames}.
*/
public SpriteFrames addAnimation(String id) {
SpriteFrames a = new SpriteFrames(id, this);
animations.put(id, a);
return a;
}
/**
* Play the given animation.
* @param id The id of the animation.
*/
public void play(String id) {
play(id, false);
}
/**
* Play the given animation.
* @param id The id of the animation.
* @param backwards If <code>true</code> the animation will be played backward.
*/
public void play(String id, boolean backwards) {
if(hasAnimation(id)) {
if(isPlaying()) {
stop();
}
if(!id.equals(currentAnimation)) {
currentAnimation = id;
if(backwards) {
currentAnimationFrame = animation(id).frameCount() - 1;
} else {
currentAnimationFrame = 0;
}
}
frameTime = 0;
playBackwards = backwards;
playing = true;
}
}
/**
* Stop the current animation without resetting the frame counter.
* The animation can be resumed by calling {@link AnimatedSprite#play(String)}.
*/
public void stop() {
playing = false;
}
/**
* Stop the current animation and reset the frame counter.
*/
public void reset() {
currentAnimation = "";
currentAnimationFrame = 0;
frameTime = 0;
playing = false;
}
@Override
protected void update() {
super.update();
if(!isPlaying()) {
return;
}
SpriteFrames anim = animation(currentAnimation);
if(anim == null) {
return;
}
frameTime += MainLoop.NANOS_PER_TICK;
if(frameTime > MainLoop.NANOSECOND / (anim.speed() * speedScale)) {
if(playBackwards) {
currentAnimationFrame--;
} else {
currentAnimationFrame++;
}
boolean looped = false;
if(currentAnimationFrame >= anim.frameCount()) {
currentAnimationFrame = 0;
looped = true;
} else if(currentAnimationFrame < 0) {
currentAnimationFrame = anim.frameCount() - 1;
looped = true;
}
if(looped && !anim.isLoop()) {
stop();
}
frameTime = 0;
}
}
@Override
protected void render(Graphics2D g) {
super.render(g);
if(currentAnimation == null) {
return;
}
SpriteFrames anim = animation(currentAnimation);
if(anim == null || currentAnimationFrame < 0 || currentAnimationFrame >= anim.frameCount()) {
return;
}
BufferedImage image = anim.getFrame(currentAnimationFrame);
g.translate(-size().width / 2.0, -size().height / 2.0);
g.scale(size().width / (double)image.getWidth(), size().height / (double)image.getHeight());
g.drawImage(image, 0, 0, null);
}
}
| 5,444 | 0.567965 | 0.563924 | 192 | 27.354166 | 22.977108 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.380208 | false | false | 4 |
6a3b0e3e72849f45d4a492775e7fad83d9012c1e | 6,957,847,021,908 | 7e10b984dd1a539888a4d4be762d315c64dc62e3 | /src/main/java/com/bitfactor/TennisMatchApplication.java | ea8293cb6bd2ed1b9657ec337bdc4ae76befadee | [] | no_license | bit-factor/bf-wemanity-tennis | https://github.com/bit-factor/bf-wemanity-tennis | 34522e1bd686245c8f9acbbcbbbd7db17f0f8423 | ff05f1f53db89da5974b5ef6820a0004606dde5a | refs/heads/master | 2021-07-06T04:16:52.396000 | 2020-10-14T03:40:20 | 2020-10-14T03:40:20 | 192,346,733 | 0 | 0 | null | false | 2020-10-14T03:40:21 | 2019-06-17T12:54:08 | 2019-06-17T20:22:49 | 2020-10-14T03:40:21 | 35 | 0 | 0 | 0 | Java | false | false | package com.bitfactor;
import com.bitfactor.match.SetPlay;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@Slf4j
public class TennisMatchApplication
{
public static void main( String[] args )
{
log.info("A tennis match is about to start between players `a` and `b`!");
SetPlay setPlay = new SetPlay("a", "b");
try (BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in))) {
while (!setPlay.isCompleted()) {
String player = buffer.readLine().trim();
setPlay.point(player);
}
} catch (IOException iox) {
log.error("A storm hit the game ... ", iox);
}
}
}
| UTF-8 | Java | 776 | java | TennisMatchApplication.java | Java | [] | null | [] | package com.bitfactor;
import com.bitfactor.match.SetPlay;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@Slf4j
public class TennisMatchApplication
{
public static void main( String[] args )
{
log.info("A tennis match is about to start between players `a` and `b`!");
SetPlay setPlay = new SetPlay("a", "b");
try (BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in))) {
while (!setPlay.isCompleted()) {
String player = buffer.readLine().trim();
setPlay.point(player);
}
} catch (IOException iox) {
log.error("A storm hit the game ... ", iox);
}
}
}
| 776 | 0.626289 | 0.622423 | 27 | 27.74074 | 24.61194 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.481481 | false | false | 4 |
6daa62702836e4d14a88edc2f2c21e9a4da704b0 | 13,099,650,291,246 | c878cd9fd5e60e59add768be2ae0318bf924736c | /Algorithms/02_Implementation/15_Forming a Magic Square/UsingDynamicallyCreatingMagicArray.java | 556bd857605daeeacd5ccabd7943af359a908829 | [] | no_license | m-Farman/HackerRankSolutions | https://github.com/m-Farman/HackerRankSolutions | 01045497eb5ad1e5f41ac2a4aef34b584f5d6eb9 | 2cf33d223f83f4f6f242ec03323a83536a59db5e | refs/heads/master | 2020-03-13T12:59:31.066000 | 2019-04-09T17:56:16 | 2019-04-09T17:56:16 | 131,130,387 | 0 | 0 | null | false | 2018-07-23T10:37:31 | 2018-04-26T09:13:18 | 2018-07-14T21:45:00 | 2018-07-23T10:37:31 | 50 | 0 | 0 | 0 | Java | false | null | import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the formingMagicSquare function below.
static int formingMagicSquare(int[][] s) {
int[][] sq = new int[3][3];
ArrayList<int[][]> magic = new ArrayList<>();
HashSet<Integer> unique = new HashSet<>();
permute2dArray(sq, 0, 0, magic, unique);
int[] diff = new int[magic.size()];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < diff.length; k++) {
diff[k] += Math.abs(magic.get(k)[i][j] - s[i][j]);
}
}
}
int minDiff = Integer.MAX_VALUE;
for (int i = 0; i < diff.length; i++) {
if (diff[i] < minDiff) {
minDiff = diff[i];
}
}
return minDiff;
}
static void permute2dArray(int[][] sq, int row, int col, ArrayList<int[][]> magic, Set<Integer> unique) {
if (row == 3) {
return;
}
int r = 0, c = 0;
for (int i = 1; i <= 9; i++) {
if (!unique.add(i)) {
continue;
}
sq[row][col] = i;
checkMagic(sq, magic);
if (col + 1 >= 3) {
c = 0;
r = row + 1;
} else {
c = col + 1;
r = row;
}
permute2dArray(sq, r, c, magic, unique);
unique.remove(i);
}
}
static void checkMagic(int[][] sq, ArrayList<int[][]> magic) {
HashSet<Integer> sum = new HashSet<>();
int rowS = 0, colS = 0, daigonalL = 0, daigonalR = 0;
for (int i = 0; i < sq.length; i++) {
rowS = 0;
colS = 0;
for (int j = 0; j < sq.length; j++) {
rowS += sq[i][j];
colS += sq[j][i];
}
sum.add(rowS);
sum.add(colS);
daigonalL += sq[i][i];
daigonalR += sq[i][2 - i];
}
sum.add(daigonalL);
sum.add(daigonalR);
if (sum.size() == 1) {
int[][] tmp = new int[3][3];
for (int i = 0; i < tmp.length; i++) {
for (int j = 0; j < tmp.length; j++) {
tmp[i][j] = sq[i][j];
}
}
magic.add(tmp);
}
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int[][] s = new int[3][3];
for (int i = 0; i < 3; i++) {
String[] sRowItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int j = 0; j < 3; j++) {
int sItem = Integer.parseInt(sRowItems[j]);
s[i][j] = sItem;
}
}
int result = formingMagicSquare(s);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
| UTF-8 | Java | 2,777 | java | UsingDynamicallyCreatingMagicArray.java | Java | [] | null | [] | import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the formingMagicSquare function below.
static int formingMagicSquare(int[][] s) {
int[][] sq = new int[3][3];
ArrayList<int[][]> magic = new ArrayList<>();
HashSet<Integer> unique = new HashSet<>();
permute2dArray(sq, 0, 0, magic, unique);
int[] diff = new int[magic.size()];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < diff.length; k++) {
diff[k] += Math.abs(magic.get(k)[i][j] - s[i][j]);
}
}
}
int minDiff = Integer.MAX_VALUE;
for (int i = 0; i < diff.length; i++) {
if (diff[i] < minDiff) {
minDiff = diff[i];
}
}
return minDiff;
}
static void permute2dArray(int[][] sq, int row, int col, ArrayList<int[][]> magic, Set<Integer> unique) {
if (row == 3) {
return;
}
int r = 0, c = 0;
for (int i = 1; i <= 9; i++) {
if (!unique.add(i)) {
continue;
}
sq[row][col] = i;
checkMagic(sq, magic);
if (col + 1 >= 3) {
c = 0;
r = row + 1;
} else {
c = col + 1;
r = row;
}
permute2dArray(sq, r, c, magic, unique);
unique.remove(i);
}
}
static void checkMagic(int[][] sq, ArrayList<int[][]> magic) {
HashSet<Integer> sum = new HashSet<>();
int rowS = 0, colS = 0, daigonalL = 0, daigonalR = 0;
for (int i = 0; i < sq.length; i++) {
rowS = 0;
colS = 0;
for (int j = 0; j < sq.length; j++) {
rowS += sq[i][j];
colS += sq[j][i];
}
sum.add(rowS);
sum.add(colS);
daigonalL += sq[i][i];
daigonalR += sq[i][2 - i];
}
sum.add(daigonalL);
sum.add(daigonalR);
if (sum.size() == 1) {
int[][] tmp = new int[3][3];
for (int i = 0; i < tmp.length; i++) {
for (int j = 0; j < tmp.length; j++) {
tmp[i][j] = sq[i][j];
}
}
magic.add(tmp);
}
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int[][] s = new int[3][3];
for (int i = 0; i < 3; i++) {
String[] sRowItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int j = 0; j < 3; j++) {
int sItem = Integer.parseInt(sRowItems[j]);
s[i][j] = sItem;
}
}
int result = formingMagicSquare(s);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
| 2,777 | 0.525387 | 0.505582 | 121 | 21.942148 | 21.178617 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.314049 | false | false | 4 |
dc32b7557087404e67a2ba074f689c96402635ef | 27,230,092,692,466 | 300d13cdee16a9d6d0fa05bd1cbdb459f9f388c0 | /CM5/Core/gui-model/src/main/java/ru/intertrust/cm/core/gui/model/form/widget/NodeContentResponse.java | 9a8d3808b2e937f682332c81c63ce31e4b715077 | [
"Apache-2.0"
] | permissive | InterTurstCo/ActiveFrame5 | https://github.com/InterTurstCo/ActiveFrame5 | c0f3ef01642b6c564bec5fbc92ac64db4f33fd31 | a042afd5297be9636656701e502918bdbd63ce80 | refs/heads/master | 2021-12-14T01:26:12.718000 | 2021-12-06T16:40:01 | 2021-12-06T16:40:01 | 223,143,464 | 4 | 3 | Apache-2.0 | false | 2021-12-06T16:49:49 | 2019-11-21T10:01:48 | 2021-12-06T16:49:18 | 2021-12-06T16:48:11 | 232,529 | 4 | 1 | 3 | Java | false | false | package ru.intertrust.cm.core.gui.model.form.widget;
import ru.intertrust.cm.core.business.api.dto.Dto;
import ru.intertrust.cm.core.business.api.dto.Id;
import ru.intertrust.cm.core.config.gui.form.widget.NodeCollectionDefConfig;
import java.util.List;
/**
* @author Yaroslav Bondarchuk
* Date: 23.12.13
* Time: 13:15
*/
public class NodeContentResponse implements Dto {
private List<HierarchyBrowserItem> nodeContent;
private String parentCollectionName;
private List<NodeCollectionDefConfig> nodeCollectionDefConfigs;
private Id parentId;
public List<HierarchyBrowserItem> getNodeContent() {
return nodeContent;
}
public void setNodeContent(List<HierarchyBrowserItem> nodeContent) {
this.nodeContent = nodeContent;
}
public Id getParentId() {
return parentId;
}
public void setParentId(Id parentId) {
this.parentId = parentId;
}
public String getParentCollectionName() {
return parentCollectionName;
}
public void setParentCollectionName(String parentCollectionName) {
this.parentCollectionName = parentCollectionName;
}
public List<NodeCollectionDefConfig> getNodeCollectionDefConfigs() {
return nodeCollectionDefConfigs;
}
public void setNodeCollectionDefConfigs(List<NodeCollectionDefConfig> nodeCollectionDefConfigs) {
this.nodeCollectionDefConfigs = nodeCollectionDefConfigs;
}
}
| UTF-8 | Java | 1,464 | java | NodeContentResponse.java | Java | [
{
"context": "DefConfig;\n\nimport java.util.List;\n\n/**\n * @author Yaroslav Bondarchuk\n * Date: 23.12.13\n * Time: 13:15\n",
"end": 291,
"score": 0.9997888803482056,
"start": 272,
"tag": "NAME",
"value": "Yaroslav Bondarchuk"
}
] | null | [] | package ru.intertrust.cm.core.gui.model.form.widget;
import ru.intertrust.cm.core.business.api.dto.Dto;
import ru.intertrust.cm.core.business.api.dto.Id;
import ru.intertrust.cm.core.config.gui.form.widget.NodeCollectionDefConfig;
import java.util.List;
/**
* @author <NAME>
* Date: 23.12.13
* Time: 13:15
*/
public class NodeContentResponse implements Dto {
private List<HierarchyBrowserItem> nodeContent;
private String parentCollectionName;
private List<NodeCollectionDefConfig> nodeCollectionDefConfigs;
private Id parentId;
public List<HierarchyBrowserItem> getNodeContent() {
return nodeContent;
}
public void setNodeContent(List<HierarchyBrowserItem> nodeContent) {
this.nodeContent = nodeContent;
}
public Id getParentId() {
return parentId;
}
public void setParentId(Id parentId) {
this.parentId = parentId;
}
public String getParentCollectionName() {
return parentCollectionName;
}
public void setParentCollectionName(String parentCollectionName) {
this.parentCollectionName = parentCollectionName;
}
public List<NodeCollectionDefConfig> getNodeCollectionDefConfigs() {
return nodeCollectionDefConfigs;
}
public void setNodeCollectionDefConfigs(List<NodeCollectionDefConfig> nodeCollectionDefConfigs) {
this.nodeCollectionDefConfigs = nodeCollectionDefConfigs;
}
}
| 1,451 | 0.728825 | 0.721995 | 52 | 27.153847 | 26.652597 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.326923 | false | false | 4 |
281e1d765ae7310a1823f3a230a2423c1c8f10ae | 3,470,333,633,534 | 6fc28fbe61a8a07d43a464062116b73751a851d3 | /src/main/java/com/amela/service/ProductService.java | adf37f47a5623c030db4c787f9e6a056625640b2 | [] | no_license | tungnk0711/amela-jpa-demo | https://github.com/tungnk0711/amela-jpa-demo | 5b82eaca55c2e9e957efeb44fd2b42253daed6f7 | 6966d0e3c23ddf9328a817e71cc611c943076667 | refs/heads/master | 2023-06-29T19:12:00.610000 | 2021-08-03T09:06:39 | 2021-08-03T09:06:39 | 388,865,413 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.amela.service;
import com.amela.model.Product;
import com.amela.repository.IProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class ProductService implements IProductService {
@Autowired
private IProductRepository productRepository;
@Override
public List<Product> findAll() {
return productRepository.findAll();
}
@Override
public void saveProduct(Product product){
}
@Override
public Product findById(Long id) {
return productRepository.findById(id);
}
}
| UTF-8 | Java | 603 | java | ProductService.java | Java | [] | null | [] | package com.amela.service;
import com.amela.model.Product;
import com.amela.repository.IProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class ProductService implements IProductService {
@Autowired
private IProductRepository productRepository;
@Override
public List<Product> findAll() {
return productRepository.findAll();
}
@Override
public void saveProduct(Product product){
}
@Override
public Product findById(Long id) {
return productRepository.findById(id);
}
}
| 603 | 0.72471 | 0.72471 | 32 | 17.8125 | 20.20742 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 4 |
080ff9fc5e44396f3ff5e41832946508f57eb6eb | 14,396,730,427,186 | e8108ce9387380c1be0aba036ced34e4995b69a6 | /src/main/java/com/spring/boot/demo/algorithm/june/RotateArray_189.java | 3de1018709466f7986edc120dedc0e6c465ae127 | [] | no_license | bupt-yjw/springboot | https://github.com/bupt-yjw/springboot | 8b1add6631ea39b694e1cbe95dfa05883180276b | 1f86d105bdc2f264394c23d08c0643790beef63c | refs/heads/master | 2022-12-26T13:15:30.001000 | 2020-10-10T11:58:41 | 2020-10-10T11:58:41 | 302,882,265 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.spring.boot.demo.algorithm.june;
/** TODO
* Created by weiyongjun on 2020/6/11
* 三种方法。1。使用两层循环,外层控制旋转次数,内层控制元素交换位置。此解法时间复杂度为O(n*k),空间复杂度为O(1)。
* 2。新建一个大小和nums一样的数组,然后将旋转后的元素放入新的数组中。此解法的时间复杂度是O(n),空间复杂度是O(n)
* 3。通过三次反转数组实现。此解法的时间复杂度是O(n),空间复杂度是O(1)。
* 参考链接:https://www.cnblogs.com/xiaochuan94/p/10024317.html
*/
public class RotateArray_189 {
public void rotate(int[] nums, int k) {
k = k% nums.length;
if(k==0) {
return;
}
reverse(nums,0, nums.length-1);
reverse(nums,0, k-1);
reverse(nums,k, nums.length-1);
}
private void reverse(int[] nums, int start, int end) {
while (start < end){
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;end--;
}
}
}
| UTF-8 | Java | 1,130 | java | RotateArray_189.java | Java | [
{
"context": ".boot.demo.algorithm.june;\n\n/** TODO\n * Created by weiyongjun on 2020/6/11\n * 三种方法。1。使用两层循环,外层控制旋转次数,内层控制元素交换位置",
"end": 79,
"score": 0.9996459484100342,
"start": 69,
"tag": "USERNAME",
"value": "weiyongjun"
},
{
"context": "杂度是O(1)。\n * 参考链接:https://www.cnblogs.com/xiaochuan94/p/10024317.html\n */\npublic class RotateArray_189 ",
"end": 336,
"score": 0.9996482729911804,
"start": 325,
"tag": "USERNAME",
"value": "xiaochuan94"
}
] | null | [] | package com.spring.boot.demo.algorithm.june;
/** TODO
* Created by weiyongjun on 2020/6/11
* 三种方法。1。使用两层循环,外层控制旋转次数,内层控制元素交换位置。此解法时间复杂度为O(n*k),空间复杂度为O(1)。
* 2。新建一个大小和nums一样的数组,然后将旋转后的元素放入新的数组中。此解法的时间复杂度是O(n),空间复杂度是O(n)
* 3。通过三次反转数组实现。此解法的时间复杂度是O(n),空间复杂度是O(1)。
* 参考链接:https://www.cnblogs.com/xiaochuan94/p/10024317.html
*/
public class RotateArray_189 {
public void rotate(int[] nums, int k) {
k = k% nums.length;
if(k==0) {
return;
}
reverse(nums,0, nums.length-1);
reverse(nums,0, k-1);
reverse(nums,k, nums.length-1);
}
private void reverse(int[] nums, int start, int end) {
while (start < end){
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;end--;
}
}
}
| 1,130 | 0.561343 | 0.525463 | 31 | 26.870968 | 21.318993 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.645161 | false | false | 4 |
196a3cf4da774545978a67ed4ad7d802f237f385 | 7,335,804,206,726 | f0332942b22222781098807ecce0e49f5fb8db1e | /Sys_Matricula_Server/src/java/Services/Servicio_Profesor.java | bac910f783fdd40f3980dcf0743f8287c7489a72 | [] | no_license | spidyxD/Lab1_2 | https://github.com/spidyxD/Lab1_2 | d315326f6ef6fe8c77ccd5fddd6803fc9edaab68 | 0951c98fe60bc1db4b42f8f5d967526cce87b047 | refs/heads/master | 2020-04-25T14:33:09.107000 | 2019-06-03T03:45:22 | 2019-06-03T03:45:22 | 172,845,696 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 Services;
import Dao.Data;
import Entities.Profesor;
import Entities.Usuario;
import java.util.ArrayList;
/**
*
* @author Addiel
*/
public class Servicio_Profesor {
private static Servicio_Profesor uniqueInstance;
public static Servicio_Profesor instance(){
if (uniqueInstance == null){
uniqueInstance = new Servicio_Profesor();
}
return uniqueInstance;
}
public void insertarProfesor(Profesor profesor, Usuario user) {
try{
Data.instance().getServicioProfesor().insertarProfesor(profesor, user);
}
catch(Exception e){}
}
public void modificarProfesor(Profesor profesor, Usuario user){
try{
Data.instance().getServicioProfesor().modificarProfesor(profesor, user);
}
catch(Exception e){}
}
public void eliminarProfesor(int codigo){
try{
Data.instance().getServicioProfesor().eliminarProfesor(codigo);
}
catch(Exception e){}
}
public ArrayList<Profesor> verProfesores() throws Exception{
ArrayList aux = null;
try{
return Data.instance().getServicioProfesor().verProfesores();
}
catch(Exception e){}
throw new Exception();
}
public void modificarProfesorAdmin(Profesor profesor){
try{
Data.instance().getServicioProfesor().modificarProfesorAdmin(profesor);
}
catch(Exception e){}
}
}
| UTF-8 | Java | 1,680 | java | Servicio_Profesor.java | Java | [
{
"context": "io;\nimport java.util.ArrayList;\n\n/**\n *\n * @author Addiel\n */\npublic class Servicio_Profesor {\n private ",
"end": 325,
"score": 0.998430609703064,
"start": 319,
"tag": "NAME",
"value": "Addiel"
}
] | null | [] | /*
* 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 Services;
import Dao.Data;
import Entities.Profesor;
import Entities.Usuario;
import java.util.ArrayList;
/**
*
* @author Addiel
*/
public class Servicio_Profesor {
private static Servicio_Profesor uniqueInstance;
public static Servicio_Profesor instance(){
if (uniqueInstance == null){
uniqueInstance = new Servicio_Profesor();
}
return uniqueInstance;
}
public void insertarProfesor(Profesor profesor, Usuario user) {
try{
Data.instance().getServicioProfesor().insertarProfesor(profesor, user);
}
catch(Exception e){}
}
public void modificarProfesor(Profesor profesor, Usuario user){
try{
Data.instance().getServicioProfesor().modificarProfesor(profesor, user);
}
catch(Exception e){}
}
public void eliminarProfesor(int codigo){
try{
Data.instance().getServicioProfesor().eliminarProfesor(codigo);
}
catch(Exception e){}
}
public ArrayList<Profesor> verProfesores() throws Exception{
ArrayList aux = null;
try{
return Data.instance().getServicioProfesor().verProfesores();
}
catch(Exception e){}
throw new Exception();
}
public void modificarProfesorAdmin(Profesor profesor){
try{
Data.instance().getServicioProfesor().modificarProfesorAdmin(profesor);
}
catch(Exception e){}
}
}
| 1,680 | 0.63631 | 0.63631 | 59 | 27.474577 | 25.258902 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.372881 | false | false | 4 |
4580b7ac4381a2cf2d32987ff32fe9400f182b2e | 5,248,450,068,801 | 363e6da34f9e152b8610269528876b2356c266ba | /src/main/java/io/github/monstersunited/monstergame/objects/enums/Corner.java | 8caf88cc3d942c9fdbd1d49de3f6366d7a8e8d77 | [] | no_license | bigbeno37/MonstersUnited | https://github.com/bigbeno37/MonstersUnited | 0a638aa3eef7cd41be639479a69ca264dd27f61a | b8b4faea7f5864743bb96a8fe423107b8be3ae0d | refs/heads/master | 2020-03-23T01:46:07.743000 | 2017-11-12T10:53:10 | 2017-11-12T10:53:10 | 140,936,447 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.github.monstersunited.monstergame.objects.enums;
// Convenience for determining which position to set
// the player
public enum Corner {
TOP_LEFT(0, 0), TOP_RIGHT(8, 0), BOTTOM_LEFT(0, 8), BOTTOM_RIGHT(8, 8);
public int x;
public int y;
Corner(int x, int y) {
this.x = x;
this.y = y;
}
}
| UTF-8 | Java | 338 | java | Corner.java | Java | [] | null | [] | package io.github.monstersunited.monstergame.objects.enums;
// Convenience for determining which position to set
// the player
public enum Corner {
TOP_LEFT(0, 0), TOP_RIGHT(8, 0), BOTTOM_LEFT(0, 8), BOTTOM_RIGHT(8, 8);
public int x;
public int y;
Corner(int x, int y) {
this.x = x;
this.y = y;
}
}
| 338 | 0.621302 | 0.597633 | 15 | 21.533333 | 22.249695 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.933333 | false | false | 4 |
9b699875ee13ef3a2a578e936e8ed114d0307910 | 8,400,956,049,141 | 4d6c00789d5eb8118e6df6fc5bcd0f671bbcdd2d | /src/main/java/com/alipay/api/domain/AlipayCreditAutofinanceLoanApplyModel.java | b038ce1847c56ea8528e4aefa5ef04ecdb3a1e02 | [
"Apache-2.0"
] | permissive | weizai118/payment-alipay | https://github.com/weizai118/payment-alipay | 042898e172ce7f1162a69c1dc445e69e53a1899c | e3c1ad17d96524e5f1c4ba6d0af5b9e8fce97ac1 | refs/heads/master | 2020-04-05T06:29:57.113000 | 2018-11-06T11:03:05 | 2018-11-06T11:03:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 提交贷款订单
*
* @author auto create
* @since 1.0, 2017-11-23 15:49:56
*/
public class AlipayCreditAutofinanceLoanApplyModel extends AlipayObject {
private static final long serialVersionUID = 4524683478846366411L;
/**
* 区域
*/
@ApiField("area")
private String area;
/**
* 征信结果回调地址
*/
@ApiField("backurl")
private String backurl;
/**
* 扩展参数信息,json格式,针对不同的业务平台有不同的参数,目前大搜车业务支持的参数有:firstpayamt 首付租金,firstpayprop 首付比例,lastpayamt 回购尾款,loantenor 贷款期数,monthpayamt 每月还款额度
*/
@ApiField("extparam")
private String extparam;
/**
* 外部平台宝贝ID
*/
@ApiField("itemid")
private String itemid;
/**
* 机构编码
*/
@ApiField("orgcode")
private String orgcode;
/**
* 外部平台订单号,64个字符以内、只能包含字母、数字、下划线;需保证在外部平台端不重复
*/
@ApiField("outorderno")
private String outorderno;
/**
* 支付宝账号数字ID
*/
@ApiField("uid")
private String uid;
/**
* 核身VID
*/
@ApiField("verifyid")
private String verifyid;
/**
* 当前安装的支付宝钱包版本号
*/
@ApiField("version")
private String version;
/**
* Gets area.
*
* @return the area
*/
public String getArea() {
return this.area;
}
/**
* Sets area.
*
* @param area the area
*/
public void setArea(String area) {
this.area = area;
}
/**
* Gets backurl.
*
* @return the backurl
*/
public String getBackurl() {
return this.backurl;
}
/**
* Sets backurl.
*
* @param backurl the backurl
*/
public void setBackurl(String backurl) {
this.backurl = backurl;
}
/**
* Gets extparam.
*
* @return the extparam
*/
public String getExtparam() {
return this.extparam;
}
/**
* Sets extparam.
*
* @param extparam the extparam
*/
public void setExtparam(String extparam) {
this.extparam = extparam;
}
/**
* Gets itemid.
*
* @return the itemid
*/
public String getItemid() {
return this.itemid;
}
/**
* Sets itemid.
*
* @param itemid the itemid
*/
public void setItemid(String itemid) {
this.itemid = itemid;
}
/**
* Gets orgcode.
*
* @return the orgcode
*/
public String getOrgcode() {
return this.orgcode;
}
/**
* Sets orgcode.
*
* @param orgcode the orgcode
*/
public void setOrgcode(String orgcode) {
this.orgcode = orgcode;
}
/**
* Gets outorderno.
*
* @return the outorderno
*/
public String getOutorderno() {
return this.outorderno;
}
/**
* Sets outorderno.
*
* @param outorderno the outorderno
*/
public void setOutorderno(String outorderno) {
this.outorderno = outorderno;
}
/**
* Gets uid.
*
* @return the uid
*/
public String getUid() {
return this.uid;
}
/**
* Sets uid.
*
* @param uid the uid
*/
public void setUid(String uid) {
this.uid = uid;
}
/**
* Gets verifyid.
*
* @return the verifyid
*/
public String getVerifyid() {
return this.verifyid;
}
/**
* Sets verifyid.
*
* @param verifyid the verifyid
*/
public void setVerifyid(String verifyid) {
this.verifyid = verifyid;
}
/**
* Gets version.
*
* @return the version
*/
public String getVersion() {
return this.version;
}
/**
* Sets version.
*
* @param version the version
*/
public void setVersion(String version) {
this.version = version;
}
}
| UTF-8 | Java | 3,952 | java | AlipayCreditAutofinanceLoanApplyModel.java | Java | [
{
"context": "nal.mapping.ApiField;\n\n/**\n * 提交贷款订单\n *\n * @author auto create\n * @since 1.0, 2017-11-23 15:49:56\n */\npublic cla",
"end": 157,
"score": 0.7010976076126099,
"start": 146,
"tag": "USERNAME",
"value": "auto create"
}
] | null | [] | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 提交贷款订单
*
* @author auto create
* @since 1.0, 2017-11-23 15:49:56
*/
public class AlipayCreditAutofinanceLoanApplyModel extends AlipayObject {
private static final long serialVersionUID = 4524683478846366411L;
/**
* 区域
*/
@ApiField("area")
private String area;
/**
* 征信结果回调地址
*/
@ApiField("backurl")
private String backurl;
/**
* 扩展参数信息,json格式,针对不同的业务平台有不同的参数,目前大搜车业务支持的参数有:firstpayamt 首付租金,firstpayprop 首付比例,lastpayamt 回购尾款,loantenor 贷款期数,monthpayamt 每月还款额度
*/
@ApiField("extparam")
private String extparam;
/**
* 外部平台宝贝ID
*/
@ApiField("itemid")
private String itemid;
/**
* 机构编码
*/
@ApiField("orgcode")
private String orgcode;
/**
* 外部平台订单号,64个字符以内、只能包含字母、数字、下划线;需保证在外部平台端不重复
*/
@ApiField("outorderno")
private String outorderno;
/**
* 支付宝账号数字ID
*/
@ApiField("uid")
private String uid;
/**
* 核身VID
*/
@ApiField("verifyid")
private String verifyid;
/**
* 当前安装的支付宝钱包版本号
*/
@ApiField("version")
private String version;
/**
* Gets area.
*
* @return the area
*/
public String getArea() {
return this.area;
}
/**
* Sets area.
*
* @param area the area
*/
public void setArea(String area) {
this.area = area;
}
/**
* Gets backurl.
*
* @return the backurl
*/
public String getBackurl() {
return this.backurl;
}
/**
* Sets backurl.
*
* @param backurl the backurl
*/
public void setBackurl(String backurl) {
this.backurl = backurl;
}
/**
* Gets extparam.
*
* @return the extparam
*/
public String getExtparam() {
return this.extparam;
}
/**
* Sets extparam.
*
* @param extparam the extparam
*/
public void setExtparam(String extparam) {
this.extparam = extparam;
}
/**
* Gets itemid.
*
* @return the itemid
*/
public String getItemid() {
return this.itemid;
}
/**
* Sets itemid.
*
* @param itemid the itemid
*/
public void setItemid(String itemid) {
this.itemid = itemid;
}
/**
* Gets orgcode.
*
* @return the orgcode
*/
public String getOrgcode() {
return this.orgcode;
}
/**
* Sets orgcode.
*
* @param orgcode the orgcode
*/
public void setOrgcode(String orgcode) {
this.orgcode = orgcode;
}
/**
* Gets outorderno.
*
* @return the outorderno
*/
public String getOutorderno() {
return this.outorderno;
}
/**
* Sets outorderno.
*
* @param outorderno the outorderno
*/
public void setOutorderno(String outorderno) {
this.outorderno = outorderno;
}
/**
* Gets uid.
*
* @return the uid
*/
public String getUid() {
return this.uid;
}
/**
* Sets uid.
*
* @param uid the uid
*/
public void setUid(String uid) {
this.uid = uid;
}
/**
* Gets verifyid.
*
* @return the verifyid
*/
public String getVerifyid() {
return this.verifyid;
}
/**
* Sets verifyid.
*
* @param verifyid the verifyid
*/
public void setVerifyid(String verifyid) {
this.verifyid = verifyid;
}
/**
* Gets version.
*
* @return the version
*/
public String getVersion() {
return this.version;
}
/**
* Sets version.
*
* @param version the version
*/
public void setVersion(String version) {
this.version = version;
}
}
| 3,952 | 0.573505 | 0.563357 | 232 | 14.715517 | 15.583372 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.573276 | false | false | 4 |
31019f8dce2a0d5047ed85c41c27d57b16815fce | 18,373,870,099,547 | 667e5503eb6bacce5fff8a673b48511b03b5609d | /crm/src/cn/wx/crm/mapper/UserMapper.java | 8d7e5038728c1b0536f5ce02700cfe61686983b7 | [] | no_license | wanxiao777/wanxiao | https://github.com/wanxiao777/wanxiao | c410d68428ca92e1ce170f2f41685108dfc082c7 | 2742d382800f9b5977c5b6ebf9a90d1558f63758 | refs/heads/master | 2021-09-09T09:09:17.668000 | 2018-03-14T13:22:20 | 2018-03-14T13:32:39 | 112,626,433 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.wx.crm.mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import cn.wx.crm.entity.User;
public interface UserMapper {
@Select("select u.id,u.name,u.password,u.enabled,u.salt,r.name as \"role.name\""
+ "from users u left outer join roles r on u.role_id = r.id where u.name = #{username}")
User getUserByName(@Param("username") String username);
}
| UTF-8 | Java | 425 | java | UserMapper.java | Java | [] | null | [] | package cn.wx.crm.mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import cn.wx.crm.entity.User;
public interface UserMapper {
@Select("select u.id,u.name,u.password,u.enabled,u.salt,r.name as \"role.name\""
+ "from users u left outer join roles r on u.role_id = r.id where u.name = #{username}")
User getUserByName(@Param("username") String username);
}
| 425 | 0.712941 | 0.712941 | 13 | 30.692308 | 30.159536 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.153846 | false | false | 4 |
198248a5c340e8472159b3782345b0d1d8ea156b | 32,280,974,198,662 | ebf61403934087eefaef439d7e2bcc5b59b06c9b | /src/Day16/Task02.java | 60147e7fd23511099a853bb993e0472e568f0aad | [] | no_license | m-abdullaev/TechnoStudy | https://github.com/m-abdullaev/TechnoStudy | db6d4191e29a940bf8a79574b73c651a9bbc499f | ab46b2b5ede280b81ec0ac31e79e7d92a8315018 | refs/heads/master | 2022-12-02T05:30:52.116000 | 2020-08-05T00:13:13 | 2020-08-05T00:13:13 | 265,141,293 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Day16;
public class Task02 {
// Write a Java program to sum values of an array
// constraints: size should be 5
// {10, 10, 30, 40, 10} => 100
public static void main(String[] args) {
int[] array = {10, 10, 30, 40, 10};
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
System.out.println("Sum is: " + sum);
}
}
| UTF-8 | Java | 417 | java | Task02.java | Java | [] | null | [] | package Day16;
public class Task02 {
// Write a Java program to sum values of an array
// constraints: size should be 5
// {10, 10, 30, 40, 10} => 100
public static void main(String[] args) {
int[] array = {10, 10, 30, 40, 10};
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
System.out.println("Sum is: " + sum);
}
}
| 417 | 0.508393 | 0.436451 | 16 | 25.0625 | 18.119287 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.9375 | false | false | 4 |
5b4df42f41186939f3517cb99d08fdd4d0f001d2 | 15,410,342,678,642 | ff88e7ac2dfd0f5c45aa4569939eca2bd5032862 | /src/main/java/figurky/Figurka.java | 76f7cabc1b7c17b0ddfbd05bb7c5c7041a3fc1c4 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | kedar700cz/Chess-PRJ | https://github.com/kedar700cz/Chess-PRJ | e3c9c242560b9966a8b2a2e654fbd200a041e00f | 68e634bed8eef7e077d05615e7dc30d3d4fd5166 | refs/heads/master | 2020-09-30T01:29:22.969000 | 2019-12-16T17:40:46 | 2019-12-16T17:40:46 | 227,166,899 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 figurky;
import hraci_deska.Policka;
import javafx.scene.Group;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
/**
*
* @author kedar
*/
public abstract class Figurka extends Group implements Movable {
private final Color barva;
public Figurka(Color b){
this.barva = b;
String BARVA = "WHITE";
if (b == Color.BLACK) {
BARVA = "BLACK";
}
Image img = new Image(BARVA + "_" + this.getClass().getSimpleName().toUpperCase() + ".png");
ImageView iv = new ImageView(img);
iv.setFitWidth(Policka.VELIKOST);
iv.setFitHeight(Policka.VELIKOST);
this.getChildren().add(iv);
}
public void move() {
}
public Color getColor() {
return this.barva;
}
}
| UTF-8 | Java | 1,048 | java | Figurka.java | Java | [
{
"context": "import javafx.scene.paint.Color;\n/**\n *\n * @author kedar\n */\npublic abstract class Figurka extends Group i",
"end": 385,
"score": 0.9626628756523132,
"start": 380,
"tag": "USERNAME",
"value": "kedar"
}
] | null | [] | /*
* 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 figurky;
import hraci_deska.Policka;
import javafx.scene.Group;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
/**
*
* @author kedar
*/
public abstract class Figurka extends Group implements Movable {
private final Color barva;
public Figurka(Color b){
this.barva = b;
String BARVA = "WHITE";
if (b == Color.BLACK) {
BARVA = "BLACK";
}
Image img = new Image(BARVA + "_" + this.getClass().getSimpleName().toUpperCase() + ".png");
ImageView iv = new ImageView(img);
iv.setFitWidth(Policka.VELIKOST);
iv.setFitHeight(Policka.VELIKOST);
this.getChildren().add(iv);
}
public void move() {
}
public Color getColor() {
return this.barva;
}
}
| 1,048 | 0.618321 | 0.618321 | 48 | 20.833334 | 22.402876 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.708333 | false | false | 4 |
866269f47f55b709c98d5f4d3750f7b08861fecb | 21,698,174,840,551 | f5f11b61fecfbcc89234b74db88048d1147c2e37 | /src/main/java/com/monql/operator/Operator.java | 62f4bbcd10c426fdd2ea711e980e1305f363db66 | [] | no_license | narry/monql-java | https://github.com/narry/monql-java | cf03aed6de98afa56a5d755803a6735a130fb7cf | 5e8162285396d2b11900bb09892ce421def0a677 | refs/heads/master | 2021-01-09T20:54:48.291000 | 2013-10-07T05:07:58 | 2013-10-07T05:07:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.monql.operator;
import com.mongodb.DBObject;
/**
* 操作符接口
*
* @author monql
* @since 2012-1-25 上午11:09:38
*/
public interface Operator {
/**
* 生成该操作符下的DBObject
*
* @param key doc中的key
* @param value doc中的value
* @return
*/
public DBObject execute(Object value);
/**
* 检查key
*
* @param key doc中的key
*/
public void checkKey(String key);
/**
* 检查value
*
* @param value doc中的value
*/
public void checkValue(Object value);
}
| UTF-8 | Java | 606 | java | Operator.java | Java | [
{
"context": "com.mongodb.DBObject;\n\n/**\n * 操作符接口\n * \n * @author monql\n * @since 2012-1-25 上午11:09:38\n */\npublic interfa",
"end": 92,
"score": 0.999566376209259,
"start": 87,
"tag": "USERNAME",
"value": "monql"
}
] | null | [] | package com.monql.operator;
import com.mongodb.DBObject;
/**
* 操作符接口
*
* @author monql
* @since 2012-1-25 上午11:09:38
*/
public interface Operator {
/**
* 生成该操作符下的DBObject
*
* @param key doc中的key
* @param value doc中的value
* @return
*/
public DBObject execute(Object value);
/**
* 检查key
*
* @param key doc中的key
*/
public void checkKey(String key);
/**
* 检查value
*
* @param value doc中的value
*/
public void checkValue(Object value);
}
| 606 | 0.547101 | 0.523551 | 36 | 14.333333 | 12.487772 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.138889 | false | false | 4 |
79eb4d18ca4c76eb85bc74e3c8d8c0c88d9f88d9 | 28,716,151,356,543 | 6fe3f58aea74d1f4662b5b5021770ea64976c798 | /escola-util/src/main/java/com/escola/utils/constants/EscolaConfigConstant.java | 46c746db6aea039676e3eae04a431d9d372b722a | [] | no_license | rockonmahi/escola | https://github.com/rockonmahi/escola | c4d761c0afc8b5eef8a8a94a97b4ac27d04e51d0 | 4a589030727e59289e1fb55a981537f9ea8387c2 | HEAD | 2018-11-01T05:37:09.161000 | 2018-10-24T04:19:52 | 2018-10-24T04:19:52 | 152,886,847 | 0 | 2 | null | false | 2019-09-23T07:42:55 | 2018-10-13T15:39:24 | 2019-08-13T09:27:54 | 2019-09-23T07:42:54 | 8,645 | 0 | 0 | 0 | JavaScript | false | false | package com.escola.utils.constants;
public class EscolaConfigConstant {
public static final String SCAN_PACKAGE_PATH="com.escola";
public static final String TILES_FILE_PATH="/config/tiles/tiles.xml";
public static final String LAYOUT_FILE_PATH="/config/tiles/layout.xml";
public static final String STATIC_FILE_PATH="/static/";
public static final String JS_URL_PATH="/*.js/**";
public static final String CSS_URL_PATH="/*.css/**";
public static final String STATIC_URL_PATH="/static/**";
public static final String APPLICATION_URL_PATH="/escola/**";
public static final String DASHBOARD_URL_PATH="/dashboard";
public static final String SLACH_URL_PATH="/";
public static final String SLACH_STAR_URL_PATH="/*";
public static final String API_URL_PATH="/api/**";
public static final String LOGIN_URL_PATH="/login";
public static final String LOGIN_SSO_PATH="/ssoLogin";
public static final String LOGOUT_URL_PATH="/logout";
public static final String ACCESS_DENIED_URL_PATH="/accessDenied";
public static final String REQUEST_POST="POST";
public static final String REQUEST_GET="GET";
public static final String UTF_8="UTF-8";
}
| UTF-8 | Java | 1,158 | java | EscolaConfigConstant.java | Java | [] | null | [] | package com.escola.utils.constants;
public class EscolaConfigConstant {
public static final String SCAN_PACKAGE_PATH="com.escola";
public static final String TILES_FILE_PATH="/config/tiles/tiles.xml";
public static final String LAYOUT_FILE_PATH="/config/tiles/layout.xml";
public static final String STATIC_FILE_PATH="/static/";
public static final String JS_URL_PATH="/*.js/**";
public static final String CSS_URL_PATH="/*.css/**";
public static final String STATIC_URL_PATH="/static/**";
public static final String APPLICATION_URL_PATH="/escola/**";
public static final String DASHBOARD_URL_PATH="/dashboard";
public static final String SLACH_URL_PATH="/";
public static final String SLACH_STAR_URL_PATH="/*";
public static final String API_URL_PATH="/api/**";
public static final String LOGIN_URL_PATH="/login";
public static final String LOGIN_SSO_PATH="/ssoLogin";
public static final String LOGOUT_URL_PATH="/logout";
public static final String ACCESS_DENIED_URL_PATH="/accessDenied";
public static final String REQUEST_POST="POST";
public static final String REQUEST_GET="GET";
public static final String UTF_8="UTF-8";
}
| 1,158 | 0.746114 | 0.744387 | 28 | 40.357143 | 24.343105 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.535714 | false | false | 4 |
4c19c8958cd62e3a3f7cda2485ca5cd15b28812d | 7,816,840,546,318 | e9cf599f2e74680aba4860aed0443f37a6b55a18 | /src/main/java/com/course/microservice/broker/listener/saga_choreography/BonusRecordedCompensatingListener.java | f352acb7d4be36e09d9f795417a208890d7aae77 | [] | no_license | sam-germany/kafka-c_performance-management_Tim | https://github.com/sam-germany/kafka-c_performance-management_Tim | 00e7671cd8b19eb3c872dbf845f5fee2b4a109e3 | daa36c2bae38db6cd1b89f54afd1191d99ac0599 | refs/heads/master | 2023-02-16T14:09:29.889000 | 2021-01-17T14:56:01 | 2021-01-17T14:56:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.course.microservice.broker.listener.saga_choreography;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaHandler;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import com.course.microservice.broker.message.BonusRecordedMessage;
import com.course.microservice.broker.message.RecordBonusErrorMessage;
import com.course.microservice.command.service.CoreographyPerformanceAppraisalService;
/*
Note: we are listning this topic form the "organization-development" and their it can send normal message or Error message through the topic
so as we are getting 2 types of messages so here we create 2 methods with @KafkaHandler(), each take another type of argument
if normal message then first method and if error message then second method with @KafkaHandler() will be called
*/
@Component
@KafkaListener(topics = "t.saga02.organizationdevelopment")
public class BonusRecordedCompensatingListener {
private static final Logger LOG = LoggerFactory.getLogger(BonusRecordedCompensatingListener.class);
@Autowired
private CoreographyPerformanceAppraisalService performanceAppraisalService;
@KafkaHandler
public void listenBonusRecorded(BonusRecordedMessage message) throws InterruptedException {
LOG.debug("[Choreography-Saga] Listening bonus recorded message for appraisal {}", message.getAppraisalId());
// simulate finalization process
Thread.sleep(3000);
LOG.debug("[Choreography-Saga] Finalizing appraisal for {}", message.getAppraisalId());
// update appraisal status to approved
performanceAppraisalService.finalizePerformanceAppraisal(message.getAppraisalId());
}
@KafkaHandler
public void listenErrorFromBonusRecord(RecordBonusErrorMessage message) throws InterruptedException {
LOG.debug("[Choreography-Compensating Saga] Listening bonus record error message for appraisal {}", message.getAppraisalId());
// simulate compensation
Thread.sleep(3000);
LOG.debug("[Choreography-Compensating Saga] Compensate previous transaction, e.g. create log history, then update status to error");
// update appraisal status to error
performanceAppraisalService.errorPerformanceAppraisal(message.getAppraisalId());
}
}
| UTF-8 | Java | 2,346 | java | BonusRecordedCompensatingListener.java | Java | [] | null | [] | package com.course.microservice.broker.listener.saga_choreography;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaHandler;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import com.course.microservice.broker.message.BonusRecordedMessage;
import com.course.microservice.broker.message.RecordBonusErrorMessage;
import com.course.microservice.command.service.CoreographyPerformanceAppraisalService;
/*
Note: we are listning this topic form the "organization-development" and their it can send normal message or Error message through the topic
so as we are getting 2 types of messages so here we create 2 methods with @KafkaHandler(), each take another type of argument
if normal message then first method and if error message then second method with @KafkaHandler() will be called
*/
@Component
@KafkaListener(topics = "t.saga02.organizationdevelopment")
public class BonusRecordedCompensatingListener {
private static final Logger LOG = LoggerFactory.getLogger(BonusRecordedCompensatingListener.class);
@Autowired
private CoreographyPerformanceAppraisalService performanceAppraisalService;
@KafkaHandler
public void listenBonusRecorded(BonusRecordedMessage message) throws InterruptedException {
LOG.debug("[Choreography-Saga] Listening bonus recorded message for appraisal {}", message.getAppraisalId());
// simulate finalization process
Thread.sleep(3000);
LOG.debug("[Choreography-Saga] Finalizing appraisal for {}", message.getAppraisalId());
// update appraisal status to approved
performanceAppraisalService.finalizePerformanceAppraisal(message.getAppraisalId());
}
@KafkaHandler
public void listenErrorFromBonusRecord(RecordBonusErrorMessage message) throws InterruptedException {
LOG.debug("[Choreography-Compensating Saga] Listening bonus record error message for appraisal {}", message.getAppraisalId());
// simulate compensation
Thread.sleep(3000);
LOG.debug("[Choreography-Compensating Saga] Compensate previous transaction, e.g. create log history, then update status to error");
// update appraisal status to error
performanceAppraisalService.errorPerformanceAppraisal(message.getAppraisalId());
}
}
| 2,346 | 0.820972 | 0.815004 | 55 | 41.654545 | 43.351509 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.072727 | false | false | 4 |
ffe5397c311d6721e175577cc58f22bf6fbb543d | 10,041,633,538,165 | 263a8a36623aa8e7d5f86912455b582fbbc0f4d8 | /test/unit/src/org/openadaptor/auxil/connector/jdbc/reader/JDBCReadConnectorUnitTestCase.java | bd3c616a764688eda9753d3ae1ff016543f0a231 | [
"MIT"
] | permissive | commpeter/openadaptor3 | https://github.com/commpeter/openadaptor3 | 142aff5c02b2f4d1861dad1c2c070ce507cfc2d1 | 6a434ab58c2cb3cbcf8b02b79ba60de4aa3f328b | refs/heads/master | 2020-12-07T19:14:36.209000 | 2012-01-17T15:37:48 | 2012-01-17T15:37:48 | 66,144,466 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
Copyright (C) 2001 - 2007 The Software Conservancy as Trustee. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in the
Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Nothing in this notice shall be deemed to grant any rights to trademarks, copyrights,
patents, trade secrets or any other intellectual property of the licensor or any
contributor except as expressly stated herein. No patent license is granted separate
from the Software, for code that you delete from the Software, or for combinations
of the Software with other software or hardware.
*/
package org.openadaptor.auxil.connector.jdbc.reader;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Map;
import org.jmock.Mock;
import org.openadaptor.auxil.orderedmap.IOrderedMap;
import org.openadaptor.auxil.orderedmap.OrderedHashMap;
import org.openadaptor.core.IReadConnector;
import org.openadaptor.core.connector.DBEventDrivenPollingReadConnector;
import org.openadaptor.core.exception.ConnectionException;
/**
* Unit tests for {@link JDBCReadConnector}.
* The tests verify that {@link JDBCReadConnector}, perhaps in combination with a {@link IPollingReadConnector}
* implementation, is compatible with the pre 3.3 JDBC read connectors which it has replaced:
* {@OldJDBCReadConnector)
* {@JDBCPollConnector}
* {@JDBCEventReadConnector}
*
* Additionally, some tests verify new functionality such as batching (that didn't exist in
* any of the legacy connectors).
*
* @author Kris Lachor
*/
public class JDBCReadConnectorUnitTestCase extends AbstractJDBCConnectorTest{
private JDBCReadConnector jdbcReadConnector = new JDBCReadConnector();
/**
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
jdbcReadConnector.setId("Test Read Connector");
jdbcReadConnector.setSql(SQL);
jdbcReadConnector.setJdbcConnection(mockConnection);
}
/**
* Tests {@link JDBCReadConnector#connect}.
*/
public void testConnect(){
mockSqlConnection.expects(once()).method("createStatement").will(returnValue(mockStatement.proxy()));
assertNull(jdbcReadConnector.statement);
jdbcReadConnector.connect();
assertEquals(mockStatement.proxy(), jdbcReadConnector.statement);
}
/**
* Tests {@link JDBCReadConnector#connect}.
* Creating the statement throws exception.
*/
public void testConnect2(){
mockSqlConnection.expects(once()).method("createStatement").will(throwException(new SQLException("test", "test")));
assertNull(jdbcReadConnector.statement);
try{
jdbcReadConnector.connect();
}catch(ConnectionException ce){
assertNull(jdbcReadConnector.statement);
return;
}
assertTrue(false);
}
/**
* Tests {@link JDBCReadConnector#connect}.
* Ported from the legacy {@link JDBCEventReadConnectorUnitTestCase#testConnect()}.
*/
public void testConnect3(){
DBEventDrivenPollingReadConnector pollingReadConnector = new DBEventDrivenPollingReadConnector();
pollingReadConnector.setEventServiceID("10");
pollingReadConnector.setEventTypeID("20");
pollingReadConnector.setJdbcConnection(mockConnection);
pollingReadConnector.setDelegate(jdbcReadConnector);
Mock mockCallableStatement = new Mock(CallableStatement.class);
connectDBEventDrivenConnector(mockCallableStatement, pollingReadConnector);
}
/**
* Test the scenario when the afterConnectSql property is set.
*
* Tests {@link JDBCReadConnector#connect}.
*/
public void testConnectWithAfterConnectSql(){
Mock mockAfterConnectPreparedStatement = new Mock(PreparedStatement.class);
String afterConnectSql = "SELECT * FROM ...";
mockSqlConnection.expects(once()).method("createStatement").will(returnValue(mockStatement.proxy()));
mockSqlConnection.expects(once()).method("prepareStatement").with(eq(afterConnectSql))
.will(returnValue(mockAfterConnectPreparedStatement.proxy()));
mockAfterConnectPreparedStatement.expects(once()).method("execute").will(returnValue(false));
mockAfterConnectPreparedStatement.expects(once()).method("close");
assertNull(jdbcReadConnector.statement);
jdbcReadConnector.setAfterConnectSql(afterConnectSql);
jdbcReadConnector.connect();
assertEquals(mockStatement.proxy(), jdbcReadConnector.statement);
}
/**
* Tests {@link JDBCReadConnector#disconnect}.
*/
public void testDisonnect(){
testConnect();
mockStatement.expects(once()).method("close");
mockSqlConnection.expects(once()).method("close");
jdbcReadConnector.disconnect();
}
/**
* Tests {@link JDBCReadConnector#disconnect}.
*/
public void testDisonnectWithBeforeDisconnectSql(){
Mock mockBeforeDisconnectPreparedStatement = new Mock(PreparedStatement.class);
String beforeDisconnectSql = "SELECT * FROM ...";
jdbcReadConnector.setBeforeDisconnectSql(beforeDisconnectSql);
testConnect();
mockStatement.expects(once()).method("close");
/* Part specific to beforeDisconnectSql */
mockSqlConnection.expects(once()).method("prepareStatement").with(eq(beforeDisconnectSql))
.will(returnValue(mockBeforeDisconnectPreparedStatement.proxy()));
mockBeforeDisconnectPreparedStatement.expects(once()).method("execute").will(returnValue(false));
mockBeforeDisconnectPreparedStatement.expects(once()).method("close");
mockSqlConnection.expects(once()).method("close");
jdbcReadConnector.disconnect();
}
/**
* Test method for {@link org.openadaptor.auxil.connector.jdbc.reader.JDBCReadConnector#next(long)}.
* Initialises mock interfaces to return a result set with one column and one row.
* One call to the {@link JDBCReadConnector#next(long)} method.
* Ported from the legacy OldJDBCReadConnectorUnitTestCase.
*/
public void testNextOneRow1() {
setMocksToReturnNumberOfRows(1);
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(false)));
jdbcReadConnector.connect();
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
Object [] arr = (Object []) jdbcReadConnector.next(10);
assertTrue("Unexpected result type", arr[0] instanceof Map);
assertTrue("Unexpected result count", arr.length == 1);
Map map = (Map) arr[0];
String s = (String) map.get(COL1);
assertTrue("Unexpected result", s.equals(TEST_STRING));
}
/**
* Test method for {@link org.openadaptor.auxil.connector.jdbc.reader.JDBCReadConnector#next(long)}.
* This is identical to #testNextOneRow1 except that <code>postSubstitutionSql</code> is set and therefore
* should be used in place of <code>sql</code>.
*/
public void testNextOneRow1WithPostSubtitutionSqlSet() {
String someSQL = "Some other SQL";
jdbcReadConnector.postSubstitutionSql = someSQL;
/* slightly modified version of setMocksToReturnNumberOfRows(1)*/
mockStatement.expects(once()).method("executeQuery").with(eq(someSQL)).will(returnValue(mockResultSet.proxy()));
mockSqlConnection.expects(once()).method("createStatement").will(returnValue(mockStatement.proxy()));
mockResultSet.expects(atLeastOnce()).method("getMetaData").will(returnValue(mockResultSetMetaData.proxy()));
for(int i=0; i<1; i++){
mockResultSetMetaData.expects(once()).method("getColumnCount").will(returnValue(1));
mockResultSetMetaData.expects(once()).method("getColumnName").will(returnValue(COL1));
mockResultSet.expects(once()).method("getObject").with(eq(1)).will(returnValue(TEST_STRING));
}
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(false)));
jdbcReadConnector.connect();
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
Object [] arr = (Object []) jdbcReadConnector.next(10);
assertTrue("Unexpected result type", arr[0] instanceof Map);
assertTrue("Unexpected result count", arr.length == 1);
Map map = (Map) arr[0];
String s = (String) map.get(COL1);
assertTrue("Unexpected result", s.equals(TEST_STRING));
}
/**
* Test method for {@link org.openadaptor.auxil.connector.jdbc.reader.JDBCReadConnector#next(long)}.
* Initialises mock interfaces to return a result set with one column and one row.
* Two calls to the {@link JDBCReadConnector#next(long)} method.
* Checks value {@link JDBCReadConnector#isDry()}.
* Ported from the legacy OldJDBCReadConnectorUnitTestCase.
*/
public void testNextOneRow2() {
setMocksToReturnNumberOfRows(1);
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(false)));
mockResultSet.expects(once()).method("close");
jdbcReadConnector.connect();
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
Object [] arr = (Object []) jdbcReadConnector.next(10);
assertTrue("Unexpected result type", arr[0] instanceof Map);
assertTrue("Unexpected result count", arr.length == 1);
Map map = (Map) arr[0];
String s = (String) map.get(COL1);
assertTrue("Unexpected result", s.equals(TEST_STRING));
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
jdbcReadConnector.next(10);
assertTrue("Read connector not dry. Should be.", jdbcReadConnector.isDry());
}
/**
* Based on {@link #testNextOneRow2()} but also sets 'preReadSql' property.
*/
public void testNextOneRow2WithPreReadSql() {
Mock mockPreReadSqlPreparedStatement = new Mock(PreparedStatement.class);
String preReadSql = "UPDATE ...";
jdbcReadConnector.setPreReadSql(preReadSql);
setMocksToReturnNumberOfRows(1);
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(false)));
/* Part specific to preReadSql */
mockSqlConnection.expects(once()).method("prepareStatement").with(eq(preReadSql))
.will(returnValue(mockPreReadSqlPreparedStatement.proxy()));
mockPreReadSqlPreparedStatement.expects(once()).method("execute").will(returnValue(false));
mockPreReadSqlPreparedStatement.expects(once()).method("close");
mockResultSet.expects(once()).method("close");
jdbcReadConnector.connect();
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
Object [] arr = (Object []) jdbcReadConnector.next(10);
assertTrue("Unexpected result type", arr[0] instanceof Map);
assertTrue("Unexpected result count", arr.length == 1);
Map map = (Map) arr[0];
String s = (String) map.get(COL1);
assertTrue("Unexpected result", s.equals(TEST_STRING));
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
jdbcReadConnector.next(10);
assertTrue("Read connector not dry. Should be.", jdbcReadConnector.isDry());
}
/**
* Based on {@link #testNextOneRow2()} but also sets 'postReadSql' property.
*/
public void testNextOneRow2WithPostReadSql() {
Mock mockPostReadSqlPreparedStatement = new Mock(PreparedStatement.class);
String postReadSql = "UPDATE ...";
jdbcReadConnector.setPostReadSql(postReadSql);
setMocksToReturnNumberOfRows(1);
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(false)));
mockResultSet.expects(once()).method("close");
/* Part specific to postReadSql */
mockSqlConnection.expects(once()).method("prepareStatement").with(eq(postReadSql))
.will(returnValue(mockPostReadSqlPreparedStatement.proxy()));
mockPostReadSqlPreparedStatement.expects(once()).method("execute").will(returnValue(false));
mockPostReadSqlPreparedStatement.expects(once()).method("close");
jdbcReadConnector.connect();
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
Object [] arr = (Object []) jdbcReadConnector.next(10);
assertTrue("Unexpected result type", arr[0] instanceof Map);
assertTrue("Unexpected result count", arr.length == 1);
Map map = (Map) arr[0];
String s = (String) map.get(COL1);
assertTrue("Unexpected result", s.equals(TEST_STRING));
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
jdbcReadConnector.next(10);
assertTrue("Read connector not dry. Should be.", jdbcReadConnector.isDry());
}
/**
* Test method for {@link org.openadaptor.auxil.connector.jdbc.reader.JDBCReadConnector#next(long)}.
* Initialises mock interfaces to return a result set with one column and three rows.
* Batch size is set to 0 (= return all records in one batch).
* Checks value {@link JDBCReadConnector#isDry()}.
*/
public void testNextBatchAll() {
setMocksToReturnNumberOfRows(3);
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(true), returnValue(true), returnValue(false)));
mockResultSet.expects(once()).method("close");
jdbcReadConnector.setBatchSize(0);
jdbcReadConnector.connect();
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
Object [] arr = (Object []) jdbcReadConnector.next(10);
assertTrue("Unexpected result type", arr[0] instanceof Map);
assertTrue("Unexpected result count", arr.length == 3);
Map map = (Map) arr[0];
String s = (String) map.get(COL1);
assertTrue("Unexpected result", s.equals(TEST_STRING));
assertTrue("Read connector not dry. Should be.", jdbcReadConnector.isDry());
}
/**
* Test method for {@link org.openadaptor.auxil.connector.jdbc.reader.JDBCReadConnector#next(long)}.
* Initialises mock interfaces to return a result set with one column and three rows.
* Batch size is set to 2 (= next() should return one batch with two elements and the second batch with one
* element). Checks value {@link JDBCReadConnector#isDry()}.
*/
public void testNextBatchTwo() {
setMocksToReturnNumberOfRows(3);
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(true), returnValue(true), returnValue(false)));
mockResultSet.expects(once()).method("close");
jdbcReadConnector.setBatchSize(2);
jdbcReadConnector.connect();
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
Object [] arr = (Object []) jdbcReadConnector.next(10);
assertTrue("Unexpected result type", arr[0] instanceof Map);
assertTrue("Unexpected result count", arr.length == 2);
Map map = (Map) arr[0];
String s = (String) map.get(COL1);
assertTrue("Unexpected result", s.equals(TEST_STRING));
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
arr = (Object []) jdbcReadConnector.next(10);
assertTrue("Unexpected result type", arr[0] instanceof Map);
assertTrue("Unexpected result count", arr.length == 1);
map = (Map) arr[0];
s = (String) map.get(COL1);
assertTrue("Unexpected result", s.equals(TEST_STRING));
assertTrue("Read connector not dry. Should be.", jdbcReadConnector.isDry());
}
private void setMocksToReturnNumberOfRows(int numRows){
mockStatement.expects(once()).method("executeQuery").with(eq(SQL)).will(returnValue(mockResultSet.proxy()));
mockSqlConnection.expects(once()).method("createStatement").will(returnValue(mockStatement.proxy()));
mockResultSet.expects(atLeastOnce()).method("getMetaData").will(returnValue(mockResultSetMetaData.proxy()));
for(int i=0; i<numRows; i++){
mockResultSetMetaData.expects(once()).method("getColumnCount").will(returnValue(1));
mockResultSetMetaData.expects(once()).method("getColumnName").will(returnValue(COL1));
mockResultSet.expects(once()).method("getObject").with(eq(1)).will(returnValue(TEST_STRING));
}
}
/**
* Test method for {@link JDBCReadConnector#next(long)}.
* Ported from the legacy JDBCEventReadConnector unit tests.
* Stored procedure that polls returns nothing (no new events).
*/
public void testNextEventDriven1() {
DBEventDrivenPollingReadConnector pollingReadConnector = new DBEventDrivenPollingReadConnector();
pollingReadConnector.setEventServiceID("10");
pollingReadConnector.setEventTypeID("20");
pollingReadConnector.setJdbcConnection(mockConnection);
pollingReadConnector.setDelegate(jdbcReadConnector);
Mock mockPollStatement = new Mock(CallableStatement.class);
connectDBEventDrivenConnector(mockPollStatement, pollingReadConnector);
/*
* actual call to next. executeQuery returns a result set that is immediately closed
* (because of an SQLException thrown when no results are found..).
*/
mockPollStatement.expects(once()).method("executeQuery").will(returnValue(mockResultSet.proxy()));
mockPollStatement.expects(once()).method("close");
mockResultSet.expects(once()).method("getMetaData").will(returnValue(mockResultSetMetaData.proxy()));
mockResultSet.expects(once()).method("next").will(returnValue(false));
mockResultSet.expects(once()).method("close");
assertFalse("Read connector dry to soon.", pollingReadConnector.isDry());
assertNull(pollingReadConnector.next(10));
}
/**
* Test method for {@link JDBCReadConnector#next(long)}.
* Ported from the legacy JDBCEventReadConnector unit tests.
* Stored procesure that polls returns one new event. Query constructed based on this
* event returns an empty result set.
*/
public void testNextEventDriven2(){
DBEventDrivenPollingReadConnector pollingReadConnector = new DBEventDrivenPollingReadConnector();
pollingReadConnector.setEventServiceID("10");
pollingReadConnector.setEventTypeID("20");
pollingReadConnector.setJdbcConnection(mockConnection);
pollingReadConnector.setDelegate(jdbcReadConnector);
Mock mockPollStatement = new Mock(CallableStatement.class);
connectDBEventDrivenConnector(mockPollStatement, pollingReadConnector);
/* actual call to next */
mockPollStatement.expects(once()).method("executeQuery").will(returnValue(mockResultSet.proxy()));
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(false), returnValue(false)));
mockResultSet.expects(atLeastOnce()).method("getMetaData").will(returnValue(mockResultSetMetaData.proxy()));
mockResultSetMetaData.expects(atLeastOnce()).method("getColumnCount").will(returnValue(15));
for(int i=1; i<=15; i++){
mockResultSetMetaData.expects(once()).method("getColumnName").with(eq(i)).will(returnValue("COL" + new Integer(i)));
}
mockResultSet.expects(atLeastOnce()).method("getObject").will(returnValue("TEST"));
mockResultSet.expects(once()).method("close");
Mock mockActualStatement = new Mock(CallableStatement.class);
mockSqlConnection.expects(once()).method("prepareCall").with(eq("{ call TEST (?,?,?,?,?,?,?,?,?,?)}")).will(returnValue(mockActualStatement.proxy()));
mockActualStatement.expects(atLeastOnce()).method("setString");
mockActualStatement.expects(once()).method("executeQuery").will(returnValue(mockResultSet.proxy()));
mockResultSet.expects(once()).method("close");
mockActualStatement.expects(once()).method("close");
assertFalse("Read connector dry to soon.", pollingReadConnector.isDry());
Object [] arr = (Object []) pollingReadConnector.next(10);
assertTrue("Unexpected result count", arr.length == 0);
}
/**
* Test method for {@link JDBCReadConnector#next(long)}.
* Ported from the legacy JDBCEventReadConnector unit tests.
* Stored procesure that polls returns one new event. Query constructed based on this
* event returns a result set with one row.
*/
public void testNextEventDriven3() {
DBEventDrivenPollingReadConnector pollingReadConnector = new DBEventDrivenPollingReadConnector();
pollingReadConnector.setEventServiceID("10");
pollingReadConnector.setEventTypeID("20");
pollingReadConnector.setJdbcConnection(mockConnection);
pollingReadConnector.setDelegate(jdbcReadConnector);
Mock mockPollStatement = new Mock(CallableStatement.class);
Mock mockResultSet2 = new Mock(ResultSet.class);
Mock mockResultSetMetaData2 = new Mock(ResultSetMetaData.class);
connectDBEventDrivenConnector(mockPollStatement, pollingReadConnector);
/* actual call to next */
mockPollStatement.expects(once()).method("executeQuery").will(returnValue(mockResultSet.proxy()));
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(false)));
mockResultSet.expects(once()).method("getMetaData").will(returnValue(mockResultSetMetaData.proxy()));
mockResultSetMetaData.expects(atLeastOnce()).method("getColumnCount").will(returnValue(15));
for(int i=1; i<=15; i++){
mockResultSetMetaData.expects(once()).method("getColumnName").with(eq(i)).will(returnValue("COL" + new Integer(i)));
}
mockResultSet.expects(atLeastOnce()).method("getObject").will(returnValue("TEST"));
Mock mockActualStatement = new Mock(CallableStatement.class);
mockSqlConnection.expects(once()).method("prepareCall").with(eq("{ call TEST (?,?,?,?,?,?,?,?,?,?)}")).will(returnValue(mockActualStatement.proxy()));
mockActualStatement.expects(atLeastOnce()).method("setString");
mockActualStatement.expects(once()).method("executeQuery").will(returnValue(mockResultSet2.proxy()));
mockResultSet2.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(false)));
mockResultSet2.expects(once()).method("getMetaData").will(returnValue(mockResultSetMetaData2.proxy()));
mockResultSet2.expects(atLeastOnce()).method("getObject").will(returnValue("TEST2"));
mockResultSetMetaData2.expects(once()).method("getColumnCount").will(returnValue(1));
mockResultSetMetaData2.expects(once()).method("getColumnName").with(eq(1)).will(returnValue("COL1"));
mockResultSet.expects(once()).method("close");
mockActualStatement.expects(once()).method("close");
assertFalse("Read connector dry to soon.", pollingReadConnector.isDry());
Object [] arr = (Object []) pollingReadConnector.next(10);
assertTrue("Unexpected result count", arr.length == 1);
}
/**
* Test for {@link JDBCReadConnector#next(org.openadaptor.auxil.orderedmap.IOrderedMap, long)}
*/
public void testSetParametersForQuery1(){
IOrderedMap inputParams = new OrderedHashMap();
inputParams.put("param1", "1");
String sql = "SELECT a FROM TABLE1 WHERE a=?";
jdbcReadConnector.setSql(sql);
jdbcReadConnector.setParametersForQuery(inputParams);
assertEquals(jdbcReadConnector.sql, sql);
assertEquals(jdbcReadConnector.postSubstitutionSql, "SELECT a FROM TABLE1 WHERE a=1");
}
/**
* Test for {@link JDBCReadConnector#next(org.openadaptor.auxil.orderedmap.IOrderedMap, long)}
* No placeholders in the query.
*/
public void testSetParametersForQuery2(){
IOrderedMap inputParams = new OrderedHashMap();
inputParams.put("param1", "1");
String sql = "SELECT a FROM TABLE1 WHERE a=10";
jdbcReadConnector.setSql(sql);
jdbcReadConnector.setParametersForQuery(inputParams);
assertEquals(jdbcReadConnector.sql, sql);
assertNull(jdbcReadConnector.postSubstitutionSql);
}
/**
* Test for {@link JDBCReadConnector#next(org.openadaptor.auxil.orderedmap.IOrderedMap, long)}
* More placeholders than params.
*/
public void testSetParametersForQuery3(){
IOrderedMap inputParams = new OrderedHashMap();
inputParams.put("param1", "1");
String sql = "SELECT a FROM TABLE1 WHERE a=? AND b=?";
jdbcReadConnector.setSql(sql);
jdbcReadConnector.setParametersForQuery(inputParams);
assertEquals(jdbcReadConnector.sql, sql);
assertEquals(jdbcReadConnector.postSubstitutionSql, "SELECT a FROM TABLE1 WHERE a=1 AND b=?");
}
/**
* Test for {@link JDBCReadConnector#next(org.openadaptor.auxil.orderedmap.IOrderedMap, long)}
* More placeholders than params.
*/
public void testSetParametersForQuery4(){
IOrderedMap inputParams = new OrderedHashMap();
inputParams.put("param1", "1");
inputParams.put("param2", "2");
String sql = "SELECT a FROM TABLE1 WHERE a=? AND b=?";
jdbcReadConnector.setSql(sql);
jdbcReadConnector.setParametersForQuery(inputParams);
assertEquals(jdbcReadConnector.sql, sql);
assertEquals(jdbcReadConnector.postSubstitutionSql, "SELECT a FROM TABLE1 WHERE a=1 AND b=2");
}
/**
* Test for {@link JDBCReadConnector#next(org.openadaptor.auxil.orderedmap.IOrderedMap, long)}
* Null input params;
*/
public void testsetParametersForQuery5(){
String sql = "SELECT a FROM TABLE1 WHERE a=?";
jdbcReadConnector.setSql(sql);
jdbcReadConnector.setParametersForQuery(null);
assertEquals(jdbcReadConnector.sql, sql);
assertEquals(jdbcReadConnector.postSubstitutionSql, null);
}
private void connectDBEventDrivenConnector(Mock mockStatement, IReadConnector readConnector){
/* Callable statement for the pollingReadConnector */
mockSqlConnection.expects(once()).method("prepareCall").will(returnValue(mockStatement.proxy()));
/* 'Plain' statement for the underlying connector */
//mockSqlConnection.expects(once()).method("createStatement");
mockStatement.expects(once()).method("registerOutParameter").with(eq(1), eq(java.sql.Types.INTEGER));
mockStatement.expects(once()).method("setInt").with(eq(2), eq(10));
mockStatement.expects(once()).method("setInt").with(eq(3), eq(20));
readConnector.connect();
}
}
| UTF-8 | Java | 27,408 | java | JDBCReadConnectorUnitTestCase.java | Java | [
{
"context": " * any of the legacy connectors).\r\n * \r\n * @author Kris Lachor\r\n */\r\npublic class JDBCReadConnectorUnitTestCase ",
"end": 2614,
"score": 0.9998382329940796,
"start": 2603,
"tag": "NAME",
"value": "Kris Lachor"
}
] | null | [] | /*
Copyright (C) 2001 - 2007 The Software Conservancy as Trustee. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in the
Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Nothing in this notice shall be deemed to grant any rights to trademarks, copyrights,
patents, trade secrets or any other intellectual property of the licensor or any
contributor except as expressly stated herein. No patent license is granted separate
from the Software, for code that you delete from the Software, or for combinations
of the Software with other software or hardware.
*/
package org.openadaptor.auxil.connector.jdbc.reader;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Map;
import org.jmock.Mock;
import org.openadaptor.auxil.orderedmap.IOrderedMap;
import org.openadaptor.auxil.orderedmap.OrderedHashMap;
import org.openadaptor.core.IReadConnector;
import org.openadaptor.core.connector.DBEventDrivenPollingReadConnector;
import org.openadaptor.core.exception.ConnectionException;
/**
* Unit tests for {@link JDBCReadConnector}.
* The tests verify that {@link JDBCReadConnector}, perhaps in combination with a {@link IPollingReadConnector}
* implementation, is compatible with the pre 3.3 JDBC read connectors which it has replaced:
* {@OldJDBCReadConnector)
* {@JDBCPollConnector}
* {@JDBCEventReadConnector}
*
* Additionally, some tests verify new functionality such as batching (that didn't exist in
* any of the legacy connectors).
*
* @author <NAME>
*/
public class JDBCReadConnectorUnitTestCase extends AbstractJDBCConnectorTest{
private JDBCReadConnector jdbcReadConnector = new JDBCReadConnector();
/**
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
jdbcReadConnector.setId("Test Read Connector");
jdbcReadConnector.setSql(SQL);
jdbcReadConnector.setJdbcConnection(mockConnection);
}
/**
* Tests {@link JDBCReadConnector#connect}.
*/
public void testConnect(){
mockSqlConnection.expects(once()).method("createStatement").will(returnValue(mockStatement.proxy()));
assertNull(jdbcReadConnector.statement);
jdbcReadConnector.connect();
assertEquals(mockStatement.proxy(), jdbcReadConnector.statement);
}
/**
* Tests {@link JDBCReadConnector#connect}.
* Creating the statement throws exception.
*/
public void testConnect2(){
mockSqlConnection.expects(once()).method("createStatement").will(throwException(new SQLException("test", "test")));
assertNull(jdbcReadConnector.statement);
try{
jdbcReadConnector.connect();
}catch(ConnectionException ce){
assertNull(jdbcReadConnector.statement);
return;
}
assertTrue(false);
}
/**
* Tests {@link JDBCReadConnector#connect}.
* Ported from the legacy {@link JDBCEventReadConnectorUnitTestCase#testConnect()}.
*/
public void testConnect3(){
DBEventDrivenPollingReadConnector pollingReadConnector = new DBEventDrivenPollingReadConnector();
pollingReadConnector.setEventServiceID("10");
pollingReadConnector.setEventTypeID("20");
pollingReadConnector.setJdbcConnection(mockConnection);
pollingReadConnector.setDelegate(jdbcReadConnector);
Mock mockCallableStatement = new Mock(CallableStatement.class);
connectDBEventDrivenConnector(mockCallableStatement, pollingReadConnector);
}
/**
* Test the scenario when the afterConnectSql property is set.
*
* Tests {@link JDBCReadConnector#connect}.
*/
public void testConnectWithAfterConnectSql(){
Mock mockAfterConnectPreparedStatement = new Mock(PreparedStatement.class);
String afterConnectSql = "SELECT * FROM ...";
mockSqlConnection.expects(once()).method("createStatement").will(returnValue(mockStatement.proxy()));
mockSqlConnection.expects(once()).method("prepareStatement").with(eq(afterConnectSql))
.will(returnValue(mockAfterConnectPreparedStatement.proxy()));
mockAfterConnectPreparedStatement.expects(once()).method("execute").will(returnValue(false));
mockAfterConnectPreparedStatement.expects(once()).method("close");
assertNull(jdbcReadConnector.statement);
jdbcReadConnector.setAfterConnectSql(afterConnectSql);
jdbcReadConnector.connect();
assertEquals(mockStatement.proxy(), jdbcReadConnector.statement);
}
/**
* Tests {@link JDBCReadConnector#disconnect}.
*/
public void testDisonnect(){
testConnect();
mockStatement.expects(once()).method("close");
mockSqlConnection.expects(once()).method("close");
jdbcReadConnector.disconnect();
}
/**
* Tests {@link JDBCReadConnector#disconnect}.
*/
public void testDisonnectWithBeforeDisconnectSql(){
Mock mockBeforeDisconnectPreparedStatement = new Mock(PreparedStatement.class);
String beforeDisconnectSql = "SELECT * FROM ...";
jdbcReadConnector.setBeforeDisconnectSql(beforeDisconnectSql);
testConnect();
mockStatement.expects(once()).method("close");
/* Part specific to beforeDisconnectSql */
mockSqlConnection.expects(once()).method("prepareStatement").with(eq(beforeDisconnectSql))
.will(returnValue(mockBeforeDisconnectPreparedStatement.proxy()));
mockBeforeDisconnectPreparedStatement.expects(once()).method("execute").will(returnValue(false));
mockBeforeDisconnectPreparedStatement.expects(once()).method("close");
mockSqlConnection.expects(once()).method("close");
jdbcReadConnector.disconnect();
}
/**
* Test method for {@link org.openadaptor.auxil.connector.jdbc.reader.JDBCReadConnector#next(long)}.
* Initialises mock interfaces to return a result set with one column and one row.
* One call to the {@link JDBCReadConnector#next(long)} method.
* Ported from the legacy OldJDBCReadConnectorUnitTestCase.
*/
public void testNextOneRow1() {
setMocksToReturnNumberOfRows(1);
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(false)));
jdbcReadConnector.connect();
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
Object [] arr = (Object []) jdbcReadConnector.next(10);
assertTrue("Unexpected result type", arr[0] instanceof Map);
assertTrue("Unexpected result count", arr.length == 1);
Map map = (Map) arr[0];
String s = (String) map.get(COL1);
assertTrue("Unexpected result", s.equals(TEST_STRING));
}
/**
* Test method for {@link org.openadaptor.auxil.connector.jdbc.reader.JDBCReadConnector#next(long)}.
* This is identical to #testNextOneRow1 except that <code>postSubstitutionSql</code> is set and therefore
* should be used in place of <code>sql</code>.
*/
public void testNextOneRow1WithPostSubtitutionSqlSet() {
String someSQL = "Some other SQL";
jdbcReadConnector.postSubstitutionSql = someSQL;
/* slightly modified version of setMocksToReturnNumberOfRows(1)*/
mockStatement.expects(once()).method("executeQuery").with(eq(someSQL)).will(returnValue(mockResultSet.proxy()));
mockSqlConnection.expects(once()).method("createStatement").will(returnValue(mockStatement.proxy()));
mockResultSet.expects(atLeastOnce()).method("getMetaData").will(returnValue(mockResultSetMetaData.proxy()));
for(int i=0; i<1; i++){
mockResultSetMetaData.expects(once()).method("getColumnCount").will(returnValue(1));
mockResultSetMetaData.expects(once()).method("getColumnName").will(returnValue(COL1));
mockResultSet.expects(once()).method("getObject").with(eq(1)).will(returnValue(TEST_STRING));
}
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(false)));
jdbcReadConnector.connect();
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
Object [] arr = (Object []) jdbcReadConnector.next(10);
assertTrue("Unexpected result type", arr[0] instanceof Map);
assertTrue("Unexpected result count", arr.length == 1);
Map map = (Map) arr[0];
String s = (String) map.get(COL1);
assertTrue("Unexpected result", s.equals(TEST_STRING));
}
/**
* Test method for {@link org.openadaptor.auxil.connector.jdbc.reader.JDBCReadConnector#next(long)}.
* Initialises mock interfaces to return a result set with one column and one row.
* Two calls to the {@link JDBCReadConnector#next(long)} method.
* Checks value {@link JDBCReadConnector#isDry()}.
* Ported from the legacy OldJDBCReadConnectorUnitTestCase.
*/
public void testNextOneRow2() {
setMocksToReturnNumberOfRows(1);
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(false)));
mockResultSet.expects(once()).method("close");
jdbcReadConnector.connect();
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
Object [] arr = (Object []) jdbcReadConnector.next(10);
assertTrue("Unexpected result type", arr[0] instanceof Map);
assertTrue("Unexpected result count", arr.length == 1);
Map map = (Map) arr[0];
String s = (String) map.get(COL1);
assertTrue("Unexpected result", s.equals(TEST_STRING));
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
jdbcReadConnector.next(10);
assertTrue("Read connector not dry. Should be.", jdbcReadConnector.isDry());
}
/**
* Based on {@link #testNextOneRow2()} but also sets 'preReadSql' property.
*/
public void testNextOneRow2WithPreReadSql() {
Mock mockPreReadSqlPreparedStatement = new Mock(PreparedStatement.class);
String preReadSql = "UPDATE ...";
jdbcReadConnector.setPreReadSql(preReadSql);
setMocksToReturnNumberOfRows(1);
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(false)));
/* Part specific to preReadSql */
mockSqlConnection.expects(once()).method("prepareStatement").with(eq(preReadSql))
.will(returnValue(mockPreReadSqlPreparedStatement.proxy()));
mockPreReadSqlPreparedStatement.expects(once()).method("execute").will(returnValue(false));
mockPreReadSqlPreparedStatement.expects(once()).method("close");
mockResultSet.expects(once()).method("close");
jdbcReadConnector.connect();
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
Object [] arr = (Object []) jdbcReadConnector.next(10);
assertTrue("Unexpected result type", arr[0] instanceof Map);
assertTrue("Unexpected result count", arr.length == 1);
Map map = (Map) arr[0];
String s = (String) map.get(COL1);
assertTrue("Unexpected result", s.equals(TEST_STRING));
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
jdbcReadConnector.next(10);
assertTrue("Read connector not dry. Should be.", jdbcReadConnector.isDry());
}
/**
* Based on {@link #testNextOneRow2()} but also sets 'postReadSql' property.
*/
public void testNextOneRow2WithPostReadSql() {
Mock mockPostReadSqlPreparedStatement = new Mock(PreparedStatement.class);
String postReadSql = "UPDATE ...";
jdbcReadConnector.setPostReadSql(postReadSql);
setMocksToReturnNumberOfRows(1);
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(false)));
mockResultSet.expects(once()).method("close");
/* Part specific to postReadSql */
mockSqlConnection.expects(once()).method("prepareStatement").with(eq(postReadSql))
.will(returnValue(mockPostReadSqlPreparedStatement.proxy()));
mockPostReadSqlPreparedStatement.expects(once()).method("execute").will(returnValue(false));
mockPostReadSqlPreparedStatement.expects(once()).method("close");
jdbcReadConnector.connect();
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
Object [] arr = (Object []) jdbcReadConnector.next(10);
assertTrue("Unexpected result type", arr[0] instanceof Map);
assertTrue("Unexpected result count", arr.length == 1);
Map map = (Map) arr[0];
String s = (String) map.get(COL1);
assertTrue("Unexpected result", s.equals(TEST_STRING));
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
jdbcReadConnector.next(10);
assertTrue("Read connector not dry. Should be.", jdbcReadConnector.isDry());
}
/**
* Test method for {@link org.openadaptor.auxil.connector.jdbc.reader.JDBCReadConnector#next(long)}.
* Initialises mock interfaces to return a result set with one column and three rows.
* Batch size is set to 0 (= return all records in one batch).
* Checks value {@link JDBCReadConnector#isDry()}.
*/
public void testNextBatchAll() {
setMocksToReturnNumberOfRows(3);
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(true), returnValue(true), returnValue(false)));
mockResultSet.expects(once()).method("close");
jdbcReadConnector.setBatchSize(0);
jdbcReadConnector.connect();
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
Object [] arr = (Object []) jdbcReadConnector.next(10);
assertTrue("Unexpected result type", arr[0] instanceof Map);
assertTrue("Unexpected result count", arr.length == 3);
Map map = (Map) arr[0];
String s = (String) map.get(COL1);
assertTrue("Unexpected result", s.equals(TEST_STRING));
assertTrue("Read connector not dry. Should be.", jdbcReadConnector.isDry());
}
/**
* Test method for {@link org.openadaptor.auxil.connector.jdbc.reader.JDBCReadConnector#next(long)}.
* Initialises mock interfaces to return a result set with one column and three rows.
* Batch size is set to 2 (= next() should return one batch with two elements and the second batch with one
* element). Checks value {@link JDBCReadConnector#isDry()}.
*/
public void testNextBatchTwo() {
setMocksToReturnNumberOfRows(3);
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(true), returnValue(true), returnValue(false)));
mockResultSet.expects(once()).method("close");
jdbcReadConnector.setBatchSize(2);
jdbcReadConnector.connect();
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
Object [] arr = (Object []) jdbcReadConnector.next(10);
assertTrue("Unexpected result type", arr[0] instanceof Map);
assertTrue("Unexpected result count", arr.length == 2);
Map map = (Map) arr[0];
String s = (String) map.get(COL1);
assertTrue("Unexpected result", s.equals(TEST_STRING));
assertFalse("Read connector dry to soon.", jdbcReadConnector.isDry());
arr = (Object []) jdbcReadConnector.next(10);
assertTrue("Unexpected result type", arr[0] instanceof Map);
assertTrue("Unexpected result count", arr.length == 1);
map = (Map) arr[0];
s = (String) map.get(COL1);
assertTrue("Unexpected result", s.equals(TEST_STRING));
assertTrue("Read connector not dry. Should be.", jdbcReadConnector.isDry());
}
private void setMocksToReturnNumberOfRows(int numRows){
mockStatement.expects(once()).method("executeQuery").with(eq(SQL)).will(returnValue(mockResultSet.proxy()));
mockSqlConnection.expects(once()).method("createStatement").will(returnValue(mockStatement.proxy()));
mockResultSet.expects(atLeastOnce()).method("getMetaData").will(returnValue(mockResultSetMetaData.proxy()));
for(int i=0; i<numRows; i++){
mockResultSetMetaData.expects(once()).method("getColumnCount").will(returnValue(1));
mockResultSetMetaData.expects(once()).method("getColumnName").will(returnValue(COL1));
mockResultSet.expects(once()).method("getObject").with(eq(1)).will(returnValue(TEST_STRING));
}
}
/**
* Test method for {@link JDBCReadConnector#next(long)}.
* Ported from the legacy JDBCEventReadConnector unit tests.
* Stored procedure that polls returns nothing (no new events).
*/
public void testNextEventDriven1() {
DBEventDrivenPollingReadConnector pollingReadConnector = new DBEventDrivenPollingReadConnector();
pollingReadConnector.setEventServiceID("10");
pollingReadConnector.setEventTypeID("20");
pollingReadConnector.setJdbcConnection(mockConnection);
pollingReadConnector.setDelegate(jdbcReadConnector);
Mock mockPollStatement = new Mock(CallableStatement.class);
connectDBEventDrivenConnector(mockPollStatement, pollingReadConnector);
/*
* actual call to next. executeQuery returns a result set that is immediately closed
* (because of an SQLException thrown when no results are found..).
*/
mockPollStatement.expects(once()).method("executeQuery").will(returnValue(mockResultSet.proxy()));
mockPollStatement.expects(once()).method("close");
mockResultSet.expects(once()).method("getMetaData").will(returnValue(mockResultSetMetaData.proxy()));
mockResultSet.expects(once()).method("next").will(returnValue(false));
mockResultSet.expects(once()).method("close");
assertFalse("Read connector dry to soon.", pollingReadConnector.isDry());
assertNull(pollingReadConnector.next(10));
}
/**
* Test method for {@link JDBCReadConnector#next(long)}.
* Ported from the legacy JDBCEventReadConnector unit tests.
* Stored procesure that polls returns one new event. Query constructed based on this
* event returns an empty result set.
*/
public void testNextEventDriven2(){
DBEventDrivenPollingReadConnector pollingReadConnector = new DBEventDrivenPollingReadConnector();
pollingReadConnector.setEventServiceID("10");
pollingReadConnector.setEventTypeID("20");
pollingReadConnector.setJdbcConnection(mockConnection);
pollingReadConnector.setDelegate(jdbcReadConnector);
Mock mockPollStatement = new Mock(CallableStatement.class);
connectDBEventDrivenConnector(mockPollStatement, pollingReadConnector);
/* actual call to next */
mockPollStatement.expects(once()).method("executeQuery").will(returnValue(mockResultSet.proxy()));
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(false), returnValue(false)));
mockResultSet.expects(atLeastOnce()).method("getMetaData").will(returnValue(mockResultSetMetaData.proxy()));
mockResultSetMetaData.expects(atLeastOnce()).method("getColumnCount").will(returnValue(15));
for(int i=1; i<=15; i++){
mockResultSetMetaData.expects(once()).method("getColumnName").with(eq(i)).will(returnValue("COL" + new Integer(i)));
}
mockResultSet.expects(atLeastOnce()).method("getObject").will(returnValue("TEST"));
mockResultSet.expects(once()).method("close");
Mock mockActualStatement = new Mock(CallableStatement.class);
mockSqlConnection.expects(once()).method("prepareCall").with(eq("{ call TEST (?,?,?,?,?,?,?,?,?,?)}")).will(returnValue(mockActualStatement.proxy()));
mockActualStatement.expects(atLeastOnce()).method("setString");
mockActualStatement.expects(once()).method("executeQuery").will(returnValue(mockResultSet.proxy()));
mockResultSet.expects(once()).method("close");
mockActualStatement.expects(once()).method("close");
assertFalse("Read connector dry to soon.", pollingReadConnector.isDry());
Object [] arr = (Object []) pollingReadConnector.next(10);
assertTrue("Unexpected result count", arr.length == 0);
}
/**
* Test method for {@link JDBCReadConnector#next(long)}.
* Ported from the legacy JDBCEventReadConnector unit tests.
* Stored procesure that polls returns one new event. Query constructed based on this
* event returns a result set with one row.
*/
public void testNextEventDriven3() {
DBEventDrivenPollingReadConnector pollingReadConnector = new DBEventDrivenPollingReadConnector();
pollingReadConnector.setEventServiceID("10");
pollingReadConnector.setEventTypeID("20");
pollingReadConnector.setJdbcConnection(mockConnection);
pollingReadConnector.setDelegate(jdbcReadConnector);
Mock mockPollStatement = new Mock(CallableStatement.class);
Mock mockResultSet2 = new Mock(ResultSet.class);
Mock mockResultSetMetaData2 = new Mock(ResultSetMetaData.class);
connectDBEventDrivenConnector(mockPollStatement, pollingReadConnector);
/* actual call to next */
mockPollStatement.expects(once()).method("executeQuery").will(returnValue(mockResultSet.proxy()));
mockResultSet.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(false)));
mockResultSet.expects(once()).method("getMetaData").will(returnValue(mockResultSetMetaData.proxy()));
mockResultSetMetaData.expects(atLeastOnce()).method("getColumnCount").will(returnValue(15));
for(int i=1; i<=15; i++){
mockResultSetMetaData.expects(once()).method("getColumnName").with(eq(i)).will(returnValue("COL" + new Integer(i)));
}
mockResultSet.expects(atLeastOnce()).method("getObject").will(returnValue("TEST"));
Mock mockActualStatement = new Mock(CallableStatement.class);
mockSqlConnection.expects(once()).method("prepareCall").with(eq("{ call TEST (?,?,?,?,?,?,?,?,?,?)}")).will(returnValue(mockActualStatement.proxy()));
mockActualStatement.expects(atLeastOnce()).method("setString");
mockActualStatement.expects(once()).method("executeQuery").will(returnValue(mockResultSet2.proxy()));
mockResultSet2.expects(atLeastOnce()).method("next").will(onConsecutiveCalls(returnValue(true), returnValue(false)));
mockResultSet2.expects(once()).method("getMetaData").will(returnValue(mockResultSetMetaData2.proxy()));
mockResultSet2.expects(atLeastOnce()).method("getObject").will(returnValue("TEST2"));
mockResultSetMetaData2.expects(once()).method("getColumnCount").will(returnValue(1));
mockResultSetMetaData2.expects(once()).method("getColumnName").with(eq(1)).will(returnValue("COL1"));
mockResultSet.expects(once()).method("close");
mockActualStatement.expects(once()).method("close");
assertFalse("Read connector dry to soon.", pollingReadConnector.isDry());
Object [] arr = (Object []) pollingReadConnector.next(10);
assertTrue("Unexpected result count", arr.length == 1);
}
/**
* Test for {@link JDBCReadConnector#next(org.openadaptor.auxil.orderedmap.IOrderedMap, long)}
*/
public void testSetParametersForQuery1(){
IOrderedMap inputParams = new OrderedHashMap();
inputParams.put("param1", "1");
String sql = "SELECT a FROM TABLE1 WHERE a=?";
jdbcReadConnector.setSql(sql);
jdbcReadConnector.setParametersForQuery(inputParams);
assertEquals(jdbcReadConnector.sql, sql);
assertEquals(jdbcReadConnector.postSubstitutionSql, "SELECT a FROM TABLE1 WHERE a=1");
}
/**
* Test for {@link JDBCReadConnector#next(org.openadaptor.auxil.orderedmap.IOrderedMap, long)}
* No placeholders in the query.
*/
public void testSetParametersForQuery2(){
IOrderedMap inputParams = new OrderedHashMap();
inputParams.put("param1", "1");
String sql = "SELECT a FROM TABLE1 WHERE a=10";
jdbcReadConnector.setSql(sql);
jdbcReadConnector.setParametersForQuery(inputParams);
assertEquals(jdbcReadConnector.sql, sql);
assertNull(jdbcReadConnector.postSubstitutionSql);
}
/**
* Test for {@link JDBCReadConnector#next(org.openadaptor.auxil.orderedmap.IOrderedMap, long)}
* More placeholders than params.
*/
public void testSetParametersForQuery3(){
IOrderedMap inputParams = new OrderedHashMap();
inputParams.put("param1", "1");
String sql = "SELECT a FROM TABLE1 WHERE a=? AND b=?";
jdbcReadConnector.setSql(sql);
jdbcReadConnector.setParametersForQuery(inputParams);
assertEquals(jdbcReadConnector.sql, sql);
assertEquals(jdbcReadConnector.postSubstitutionSql, "SELECT a FROM TABLE1 WHERE a=1 AND b=?");
}
/**
* Test for {@link JDBCReadConnector#next(org.openadaptor.auxil.orderedmap.IOrderedMap, long)}
* More placeholders than params.
*/
public void testSetParametersForQuery4(){
IOrderedMap inputParams = new OrderedHashMap();
inputParams.put("param1", "1");
inputParams.put("param2", "2");
String sql = "SELECT a FROM TABLE1 WHERE a=? AND b=?";
jdbcReadConnector.setSql(sql);
jdbcReadConnector.setParametersForQuery(inputParams);
assertEquals(jdbcReadConnector.sql, sql);
assertEquals(jdbcReadConnector.postSubstitutionSql, "SELECT a FROM TABLE1 WHERE a=1 AND b=2");
}
/**
* Test for {@link JDBCReadConnector#next(org.openadaptor.auxil.orderedmap.IOrderedMap, long)}
* Null input params;
*/
public void testsetParametersForQuery5(){
String sql = "SELECT a FROM TABLE1 WHERE a=?";
jdbcReadConnector.setSql(sql);
jdbcReadConnector.setParametersForQuery(null);
assertEquals(jdbcReadConnector.sql, sql);
assertEquals(jdbcReadConnector.postSubstitutionSql, null);
}
private void connectDBEventDrivenConnector(Mock mockStatement, IReadConnector readConnector){
/* Callable statement for the pollingReadConnector */
mockSqlConnection.expects(once()).method("prepareCall").will(returnValue(mockStatement.proxy()));
/* 'Plain' statement for the underlying connector */
//mockSqlConnection.expects(once()).method("createStatement");
mockStatement.expects(once()).method("registerOutParameter").with(eq(1), eq(java.sql.Types.INTEGER));
mockStatement.expects(once()).method("setInt").with(eq(2), eq(10));
mockStatement.expects(once()).method("setInt").with(eq(3), eq(20));
readConnector.connect();
}
}
| 27,403 | 0.716616 | 0.710048 | 558 | 47.118279 | 34.90818 | 158 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.774194 | false | false | 4 |
af24cbf2007991e68262178e2cd556a5276591a1 | 5,171,140,684,782 | 62527b99469e344d4f00910b0dd25da292d982fa | /SwordToOffer/src/main/java/com/yanyun/sword/_019_printMatrix.java | e929b2c26ba7a7129e08760dcaee04cb7956c780 | [] | no_license | bellmit/MyAlgorithm | https://github.com/bellmit/MyAlgorithm | 30bf7fcd3ba4b3f79b9c2b91e0854d2eabd44c39 | bfc4ff4f118003e99a72cf54436de3ca5ff2ebf9 | refs/heads/master | 2023-03-29T22:33:32.334000 | 2021-04-11T12:15:30 | 2021-04-11T12:15:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yanyun.sword;
import java.util.*;
/**
* 回旋矩阵的打印
*/
public class _019_printMatrix {
/**
* 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字例如,如果输入如下4 X 4矩阵:
* 1 2 3 4
* 5 6 7 8
* 9 10 11 12
* 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10
* <p>
* --------------------------------------------------SOLUTION-------------------------------------------------------
* <p>
* 递归
*/
public ArrayList<Integer> printMatrix(int[][] matrix) {
ArrayList<Integer> list = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return list;
}
int up = 0;
int down = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
while (true) {
// 最上面一行
for (int col = left; col <= right; col++) {
list.add(matrix[up][col]);
}
// 向下逼近
up++;
// 判断是否越界
if (up > down) {
break;
}
// 最右边一行
for (int row = up; row <= down; row++) {
list.add(matrix[row][right]);
}
// 向左逼近
right--;
// 判断是否越界
if (left > right) {
break;
}
// 最下面一行
for (int col = right; col >= left; col--) {
list.add(matrix[down][col]);
}
// 向上逼近
down--;
// 判断是否越界
if (up > down) {
break;
}
// 最左边一行
for (int row = down; row >= up; row--) {
list.add(matrix[row][left]);
}
// 向右逼近
left++;
// 判断是否越界
if (left > right) {
break;
}
}
return list;
}
private static List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return list;
}
int m = matrix.length;
int n = matrix[0].length;
for (int i = 0; i < (Math.min(m, n) + 1) / 2; i++) {
//上边
for (int j = i; j < n - i; j++) {
list.add(matrix[i][j]);
}
//右边
for (int j = i + 1; j < m - i; j++) {
list.add(matrix[j][(n - 1) - i]);
}
//下边
for (int j = i + 1; j < n - i; j++) {
list.add(matrix[m - 1 - i][n - 1 - j]);
}
//左边
for (int j = i + 1; j < m - 1 - i; j++) {
list.add(matrix[m - 1 - j][i]);
}
}
return list;
}
/**
* --------------------------------------------------MAIN-----------------------------------------------------------
*/
public static void main(String[] args) {
_019_printMatrix clazz = new _019_printMatrix();
ArrayList<Integer> list = clazz.printMatrix(matrix);
System.out.println(Arrays.toString(list.toArray()));
}
/**
* --------------------------------------------------INIT-----------------------------------------------------------
*/
private static int[][] matrix;
static {
matrix = new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
int[][] matrix = {
{1, 2, 3, 4, 5,},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20}
};
int[][] matrix1 = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}
};
}
}
| UTF-8 | Java | 4,128 | java | _019_printMatrix.java | Java | [] | null | [] | package com.yanyun.sword;
import java.util.*;
/**
* 回旋矩阵的打印
*/
public class _019_printMatrix {
/**
* 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字例如,如果输入如下4 X 4矩阵:
* 1 2 3 4
* 5 6 7 8
* 9 10 11 12
* 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10
* <p>
* --------------------------------------------------SOLUTION-------------------------------------------------------
* <p>
* 递归
*/
public ArrayList<Integer> printMatrix(int[][] matrix) {
ArrayList<Integer> list = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return list;
}
int up = 0;
int down = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
while (true) {
// 最上面一行
for (int col = left; col <= right; col++) {
list.add(matrix[up][col]);
}
// 向下逼近
up++;
// 判断是否越界
if (up > down) {
break;
}
// 最右边一行
for (int row = up; row <= down; row++) {
list.add(matrix[row][right]);
}
// 向左逼近
right--;
// 判断是否越界
if (left > right) {
break;
}
// 最下面一行
for (int col = right; col >= left; col--) {
list.add(matrix[down][col]);
}
// 向上逼近
down--;
// 判断是否越界
if (up > down) {
break;
}
// 最左边一行
for (int row = down; row >= up; row--) {
list.add(matrix[row][left]);
}
// 向右逼近
left++;
// 判断是否越界
if (left > right) {
break;
}
}
return list;
}
private static List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return list;
}
int m = matrix.length;
int n = matrix[0].length;
for (int i = 0; i < (Math.min(m, n) + 1) / 2; i++) {
//上边
for (int j = i; j < n - i; j++) {
list.add(matrix[i][j]);
}
//右边
for (int j = i + 1; j < m - i; j++) {
list.add(matrix[j][(n - 1) - i]);
}
//下边
for (int j = i + 1; j < n - i; j++) {
list.add(matrix[m - 1 - i][n - 1 - j]);
}
//左边
for (int j = i + 1; j < m - 1 - i; j++) {
list.add(matrix[m - 1 - j][i]);
}
}
return list;
}
/**
* --------------------------------------------------MAIN-----------------------------------------------------------
*/
public static void main(String[] args) {
_019_printMatrix clazz = new _019_printMatrix();
ArrayList<Integer> list = clazz.printMatrix(matrix);
System.out.println(Arrays.toString(list.toArray()));
}
/**
* --------------------------------------------------INIT-----------------------------------------------------------
*/
private static int[][] matrix;
static {
matrix = new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
int[][] matrix = {
{1, 2, 3, 4, 5,},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20}
};
int[][] matrix1 = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}
};
}
}
| 4,128 | 0.335054 | 0.289623 | 134 | 27.880596 | 23.359949 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.029851 | false | false | 4 |
42ca06bd35b50db6558309103d30b392ac3a53ce | 18,184,891,600,080 | 3a90bd264e1779e5f2303a9b85e3853141356497 | /src/main/java/ocp/regexp/TestSplit.java | 764e45dc127dd97bd5f8ff3b5c8a677e78513204 | [] | no_license | RosenPIvanov/certJ | https://github.com/RosenPIvanov/certJ | eab566cc0f40175abad3916b7a6991b7185474ce | f929585a8d41b8464f7b4374b2036c3d9f73f35d | refs/heads/master | 2021-01-21T14:53:46.109000 | 2017-09-27T17:37:33 | 2017-09-27T17:37:33 | 95,355,925 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ocp.regexp;
public class TestSplit {
public static void main(String[] args) {
String names = "Shreya;.-Selvan;.-Paul;.-Harry";
String[] results = names.split(";..");
for (String str : results) {
System.out.print(str);
}
}
}
| UTF-8 | Java | 285 | java | TestSplit.java | Java | [
{
"context": "oid main(String[] args) {\n String names = \"Shreya;.-Selvan;.-Paul;.-Harry\";\n String[] result",
"end": 121,
"score": 0.9998078346252441,
"start": 115,
"tag": "NAME",
"value": "Shreya"
},
{
"context": "String[] args) {\n String names = \"Shreya;.-Selvan;.-Paul;.-Harry\";\n String[] results = names",
"end": 130,
"score": 0.999140739440918,
"start": 124,
"tag": "NAME",
"value": "Selvan"
},
{
"context": "args) {\n String names = \"Shreya;.-Selvan;.-Paul;.-Harry\";\n String[] results = names.split(",
"end": 137,
"score": 0.9991634488105774,
"start": 133,
"tag": "NAME",
"value": "Paul"
},
{
"context": "\n String names = \"Shreya;.-Selvan;.-Paul;.-Harry\";\n String[] results = names.split(\";..\");\n",
"end": 145,
"score": 0.9994850158691406,
"start": 140,
"tag": "NAME",
"value": "Harry"
}
] | null | [] | package ocp.regexp;
public class TestSplit {
public static void main(String[] args) {
String names = "Shreya;.-Selvan;.-Paul;.-Harry";
String[] results = names.split(";..");
for (String str : results) {
System.out.print(str);
}
}
}
| 285 | 0.550877 | 0.550877 | 11 | 24.90909 | 18.729919 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.727273 | false | false | 4 |
273f1d26ee589be2cc86fdcf8767d78ee2b3db8f | 27,410,481,302,120 | 8b2cd828b4fe6e62c0c0eb7074e598f72d6a3c98 | /src/com/Tomcat_Test/dao/ICommitDao.java | 69e117c23d83758eb45e9849710a518609e21d00 | [] | no_license | gwshbbq/ProjectManager | https://github.com/gwshbbq/ProjectManager | 2002ea3c1a97c00644c75c9c28ead94342b91147 | 5fef0f64bcccb4ce41433a2c5563c3e670fb8783 | refs/heads/master | 2022-10-17T19:37:25.691000 | 2020-06-10T16:55:12 | 2020-06-10T16:55:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.Tomcat_Test.dao;
import com.Tomcat_Test.entity.commitEntity;
public interface ICommitDao {
public boolean commit(int userAccount,String commitName) throws Exception;
}
| UTF-8 | Java | 183 | java | ICommitDao.java | Java | [] | null | [] | package com.Tomcat_Test.dao;
import com.Tomcat_Test.entity.commitEntity;
public interface ICommitDao {
public boolean commit(int userAccount,String commitName) throws Exception;
}
| 183 | 0.814208 | 0.814208 | 7 | 25.142857 | 25.842537 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 4 |
083fc4d5f109dd6493f63243b32a4a4430b739e6 | 15,066,745,282,847 | d0fd81c97786dc8cd3c17d51c3571a35d6f3df62 | /app/src/main/java/ca/choremanager/EachUserActivity.java | 89ba28ba02d0195de07476f0e7c55ea893839010 | [] | no_license | zweldemichael/Chore-Manager | https://github.com/zweldemichael/Chore-Manager | 1717a98bbcfe9ce536188d0f0f8f2d7cb57d6731 | 60e8c6b8276cded3ae60f315d73695c3816846a5 | refs/heads/master | 2022-05-16T16:02:37.247000 | 2020-04-22T20:48:45 | 2020-04-22T20:48:45 | 258,014,289 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package choremanager.ca.choremanager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Callback;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class EachUserActivity extends AppCompatActivity {
String uid;
private RecyclerView recyclerView;
DatabaseReference dataRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_each_user);
uid = getIntent().getExtras().getString("uid");
dataRef = FirebaseDatabase.getInstance().getReference().child("Chore_Assign").child(uid);
dataRef.keepSynced(true);
// inflating the recyclew view layout
recyclerView = (RecyclerView) findViewById(R.id.recyclerToDo);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(EachUserActivity.this));
String name = getIntent().getExtras().getString("name");
String points = getIntent().getExtras().getString("points");
final String image = getIntent().getExtras().getString("image");
final CircleImageView imageView = (CircleImageView) findViewById(R.id.image);
TextView textName = (TextView) findViewById(R.id.title);
TextView textPoint = (TextView) findViewById(R.id.point);
textName.setText(name);
textPoint.setText(points);
Picasso.with(EachUserActivity.this).load(image).networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.user).into(imageView, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
Picasso.with(EachUserActivity.this).load(image).placeholder(R.drawable.user).into(imageView);
}
});
}
@Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<choreAssignModel, viewHolder> subCategoryAdapter = new FirebaseRecyclerAdapter<choreAssignModel, viewHolder>(
choreAssignModel.class, R.layout.signle_choreassignedmain, viewHolder.class, dataRef
) {
@Override
protected void populateViewHolder(final viewHolder viewHolder, final choreAssignModel model, int position) {
viewHolder.setTitle(String.valueOf(viewHolder.getAdapterPosition() + 1) + ") " + model.getValue());
viewHolder.setDeadline(" " + model.getDeadline());
}
};
recyclerView.setAdapter(subCategoryAdapter);
}
public static class viewHolder extends RecyclerView.ViewHolder {
View mView;
public viewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setTitle(String choreName) {
TextView textView = (TextView) mView.findViewById(R.id.chorename);
textView.setText(choreName);
}
public void setDeadline(String deadline) {
TextView textView = (TextView) mView.findViewById(R.id.choredeadline);
textView.setText("Deadline: " + deadline);
}
}
}
| UTF-8 | Java | 3,637 | java | EachUserActivity.java | Java | [] | null | [] | package choremanager.ca.choremanager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Callback;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class EachUserActivity extends AppCompatActivity {
String uid;
private RecyclerView recyclerView;
DatabaseReference dataRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_each_user);
uid = getIntent().getExtras().getString("uid");
dataRef = FirebaseDatabase.getInstance().getReference().child("Chore_Assign").child(uid);
dataRef.keepSynced(true);
// inflating the recyclew view layout
recyclerView = (RecyclerView) findViewById(R.id.recyclerToDo);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(EachUserActivity.this));
String name = getIntent().getExtras().getString("name");
String points = getIntent().getExtras().getString("points");
final String image = getIntent().getExtras().getString("image");
final CircleImageView imageView = (CircleImageView) findViewById(R.id.image);
TextView textName = (TextView) findViewById(R.id.title);
TextView textPoint = (TextView) findViewById(R.id.point);
textName.setText(name);
textPoint.setText(points);
Picasso.with(EachUserActivity.this).load(image).networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.user).into(imageView, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
Picasso.with(EachUserActivity.this).load(image).placeholder(R.drawable.user).into(imageView);
}
});
}
@Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<choreAssignModel, viewHolder> subCategoryAdapter = new FirebaseRecyclerAdapter<choreAssignModel, viewHolder>(
choreAssignModel.class, R.layout.signle_choreassignedmain, viewHolder.class, dataRef
) {
@Override
protected void populateViewHolder(final viewHolder viewHolder, final choreAssignModel model, int position) {
viewHolder.setTitle(String.valueOf(viewHolder.getAdapterPosition() + 1) + ") " + model.getValue());
viewHolder.setDeadline(" " + model.getDeadline());
}
};
recyclerView.setAdapter(subCategoryAdapter);
}
public static class viewHolder extends RecyclerView.ViewHolder {
View mView;
public viewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setTitle(String choreName) {
TextView textView = (TextView) mView.findViewById(R.id.chorename);
textView.setText(choreName);
}
public void setDeadline(String deadline) {
TextView textView = (TextView) mView.findViewById(R.id.choredeadline);
textView.setText("Deadline: " + deadline);
}
}
}
| 3,637 | 0.681331 | 0.680231 | 113 | 31.185841 | 33.865833 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.486726 | false | false | 4 |
2b3e7d8d82885a91c25a3f86d0146151abdd540d | 32,341,103,772,166 | fe3f05249e07880d9201d3359e247beccc330283 | /robot_ramasseur_de_palets/code_source/scenario0/Moteurs.java | b24825a97d79324259fd58daddd78c1b860fdde9 | [] | no_license | JohTandou/projects | https://github.com/JohTandou/projects | 259186c5d758b2fca389b49b2cdf1eeca70629bf | 3bfa4c965274da69083135f3bd6c2a485ec8d061 | refs/heads/main | 2023-03-21T05:30:39.435000 | 2021-03-12T03:45:54 | 2021-03-12T03:45:54 | 345,858,486 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package scenario0;
import lejos.hardware.motor.UnregulatedMotor;
import lejos.hardware.port.MotorPort;
public class Moteurs
{
//Description: concerne les trois moteurs
//Utilisée par: Main
//Utilise: rien
static UnregulatedMotor moteurGauche = new UnregulatedMotor (MotorPort.A); // Création de l'objet moteurGauche
static UnregulatedMotor moteurDroit = new UnregulatedMotor (MotorPort.B); // Création de l'objet moteurDroit
static UnregulatedMotor pinces = new UnregulatedMotor (MotorPort.C); // Création de l'objet pinces
public static void fermer3() // Libère les ressources des moteurs
{
//Description: libère les ressources des moteurs
//Entrée: rien
//Sortie: rien
moteurGauche.close();
moteurDroit.close();
pinces.close();
}
} | UTF-8 | Java | 779 | java | Moteurs.java | Java | [] | null | [] | package scenario0;
import lejos.hardware.motor.UnregulatedMotor;
import lejos.hardware.port.MotorPort;
public class Moteurs
{
//Description: concerne les trois moteurs
//Utilisée par: Main
//Utilise: rien
static UnregulatedMotor moteurGauche = new UnregulatedMotor (MotorPort.A); // Création de l'objet moteurGauche
static UnregulatedMotor moteurDroit = new UnregulatedMotor (MotorPort.B); // Création de l'objet moteurDroit
static UnregulatedMotor pinces = new UnregulatedMotor (MotorPort.C); // Création de l'objet pinces
public static void fermer3() // Libère les ressources des moteurs
{
//Description: libère les ressources des moteurs
//Entrée: rien
//Sortie: rien
moteurGauche.close();
moteurDroit.close();
pinces.close();
}
} | 779 | 0.752591 | 0.75 | 26 | 28.73077 | 33.670986 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.192308 | false | false | 4 |
83d71cad9ed9adc55073fcbf60cd0e1521eb5e6a | 16,810,502,050,612 | 6ecf6f6b974510ab91543d2a291ae68033fae1b3 | /app/src/main/java/com/haikarosetz/mikecall/DataStore/ContentStore.java | 5b1053782e00c3e162332b4e3583517368659d4d | [] | no_license | haikarosetz/mikecall | https://github.com/haikarosetz/mikecall | e8de361a3842de8bea11388f2475ac9f6d7c7926 | e6ca6dc7a1845bfabecd9d41d51eb97695e691a1 | refs/heads/master | 2020-12-14T09:53:10.525000 | 2017-06-27T09:25:36 | 2017-06-27T09:25:36 | 95,465,938 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.haikarosetz.mikecall.DataStore;
import android.content.Context;
import android.content.SharedPreferences;
import com.haikarosetz.mikecall.pojo.Assistant;
import com.haikarosetz.mikecall.pojo.Excuse;
import com.haikarosetz.mikecall.pojo.Favorite;
import com.haikarosetz.mikecall.pojo.Missed;
import com.haikarosetz.mikecall.pojo.Plan;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ContentStore {
private Context context;
public ContentStore(Context context){
this.context=context;
}
public List<Favorite> getFavorites(Context context){
SharedPreferences favorites=context.getSharedPreferences("FAVORITES", 0);
Map<String,?> myfavorites=favorites.getAll();
Set<String> keys=myfavorites.keySet();
List<Favorite> list=new ArrayList<>();
for (String key:keys
) {
Favorite item=new Favorite();
item.setName(key);
item.setPhone((String)myfavorites.get(key));
list.add(item);
}
return list;
}
public List<Missed> getAllReminders(Context context){
SharedPreferences reminders=context.getSharedPreferences("REMINDER", 0);
Map<String,?> myreminders=reminders.getAll();
Set<String> keys=myreminders.keySet();
List<Missed> list=new ArrayList<>();
for (String key:keys
) {
Missed item=new Missed();
item.setName(key);
item.setPhone((String)myreminders.get(key));
list.add(item);
}
return list;
}
public ArrayList<String> getFavoritesArrayList(Context context){
SharedPreferences favorites=context.getSharedPreferences("FAVORITES", 0);
Map<String,?> myfavorites=favorites.getAll();
Set<String> keys=myfavorites.keySet();
ArrayList<String> list=new ArrayList<>();
for (String key:keys
) {
list.add((String)myfavorites.get(key));
}
return list;
}
public ArrayList<String> getCalled(Context context){
SharedPreferences callers=context.getSharedPreferences("REMINDER", 0);
Map<String,?> myCallers=callers.getAll();
Set<String> keys=myCallers.keySet();
ArrayList<String> list=new ArrayList<>();
for (String key:keys
) {
list.add((String)myCallers.get(key));
}
return list;
}
public String getPending(Context context){
SharedPreferences pendings=context.getSharedPreferences("PENDINGS", 0);
String pendingText=pendings.getString("value", "Write your excuse here");
return pendingText;
}
public boolean getVibration(Context context){
SharedPreferences pendings=context.getSharedPreferences("VIBRATION", 0);
boolean vibrate=pendings.getBoolean("value", true);
return vibrate;
}
public String getStatus(Context context){
String stat=null;
SharedPreferences status=context.getSharedPreferences("STATUS", 0);
stat = status.getString("value", "availlable");
return stat;
}
public int getCounterCounts(){
SharedPreferences counts=context.getSharedPreferences("COUNTER",0);
int itemsCount=counts.getInt("number",0);
return itemsCount;
}
public int getAllFavoritesCount(Context context){
SharedPreferences counts=context.getSharedPreferences("FAVORITES",0);
Map<String,?> favorites=counts.getAll();
int favoritesCount=favorites.size();
return favoritesCount;
}
public Assistant getAssistant(Context context){
Assistant item=new Assistant();
SharedPreferences assistants=context.getSharedPreferences("ASSISTANTS", 0);
String value= assistants.getString("assistant","not set");
item.setName("assistant");
item.setPhone(value);
return item;
}
public Map<String,?> getSmsPlans(Context context){
SharedPreferences smsPlans=context.getSharedPreferences("SMS", 0);
Map<String,?> smsPlanAll=smsPlans.getAll();
return smsPlanAll;
}
///deleting preference all
public void deleteAllStatus(){
SharedPreferences status=context.getSharedPreferences("STATUS", 0);
SharedPreferences.Editor editor=status.edit();
editor.clear();
editor.commit();
}
public void removeAllSmsPlan(){
SharedPreferences smsPlans=context.getSharedPreferences("SMS", 0);
SharedPreferences.Editor editor=smsPlans.edit();
editor.clear();
editor.commit();
}
public void removeAllAssistant(){
SharedPreferences assistants=context.getSharedPreferences("ASSISTANTS", 0);
SharedPreferences.Editor editor=assistants.edit();
editor.clear();
editor.commit();
}
public void removeAllFavorites(){
SharedPreferences favorites=context.getSharedPreferences("FAVORITES", 0);
SharedPreferences.Editor editor=favorites.edit();
editor.clear();
editor.commit();
}
public void removeAllReminders(){
SharedPreferences reminders=context.getSharedPreferences("REMINDER", 0);
SharedPreferences.Editor editor=reminders.edit();
editor.clear();
editor.commit();
}
//removing single item
public void removeStatus(Excuse item){
SharedPreferences status=context.getSharedPreferences("STATUS", 0);
SharedPreferences.Editor editor=status.edit();
// editor.remove(item.getName());
editor.commit();
}
public void removeReminderItem(Missed item){
SharedPreferences reminders=context.getSharedPreferences("REMINDER", 0);
SharedPreferences.Editor editor=reminders.edit();
editor.remove(item.getName());
editor.commit();
}
public void removeSmsPlan(Plan item){
SharedPreferences smsPlans=context.getSharedPreferences("SMS", 0);
SharedPreferences.Editor editor=smsPlans.edit();
//editor.remove(item.);
editor.commit();
}
public void removeVibrate(Context context){
SharedPreferences status=context.getSharedPreferences("VIBRATION", 0);
SharedPreferences.Editor editor=status.edit();
editor.putBoolean("value", false);
editor.commit();
}
public void removeAssistant(Assistant item){
SharedPreferences assistants=context.getSharedPreferences("ASSISTANTS", 0);
SharedPreferences.Editor editor=assistants.edit();
editor.remove(item.getName());
editor.commit();
}
public void removeFavorites(Favorite item){
SharedPreferences favorites=context.getSharedPreferences("FAVORITES", 0);
SharedPreferences.Editor editor=favorites.edit();
editor.remove(item.getName());
editor.commit();
}
public void removeCounterItem(){
SharedPreferences counters=context.getSharedPreferences("COUNTER", 0);
SharedPreferences.Editor editor=counters.edit();
editor.clear();
editor.commit();
}
//adding preferences
public void setStatus(String state){
SharedPreferences status=context.getSharedPreferences("STATUS", 0);
SharedPreferences.Editor editor=status.edit();
editor.putString("value",state);
editor.commit();
}
public void addVibrate(Context context){
SharedPreferences status=context.getSharedPreferences("VIBRATION", 0);
SharedPreferences.Editor editor=status.edit();
editor.putBoolean("value", true);
editor.commit();
}
public void addSmsPlan(Plan item){
SharedPreferences smsPlans=context.getSharedPreferences("SMS", 0);
SharedPreferences.Editor editor=smsPlans.edit();
// editor.putString(item.getName(), item.getDetail());
editor.commit();
}
public void addPendingText(String text){
SharedPreferences pendingText=context.getSharedPreferences("PENDINGS", 0);
SharedPreferences.Editor editor=pendingText.edit();
editor.putString("value",text);
editor.commit();
}
public void addAssistant(Assistant item){
SharedPreferences assistants=context.getSharedPreferences("ASSISTANTS", 0);
SharedPreferences.Editor editor=assistants.edit();
editor.putString(item.getName(),item.getPhone());
editor.commit();
}
public void addFavorites(Favorite item){
SharedPreferences favorites=context.getSharedPreferences("FAVORITES", 0);
SharedPreferences.Editor editor=favorites.edit();
editor.putString(item.getName(),item.getPhone());
editor.commit();
}
public void addReminders(Missed item){
SharedPreferences reminders=context.getSharedPreferences("REMINDER", 0);
SharedPreferences.Editor editor=reminders.edit();
editor.putString(item.getName(),item.getPhone());
editor.commit();
}
public void addCounterItem(){
SharedPreferences pendingText=context.getSharedPreferences("COUNTER", 0);
SharedPreferences.Editor editor=pendingText.edit();
int numbers=pendingText.getInt("number",0);
numbers=numbers +1;
editor.putInt("number",numbers);
editor.commit();
}
}
| UTF-8 | Java | 9,478 | java | ContentStore.java | Java | [] | null | [] | package com.haikarosetz.mikecall.DataStore;
import android.content.Context;
import android.content.SharedPreferences;
import com.haikarosetz.mikecall.pojo.Assistant;
import com.haikarosetz.mikecall.pojo.Excuse;
import com.haikarosetz.mikecall.pojo.Favorite;
import com.haikarosetz.mikecall.pojo.Missed;
import com.haikarosetz.mikecall.pojo.Plan;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ContentStore {
private Context context;
public ContentStore(Context context){
this.context=context;
}
public List<Favorite> getFavorites(Context context){
SharedPreferences favorites=context.getSharedPreferences("FAVORITES", 0);
Map<String,?> myfavorites=favorites.getAll();
Set<String> keys=myfavorites.keySet();
List<Favorite> list=new ArrayList<>();
for (String key:keys
) {
Favorite item=new Favorite();
item.setName(key);
item.setPhone((String)myfavorites.get(key));
list.add(item);
}
return list;
}
public List<Missed> getAllReminders(Context context){
SharedPreferences reminders=context.getSharedPreferences("REMINDER", 0);
Map<String,?> myreminders=reminders.getAll();
Set<String> keys=myreminders.keySet();
List<Missed> list=new ArrayList<>();
for (String key:keys
) {
Missed item=new Missed();
item.setName(key);
item.setPhone((String)myreminders.get(key));
list.add(item);
}
return list;
}
public ArrayList<String> getFavoritesArrayList(Context context){
SharedPreferences favorites=context.getSharedPreferences("FAVORITES", 0);
Map<String,?> myfavorites=favorites.getAll();
Set<String> keys=myfavorites.keySet();
ArrayList<String> list=new ArrayList<>();
for (String key:keys
) {
list.add((String)myfavorites.get(key));
}
return list;
}
public ArrayList<String> getCalled(Context context){
SharedPreferences callers=context.getSharedPreferences("REMINDER", 0);
Map<String,?> myCallers=callers.getAll();
Set<String> keys=myCallers.keySet();
ArrayList<String> list=new ArrayList<>();
for (String key:keys
) {
list.add((String)myCallers.get(key));
}
return list;
}
public String getPending(Context context){
SharedPreferences pendings=context.getSharedPreferences("PENDINGS", 0);
String pendingText=pendings.getString("value", "Write your excuse here");
return pendingText;
}
public boolean getVibration(Context context){
SharedPreferences pendings=context.getSharedPreferences("VIBRATION", 0);
boolean vibrate=pendings.getBoolean("value", true);
return vibrate;
}
public String getStatus(Context context){
String stat=null;
SharedPreferences status=context.getSharedPreferences("STATUS", 0);
stat = status.getString("value", "availlable");
return stat;
}
public int getCounterCounts(){
SharedPreferences counts=context.getSharedPreferences("COUNTER",0);
int itemsCount=counts.getInt("number",0);
return itemsCount;
}
public int getAllFavoritesCount(Context context){
SharedPreferences counts=context.getSharedPreferences("FAVORITES",0);
Map<String,?> favorites=counts.getAll();
int favoritesCount=favorites.size();
return favoritesCount;
}
public Assistant getAssistant(Context context){
Assistant item=new Assistant();
SharedPreferences assistants=context.getSharedPreferences("ASSISTANTS", 0);
String value= assistants.getString("assistant","not set");
item.setName("assistant");
item.setPhone(value);
return item;
}
public Map<String,?> getSmsPlans(Context context){
SharedPreferences smsPlans=context.getSharedPreferences("SMS", 0);
Map<String,?> smsPlanAll=smsPlans.getAll();
return smsPlanAll;
}
///deleting preference all
public void deleteAllStatus(){
SharedPreferences status=context.getSharedPreferences("STATUS", 0);
SharedPreferences.Editor editor=status.edit();
editor.clear();
editor.commit();
}
public void removeAllSmsPlan(){
SharedPreferences smsPlans=context.getSharedPreferences("SMS", 0);
SharedPreferences.Editor editor=smsPlans.edit();
editor.clear();
editor.commit();
}
public void removeAllAssistant(){
SharedPreferences assistants=context.getSharedPreferences("ASSISTANTS", 0);
SharedPreferences.Editor editor=assistants.edit();
editor.clear();
editor.commit();
}
public void removeAllFavorites(){
SharedPreferences favorites=context.getSharedPreferences("FAVORITES", 0);
SharedPreferences.Editor editor=favorites.edit();
editor.clear();
editor.commit();
}
public void removeAllReminders(){
SharedPreferences reminders=context.getSharedPreferences("REMINDER", 0);
SharedPreferences.Editor editor=reminders.edit();
editor.clear();
editor.commit();
}
//removing single item
public void removeStatus(Excuse item){
SharedPreferences status=context.getSharedPreferences("STATUS", 0);
SharedPreferences.Editor editor=status.edit();
// editor.remove(item.getName());
editor.commit();
}
public void removeReminderItem(Missed item){
SharedPreferences reminders=context.getSharedPreferences("REMINDER", 0);
SharedPreferences.Editor editor=reminders.edit();
editor.remove(item.getName());
editor.commit();
}
public void removeSmsPlan(Plan item){
SharedPreferences smsPlans=context.getSharedPreferences("SMS", 0);
SharedPreferences.Editor editor=smsPlans.edit();
//editor.remove(item.);
editor.commit();
}
public void removeVibrate(Context context){
SharedPreferences status=context.getSharedPreferences("VIBRATION", 0);
SharedPreferences.Editor editor=status.edit();
editor.putBoolean("value", false);
editor.commit();
}
public void removeAssistant(Assistant item){
SharedPreferences assistants=context.getSharedPreferences("ASSISTANTS", 0);
SharedPreferences.Editor editor=assistants.edit();
editor.remove(item.getName());
editor.commit();
}
public void removeFavorites(Favorite item){
SharedPreferences favorites=context.getSharedPreferences("FAVORITES", 0);
SharedPreferences.Editor editor=favorites.edit();
editor.remove(item.getName());
editor.commit();
}
public void removeCounterItem(){
SharedPreferences counters=context.getSharedPreferences("COUNTER", 0);
SharedPreferences.Editor editor=counters.edit();
editor.clear();
editor.commit();
}
//adding preferences
public void setStatus(String state){
SharedPreferences status=context.getSharedPreferences("STATUS", 0);
SharedPreferences.Editor editor=status.edit();
editor.putString("value",state);
editor.commit();
}
public void addVibrate(Context context){
SharedPreferences status=context.getSharedPreferences("VIBRATION", 0);
SharedPreferences.Editor editor=status.edit();
editor.putBoolean("value", true);
editor.commit();
}
public void addSmsPlan(Plan item){
SharedPreferences smsPlans=context.getSharedPreferences("SMS", 0);
SharedPreferences.Editor editor=smsPlans.edit();
// editor.putString(item.getName(), item.getDetail());
editor.commit();
}
public void addPendingText(String text){
SharedPreferences pendingText=context.getSharedPreferences("PENDINGS", 0);
SharedPreferences.Editor editor=pendingText.edit();
editor.putString("value",text);
editor.commit();
}
public void addAssistant(Assistant item){
SharedPreferences assistants=context.getSharedPreferences("ASSISTANTS", 0);
SharedPreferences.Editor editor=assistants.edit();
editor.putString(item.getName(),item.getPhone());
editor.commit();
}
public void addFavorites(Favorite item){
SharedPreferences favorites=context.getSharedPreferences("FAVORITES", 0);
SharedPreferences.Editor editor=favorites.edit();
editor.putString(item.getName(),item.getPhone());
editor.commit();
}
public void addReminders(Missed item){
SharedPreferences reminders=context.getSharedPreferences("REMINDER", 0);
SharedPreferences.Editor editor=reminders.edit();
editor.putString(item.getName(),item.getPhone());
editor.commit();
}
public void addCounterItem(){
SharedPreferences pendingText=context.getSharedPreferences("COUNTER", 0);
SharedPreferences.Editor editor=pendingText.edit();
int numbers=pendingText.getInt("number",0);
numbers=numbers +1;
editor.putInt("number",numbers);
editor.commit();
}
}
| 9,478 | 0.656362 | 0.652775 | 365 | 24.967123 | 26.177246 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.561644 | false | false | 4 |
885daabe847bf367989c75f63c7191406be5a788 | 33,277,406,620,305 | 0ae481ca65a0aa3af7b7b3682265501355a00c35 | /src/main/java/com/ddubson/algorithms/linked_list/ReverseKGroups.java | f6a7550c35ad2a2400ea952b549dcf0c7d237a2e | [] | no_license | ddubson/code-practice | https://github.com/ddubson/code-practice | dc45d2cd7161c34c3ca645d539e24b32c77851ab | 73c35b0c96d30f3a1fdc174c551768283fa0e22c | refs/heads/master | 2020-05-21T12:23:35.353000 | 2019-03-15T19:29:23 | 2019-03-15T19:29:23 | 51,268,417 | 1 | 0 | null | false | 2016-09-13T18:46:17 | 2016-02-07T21:59:40 | 2016-09-13T18:36:32 | 2016-09-13T18:46:16 | 88 | 1 | 0 | 0 | Java | null | null | package com.ddubson.algorithms.linked_list;
/**
* Created by ddubs on 10/27/2016.
*/
public class ReverseKGroups {
public static ListNode reverseKGroup(ListNode head, int k) {
if (head == null) {
return null;
}
if (k < 2 || head.next==null) {
return head;
}
// get size of list (O(n))
int size = calcSize(head);
if(k > size) {
return head;
}
// calc number of groups
int groups = size / k;
// for each group, perform reverse
ListNode newHead = null;
ListNode prevGroupTail = null;
ListNode nextGroupHead = null;
ListNode headOfGroup = head;
ListNode prev = null;
while (groups != 0) {
// reverse grouping of k
int swaps = k;
prev = null;
ListNode groupHead = null;
ListNode groupTail = null;
ListNode current = headOfGroup;
while (swaps != 0) {
ListNode nextUp = null;
if (swaps == 1) {
groupHead = current;
nextGroupHead = current.next;
}
if (current.next != null) {
nextUp = current.next;
}
// Identify group tail
if (swaps == k)
groupTail = current;
// Swap
current.next = prev;
prev = current;
current = nextUp;
swaps--;
}
if (newHead == null) newHead = groupHead;
if (prevGroupTail != null)
prevGroupTail.next = groupHead;
groupTail.next = nextGroupHead;
prevGroupTail = groupTail;
headOfGroup = nextGroupHead;
groups--;
}
return newHead;
}
private static int calcSize(ListNode head) {
int size = 0;
while (head != null) {
size++;
head = head.next;
}
return size;
}
}
| UTF-8 | Java | 2,108 | java | ReverseKGroups.java | Java | [
{
"context": "ddubson.algorithms.linked_list;\n\n/**\n * Created by ddubs on 10/27/2016.\n */\npublic class ReverseKGroups {\n",
"end": 68,
"score": 0.9996439814567566,
"start": 63,
"tag": "USERNAME",
"value": "ddubs"
}
] | null | [] | package com.ddubson.algorithms.linked_list;
/**
* Created by ddubs on 10/27/2016.
*/
public class ReverseKGroups {
public static ListNode reverseKGroup(ListNode head, int k) {
if (head == null) {
return null;
}
if (k < 2 || head.next==null) {
return head;
}
// get size of list (O(n))
int size = calcSize(head);
if(k > size) {
return head;
}
// calc number of groups
int groups = size / k;
// for each group, perform reverse
ListNode newHead = null;
ListNode prevGroupTail = null;
ListNode nextGroupHead = null;
ListNode headOfGroup = head;
ListNode prev = null;
while (groups != 0) {
// reverse grouping of k
int swaps = k;
prev = null;
ListNode groupHead = null;
ListNode groupTail = null;
ListNode current = headOfGroup;
while (swaps != 0) {
ListNode nextUp = null;
if (swaps == 1) {
groupHead = current;
nextGroupHead = current.next;
}
if (current.next != null) {
nextUp = current.next;
}
// Identify group tail
if (swaps == k)
groupTail = current;
// Swap
current.next = prev;
prev = current;
current = nextUp;
swaps--;
}
if (newHead == null) newHead = groupHead;
if (prevGroupTail != null)
prevGroupTail.next = groupHead;
groupTail.next = nextGroupHead;
prevGroupTail = groupTail;
headOfGroup = nextGroupHead;
groups--;
}
return newHead;
}
private static int calcSize(ListNode head) {
int size = 0;
while (head != null) {
size++;
head = head.next;
}
return size;
}
}
| 2,108 | 0.455882 | 0.449715 | 86 | 23.511627 | 16.542929 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.465116 | false | false | 4 |
0ef1edc0cd77e13465fce5f01b4b05ef2d28d4f0 | 14,671,608,326,558 | c94048d80bd674b0a760baed46934486dfb01a62 | /java/src/cs224n/wordaligner/PMIModel.java | 6e4a5d4ac75feb0b0697f808008ac3094a8e5110 | [] | no_license | rmacqueen/CS224N | https://github.com/rmacqueen/CS224N | 3d44399d0522ba74e8041a87fe2da980dfe2d602 | 517a63a07cc613885ab60e0040676cdd0f7775ab | refs/heads/master | 2020-05-19T17:30:28.524000 | 2012-10-09T08:37:56 | 2012-10-09T08:37:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cs224n.wordaligner;
import cs224n.util.*;
//import java.util.List;
import java.util.*;
/**
*
*
*
* IMPORTANT: Make sure that you read the comments in the
* cs224n.wordaligner.WordAligner interface.
*
*/
public class PMIModel implements WordAligner {
private static final long serialVersionUID = 1315751943476440515L;
// TODO: Use arrays or Counters for collecting sufficient statistics
// from the training data.
private CounterMap<String,String> sourceTargetCounts;
private Counter<String> sourceCounts;
private Counter<String> targetCounts;
private double numSentences = 0;
public Alignment align(SentencePair sentencePair) {
// Placeholder code below.
// TODO Implement an inference algorithm for Eq.1 in the assignment
// handout to predict alignments based on the counts you collected with train().
//System.out.print("------------Here in Align-------------------\n");
//System.out.println(sentencePair.getSourceWords().get(0));
Alignment alignment = new Alignment();
int numSourceWords = sentencePair.getSourceWords().size();
int numTargetWords = sentencePair.getTargetWords().size();
for(int trgtIndex = 0; trgtIndex < numTargetWords; trgtIndex++){
String tgtWord = sentencePair.getTargetWords().get(trgtIndex);
double tgtProb = targetCounts.getCount(tgtWord) / targetCounts.totalCount();
int bestIndex = -1;
double bestMatch = -1.0;
for (int srcIndex = 0; srcIndex < numSourceWords; srcIndex++) {
String srcWord = sentencePair.getSourceWords().get(srcIndex);
double matchCount = sourceTargetCounts.getCount(srcWord, tgtWord);
double probMatch = matchCount / numSentences;
System.out.println(probMatch);
double srcProb = sourceCounts.getCount(srcWord) / sourceCounts.totalCount();
double a_i = probMatch / (srcProb * tgtProb);
if(a_i > bestMatch){
bestMatch = a_i;
bestIndex = srcIndex;
}
/*int tgtIndex = srcIndex;
if (tgtIndex < numTargetWords) {
// Discard null alignments
alignment.addPredictedAlignment(tgtIndex, srcIndex);
}*/
}
//if(bestIndex==0)//System.out.print("NULL predicted\n");
alignment.addPredictedAlignment(trgtIndex, bestIndex);
}
return alignment;
}
public void train(List<SentencePair> trainingPairs) {
System.out.print("------------sdfsdfHere in training-------------------\n");
sourceTargetCounts = new CounterMap<String,String>();
targetCounts = new Counter<String>();
sourceCounts = new Counter<String>();
numSentences = trainingPairs.size();
for(SentencePair pair : trainingPairs){
List<String> targetWords = pair.getTargetWords();
List<String> sourceWords = pair.getSourceWords();
//sourceWords.add(0, "<NULL>"); //not sure about this NULL
for(String s : sourceWords){
sourceCounts.incrementCount(s, 1.0);
}
for(String t : targetWords){
targetCounts.incrementCount(t, 1.0);
}
Set<String> s1 = new HashSet<String>();
for(String source : sourceWords){
if(s1.contains(source)){
continue;
}else{
s1.add(source);
}
Set<String> s2 = new HashSet<String>();
for(String target : targetWords){
if(s2.contains(target)){
continue;
}else{
s2.add(target);
}
// TODO: Warm-up. Your code here for collecting sufficient statistics.
sourceTargetCounts.incrementCount(source, target, 1.0);
}
}
}
}
}
| UTF-8 | Java | 3,544 | java | PMIModel.java | Java | [] | null | [] | package cs224n.wordaligner;
import cs224n.util.*;
//import java.util.List;
import java.util.*;
/**
*
*
*
* IMPORTANT: Make sure that you read the comments in the
* cs224n.wordaligner.WordAligner interface.
*
*/
public class PMIModel implements WordAligner {
private static final long serialVersionUID = 1315751943476440515L;
// TODO: Use arrays or Counters for collecting sufficient statistics
// from the training data.
private CounterMap<String,String> sourceTargetCounts;
private Counter<String> sourceCounts;
private Counter<String> targetCounts;
private double numSentences = 0;
public Alignment align(SentencePair sentencePair) {
// Placeholder code below.
// TODO Implement an inference algorithm for Eq.1 in the assignment
// handout to predict alignments based on the counts you collected with train().
//System.out.print("------------Here in Align-------------------\n");
//System.out.println(sentencePair.getSourceWords().get(0));
Alignment alignment = new Alignment();
int numSourceWords = sentencePair.getSourceWords().size();
int numTargetWords = sentencePair.getTargetWords().size();
for(int trgtIndex = 0; trgtIndex < numTargetWords; trgtIndex++){
String tgtWord = sentencePair.getTargetWords().get(trgtIndex);
double tgtProb = targetCounts.getCount(tgtWord) / targetCounts.totalCount();
int bestIndex = -1;
double bestMatch = -1.0;
for (int srcIndex = 0; srcIndex < numSourceWords; srcIndex++) {
String srcWord = sentencePair.getSourceWords().get(srcIndex);
double matchCount = sourceTargetCounts.getCount(srcWord, tgtWord);
double probMatch = matchCount / numSentences;
System.out.println(probMatch);
double srcProb = sourceCounts.getCount(srcWord) / sourceCounts.totalCount();
double a_i = probMatch / (srcProb * tgtProb);
if(a_i > bestMatch){
bestMatch = a_i;
bestIndex = srcIndex;
}
/*int tgtIndex = srcIndex;
if (tgtIndex < numTargetWords) {
// Discard null alignments
alignment.addPredictedAlignment(tgtIndex, srcIndex);
}*/
}
//if(bestIndex==0)//System.out.print("NULL predicted\n");
alignment.addPredictedAlignment(trgtIndex, bestIndex);
}
return alignment;
}
public void train(List<SentencePair> trainingPairs) {
System.out.print("------------sdfsdfHere in training-------------------\n");
sourceTargetCounts = new CounterMap<String,String>();
targetCounts = new Counter<String>();
sourceCounts = new Counter<String>();
numSentences = trainingPairs.size();
for(SentencePair pair : trainingPairs){
List<String> targetWords = pair.getTargetWords();
List<String> sourceWords = pair.getSourceWords();
//sourceWords.add(0, "<NULL>"); //not sure about this NULL
for(String s : sourceWords){
sourceCounts.incrementCount(s, 1.0);
}
for(String t : targetWords){
targetCounts.incrementCount(t, 1.0);
}
Set<String> s1 = new HashSet<String>();
for(String source : sourceWords){
if(s1.contains(source)){
continue;
}else{
s1.add(source);
}
Set<String> s2 = new HashSet<String>();
for(String target : targetWords){
if(s2.contains(target)){
continue;
}else{
s2.add(target);
}
// TODO: Warm-up. Your code here for collecting sufficient statistics.
sourceTargetCounts.incrementCount(source, target, 1.0);
}
}
}
}
}
| 3,544 | 0.659142 | 0.645034 | 101 | 34.089108 | 24.275278 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.762376 | false | false | 4 |
5b3306ad75cd7fb8b7bfd36e477bfc279a9bd7cd | 36,429,912,639,270 | 8c20e1dfe67ef70a8ca8f7984d6d83ff4e31f0ed | /SilkRoad-IM/src/main/java/com/silkroad/core/bean/args/IMSocketRequest.java | 3955fabb984af6a6037a40e0292601a2d3d25292 | [] | no_license | aijiacy/SmackQQ | https://github.com/aijiacy/SmackQQ | 5554126f8a2b1f5a863dfb85fc722db46f404608 | ac648188d31a5498c7b9956e59a6b2468d06920a | refs/heads/master | 2022-02-13T01:49:05.858000 | 2019-07-23T10:47:24 | 2019-07-23T10:47:24 | 26,861,736 | 0 | 0 | null | false | 2022-02-01T00:57:37 | 2014-11-19T13:05:48 | 2019-07-23T10:47:27 | 2022-02-01T00:57:35 | 11,846 | 0 | 0 | 9 | Java | false | false | package com.silkroad.core.bean.args;
import com.silkroad.core.event.IMEventType;
/**
* Created by caoyong on 2014/7/14.
*/
public class IMSocketRequest {
private IMEventType type;
private Object requestData;
public IMSocketRequest(IMEventType type) {
this.type = type;
}
public IMSocketRequest(IMEventType type, Object requestData) {
this.type = type;
this.requestData = requestData;
}
public IMEventType getType() {
return type;
}
public void setType(IMEventType type) {
this.type = type;
}
public Object getRequestData() {
return requestData;
}
public void setRequestData(Object requestData) {
this.requestData = requestData;
}
}
| UTF-8 | Java | 754 | java | IMSocketRequest.java | Java | [
{
"context": "ilkroad.core.event.IMEventType;\n\n/**\n * Created by caoyong on 2014/7/14.\n */\npublic class IMSocketRequest {\n",
"end": 108,
"score": 0.9995282292366028,
"start": 101,
"tag": "USERNAME",
"value": "caoyong"
}
] | null | [] | package com.silkroad.core.bean.args;
import com.silkroad.core.event.IMEventType;
/**
* Created by caoyong on 2014/7/14.
*/
public class IMSocketRequest {
private IMEventType type;
private Object requestData;
public IMSocketRequest(IMEventType type) {
this.type = type;
}
public IMSocketRequest(IMEventType type, Object requestData) {
this.type = type;
this.requestData = requestData;
}
public IMEventType getType() {
return type;
}
public void setType(IMEventType type) {
this.type = type;
}
public Object getRequestData() {
return requestData;
}
public void setRequestData(Object requestData) {
this.requestData = requestData;
}
}
| 754 | 0.651194 | 0.64191 | 36 | 19.944445 | 18.59203 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 4 |
be2464537180f00926f842ed53f6ad04642be566 | 6,279,242,218,009 | 643d91bcc173d52e5fe8221ae16c263cad628a41 | /src/com/whut/algorithm/high/frequence/backTrack/problem40_combination_sum_ii/CombinationSumII.java | f8ed911125c517c29a90494fb3f72cd84a8328af | [] | no_license | woshilaladui/interview_written | https://github.com/woshilaladui/interview_written | a563ea505fc9d671bdcc57a052208eba4c34ae80 | 309e601cf86758f47cb52957d88e76ea6a5ba3d9 | refs/heads/master | 2023-06-17T11:25:40.840000 | 2022-11-18T10:49:21 | 2022-11-18T10:49:21 | 323,859,058 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.whut.algorithm.high.frequence.backTrack.problem40_combination_sum_ii;
import java.util.*;
/**
* @author Administrator
* @version 1.0.0
* @date 2020/11/19 16:15
* @desription
*/
public class CombinationSumII {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new LinkedList<>();
List<Integer> path = new LinkedList<>();
Arrays.sort(candidates);
backTrack(candidates, target, result, path, 0);
return result;
}
public List<List<Integer>> combinationSum3(int[] candidates, int target) {
List<List<Integer>> result = new LinkedList<>();
List<Integer> path = new LinkedList<>();
boolean[] vis = new boolean[candidates.length];
backTrack2(candidates, target, result, path, vis);
return result;
}
private void backTrack2(
int[] candidates,
int target,
List<List<Integer>> result,
List<Integer> path,
boolean[] vis
) {
if (target == 0) {
result.add(new LinkedList<>(path));
return;
}
Set<Integer> set = new HashSet<>();
for (int i = 0; i < candidates.length; i++) {
if(target < 0)
break;
if(set.contains(candidates[i]) || vis[i]){
continue;
}
set.add(candidates[i]);
vis[i] = true;
path.add(candidates[i]);
backTrack2(candidates,target-candidates[i],result,path,vis);
vis[i] = false;
path.remove(path.size()-1);
}
}
private void backTrack(
int[] candidates,
int target,
List<List<Integer>> result,
List<Integer> path,
int index
) {
if (target == 0) {
result.add(new LinkedList<>(path));
return;
}
if (target < 0)
return;
for (int i = index; i < candidates.length; i++) {
if (candidates[i] > target)
break;
if (i != index && candidates[i] == candidates[i - 1])
continue;
path.add(candidates[i]);
backTrack(candidates, target - candidates[i], result, path, i + 1);
path.remove(path.size() - 1);
}
}
public static void main(String[] args) {
TreeMap<String , Double> map = new TreeMap<String, Double>();
map.put("ccc" , 89.0);
map.put("aaa" , 80.0);
map.put("zzz" , 80.0);
map.put("bbb" , 89.0);
System.out.println(map);
TreeSet<String> set = new TreeSet<>();
}
}
| UTF-8 | Java | 2,727 | java | CombinationSumII.java | Java | [
{
"context": "ation_sum_ii;\n\nimport java.util.*;\n\n/**\n * @author Administrator\n * @version 1.0.0\n * @date 2020/11/19 16:15\n * @d",
"end": 132,
"score": 0.9951111674308777,
"start": 119,
"tag": "NAME",
"value": "Administrator"
}
] | null | [] | package com.whut.algorithm.high.frequence.backTrack.problem40_combination_sum_ii;
import java.util.*;
/**
* @author Administrator
* @version 1.0.0
* @date 2020/11/19 16:15
* @desription
*/
public class CombinationSumII {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new LinkedList<>();
List<Integer> path = new LinkedList<>();
Arrays.sort(candidates);
backTrack(candidates, target, result, path, 0);
return result;
}
public List<List<Integer>> combinationSum3(int[] candidates, int target) {
List<List<Integer>> result = new LinkedList<>();
List<Integer> path = new LinkedList<>();
boolean[] vis = new boolean[candidates.length];
backTrack2(candidates, target, result, path, vis);
return result;
}
private void backTrack2(
int[] candidates,
int target,
List<List<Integer>> result,
List<Integer> path,
boolean[] vis
) {
if (target == 0) {
result.add(new LinkedList<>(path));
return;
}
Set<Integer> set = new HashSet<>();
for (int i = 0; i < candidates.length; i++) {
if(target < 0)
break;
if(set.contains(candidates[i]) || vis[i]){
continue;
}
set.add(candidates[i]);
vis[i] = true;
path.add(candidates[i]);
backTrack2(candidates,target-candidates[i],result,path,vis);
vis[i] = false;
path.remove(path.size()-1);
}
}
private void backTrack(
int[] candidates,
int target,
List<List<Integer>> result,
List<Integer> path,
int index
) {
if (target == 0) {
result.add(new LinkedList<>(path));
return;
}
if (target < 0)
return;
for (int i = index; i < candidates.length; i++) {
if (candidates[i] > target)
break;
if (i != index && candidates[i] == candidates[i - 1])
continue;
path.add(candidates[i]);
backTrack(candidates, target - candidates[i], result, path, i + 1);
path.remove(path.size() - 1);
}
}
public static void main(String[] args) {
TreeMap<String , Double> map = new TreeMap<String, Double>();
map.put("ccc" , 89.0);
map.put("aaa" , 80.0);
map.put("zzz" , 80.0);
map.put("bbb" , 89.0);
System.out.println(map);
TreeSet<String> set = new TreeSet<>();
}
}
| 2,727 | 0.512651 | 0.496516 | 108 | 24.25 | 21.900501 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.703704 | false | false | 4 |
7222aeea316ab064642920cab9095700e797f3fb | 1,786,706,426,672 | 0977163bbe0761b762adf23454f3be64bf814eb6 | /LYEC/src/com/cqut/compusEC/entity/TbRole.java | f9007e45ab068bd32d60d24c29c3c0abd14e0c86 | [
"Apache-2.0"
] | permissive | CrazyRoy/RoyEC | https://github.com/CrazyRoy/RoyEC | cf08a40932639a83d7f158f105cc0fd3fcc9ed5c | d03a0cd8a1e4caf1a131d38c36120fc934a49b7e | refs/heads/master | 2020-12-30T13:28:37.387000 | 2018-03-23T06:57:18 | 2018-03-23T06:57:18 | 91,221,637 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cqut.compusEC.entity;
public class TbRole extends Entity{
private String ROLEID;//角色ID
private String ROLENAME;//角色名称
private String CREATETIME;//创建时间
private String REMARKS;//备注
public String getROLEID() {
return ROLEID;
}
public void setROLEID(String rOLEID) {
ROLEID = rOLEID;
}
public String getROLENAME() {
return ROLENAME;
}
public void setROLENAME(String rOLENAME) {
ROLENAME = rOLENAME;
}
public String getCREATETIME() {
return CREATETIME;
}
public void setCREATETIME(String cREATETIME) {
CREATETIME = cREATETIME;
}
public String getREMARKS() {
return REMARKS;
}
public void setREMARKS(String rEMARKS) {
REMARKS = rEMARKS;
}
@Override
public String getTableName() {
// TODO Auto-generated method stub
return "tb_role";
}
@Override
public String getPrimaryKey() {
// TODO Auto-generated method stub
return "ROLEID";
}
}
| UTF-8 | Java | 981 | java | TbRole.java | Java | [] | null | [] | package com.cqut.compusEC.entity;
public class TbRole extends Entity{
private String ROLEID;//角色ID
private String ROLENAME;//角色名称
private String CREATETIME;//创建时间
private String REMARKS;//备注
public String getROLEID() {
return ROLEID;
}
public void setROLEID(String rOLEID) {
ROLEID = rOLEID;
}
public String getROLENAME() {
return ROLENAME;
}
public void setROLENAME(String rOLENAME) {
ROLENAME = rOLENAME;
}
public String getCREATETIME() {
return CREATETIME;
}
public void setCREATETIME(String cREATETIME) {
CREATETIME = cREATETIME;
}
public String getREMARKS() {
return REMARKS;
}
public void setREMARKS(String rEMARKS) {
REMARKS = rEMARKS;
}
@Override
public String getTableName() {
// TODO Auto-generated method stub
return "tb_role";
}
@Override
public String getPrimaryKey() {
// TODO Auto-generated method stub
return "ROLEID";
}
}
| 981 | 0.672936 | 0.672936 | 54 | 15.722222 | 14.97333 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.222222 | false | false | 4 |
303a7678fbf1538947424ae1e91ce7d7cb102932 | 25,391,846,674,327 | 625d82f8febd5a7e24a9a3358dc17afff232f11b | /eLeave/src/sg/edu/nus/iss/eleave/exception/DAOException.java | 978e9afa7476819b67c917fa4fe98992f9869230 | [] | no_license | wjquery/cloud-computing-ca | https://github.com/wjquery/cloud-computing-ca | 21093aeb248622cac3f549f0ae914d10cb35ff6a | 84a7fab1c09cb7189a4d7130d4946d24b0680be8 | refs/heads/master | 2020-06-05T12:33:34.421000 | 2013-07-05T18:23:37 | 2013-07-05T18:23:37 | 32,123,696 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package sg.edu.nus.iss.eleave.exception;
public class DAOException extends Exception {
static final long serialVersionUID = 1L;
public DAOException() {}
public DAOException(String s) {
super(s);
}
public DAOException(Exception e) {
super(e);
}
}
| UTF-8 | Java | 312 | java | DAOException.java | Java | [] | null | [] |
package sg.edu.nus.iss.eleave.exception;
public class DAOException extends Exception {
static final long serialVersionUID = 1L;
public DAOException() {}
public DAOException(String s) {
super(s);
}
public DAOException(Exception e) {
super(e);
}
}
| 312 | 0.602564 | 0.599359 | 15 | 18.533333 | 16.716724 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 4 |
e4bdf4032d87da6f68ceb21425c86cc47e547802 | 20,581,483,323,826 | e742cf54e52b092ac86711ae658e8c80b3905adb | /src/main/java/com/l/controller/AuthController.java | ce7ffcb71741bc4d2628faf5851282a7f69bf356 | [] | no_license | ByaoH/white-jotter-spring | https://github.com/ByaoH/white-jotter-spring | 6a61a5182a18e64c5ebc6737eee219acfc415479 | 5983a6c87b3975b5f7eac0914dafbb5401752d29 | refs/heads/master | 2023-03-08T18:42:17.885000 | 2021-02-23T13:24:35 | 2021-02-23T13:24:35 | 325,694,681 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.l.controller;
import com.l.dto.LoginUser;
import com.l.result.Result;
import com.l.result.ResultFactory;
import com.l.service.AuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
/**
* @author l
*/
@RestController
@Api(tags = "认证")
@RequestMapping("/auth")
public class AuthController {
private final AuthService authService;
public AuthController(AuthService authService) {
this.authService = authService;
}
@ApiOperation("登陆")
@PostMapping(value = "/login")
public Result<?> login(@RequestBody LoginUser requestUser) {
String token = authService.getToken(requestUser);
return ResultFactory.buildSuccessResult("认证成功!", token);
}
@ApiOperation("登出")
@GetMapping("/logout")
public Result<Void> logout() {
String username = authService.deleteTokenFromRedis();
return ResultFactory.buildSuccessResult(username + " 你已登出...");
}
}
| UTF-8 | Java | 1,048 | java | AuthController.java | Java | [
{
"context": "ngframework.web.bind.annotation.*;\n\n/**\n * @author l\n */\n@RestController\n@Api(tags = \"认证\")\n@RequestMap",
"end": 298,
"score": 0.8962644338607788,
"start": 297,
"tag": "USERNAME",
"value": "l"
}
] | null | [] | package com.l.controller;
import com.l.dto.LoginUser;
import com.l.result.Result;
import com.l.result.ResultFactory;
import com.l.service.AuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
/**
* @author l
*/
@RestController
@Api(tags = "认证")
@RequestMapping("/auth")
public class AuthController {
private final AuthService authService;
public AuthController(AuthService authService) {
this.authService = authService;
}
@ApiOperation("登陆")
@PostMapping(value = "/login")
public Result<?> login(@RequestBody LoginUser requestUser) {
String token = authService.getToken(requestUser);
return ResultFactory.buildSuccessResult("认证成功!", token);
}
@ApiOperation("登出")
@GetMapping("/logout")
public Result<Void> logout() {
String username = authService.deleteTokenFromRedis();
return ResultFactory.buildSuccessResult(username + " 你已登出...");
}
}
| 1,048 | 0.706863 | 0.706863 | 39 | 25.153847 | 21.161818 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 4 |
c6a637ae4c48e67ea4bffb977b4c6fec116506f1 | 1,168,231,161,322 | fd1ced103bf85cea01cb7436a2370b330d0eb98a | /homework1/src/homework1/qestion1.java | 350ddb730f3a1d20f79c111d0285a9944b2f9713 | [] | no_license | abiyKahsay04/java | https://github.com/abiyKahsay04/java | 52877799748e2852389d18653186874d8fcd63de | fe8adbf5fa27e13983602ab1f7b880791fe530f9 | refs/heads/master | 2023-04-04T00:56:04.239000 | 2021-04-18T01:47:21 | 2021-04-18T01:47:21 | 359,016,102 | 0 | 0 | null | false | 2021-04-18T01:46:42 | 2021-04-18T01:08:07 | 2021-04-18T01:17:04 | 2021-04-18T01:46:42 | 0 | 0 | 0 | 0 | Java | false | false | package homework1;
public class qestion1 {
public static void main(String[] arg) {
String name="Abiy";
System.out.println("Hello");
System.out.println(name);
}
}
| UTF-8 | Java | 193 | java | qestion1.java | Java | [
{
"context": " static void main(String[] arg) {\r\n\t\tString name=\"Abiy\";\r\n\t\tSystem.out.println(\"Hello\");\r\n\t\tSystem.out.p",
"end": 108,
"score": 0.9995369911193848,
"start": 104,
"tag": "NAME",
"value": "Abiy"
}
] | null | [] | package homework1;
public class qestion1 {
public static void main(String[] arg) {
String name="Abiy";
System.out.println("Hello");
System.out.println(name);
}
}
| 193 | 0.61658 | 0.606218 | 13 | 12.846154 | 13.563787 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.307692 | false | false | 4 |
20448f15d373c2e748029194ebd150a2eb3d08e4 | 5,574,867,588,008 | c405671aeec556be37c9ff795887e8e7730a631a | /plugin-infra/go-plugin-infra/src/test/java/com/thoughtworks/go/plugin/infra/FelixGoPluginOSGiFrameworkTest.java | c04f4e13ddb34322f7e949fc0786288f4b4114fc | [
"Apache-2.0"
] | permissive | naveenbhaskar/gocd | https://github.com/naveenbhaskar/gocd | e13efb06d25cd65e01b53af5256db9bd2484143f | eacc5b10804cc9d9fb09396a76ea25141aedea4c | refs/heads/master | 2020-04-06T04:26:59.167000 | 2019-06-03T10:26:08 | 2019-06-03T10:26:08 | 66,810,821 | 1 | 0 | Apache-2.0 | true | 2018-08-28T04:08:02 | 2016-08-29T04:17:05 | 2016-08-29T04:17:24 | 2018-08-28T04:08:02 | 267,066 | 0 | 0 | 0 | Java | false | null | /*
* Copyright 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.plugin.infra;
import com.thoughtworks.go.plugin.api.GoPlugin;
import com.thoughtworks.go.plugin.api.GoPluginIdentifier;
import com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptor;
import com.thoughtworks.go.plugin.infra.plugininfo.PluginRegistry;
import com.thoughtworks.go.plugin.infra.service.DefaultPluginHealthService;
import com.thoughtworks.go.plugin.infra.service.DefaultPluginLoggingService;
import com.thoughtworks.go.plugin.internal.api.LoggingService;
import com.thoughtworks.go.plugin.internal.api.PluginHealthService;
import com.thoughtworks.go.util.SystemEnvironment;
import org.apache.felix.framework.util.FelixConstants;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.osgi.framework.*;
import org.osgi.framework.launch.Framework;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
class FelixGoPluginOSGiFrameworkTest {
private static final String TEST_SYMBOLIC_NAME = "testplugin.descriptorValidator";
@Mock
private BundleContext bundleContext;
@Mock
private Bundle bundle;
@Mock
private Framework framework;
@Mock
private PluginRegistry registry;
@Mock
private SystemEnvironment systemEnvironment;
@Mock
private PluginExtensionsAndVersionValidator pluginExtensionsAndVersionValidator;
private FelixGoPluginOSGiFramework spy;
@BeforeEach
void setUp() {
initMocks(this);
FelixGoPluginOSGiFramework goPluginOSGiFramework = new FelixGoPluginOSGiFramework(registry, systemEnvironment) {
@Override
protected HashMap<String, String> generateOSGiFrameworkConfig() {
HashMap<String, String> config = super.generateOSGiFrameworkConfig();
config.put(FelixConstants.RESOLVER_PARALLELISM, "1");
return config;
}
};
spy = spy(goPluginOSGiFramework);
spy.setPluginExtensionsAndVersionValidator(pluginExtensionsAndVersionValidator);
when(framework.getBundleContext()).thenReturn(bundleContext);
when(registry.getPlugin(TEST_SYMBOLIC_NAME)).thenReturn(buildExpectedDescriptor(TEST_SYMBOLIC_NAME));
doReturn(framework).when(spy).getFelixFramework(any());
}
@AfterEach
void tearDown() {
spy.stop();
}
@Test
void shouldRegisterAnInstanceOfEachOfTheRequiredPluginServicesAfterOSGiFrameworkIsInitialized() {
spy.start();
verify(bundleContext).registerService(eq(PluginHealthService.class), any(DefaultPluginHealthService.class), isNull(Dictionary.class));
verify(bundleContext).registerService(eq(LoggingService.class), any(DefaultPluginLoggingService.class), isNull(Dictionary.class));
}
@Test
void doOnShouldRunAnActionOnSpecifiedPluginImplementationsOfAGivenInterface() throws Exception {
SomeInterface firstService = mock(SomeInterface.class);
SomeInterface secondService = mock(SomeInterface.class);
registerService(firstService, "plugin-one", "extension-one");
registerService(secondService, "plugin-two", "extension-two");
spy.start();
spy.doOn(SomeInterface.class, "plugin-two", "extension-two", (obj, pluginDescriptor) -> {
assertThat(pluginDescriptor).isEqualTo(buildExpectedDescriptor("plugin-two"));
return obj.someMethodWithReturn();
});
verify(firstService, never()).someMethodWithReturn();
verify(secondService).someMethodWithReturn();
verifyNoMoreInteractions(firstService, secondService);
}
@Test
void doOnShouldThrowAnExceptionWhenThereAreMultipleServicesWithSamePluginIdAndSameExtensionType_IdeallyThisShouldNotHappenInProductionSincePluginIdIsSymbolicName() throws Exception {
SomeInterface firstService = mock(SomeInterface.class);
SomeInterface secondService = mock(SomeInterface.class);
String symbolicName = "same_symbolic_name";
registerServicesWithSameSymbolicName(symbolicName, "test-extension", firstService, secondService);
spy.start();
try {
spy.doOn(SomeInterface.class, symbolicName, "test-extension", (obj, pluginDescriptor) -> {
assertThat(pluginDescriptor).isEqualTo(buildExpectedDescriptor(symbolicName));
return obj.someMethodWithReturn();
});
fail("Should throw plugin framework exception");
} catch (GoPluginFrameworkException ex) {
assertThat(ex.getMessage().startsWith("More than one reference found")).isTrue();
assertThat(ex.getMessage().contains(SomeInterface.class.getCanonicalName())).isTrue();
assertThat(ex.getMessage().contains(symbolicName)).isTrue();
}
verify(firstService, never()).someMethodWithReturn();
verify(secondService, never()).someMethodWithReturn();
verify(secondService, never()).someMethod();
verifyNoMoreInteractions(firstService, secondService);
}
@Test
void doOnShouldThrowAnExceptionWhenNoServicesAreFoundForTheGivenFilterAndServiceReference() throws Exception {
SomeInterface firstService = mock(SomeInterface.class);
SomeInterface secondService = mock(SomeInterface.class);
String symbolicName = "dummy_symbolic_name";
registerServicesWithSameSymbolicName(symbolicName, "test-extension", firstService, secondService);
spy.start();
try {
spy.doOn(SomeOtherInterface.class, symbolicName, "test-extension", (obj, pluginDescriptor) -> {
assertThat(pluginDescriptor).isEqualTo(buildExpectedDescriptor(symbolicName));
throw new RuntimeException("Should Not Be invoked");
});
fail("Should throw plugin framework exception");
} catch (GoPluginFrameworkException ex) {
assertThat(ex.getMessage().startsWith("No reference found")).isTrue();
assertThat(ex.getMessage().contains(SomeOtherInterface.class.getCanonicalName())).isTrue();
assertThat(ex.getMessage().contains(symbolicName)).isTrue();
}
verify(firstService, never()).someMethodWithReturn();
verify(secondService, never()).someMethodWithReturn();
verify(secondService, never()).someMethod();
verifyNoMoreInteractions(firstService, secondService);
}
@Test
void hasReferencesShouldReturnAppropriateValueIfSpecifiedPluginImplementationsOfAGivenInterfaceIsFoundOrNotFound() throws Exception {
SomeInterface firstService = mock(SomeInterface.class);
SomeInterface secondService = mock(SomeInterface.class);
spy.start();
boolean reference = spy.hasReferenceFor(SomeInterface.class, secondService.toString(), "extension-two");
assertThat(reference).isFalse();
registerService(firstService, "plugin-one", "extension-one");
registerService(secondService, "plugin-two", "extension-two");
reference = spy.hasReferenceFor(SomeInterface.class, "plugin-two", "extension-two");
assertThat(reference).isTrue();
verifyNoMoreInteractions(firstService, secondService);
}
@Test
void shouldUnloadAPlugin() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
when(pluginDescriptor.bundle()).thenReturn(bundle);
spy.unloadPlugin(pluginDescriptor);
verify(bundle, atLeastOnce()).stop();
verify(bundle, atLeastOnce()).uninstall();
}
@Test
void shouldNotFailToUnloadAPluginWhoseBundleIsNull() {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
when(pluginDescriptor.bundle()).thenReturn(null);
try {
spy.unloadPlugin(pluginDescriptor);
} catch (Exception e) {
fail("Should not have thrown an exception");
}
}
@Test
void shouldNotFailToUnloadAPluginWhenAPluginUnloadListenerFails() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
when(pluginDescriptor.bundle()).thenReturn(bundle);
PluginChangeListener listenerWhichThrowsWhenUnloading = mock(PluginChangeListener.class);
doThrow(new RuntimeException("Fail!")).when(listenerWhichThrowsWhenUnloading).pluginUnLoaded(pluginDescriptor);
spy.addPluginChangeListener(listenerWhichThrowsWhenUnloading);
spy.unloadPlugin(pluginDescriptor);
verify(bundle, times(1)).stop();
verify(bundle, times(1)).uninstall();
}
@Test
void shouldRunOtherUnloadListenersEvenIfOneFails() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
when(pluginDescriptor.bundle()).thenReturn(bundle);
PluginChangeListener listenerWhichWorks1 = mock(PluginChangeListener.class, "Listener Which Works: 1");
PluginChangeListener listenerWhichWorks2 = mock(PluginChangeListener.class, "Listener Which Works: 2");
PluginChangeListener listenerWhichThrowsWhenUnloading = mock(PluginChangeListener.class, "Listener Which Throws");
doThrow(new RuntimeException("Fail!")).when(listenerWhichThrowsWhenUnloading).pluginUnLoaded(pluginDescriptor);
spy.addPluginChangeListener(listenerWhichWorks1);
spy.addPluginChangeListener(listenerWhichThrowsWhenUnloading);
spy.addPluginChangeListener(listenerWhichWorks2);
spy.unloadPlugin(pluginDescriptor);
verify(listenerWhichWorks1, times(1)).pluginUnLoaded(pluginDescriptor);
verify(listenerWhichThrowsWhenUnloading, times(1)).pluginUnLoaded(pluginDescriptor);
verify(listenerWhichWorks2, times(1)).pluginUnLoaded(pluginDescriptor);
verify(bundle, times(1)).stop();
verify(bundle, times(1)).uninstall();
}
@Test
void shouldMarkThePluginAsInvalidIfAnyExceptionOccursAfterLoad() throws BundleException {
final Bundle bundle = mock(Bundle.class);
spy.addPluginChangeListener(new PluginChangeListener() {
@Override
public void pluginLoaded(GoPluginDescriptor pluginDescriptor) {
throw new RuntimeException("some error");
}
@Override
public void pluginUnLoaded(GoPluginDescriptor pluginDescriptor) {
}
});
when(bundleContext.installBundle(any(String.class))).thenReturn(bundle);
final GoPluginDescriptor goPluginDescriptor = new GoPluginDescriptor(TEST_SYMBOLIC_NAME, "1.0", null, "location", new File(""), false);
spy.start();
try {
spy.loadPlugin(goPluginDescriptor);
fail("should throw exception");
} catch (Exception e) {
assertThat(goPluginDescriptor.getStatus().isInvalid()).isTrue();
}
}
@Test
void shouldRegisterExtensionInfosWithPluginRegistry() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
final PluginExtensionsAndVersionValidator.ValidationResult result = mock(PluginExtensionsAndVersionValidator.ValidationResult.class);
when(pluginDescriptor.id()).thenReturn("some-id");
when(pluginDescriptor.bundle()).thenReturn(bundle);
when(pluginDescriptor.bundleLocation()).thenReturn(new File("foo"));
when(bundleContext.installBundle(any(String.class))).thenReturn(bundle);
when(pluginExtensionsAndVersionValidator.validate(pluginDescriptor)).thenReturn(result);
when(result.hasError()).thenReturn(false);
doReturn(singletonMap("elastic-agent", singletonList("1.0"))).when(spy).getExtensionsInfoFromThePlugin("some-id");
spy.start();
spy.loadPlugin(pluginDescriptor);
InOrder inOrder = inOrder(bundle, framework, registry, pluginExtensionsAndVersionValidator);
inOrder.verify(framework, times(2)).getBundleContext();
inOrder.verify(bundle).start();
inOrder.verify(registry).registerExtensions(pluginDescriptor, singletonMap("elastic-agent", singletonList("1.0")));
inOrder.verify(pluginExtensionsAndVersionValidator).validate(pluginDescriptor);
}
@Nested
class GetExtensionsInfoFromThePlugin {
@Test
void shouldGetExtensionsInfoForThePlugin() throws Exception {
when(registry.getPlugin(anyString())).thenReturn(mock(GoPluginDescriptor.class));
GoPlugin firstService = mock(GoPlugin.class);
GoPlugin secondService = mock(GoPlugin.class);
final GoPluginIdentifier firstPluginIdentifier = mock(GoPluginIdentifier.class);
when(firstService.pluginIdentifier()).thenReturn(firstPluginIdentifier);
when(firstPluginIdentifier.getExtension()).thenReturn("elastic-agent");
when(firstPluginIdentifier.getSupportedExtensionVersions()).thenReturn(asList("1.0", "2.0"));
final GoPluginIdentifier secondPluginIdentifier = mock(GoPluginIdentifier.class);
when(secondService.pluginIdentifier()).thenReturn(secondPluginIdentifier);
when(secondPluginIdentifier.getExtension()).thenReturn("authorization");
when(secondPluginIdentifier.getSupportedExtensionVersions()).thenReturn(singletonList("1.0"));
registerService("plugin-one", firstService, secondService);
spy.start();
final Map<String, List<String>> info = spy.getExtensionsInfoFromThePlugin("plugin-one");
assertThat(info).hasSize(2)
.containsEntry("elastic-agent", asList("1.0", "2.0"))
.containsEntry("authorization", singletonList("1.0"));
}
}
@Test
void shouldNotifyAllPluginChangeListenerOncePluginIsLoaded() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
final PluginExtensionsAndVersionValidator.ValidationResult result = mock(PluginExtensionsAndVersionValidator.ValidationResult.class);
when(pluginDescriptor.bundle()).thenReturn(bundle);
when(pluginDescriptor.bundleLocation()).thenReturn(new File("foo"));
when(bundleContext.installBundle(any(String.class))).thenReturn(bundle);
when(pluginExtensionsAndVersionValidator.validate(pluginDescriptor)).thenReturn(result);
when(result.hasError()).thenReturn(false);
PluginChangeListener listener1 = mock(PluginChangeListener.class);
PluginChangeListener listener2 = mock(PluginChangeListener.class);
PluginChangeListener listener3 = mock(PluginChangeListener.class);
spy.addPluginChangeListener(listener1);
spy.addPluginChangeListener(listener2);
spy.addPluginChangeListener(listener3);
spy.start();
spy.loadPlugin(pluginDescriptor);
verify(listener1, times(1)).pluginLoaded(pluginDescriptor);
verify(listener3, times(1)).pluginLoaded(pluginDescriptor);
verify(listener2, times(1)).pluginLoaded(pluginDescriptor);
verify(bundle, times(1)).start();
}
@Test
void shouldMarkPluginDescriptorInvalidAndNotNotifyPluginChangeListenersWhenExtensionVersionsRequiredByThePluginIsNotSupportedByGoCD() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
final PluginExtensionsAndVersionValidator.ValidationResult result = mock(PluginExtensionsAndVersionValidator.ValidationResult.class);
when(pluginDescriptor.bundle()).thenReturn(bundle);
when(pluginDescriptor.bundleLocation()).thenReturn(new File("foo"));
when(bundleContext.installBundle(any(String.class))).thenReturn(bundle);
when(pluginExtensionsAndVersionValidator.validate(pluginDescriptor)).thenReturn(result);
when(result.hasError()).thenReturn(true);
PluginChangeListener listener1 = mock(PluginChangeListener.class);
PluginChangeListener listener2 = mock(PluginChangeListener.class);
PluginChangeListener listener3 = mock(PluginChangeListener.class);
spy.addPluginChangeListener(listener1);
spy.addPluginChangeListener(listener2);
spy.addPluginChangeListener(listener3);
spy.start();
spy.loadPlugin(pluginDescriptor);
verifyZeroInteractions(listener1);
verifyZeroInteractions(listener3);
verifyZeroInteractions(listener2);
verify(bundle, times(1)).start();
verify(pluginDescriptor).markAsInvalid(anyList(), eq(null));
}
@Test
void shouldMigrateElasticAgentInformationAsPartOfMigrateConfigurationCall() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
ElasticAgentInformationMigrator migrator = mock(ElasticAgentInformationMigrator.class);
when(migrator.migrate(any())).thenReturn(true);
spy.setElasticAgentInformationMigrator(migrator);
boolean migratedSuccessfully = spy.migrateConfig(pluginDescriptor);
assertThat(migratedSuccessfully).isTrue();
verify(migrator, times(1)).migrate(pluginDescriptor);
}
@Test
void shouldReturnWhetherMigrationSuccessStatus() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
ElasticAgentInformationMigrator migrator = mock(ElasticAgentInformationMigrator.class);
when(migrator.migrate(any())).thenReturn(false);
spy.setElasticAgentInformationMigrator(migrator);
boolean migratedSuccessfully = spy.migrateConfig(pluginDescriptor);
assertThat(migratedSuccessfully).isFalse();
verify(migrator, times(1)).migrate(pluginDescriptor);
}
@Test
void shouldNotMigrateElasticAgentInformationWhenNoMigratorIsSpecified() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
ElasticAgentInformationMigrator migrator = mock(ElasticAgentInformationMigrator.class);
boolean migratedSuccessfully = spy.migrateConfig(pluginDescriptor);
assertThat(migratedSuccessfully).isTrue();
verifyNoMoreInteractions(migrator);
}
@Test
void shouldSkipUninstallIfPluginIsPreviouslyUninstalled() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
when(pluginDescriptor.bundle()).thenReturn(bundle);
when(bundle.getState()).thenReturn(Bundle.UNINSTALLED);
spy.unloadPlugin(pluginDescriptor);
verify(bundle, never()).start();
verify(bundle, never()).uninstall();
}
private void registerServicesWithSameSymbolicName(String symbolicName, String extensionType, SomeInterface... someInterfaces) throws InvalidSyntaxException {
ArrayList<ServiceReference<SomeInterface>> references = new ArrayList<>();
for (SomeInterface someInterface : someInterfaces) {
ServiceReference<SomeInterface> reference = mock(ServiceReference.class);
Bundle bundle = mock(Bundle.class);
when(reference.getBundle()).thenReturn(bundle);
when(bundle.getSymbolicName()).thenReturn(symbolicName);
when(bundleContext.getService(reference)).thenReturn(someInterface);
references.add(reference);
}
String propertyFormat = String.format("(&(%s=%s)(%s=%s))", Constants.BUNDLE_SYMBOLICNAME, symbolicName, Constants.BUNDLE_CATEGORY, extensionType);
when(bundleContext.getServiceReferences(SomeInterface.class, propertyFormat)).thenReturn(references);
when(registry.getPlugin(symbolicName)).thenReturn(buildExpectedDescriptor(symbolicName));
}
private void registerService(SomeInterface someInterface, String pluginID, String extension) throws InvalidSyntaxException {
ServiceReference<SomeInterface> reference = mock(ServiceReference.class);
when(reference.getBundle()).thenReturn(bundle);
when(bundle.getSymbolicName()).thenReturn(pluginID);
when(bundleContext.getService(reference)).thenReturn(someInterface);
when(registry.getPlugin(pluginID)).thenReturn(buildExpectedDescriptor(pluginID));
String propertyFormat = String.format("(&(%s=%s)(%s=%s))", Constants.BUNDLE_SYMBOLICNAME, pluginID, Constants.BUNDLE_CATEGORY, extension);
when(bundleContext.getServiceReferences(SomeInterface.class, propertyFormat)).thenReturn(singletonList(reference));
when(bundleContext.getServiceReferences(SomeInterface.class, null)).thenReturn(singletonList(reference));
}
private void registerService(String pluginID, GoPlugin... someInterfaces) throws InvalidSyntaxException {
final List<ServiceReference<GoPlugin>> serviceReferences = Arrays.stream(someInterfaces).map(someInterface -> {
ServiceReference<GoPlugin> reference = mock(ServiceReference.class);
when(reference.getBundle()).thenReturn(bundle);
when(bundle.getSymbolicName()).thenReturn(pluginID);
when(bundleContext.getService(reference)).thenReturn(someInterface);
when(registry.getPlugin(pluginID)).thenReturn(buildExpectedDescriptor(pluginID));
return reference;
}).collect(Collectors.toList());
String propertyFormat = String.format("(&(%s=%s))", Constants.BUNDLE_SYMBOLICNAME, pluginID);
when(bundleContext.getServiceReferences(GoPlugin.class, propertyFormat)).thenReturn(serviceReferences);
}
private GoPluginDescriptor buildExpectedDescriptor(String pluginID) {
return new GoPluginDescriptor(pluginID, "1",
new GoPluginDescriptor.About("Plugin Descriptor Validator", "1.0.1", "17.12", "Validates its own plugin descriptor",
new GoPluginDescriptor.Vendor("ThoughtWorks GoCD Team", "www.thoughtworks.com"), asList("Linux", "Windows")), null, null, true
);
}
private interface SomeInterface {
void someMethod();
Object someMethodWithReturn();
}
private interface SomeOtherInterface {
}
}
| UTF-8 | Java | 23,206 | java | FelixGoPluginOSGiFrameworkTest.java | Java | [] | null | [] | /*
* Copyright 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.plugin.infra;
import com.thoughtworks.go.plugin.api.GoPlugin;
import com.thoughtworks.go.plugin.api.GoPluginIdentifier;
import com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptor;
import com.thoughtworks.go.plugin.infra.plugininfo.PluginRegistry;
import com.thoughtworks.go.plugin.infra.service.DefaultPluginHealthService;
import com.thoughtworks.go.plugin.infra.service.DefaultPluginLoggingService;
import com.thoughtworks.go.plugin.internal.api.LoggingService;
import com.thoughtworks.go.plugin.internal.api.PluginHealthService;
import com.thoughtworks.go.util.SystemEnvironment;
import org.apache.felix.framework.util.FelixConstants;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.osgi.framework.*;
import org.osgi.framework.launch.Framework;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
class FelixGoPluginOSGiFrameworkTest {
private static final String TEST_SYMBOLIC_NAME = "testplugin.descriptorValidator";
@Mock
private BundleContext bundleContext;
@Mock
private Bundle bundle;
@Mock
private Framework framework;
@Mock
private PluginRegistry registry;
@Mock
private SystemEnvironment systemEnvironment;
@Mock
private PluginExtensionsAndVersionValidator pluginExtensionsAndVersionValidator;
private FelixGoPluginOSGiFramework spy;
@BeforeEach
void setUp() {
initMocks(this);
FelixGoPluginOSGiFramework goPluginOSGiFramework = new FelixGoPluginOSGiFramework(registry, systemEnvironment) {
@Override
protected HashMap<String, String> generateOSGiFrameworkConfig() {
HashMap<String, String> config = super.generateOSGiFrameworkConfig();
config.put(FelixConstants.RESOLVER_PARALLELISM, "1");
return config;
}
};
spy = spy(goPluginOSGiFramework);
spy.setPluginExtensionsAndVersionValidator(pluginExtensionsAndVersionValidator);
when(framework.getBundleContext()).thenReturn(bundleContext);
when(registry.getPlugin(TEST_SYMBOLIC_NAME)).thenReturn(buildExpectedDescriptor(TEST_SYMBOLIC_NAME));
doReturn(framework).when(spy).getFelixFramework(any());
}
@AfterEach
void tearDown() {
spy.stop();
}
@Test
void shouldRegisterAnInstanceOfEachOfTheRequiredPluginServicesAfterOSGiFrameworkIsInitialized() {
spy.start();
verify(bundleContext).registerService(eq(PluginHealthService.class), any(DefaultPluginHealthService.class), isNull(Dictionary.class));
verify(bundleContext).registerService(eq(LoggingService.class), any(DefaultPluginLoggingService.class), isNull(Dictionary.class));
}
@Test
void doOnShouldRunAnActionOnSpecifiedPluginImplementationsOfAGivenInterface() throws Exception {
SomeInterface firstService = mock(SomeInterface.class);
SomeInterface secondService = mock(SomeInterface.class);
registerService(firstService, "plugin-one", "extension-one");
registerService(secondService, "plugin-two", "extension-two");
spy.start();
spy.doOn(SomeInterface.class, "plugin-two", "extension-two", (obj, pluginDescriptor) -> {
assertThat(pluginDescriptor).isEqualTo(buildExpectedDescriptor("plugin-two"));
return obj.someMethodWithReturn();
});
verify(firstService, never()).someMethodWithReturn();
verify(secondService).someMethodWithReturn();
verifyNoMoreInteractions(firstService, secondService);
}
@Test
void doOnShouldThrowAnExceptionWhenThereAreMultipleServicesWithSamePluginIdAndSameExtensionType_IdeallyThisShouldNotHappenInProductionSincePluginIdIsSymbolicName() throws Exception {
SomeInterface firstService = mock(SomeInterface.class);
SomeInterface secondService = mock(SomeInterface.class);
String symbolicName = "same_symbolic_name";
registerServicesWithSameSymbolicName(symbolicName, "test-extension", firstService, secondService);
spy.start();
try {
spy.doOn(SomeInterface.class, symbolicName, "test-extension", (obj, pluginDescriptor) -> {
assertThat(pluginDescriptor).isEqualTo(buildExpectedDescriptor(symbolicName));
return obj.someMethodWithReturn();
});
fail("Should throw plugin framework exception");
} catch (GoPluginFrameworkException ex) {
assertThat(ex.getMessage().startsWith("More than one reference found")).isTrue();
assertThat(ex.getMessage().contains(SomeInterface.class.getCanonicalName())).isTrue();
assertThat(ex.getMessage().contains(symbolicName)).isTrue();
}
verify(firstService, never()).someMethodWithReturn();
verify(secondService, never()).someMethodWithReturn();
verify(secondService, never()).someMethod();
verifyNoMoreInteractions(firstService, secondService);
}
@Test
void doOnShouldThrowAnExceptionWhenNoServicesAreFoundForTheGivenFilterAndServiceReference() throws Exception {
SomeInterface firstService = mock(SomeInterface.class);
SomeInterface secondService = mock(SomeInterface.class);
String symbolicName = "dummy_symbolic_name";
registerServicesWithSameSymbolicName(symbolicName, "test-extension", firstService, secondService);
spy.start();
try {
spy.doOn(SomeOtherInterface.class, symbolicName, "test-extension", (obj, pluginDescriptor) -> {
assertThat(pluginDescriptor).isEqualTo(buildExpectedDescriptor(symbolicName));
throw new RuntimeException("Should Not Be invoked");
});
fail("Should throw plugin framework exception");
} catch (GoPluginFrameworkException ex) {
assertThat(ex.getMessage().startsWith("No reference found")).isTrue();
assertThat(ex.getMessage().contains(SomeOtherInterface.class.getCanonicalName())).isTrue();
assertThat(ex.getMessage().contains(symbolicName)).isTrue();
}
verify(firstService, never()).someMethodWithReturn();
verify(secondService, never()).someMethodWithReturn();
verify(secondService, never()).someMethod();
verifyNoMoreInteractions(firstService, secondService);
}
@Test
void hasReferencesShouldReturnAppropriateValueIfSpecifiedPluginImplementationsOfAGivenInterfaceIsFoundOrNotFound() throws Exception {
SomeInterface firstService = mock(SomeInterface.class);
SomeInterface secondService = mock(SomeInterface.class);
spy.start();
boolean reference = spy.hasReferenceFor(SomeInterface.class, secondService.toString(), "extension-two");
assertThat(reference).isFalse();
registerService(firstService, "plugin-one", "extension-one");
registerService(secondService, "plugin-two", "extension-two");
reference = spy.hasReferenceFor(SomeInterface.class, "plugin-two", "extension-two");
assertThat(reference).isTrue();
verifyNoMoreInteractions(firstService, secondService);
}
@Test
void shouldUnloadAPlugin() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
when(pluginDescriptor.bundle()).thenReturn(bundle);
spy.unloadPlugin(pluginDescriptor);
verify(bundle, atLeastOnce()).stop();
verify(bundle, atLeastOnce()).uninstall();
}
@Test
void shouldNotFailToUnloadAPluginWhoseBundleIsNull() {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
when(pluginDescriptor.bundle()).thenReturn(null);
try {
spy.unloadPlugin(pluginDescriptor);
} catch (Exception e) {
fail("Should not have thrown an exception");
}
}
@Test
void shouldNotFailToUnloadAPluginWhenAPluginUnloadListenerFails() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
when(pluginDescriptor.bundle()).thenReturn(bundle);
PluginChangeListener listenerWhichThrowsWhenUnloading = mock(PluginChangeListener.class);
doThrow(new RuntimeException("Fail!")).when(listenerWhichThrowsWhenUnloading).pluginUnLoaded(pluginDescriptor);
spy.addPluginChangeListener(listenerWhichThrowsWhenUnloading);
spy.unloadPlugin(pluginDescriptor);
verify(bundle, times(1)).stop();
verify(bundle, times(1)).uninstall();
}
@Test
void shouldRunOtherUnloadListenersEvenIfOneFails() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
when(pluginDescriptor.bundle()).thenReturn(bundle);
PluginChangeListener listenerWhichWorks1 = mock(PluginChangeListener.class, "Listener Which Works: 1");
PluginChangeListener listenerWhichWorks2 = mock(PluginChangeListener.class, "Listener Which Works: 2");
PluginChangeListener listenerWhichThrowsWhenUnloading = mock(PluginChangeListener.class, "Listener Which Throws");
doThrow(new RuntimeException("Fail!")).when(listenerWhichThrowsWhenUnloading).pluginUnLoaded(pluginDescriptor);
spy.addPluginChangeListener(listenerWhichWorks1);
spy.addPluginChangeListener(listenerWhichThrowsWhenUnloading);
spy.addPluginChangeListener(listenerWhichWorks2);
spy.unloadPlugin(pluginDescriptor);
verify(listenerWhichWorks1, times(1)).pluginUnLoaded(pluginDescriptor);
verify(listenerWhichThrowsWhenUnloading, times(1)).pluginUnLoaded(pluginDescriptor);
verify(listenerWhichWorks2, times(1)).pluginUnLoaded(pluginDescriptor);
verify(bundle, times(1)).stop();
verify(bundle, times(1)).uninstall();
}
@Test
void shouldMarkThePluginAsInvalidIfAnyExceptionOccursAfterLoad() throws BundleException {
final Bundle bundle = mock(Bundle.class);
spy.addPluginChangeListener(new PluginChangeListener() {
@Override
public void pluginLoaded(GoPluginDescriptor pluginDescriptor) {
throw new RuntimeException("some error");
}
@Override
public void pluginUnLoaded(GoPluginDescriptor pluginDescriptor) {
}
});
when(bundleContext.installBundle(any(String.class))).thenReturn(bundle);
final GoPluginDescriptor goPluginDescriptor = new GoPluginDescriptor(TEST_SYMBOLIC_NAME, "1.0", null, "location", new File(""), false);
spy.start();
try {
spy.loadPlugin(goPluginDescriptor);
fail("should throw exception");
} catch (Exception e) {
assertThat(goPluginDescriptor.getStatus().isInvalid()).isTrue();
}
}
@Test
void shouldRegisterExtensionInfosWithPluginRegistry() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
final PluginExtensionsAndVersionValidator.ValidationResult result = mock(PluginExtensionsAndVersionValidator.ValidationResult.class);
when(pluginDescriptor.id()).thenReturn("some-id");
when(pluginDescriptor.bundle()).thenReturn(bundle);
when(pluginDescriptor.bundleLocation()).thenReturn(new File("foo"));
when(bundleContext.installBundle(any(String.class))).thenReturn(bundle);
when(pluginExtensionsAndVersionValidator.validate(pluginDescriptor)).thenReturn(result);
when(result.hasError()).thenReturn(false);
doReturn(singletonMap("elastic-agent", singletonList("1.0"))).when(spy).getExtensionsInfoFromThePlugin("some-id");
spy.start();
spy.loadPlugin(pluginDescriptor);
InOrder inOrder = inOrder(bundle, framework, registry, pluginExtensionsAndVersionValidator);
inOrder.verify(framework, times(2)).getBundleContext();
inOrder.verify(bundle).start();
inOrder.verify(registry).registerExtensions(pluginDescriptor, singletonMap("elastic-agent", singletonList("1.0")));
inOrder.verify(pluginExtensionsAndVersionValidator).validate(pluginDescriptor);
}
@Nested
class GetExtensionsInfoFromThePlugin {
@Test
void shouldGetExtensionsInfoForThePlugin() throws Exception {
when(registry.getPlugin(anyString())).thenReturn(mock(GoPluginDescriptor.class));
GoPlugin firstService = mock(GoPlugin.class);
GoPlugin secondService = mock(GoPlugin.class);
final GoPluginIdentifier firstPluginIdentifier = mock(GoPluginIdentifier.class);
when(firstService.pluginIdentifier()).thenReturn(firstPluginIdentifier);
when(firstPluginIdentifier.getExtension()).thenReturn("elastic-agent");
when(firstPluginIdentifier.getSupportedExtensionVersions()).thenReturn(asList("1.0", "2.0"));
final GoPluginIdentifier secondPluginIdentifier = mock(GoPluginIdentifier.class);
when(secondService.pluginIdentifier()).thenReturn(secondPluginIdentifier);
when(secondPluginIdentifier.getExtension()).thenReturn("authorization");
when(secondPluginIdentifier.getSupportedExtensionVersions()).thenReturn(singletonList("1.0"));
registerService("plugin-one", firstService, secondService);
spy.start();
final Map<String, List<String>> info = spy.getExtensionsInfoFromThePlugin("plugin-one");
assertThat(info).hasSize(2)
.containsEntry("elastic-agent", asList("1.0", "2.0"))
.containsEntry("authorization", singletonList("1.0"));
}
}
@Test
void shouldNotifyAllPluginChangeListenerOncePluginIsLoaded() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
final PluginExtensionsAndVersionValidator.ValidationResult result = mock(PluginExtensionsAndVersionValidator.ValidationResult.class);
when(pluginDescriptor.bundle()).thenReturn(bundle);
when(pluginDescriptor.bundleLocation()).thenReturn(new File("foo"));
when(bundleContext.installBundle(any(String.class))).thenReturn(bundle);
when(pluginExtensionsAndVersionValidator.validate(pluginDescriptor)).thenReturn(result);
when(result.hasError()).thenReturn(false);
PluginChangeListener listener1 = mock(PluginChangeListener.class);
PluginChangeListener listener2 = mock(PluginChangeListener.class);
PluginChangeListener listener3 = mock(PluginChangeListener.class);
spy.addPluginChangeListener(listener1);
spy.addPluginChangeListener(listener2);
spy.addPluginChangeListener(listener3);
spy.start();
spy.loadPlugin(pluginDescriptor);
verify(listener1, times(1)).pluginLoaded(pluginDescriptor);
verify(listener3, times(1)).pluginLoaded(pluginDescriptor);
verify(listener2, times(1)).pluginLoaded(pluginDescriptor);
verify(bundle, times(1)).start();
}
@Test
void shouldMarkPluginDescriptorInvalidAndNotNotifyPluginChangeListenersWhenExtensionVersionsRequiredByThePluginIsNotSupportedByGoCD() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
final PluginExtensionsAndVersionValidator.ValidationResult result = mock(PluginExtensionsAndVersionValidator.ValidationResult.class);
when(pluginDescriptor.bundle()).thenReturn(bundle);
when(pluginDescriptor.bundleLocation()).thenReturn(new File("foo"));
when(bundleContext.installBundle(any(String.class))).thenReturn(bundle);
when(pluginExtensionsAndVersionValidator.validate(pluginDescriptor)).thenReturn(result);
when(result.hasError()).thenReturn(true);
PluginChangeListener listener1 = mock(PluginChangeListener.class);
PluginChangeListener listener2 = mock(PluginChangeListener.class);
PluginChangeListener listener3 = mock(PluginChangeListener.class);
spy.addPluginChangeListener(listener1);
spy.addPluginChangeListener(listener2);
spy.addPluginChangeListener(listener3);
spy.start();
spy.loadPlugin(pluginDescriptor);
verifyZeroInteractions(listener1);
verifyZeroInteractions(listener3);
verifyZeroInteractions(listener2);
verify(bundle, times(1)).start();
verify(pluginDescriptor).markAsInvalid(anyList(), eq(null));
}
@Test
void shouldMigrateElasticAgentInformationAsPartOfMigrateConfigurationCall() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
ElasticAgentInformationMigrator migrator = mock(ElasticAgentInformationMigrator.class);
when(migrator.migrate(any())).thenReturn(true);
spy.setElasticAgentInformationMigrator(migrator);
boolean migratedSuccessfully = spy.migrateConfig(pluginDescriptor);
assertThat(migratedSuccessfully).isTrue();
verify(migrator, times(1)).migrate(pluginDescriptor);
}
@Test
void shouldReturnWhetherMigrationSuccessStatus() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
ElasticAgentInformationMigrator migrator = mock(ElasticAgentInformationMigrator.class);
when(migrator.migrate(any())).thenReturn(false);
spy.setElasticAgentInformationMigrator(migrator);
boolean migratedSuccessfully = spy.migrateConfig(pluginDescriptor);
assertThat(migratedSuccessfully).isFalse();
verify(migrator, times(1)).migrate(pluginDescriptor);
}
@Test
void shouldNotMigrateElasticAgentInformationWhenNoMigratorIsSpecified() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
ElasticAgentInformationMigrator migrator = mock(ElasticAgentInformationMigrator.class);
boolean migratedSuccessfully = spy.migrateConfig(pluginDescriptor);
assertThat(migratedSuccessfully).isTrue();
verifyNoMoreInteractions(migrator);
}
@Test
void shouldSkipUninstallIfPluginIsPreviouslyUninstalled() throws BundleException {
GoPluginDescriptor pluginDescriptor = mock(GoPluginDescriptor.class);
when(pluginDescriptor.bundle()).thenReturn(bundle);
when(bundle.getState()).thenReturn(Bundle.UNINSTALLED);
spy.unloadPlugin(pluginDescriptor);
verify(bundle, never()).start();
verify(bundle, never()).uninstall();
}
private void registerServicesWithSameSymbolicName(String symbolicName, String extensionType, SomeInterface... someInterfaces) throws InvalidSyntaxException {
ArrayList<ServiceReference<SomeInterface>> references = new ArrayList<>();
for (SomeInterface someInterface : someInterfaces) {
ServiceReference<SomeInterface> reference = mock(ServiceReference.class);
Bundle bundle = mock(Bundle.class);
when(reference.getBundle()).thenReturn(bundle);
when(bundle.getSymbolicName()).thenReturn(symbolicName);
when(bundleContext.getService(reference)).thenReturn(someInterface);
references.add(reference);
}
String propertyFormat = String.format("(&(%s=%s)(%s=%s))", Constants.BUNDLE_SYMBOLICNAME, symbolicName, Constants.BUNDLE_CATEGORY, extensionType);
when(bundleContext.getServiceReferences(SomeInterface.class, propertyFormat)).thenReturn(references);
when(registry.getPlugin(symbolicName)).thenReturn(buildExpectedDescriptor(symbolicName));
}
private void registerService(SomeInterface someInterface, String pluginID, String extension) throws InvalidSyntaxException {
ServiceReference<SomeInterface> reference = mock(ServiceReference.class);
when(reference.getBundle()).thenReturn(bundle);
when(bundle.getSymbolicName()).thenReturn(pluginID);
when(bundleContext.getService(reference)).thenReturn(someInterface);
when(registry.getPlugin(pluginID)).thenReturn(buildExpectedDescriptor(pluginID));
String propertyFormat = String.format("(&(%s=%s)(%s=%s))", Constants.BUNDLE_SYMBOLICNAME, pluginID, Constants.BUNDLE_CATEGORY, extension);
when(bundleContext.getServiceReferences(SomeInterface.class, propertyFormat)).thenReturn(singletonList(reference));
when(bundleContext.getServiceReferences(SomeInterface.class, null)).thenReturn(singletonList(reference));
}
private void registerService(String pluginID, GoPlugin... someInterfaces) throws InvalidSyntaxException {
final List<ServiceReference<GoPlugin>> serviceReferences = Arrays.stream(someInterfaces).map(someInterface -> {
ServiceReference<GoPlugin> reference = mock(ServiceReference.class);
when(reference.getBundle()).thenReturn(bundle);
when(bundle.getSymbolicName()).thenReturn(pluginID);
when(bundleContext.getService(reference)).thenReturn(someInterface);
when(registry.getPlugin(pluginID)).thenReturn(buildExpectedDescriptor(pluginID));
return reference;
}).collect(Collectors.toList());
String propertyFormat = String.format("(&(%s=%s))", Constants.BUNDLE_SYMBOLICNAME, pluginID);
when(bundleContext.getServiceReferences(GoPlugin.class, propertyFormat)).thenReturn(serviceReferences);
}
private GoPluginDescriptor buildExpectedDescriptor(String pluginID) {
return new GoPluginDescriptor(pluginID, "1",
new GoPluginDescriptor.About("Plugin Descriptor Validator", "1.0.1", "17.12", "Validates its own plugin descriptor",
new GoPluginDescriptor.Vendor("ThoughtWorks GoCD Team", "www.thoughtworks.com"), asList("Linux", "Windows")), null, null, true
);
}
private interface SomeInterface {
void someMethod();
Object someMethodWithReturn();
}
private interface SomeOtherInterface {
}
}
| 23,206 | 0.724726 | 0.721408 | 496 | 45.786289 | 39.061661 | 186 | false | false | 0 | 0 | 0 | 0 | 126 | 0.032836 | 0.802419 | false | false | 4 |
97f34524c8b6b07c970c3ed99c89b2c5c67db131 | 4,380,866,658,376 | 4409cf4612add52f52f655b25970faa1fe8b5759 | /src/main/java/br/com/communicart/backendserver/service/PessoaFisicaService.java | 43e6dfd513c37d8a587e42e1e8571256827fa9c2 | [] | no_license | arthurdias-trad/communicart-backend-server | https://github.com/arthurdias-trad/communicart-backend-server | 45327d22ac9ae0f41e1c2c5bcea5a0d3abbc4203 | b70dcebf5b49669202a2c51cf565840c84a293df | refs/heads/master | 2023-01-23T14:03:07.531000 | 2020-12-02T12:28:54 | 2020-12-02T12:28:54 | 305,465,623 | 0 | 1 | null | false | 2020-12-02T12:28:55 | 2020-10-19T17:40:32 | 2020-12-02T03:36:33 | 2020-12-02T12:28:55 | 322 | 0 | 1 | 0 | Java | false | false | package br.com.communicart.backendserver.service;
import javax.validation.Valid;
import org.springframework.stereotype.Service;
import br.com.communicart.backendserver.model.entity.PessoaFisica;
import br.com.communicart.backendserver.repository.PessoaFisicaRepository;
import lombok.AllArgsConstructor;
@Service
@AllArgsConstructor
public class PessoaFisicaService {
private final PessoaFisicaRepository pessoaFisicaRepository;
public PessoaFisica create(@Valid PessoaFisica pessoaFisica) {
return this.pessoaFisicaRepository.save(pessoaFisica);
}
}
| UTF-8 | Java | 564 | java | PessoaFisicaService.java | Java | [] | null | [] | package br.com.communicart.backendserver.service;
import javax.validation.Valid;
import org.springframework.stereotype.Service;
import br.com.communicart.backendserver.model.entity.PessoaFisica;
import br.com.communicart.backendserver.repository.PessoaFisicaRepository;
import lombok.AllArgsConstructor;
@Service
@AllArgsConstructor
public class PessoaFisicaService {
private final PessoaFisicaRepository pessoaFisicaRepository;
public PessoaFisica create(@Valid PessoaFisica pessoaFisica) {
return this.pessoaFisicaRepository.save(pessoaFisica);
}
}
| 564 | 0.845745 | 0.845745 | 20 | 27.200001 | 26.415148 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 4 |
b4294f9bb499b76eb6d427f802816193dc951edb | 10,591,389,420,983 | e3e9687ae836a631b423b570027a9184fed248ec | /src/main/java/at/ac/uibk/dps/biohadoop/algorithms/nsgaii/algorithm/NsgaII.java | 9fd0807b67eb7a549f3ee0e852852d18b027951d | [] | no_license | Rasemi86/biohadoop-algorithms | https://github.com/Rasemi86/biohadoop-algorithms | c2f0775618df9d510c6fd7cde60915bf55ad9a2a | fc4c923649846aba7dcd579db2dfede1b5164626 | refs/heads/master | 2021-01-22T04:14:39.481000 | 2015-03-11T17:57:51 | 2015-03-11T17:57:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package at.ac.uibk.dps.biohadoop.algorithms.nsgaii.algorithm;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import at.ac.uibk.dps.biohadoop.algorithm.Algorithm;
import at.ac.uibk.dps.biohadoop.algorithm.AlgorithmException;
import at.ac.uibk.dps.biohadoop.algorithm.AlgorithmId;
import at.ac.uibk.dps.biohadoop.algorithm.AlgorithmService;
import at.ac.uibk.dps.biohadoop.algorithms.nsgaii.algorithm.async.TaskPool;
import at.ac.uibk.dps.biohadoop.hadoop.Environment;
import at.ac.uibk.dps.biohadoop.hadoop.launcher.WorkerParametersResolver;
import at.ac.uibk.dps.biohadoop.tasksystem.queue.TaskFuture;
public class NsgaII implements Algorithm {
public static final String GENOME_SIZE = "GENOME_SIZE";
public static final String MAX_ITERATIONS = "MAX_ITERATIONS";
public static final String POPULATION_SIZE = "POPULATION_SIZE";
public static final String FUNCTION_CLASS = "FUNCTION_CLASS";
public static final String SBX_DISTRIBUTION_FACTOR = "SBX_DISTRIBUTION_FACTOR";
public static final String MUTATION_FACTOR = "MUTATION_FACTOR";
public static final String ASYNC = "ASYNC";
private static final Logger LOG = LoggerFactory.getLogger(NsgaII.class);
private static final int LOG_STEPS = 100;
@Override
public void run(AlgorithmId solverId, Map<String, String> properties)
throws AlgorithmException {
long algorithmStartTime = System.nanoTime();
long biohadoopStartupTime = Long.parseLong(Environment
.get(Environment.BIOHADOOP_START_AT_NS));
LOG.info(
"Starting NSGA-II at System.nanoTime()={}, Biohadoop startup took {}ns",
algorithmStartTime, algorithmStartTime - biohadoopStartupTime);
Preparation prep = new Preparation(properties);
int persitedIteration = 0;
double[][] population = initializePopulation(prep.getPopSize() * 2,
prep.getGenomeSize());
double[][] objectiveValues = new double[prep.getPopSize() * 2][2];
// Initialization: compute front for initial population
List<List<Integer>> fronts = FastNonDominatedSort.sort(Arrays.copyOf(
objectiveValues, prep.getPopSize()));
// Initialization: start task pool
int workerCount = Integer.parseInt(Environment.get(Environment.WORKER_COUNT));
TaskPool pool = new TaskPool(prep.getTaskSubmitter(), 3 * workerCount);
pool.update(population, objectiveValues, fronts);
pool.start();
// Initialization: create children from initial population and compute
// objective values for them. The children overwrite the initial
// population
List<TaskFuture<Individual>> offsprings = new ArrayList<>();
if (prep.isAsync()) {
// Asynchronous generational GA
for (int i = 0; i < prep.getPopSize(); i++) {
Individual individual = pool.getFinishedIndividual();
population[i] = individual.getIndividual();
objectiveValues[i] = individual.getObjectives();
}
} else {
// Synchronous generational GA
Random rand = new Random();
for (int i = 0; i < prep.getPopSize(); i++) {
double[][] parents = new double[2][];
parents[0] = population[rand.nextInt(prep.getPopSize())];
parents[1] = population[rand.nextInt(prep.getPopSize())];
TaskFuture<Individual> offspring = prep.getTaskSubmitter().add(
parents);
offsprings.add(offspring);
}
for (int i = 0; i < prep.getPopSize(); i++) {
population[i] = offsprings.get(i).get().getIndividual();
objectiveValues[i] = offsprings.get(i).get().getObjectives();
}
}
fronts = FastNonDominatedSort.sort(Arrays.copyOf(
objectiveValues, prep.getPopSize()));
// Initialization finished
LOG.info("Algorithm initialisation until main loop took {}ns",
System.nanoTime() - algorithmStartTime);
long fullWorkerTime = 0;
long loopStartTime = System.nanoTime();
// Start algorithm
long singleIterationTime = System.nanoTime();
int iteration = 0;
boolean end = false;
while (!end) {
long workerStartTime = System.nanoTime();
offsprings.clear();
if (prep.isAsync()) {
// Asynchronous generational GA
pool.update(population, objectiveValues, fronts);
for (int i = 0; i < prep.getPopSize(); i++) {
Individual individual = pool.getFinishedIndividual();
population[i + prep.getPopSize()] = individual
.getIndividual();
objectiveValues[i + prep.getPopSize()] = individual
.getObjectives();
}
} else {
// Synchronous generational GA
for (int i = 0; i < prep.getPopSize(); i++) {
int[] parentIndexes = parentSelectionTournament(fronts,
objectiveValues);
double[][] parents = new double[2][];
parents[0] = population[parentIndexes[0]];
parents[1] = population[parentIndexes[1]];
TaskFuture<Individual> offspring = prep.getTaskSubmitter()
.add(parents);
offsprings.add(offspring);
}
for (int i = 0; i < prep.getPopSize(); i++) {
population[i + prep.getPopSize()] = offsprings.get(i).get()
.getIndividual();
objectiveValues[i + prep.getPopSize()] = offsprings.get(i)
.get().getObjectives();
}
}
fullWorkerTime += System.nanoTime() - workerStartTime;
fronts = FastNonDominatedSort.sort(objectiveValues);
double[][] newPopulation = new double[prep.getPopSize() * 2][prep
.getGenomeSize()];
double[][] newObjectiveValues = new double[prep.getPopSize() * 2][prep
.getGenomeSize()];
int currentRank = 0;
int newPopSize = 0;
while (newPopSize < prep.getPopSize()) {
List<Integer> front = fronts.get(currentRank);
// if there is place enough for a complete rank, just insert it
if (newPopSize + front.size() <= prep.getPopSize()) {
for (int individualIndex : front) {
newPopulation[newPopSize] = population[individualIndex];
newObjectiveValues[newPopSize] = objectiveValues[individualIndex];
newPopSize++;
}
}
// if there is not enough place, use crowding distance to choose
// best solutions from current front
else {
CrowdingDistance.sortFrontAccordingToCrowdingDistance(
front, objectiveValues);
int missingElements = prep.getPopSize() - newPopSize;
for (int i = 0; i < missingElements; i++) {
newPopulation[newPopSize] = population[front.get(i)];
newObjectiveValues[newPopSize] = objectiveValues[front
.get(i)];
newPopSize++;
}
}
currentRank++;
}
population = newPopulation;
objectiveValues = newObjectiveValues;
iteration++;
// By setting the progress here, we inform Biohadoop and Hadoop
// about the current progress
AlgorithmService.setProgress(solverId,
(float) iteration / prep.getIterations());
// Check for end condition
if (iteration >= prep.getIterations()) {
end = true;
}
if (iteration % 100 == 0) {
long endTime = System.nanoTime();
LOG.info("Counter: {} | last {} NSGAII iterations took {} ns",
iteration + persitedIteration, LOG_STEPS, endTime
- singleIterationTime);
singleIterationTime = endTime;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < prep.getPopSize(); i++) {
System.out.println(objectiveValues[i][0] + " "
+ objectiveValues[i][1]);
sb.append(objectiveValues[i][0] + " " + objectiveValues[i][1]
+ "\n");
}
// try {
// Files.write(Paths.get("/tmp/data.out"), sb.toString().getBytes());
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
long fullAlgorithmTime = System.nanoTime() - algorithmStartTime;
long fullLoopTime = System.nanoTime() - loopStartTime;
int workerSize = WorkerParametersResolver.getWorkerParameters().size();
prep.logProperties();
LOG.info("Async={}", prep.isAsync());
LOG.info("Workers={}", workerSize);
LOG.info("Iterations={}", prep.getIterations());
LOG.info("Algorithm run time {}ns", fullAlgorithmTime);
LOG.info("Time spent in main loop {}ns", fullLoopTime);
LOG.info("Worker time {}ns", fullWorkerTime);
LOG.info("Iteration time parseable ({} {})", workerSize,
String.format("%.3f", fullLoopTime / 1e9));
LOG.info(
"Iterations per second ({} {})",
workerSize,
String.format("%.3f", prep.getIterations()
/ (fullLoopTime / 1e9)));
LOG.info("-----------------------");
}
// Initialize population, where first half (of size populationSize) is
// filled with random numbers, and second half is initialized with
// zeros. second half contains offsprings
private double[][] initializePopulation(int populationSize, int genomeSize) {
Random rand = new Random();
double[][] population = new double[populationSize][genomeSize];
for (int i = 0; i < populationSize / 2; i++) {
for (int j = 0; j < genomeSize; j++) {
population[i][j] = rand.nextDouble();
}
}
return population;
}
private int[] parentSelectionTournament(final List<List<Integer>> fronts,
double[][] objectives) {
Random rand = new Random();
int[] parents = new int[2];
for (int i = 0; i < 2; i++) {
int p1Index = rand.nextInt(objectives.length / 2);
int p2Index = rand.nextInt(objectives.length / 2);
int p1Front = getFront(fronts, p1Index);
int p2Front = getFront(fronts, p2Index);
if (p1Front < p2Front) {
parents[i] = p1Index;
} else if (p1Front > p2Front) {
parents[i] = p2Index;
} else {
List<Integer> front = fronts.get(p1Front);
CrowdingDistance.sortFrontAccordingToCrowdingDistance(front,
objectives);
if (front.indexOf(p1Index) < front.indexOf(p2Index)) {
parents[i] = p1Index;
} else {
parents[i] = p2Index;
}
}
}
return parents;
}
private int getFront(List<List<Integer>> fronts, int index) {
for (int i = 0; i < fronts.size(); i++) {
if (fronts.get(i).contains(index)) {
return i;
}
}
throw new RuntimeException("Kacke");
}
} | UTF-8 | Java | 9,959 | java | NsgaII.java | Java | [] | null | [] | package at.ac.uibk.dps.biohadoop.algorithms.nsgaii.algorithm;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import at.ac.uibk.dps.biohadoop.algorithm.Algorithm;
import at.ac.uibk.dps.biohadoop.algorithm.AlgorithmException;
import at.ac.uibk.dps.biohadoop.algorithm.AlgorithmId;
import at.ac.uibk.dps.biohadoop.algorithm.AlgorithmService;
import at.ac.uibk.dps.biohadoop.algorithms.nsgaii.algorithm.async.TaskPool;
import at.ac.uibk.dps.biohadoop.hadoop.Environment;
import at.ac.uibk.dps.biohadoop.hadoop.launcher.WorkerParametersResolver;
import at.ac.uibk.dps.biohadoop.tasksystem.queue.TaskFuture;
public class NsgaII implements Algorithm {
public static final String GENOME_SIZE = "GENOME_SIZE";
public static final String MAX_ITERATIONS = "MAX_ITERATIONS";
public static final String POPULATION_SIZE = "POPULATION_SIZE";
public static final String FUNCTION_CLASS = "FUNCTION_CLASS";
public static final String SBX_DISTRIBUTION_FACTOR = "SBX_DISTRIBUTION_FACTOR";
public static final String MUTATION_FACTOR = "MUTATION_FACTOR";
public static final String ASYNC = "ASYNC";
private static final Logger LOG = LoggerFactory.getLogger(NsgaII.class);
private static final int LOG_STEPS = 100;
@Override
public void run(AlgorithmId solverId, Map<String, String> properties)
throws AlgorithmException {
long algorithmStartTime = System.nanoTime();
long biohadoopStartupTime = Long.parseLong(Environment
.get(Environment.BIOHADOOP_START_AT_NS));
LOG.info(
"Starting NSGA-II at System.nanoTime()={}, Biohadoop startup took {}ns",
algorithmStartTime, algorithmStartTime - biohadoopStartupTime);
Preparation prep = new Preparation(properties);
int persitedIteration = 0;
double[][] population = initializePopulation(prep.getPopSize() * 2,
prep.getGenomeSize());
double[][] objectiveValues = new double[prep.getPopSize() * 2][2];
// Initialization: compute front for initial population
List<List<Integer>> fronts = FastNonDominatedSort.sort(Arrays.copyOf(
objectiveValues, prep.getPopSize()));
// Initialization: start task pool
int workerCount = Integer.parseInt(Environment.get(Environment.WORKER_COUNT));
TaskPool pool = new TaskPool(prep.getTaskSubmitter(), 3 * workerCount);
pool.update(population, objectiveValues, fronts);
pool.start();
// Initialization: create children from initial population and compute
// objective values for them. The children overwrite the initial
// population
List<TaskFuture<Individual>> offsprings = new ArrayList<>();
if (prep.isAsync()) {
// Asynchronous generational GA
for (int i = 0; i < prep.getPopSize(); i++) {
Individual individual = pool.getFinishedIndividual();
population[i] = individual.getIndividual();
objectiveValues[i] = individual.getObjectives();
}
} else {
// Synchronous generational GA
Random rand = new Random();
for (int i = 0; i < prep.getPopSize(); i++) {
double[][] parents = new double[2][];
parents[0] = population[rand.nextInt(prep.getPopSize())];
parents[1] = population[rand.nextInt(prep.getPopSize())];
TaskFuture<Individual> offspring = prep.getTaskSubmitter().add(
parents);
offsprings.add(offspring);
}
for (int i = 0; i < prep.getPopSize(); i++) {
population[i] = offsprings.get(i).get().getIndividual();
objectiveValues[i] = offsprings.get(i).get().getObjectives();
}
}
fronts = FastNonDominatedSort.sort(Arrays.copyOf(
objectiveValues, prep.getPopSize()));
// Initialization finished
LOG.info("Algorithm initialisation until main loop took {}ns",
System.nanoTime() - algorithmStartTime);
long fullWorkerTime = 0;
long loopStartTime = System.nanoTime();
// Start algorithm
long singleIterationTime = System.nanoTime();
int iteration = 0;
boolean end = false;
while (!end) {
long workerStartTime = System.nanoTime();
offsprings.clear();
if (prep.isAsync()) {
// Asynchronous generational GA
pool.update(population, objectiveValues, fronts);
for (int i = 0; i < prep.getPopSize(); i++) {
Individual individual = pool.getFinishedIndividual();
population[i + prep.getPopSize()] = individual
.getIndividual();
objectiveValues[i + prep.getPopSize()] = individual
.getObjectives();
}
} else {
// Synchronous generational GA
for (int i = 0; i < prep.getPopSize(); i++) {
int[] parentIndexes = parentSelectionTournament(fronts,
objectiveValues);
double[][] parents = new double[2][];
parents[0] = population[parentIndexes[0]];
parents[1] = population[parentIndexes[1]];
TaskFuture<Individual> offspring = prep.getTaskSubmitter()
.add(parents);
offsprings.add(offspring);
}
for (int i = 0; i < prep.getPopSize(); i++) {
population[i + prep.getPopSize()] = offsprings.get(i).get()
.getIndividual();
objectiveValues[i + prep.getPopSize()] = offsprings.get(i)
.get().getObjectives();
}
}
fullWorkerTime += System.nanoTime() - workerStartTime;
fronts = FastNonDominatedSort.sort(objectiveValues);
double[][] newPopulation = new double[prep.getPopSize() * 2][prep
.getGenomeSize()];
double[][] newObjectiveValues = new double[prep.getPopSize() * 2][prep
.getGenomeSize()];
int currentRank = 0;
int newPopSize = 0;
while (newPopSize < prep.getPopSize()) {
List<Integer> front = fronts.get(currentRank);
// if there is place enough for a complete rank, just insert it
if (newPopSize + front.size() <= prep.getPopSize()) {
for (int individualIndex : front) {
newPopulation[newPopSize] = population[individualIndex];
newObjectiveValues[newPopSize] = objectiveValues[individualIndex];
newPopSize++;
}
}
// if there is not enough place, use crowding distance to choose
// best solutions from current front
else {
CrowdingDistance.sortFrontAccordingToCrowdingDistance(
front, objectiveValues);
int missingElements = prep.getPopSize() - newPopSize;
for (int i = 0; i < missingElements; i++) {
newPopulation[newPopSize] = population[front.get(i)];
newObjectiveValues[newPopSize] = objectiveValues[front
.get(i)];
newPopSize++;
}
}
currentRank++;
}
population = newPopulation;
objectiveValues = newObjectiveValues;
iteration++;
// By setting the progress here, we inform Biohadoop and Hadoop
// about the current progress
AlgorithmService.setProgress(solverId,
(float) iteration / prep.getIterations());
// Check for end condition
if (iteration >= prep.getIterations()) {
end = true;
}
if (iteration % 100 == 0) {
long endTime = System.nanoTime();
LOG.info("Counter: {} | last {} NSGAII iterations took {} ns",
iteration + persitedIteration, LOG_STEPS, endTime
- singleIterationTime);
singleIterationTime = endTime;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < prep.getPopSize(); i++) {
System.out.println(objectiveValues[i][0] + " "
+ objectiveValues[i][1]);
sb.append(objectiveValues[i][0] + " " + objectiveValues[i][1]
+ "\n");
}
// try {
// Files.write(Paths.get("/tmp/data.out"), sb.toString().getBytes());
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
long fullAlgorithmTime = System.nanoTime() - algorithmStartTime;
long fullLoopTime = System.nanoTime() - loopStartTime;
int workerSize = WorkerParametersResolver.getWorkerParameters().size();
prep.logProperties();
LOG.info("Async={}", prep.isAsync());
LOG.info("Workers={}", workerSize);
LOG.info("Iterations={}", prep.getIterations());
LOG.info("Algorithm run time {}ns", fullAlgorithmTime);
LOG.info("Time spent in main loop {}ns", fullLoopTime);
LOG.info("Worker time {}ns", fullWorkerTime);
LOG.info("Iteration time parseable ({} {})", workerSize,
String.format("%.3f", fullLoopTime / 1e9));
LOG.info(
"Iterations per second ({} {})",
workerSize,
String.format("%.3f", prep.getIterations()
/ (fullLoopTime / 1e9)));
LOG.info("-----------------------");
}
// Initialize population, where first half (of size populationSize) is
// filled with random numbers, and second half is initialized with
// zeros. second half contains offsprings
private double[][] initializePopulation(int populationSize, int genomeSize) {
Random rand = new Random();
double[][] population = new double[populationSize][genomeSize];
for (int i = 0; i < populationSize / 2; i++) {
for (int j = 0; j < genomeSize; j++) {
population[i][j] = rand.nextDouble();
}
}
return population;
}
private int[] parentSelectionTournament(final List<List<Integer>> fronts,
double[][] objectives) {
Random rand = new Random();
int[] parents = new int[2];
for (int i = 0; i < 2; i++) {
int p1Index = rand.nextInt(objectives.length / 2);
int p2Index = rand.nextInt(objectives.length / 2);
int p1Front = getFront(fronts, p1Index);
int p2Front = getFront(fronts, p2Index);
if (p1Front < p2Front) {
parents[i] = p1Index;
} else if (p1Front > p2Front) {
parents[i] = p2Index;
} else {
List<Integer> front = fronts.get(p1Front);
CrowdingDistance.sortFrontAccordingToCrowdingDistance(front,
objectives);
if (front.indexOf(p1Index) < front.indexOf(p2Index)) {
parents[i] = p1Index;
} else {
parents[i] = p2Index;
}
}
}
return parents;
}
private int getFront(List<List<Integer>> fronts, int index) {
for (int i = 0; i < fronts.size(); i++) {
if (fronts.get(i).contains(index)) {
return i;
}
}
throw new RuntimeException("Kacke");
}
} | 9,959 | 0.683502 | 0.676273 | 289 | 33.463669 | 23.596806 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.342561 | false | false | 4 |
2e664caaa9ae981330433aa4f20c2e0d47866c5c | 35,656,818,522,715 | 99e148f4fd32e5b8de5c575850ce8865865f12d3 | /BOJ_6588_골드바흐의추측_200810.java | bdb4077fcfc616380c9d9abdfd254bbf513a3973 | [] | no_license | rhdrlvnd/Algorithm_Solution | https://github.com/rhdrlvnd/Algorithm_Solution | 51da010a8ae0540a8519a2750452ec856a73e7e6 | 0a9ed2300f446758ce59b8c93457d93390675080 | refs/heads/master | 2021-08-22T03:09:13.996000 | 2021-06-28T04:42:28 | 2021-06-28T04:42:28 | 205,793,910 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ssafy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BOJ_6588_골드바흐의추측_200810 {
static int[] arr = new int[1000001];
static int N;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
makeArr();
while (true) {
N = Integer.parseInt(br.readLine());
if (N == 0)
break;
check(N);
}
}
public static void makeArr() {
for (int i = 2; i < 1000000; i++) {
int now = i;
if (arr[i] != 1) {
while (true) {
if(now+i <1000000) {
now += i;
arr[now] = 1;
}else
break;
}
}
}
}
public static void check(int n) {
for (int i = 3; i < 500000; i++) {
if (arr[i] == 0) {
if (arr[n - i] == 0) {
System.out.println(n + " = " + i + " + " + (n - i));
return;
}
}
}
}
}
| UTF-8 | Java | 922 | java | BOJ_6588_골드바흐의추측_200810.java | Java | [] | null | [] | package com.ssafy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BOJ_6588_골드바흐의추측_200810 {
static int[] arr = new int[1000001];
static int N;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
makeArr();
while (true) {
N = Integer.parseInt(br.readLine());
if (N == 0)
break;
check(N);
}
}
public static void makeArr() {
for (int i = 2; i < 1000000; i++) {
int now = i;
if (arr[i] != 1) {
while (true) {
if(now+i <1000000) {
now += i;
arr[now] = 1;
}else
break;
}
}
}
}
public static void check(int n) {
for (int i = 3; i < 500000; i++) {
if (arr[i] == 0) {
if (arr[n - i] == 0) {
System.out.println(n + " = " + i + " + " + (n - i));
return;
}
}
}
}
}
| 922 | 0.552863 | 0.504405 | 50 | 17.16 | 17.188787 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.54 | false | false | 4 |
3531fd4df3fee41fc13f39976b948026b7dcf16d | 24,481,313,606,083 | ac23b9e4ea5217f591b0fa6fa7d59409a6280a48 | /trunk/process/info/src/test/net/osm/process/info/WorkspaceTestCase.java | 37b56dbcd797f1db109e71331c45b7fed654fc76 | [] | no_license | BackupTheBerlios/osm-svn | https://github.com/BackupTheBerlios/osm-svn | f8acbce0f132342f6568bbd34ffce50d312a1086 | b7b47ee0ea8645d5c5b2241bda32119ca8020ff4 | refs/heads/master | 2021-01-01T06:50:16.703000 | 2009-10-18T23:07:30 | 2009-10-18T23:07:30 | 40,776,406 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2006 Stephen J. McConnell
*
* 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 net.osm.process.info;
import java.io.File;
import net.dpml.util.DOM3DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import junit.framework.TestCase;
/**
* The ProcessXsdTestCase class validates a process XML schema instance.
*
* @author <a href="http://www.dpml.net">The Digital Product Meta Library</a>
*/
public class WorkspaceTestCase extends TestCase
{
private static final String XSD_URI = "@PROJECT-XSD-URI@";
private WorkspaceDirective m_workspace;
/**
* Testcase setup.
* @exception Exception if an error occursduring testcase setup
*/
public void setUp() throws Exception
{
// get the sample xml file to parse
File testdir = new File( System.getProperty( "project.test.dir" ) );
File doc = new File( testdir, "workspace.xml" );
// define a system property declaring the location of the source xsd
File basedir = new File( System.getProperty( "project.basedir" ) );
File target = new File( basedir, "target" );
//File deliverables = new File( target, "deliverables" );
//File xsds = new File( deliverables, "xsds" );
//String version = System.getProperty( "project.version" );
File xsd = new File( target, "process.xsd" );
System.setProperty( XSD_URI, xsd.toURI().toString() );
// parse the layout file
DOM3DocumentBuilder builder = new DOM3DocumentBuilder();
Document document = builder.parse( doc.toURI() );
Element element = document.getDocumentElement();
// setup the layout directive
WorkspaceDecoder decoder = new WorkspaceDecoder();
m_workspace = decoder.build( doc );
}
/**
* Test worksace creation.
* @exception Exception if an error occurs during test execution
*/
public void testWorkspace() throws Exception
{
System.out.println( "# WORKSPACE " + m_workspace.getName() );
ProductDirective[] products = m_workspace.getProductDirectives();
for( int i=0; i<products.length; i++ )
{
ProductDirective product = products[i];
System.out.print( "# " + product.getName() );
if( product instanceof DirectoryDirective )
{
DirectoryDirective dir = (DirectoryDirective) product;
System.out.println( "\t" + dir.getPath() );
}
else
{
System.out.println( "" );
}
}
assertEquals( "count", 7, products.length );
}
/**
* Test worksace lookup.
* @exception Exception if an error occurs during test execution
*/
public void testLookup() throws Exception
{
System.out.println( "# LOOKUP " + m_workspace.getName() );
ProductDirective product = m_workspace.getProductDirective( "target/reports/test" );
System.out.println( "# TEST " + product.getName() );
}
}
| UTF-8 | Java | 3,755 | java | WorkspaceTestCase.java | Java | [
{
"context": "/*\r\n * Copyright 2006 Stephen J. McConnell\r\n *\r\n * Licensed under the Apache License, Ver",
"end": 42,
"score": 0.9996839165687561,
"start": 22,
"tag": "NAME",
"value": "Stephen J. McConnell"
}
] | null | [] | /*
* Copyright 2006 <NAME>
*
* 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 net.osm.process.info;
import java.io.File;
import net.dpml.util.DOM3DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import junit.framework.TestCase;
/**
* The ProcessXsdTestCase class validates a process XML schema instance.
*
* @author <a href="http://www.dpml.net">The Digital Product Meta Library</a>
*/
public class WorkspaceTestCase extends TestCase
{
private static final String XSD_URI = "@PROJECT-XSD-URI@";
private WorkspaceDirective m_workspace;
/**
* Testcase setup.
* @exception Exception if an error occursduring testcase setup
*/
public void setUp() throws Exception
{
// get the sample xml file to parse
File testdir = new File( System.getProperty( "project.test.dir" ) );
File doc = new File( testdir, "workspace.xml" );
// define a system property declaring the location of the source xsd
File basedir = new File( System.getProperty( "project.basedir" ) );
File target = new File( basedir, "target" );
//File deliverables = new File( target, "deliverables" );
//File xsds = new File( deliverables, "xsds" );
//String version = System.getProperty( "project.version" );
File xsd = new File( target, "process.xsd" );
System.setProperty( XSD_URI, xsd.toURI().toString() );
// parse the layout file
DOM3DocumentBuilder builder = new DOM3DocumentBuilder();
Document document = builder.parse( doc.toURI() );
Element element = document.getDocumentElement();
// setup the layout directive
WorkspaceDecoder decoder = new WorkspaceDecoder();
m_workspace = decoder.build( doc );
}
/**
* Test worksace creation.
* @exception Exception if an error occurs during test execution
*/
public void testWorkspace() throws Exception
{
System.out.println( "# WORKSPACE " + m_workspace.getName() );
ProductDirective[] products = m_workspace.getProductDirectives();
for( int i=0; i<products.length; i++ )
{
ProductDirective product = products[i];
System.out.print( "# " + product.getName() );
if( product instanceof DirectoryDirective )
{
DirectoryDirective dir = (DirectoryDirective) product;
System.out.println( "\t" + dir.getPath() );
}
else
{
System.out.println( "" );
}
}
assertEquals( "count", 7, products.length );
}
/**
* Test worksace lookup.
* @exception Exception if an error occurs during test execution
*/
public void testLookup() throws Exception
{
System.out.println( "# LOOKUP " + m_workspace.getName() );
ProductDirective product = m_workspace.getProductDirective( "target/reports/test" );
System.out.println( "# TEST " + product.getName() );
}
}
| 3,741 | 0.607989 | 0.603995 | 109 | 32.449543 | 27.214231 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.440367 | false | false | 4 |
ed015a4e48a9a8c4cf167d375864a720f3e902d1 | 39,195,871,546,708 | 8d5a28ed6804daa59f55974ec97f8a61e205b8c8 | /src/main/java/Vehicles/Components/Tires.java | c6caec27bb55977b40954817fb9e5e3451c2b20f | [] | no_license | MichaelTheTall/W12D3LAB | https://github.com/MichaelTheTall/W12D3LAB | e47b03cbdb3cd01d0266c345ac065a6c29955c93 | 1c0cb728c1c2eea576199a10e5561d34ca7b0b3a | refs/heads/master | 2020-04-01T18:10:41.123000 | 2018-10-17T15:13:13 | 2018-10-17T15:13:13 | 153,476,379 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Vehicles.Components;
public class Tires {
}
| UTF-8 | Java | 53 | java | Tires.java | Java | [] | null | [] | package Vehicles.Components;
public class Tires {
}
| 53 | 0.773585 | 0.773585 | 4 | 12.25 | 12.090802 | 28 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 4 |
b85a98939ec698d4f4e6d30e092cd6104335909a | 26,938,034,930,687 | 4423b632a339a0173535b78ee01073e45afba1bf | /app/src/main/java/com/raddarapp/presentation/android/adapter/CategoriesAdapter.java | 13c6b7298ae274f9ec061c94e5ae933913b02175 | [
"Apache-2.0"
] | permissive | jaimegc/raddarapp | https://github.com/jaimegc/raddarapp | b62bfe5f5b8d6a279c7eb99a1df62c45d2e9c8c9 | 22977618bf80195d57cb18ec5b5014d6fe1a5d09 | refs/heads/master | 2020-05-19T14:36:30.360000 | 2019-07-03T16:19:22 | 2019-07-03T16:19:22 | 185,061,381 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.raddarapp.presentation.android.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import com.raddarapp.BuildConfig;
import com.raddarapp.R;
import com.raddarapp.presentation.android.utils.FontUtils;
import com.raddarapp.presentation.android.view.FootprintEmojiCategory;
import com.vanniktech.emoji.EmojiTextView;
import java.util.ArrayList;
import java.util.List;
public class CategoriesAdapter extends RecyclerView.Adapter<CategoriesAdapter.MyViewHolder> implements Filterable {
private static final String FONT_NAME = BuildConfig.BASE_FONT_NAME;
private Context context;
private List<FootprintEmojiCategory> emojiCategoryList;
private List<FootprintEmojiCategory> emojiCategoryListFiltered;
private EmojiCategoriesAdapterListener emojiCategoriesListener;
private OnSelectListener selectListener;
public CategoriesAdapter(Context context, List<FootprintEmojiCategory> emojiCategoryList,
EmojiCategoriesAdapterListener emojiCategoriesListener, OnSelectListener selectListener) {
this.context = context;
this.emojiCategoriesListener = emojiCategoriesListener;
this.emojiCategoryList = emojiCategoryList;
this.emojiCategoryListFiltered = emojiCategoryList;
this.selectListener = selectListener;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_category, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final FootprintEmojiCategory emojiCategory = emojiCategoryListFiltered.get(position);
holder.emojiName.setText(emojiCategory.getName());
holder.emojiImage.setBackgroundDrawable(context.getDrawable(emojiCategory.getEmojiImageResource()));
}
@Override
public int getItemCount() {
return emojiCategoryListFiltered.size();
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
emojiCategoryListFiltered = emojiCategoryList;
} else {
List<FootprintEmojiCategory> filteredList = new ArrayList<>();
for (FootprintEmojiCategory row : emojiCategoryList) {
if (row.getName().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(row);
}
}
emojiCategoryListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = emojiCategoryListFiltered;
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
emojiCategoryListFiltered = (ArrayList<FootprintEmojiCategory>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView emojiName;
public EmojiTextView emojiImage;
public MyViewHolder(View view) {
super(view);
emojiName = view.findViewById(R.id.emoji_name);
emojiImage = view.findViewById(R.id.emoji_image);
view.setOnClickListener(v -> {
emojiCategoriesListener.onEmojiCategorySelected(emojiCategoryListFiltered.get(getAdapterPosition()));
selectListener.onSelectListener();
});
FontUtils fontUtils = new FontUtils();
fontUtils.applyFont(context, FONT_NAME, emojiName);
}
}
public interface EmojiCategoriesAdapterListener {
void onEmojiCategorySelected(FootprintEmojiCategory emojiCategory);
}
public interface OnSelectListener {
void onSelectListener();
}
} | UTF-8 | Java | 4,442 | java | CategoriesAdapter.java | Java | [
{
"context": ".android.view.FootprintEmojiCategory;\nimport com.vanniktech.emoji.EmojiTextView;\n\nimport java.util.ArrayList;",
"end": 531,
"score": 0.6836366653442383,
"start": 522,
"tag": "USERNAME",
"value": "anniktech"
}
] | null | [] | package com.raddarapp.presentation.android.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import com.raddarapp.BuildConfig;
import com.raddarapp.R;
import com.raddarapp.presentation.android.utils.FontUtils;
import com.raddarapp.presentation.android.view.FootprintEmojiCategory;
import com.vanniktech.emoji.EmojiTextView;
import java.util.ArrayList;
import java.util.List;
public class CategoriesAdapter extends RecyclerView.Adapter<CategoriesAdapter.MyViewHolder> implements Filterable {
private static final String FONT_NAME = BuildConfig.BASE_FONT_NAME;
private Context context;
private List<FootprintEmojiCategory> emojiCategoryList;
private List<FootprintEmojiCategory> emojiCategoryListFiltered;
private EmojiCategoriesAdapterListener emojiCategoriesListener;
private OnSelectListener selectListener;
public CategoriesAdapter(Context context, List<FootprintEmojiCategory> emojiCategoryList,
EmojiCategoriesAdapterListener emojiCategoriesListener, OnSelectListener selectListener) {
this.context = context;
this.emojiCategoriesListener = emojiCategoriesListener;
this.emojiCategoryList = emojiCategoryList;
this.emojiCategoryListFiltered = emojiCategoryList;
this.selectListener = selectListener;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_category, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final FootprintEmojiCategory emojiCategory = emojiCategoryListFiltered.get(position);
holder.emojiName.setText(emojiCategory.getName());
holder.emojiImage.setBackgroundDrawable(context.getDrawable(emojiCategory.getEmojiImageResource()));
}
@Override
public int getItemCount() {
return emojiCategoryListFiltered.size();
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
emojiCategoryListFiltered = emojiCategoryList;
} else {
List<FootprintEmojiCategory> filteredList = new ArrayList<>();
for (FootprintEmojiCategory row : emojiCategoryList) {
if (row.getName().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(row);
}
}
emojiCategoryListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = emojiCategoryListFiltered;
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
emojiCategoryListFiltered = (ArrayList<FootprintEmojiCategory>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView emojiName;
public EmojiTextView emojiImage;
public MyViewHolder(View view) {
super(view);
emojiName = view.findViewById(R.id.emoji_name);
emojiImage = view.findViewById(R.id.emoji_image);
view.setOnClickListener(v -> {
emojiCategoriesListener.onEmojiCategorySelected(emojiCategoryListFiltered.get(getAdapterPosition()));
selectListener.onSelectListener();
});
FontUtils fontUtils = new FontUtils();
fontUtils.applyFont(context, FONT_NAME, emojiName);
}
}
public interface EmojiCategoriesAdapterListener {
void onEmojiCategorySelected(FootprintEmojiCategory emojiCategory);
}
public interface OnSelectListener {
void onSelectListener();
}
} | 4,442 | 0.687753 | 0.687528 | 118 | 36.652542 | 31.419895 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.559322 | false | false | 4 |
6463cb4b58ee6a034bfe9817e0eac54c302bb24f | 11,098,195,562,103 | 34105ae527d1219d7659ea8215f06ccf400c9808 | /sanbang-front/src/main/java/com/sanbang/utils/MD5Util.java | 45c4f4821b92d1400f086301cca0bc3901f2abdb | [] | no_license | zhaibinsprojects/eza_app | https://github.com/zhaibinsprojects/eza_app | 34adb47185770c7d95df0a35d29c8d2437840fdb | c57ad2d2c8b1f566c3237b01e1607e62d8950713 | refs/heads/master | 2020-03-30T08:28:45.634000 | 2018-09-30T07:20:42 | 2018-09-30T07:20:42 | 151,018,487 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sanbang.utils;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MD5Util {
private static Logger logger = LoggerFactory.getLogger(MD5Util.class);
/***
* MD5加密 生成32位md5码
*
* @param 待加密字符串
* @return 返回32位md5码
*/
public static String md5Encode(String inStr) {
return encrypt(inStr, "");
}
private static String encrypt(String inputText, String algorithmName) {
if (inputText == null || "".equals(inputText.trim())) {
throw new IllegalArgumentException("请输入要加密的内容");
}
if (algorithmName == null || "".equals(algorithmName.trim())) {
algorithmName = "md5";
}
String encryptText = null;
try {
MessageDigest m = MessageDigest.getInstance(algorithmName);
m.update(inputText.getBytes("UTF8"));
byte s[] = m.digest();
// m.digest(inputText.getBytes("UTF8"));
return hex(s);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return encryptText;
}
// 返回十六进制字符串
private static String hex(byte[] arr) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; ++i) {
sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1,
3));
}
return sb.toString();
}
/**
* 签名字符串
*
* @param text
* 需要签名的字符串
* @param sign
* 签名结果
* @param key
* 密钥
* @param input_charset
* 编码格式
* @return 签名结果
*/
public static boolean verify(String text, String sign, String key, String charset) throws Exception {
text = text + key;
String mysign = DigestUtils.md5Hex(getContentBytes(text, charset));
if (mysign.equals(sign)) {
return true;
} else {
return false;
}
}
/**
* @param content
* @param charset
* @return
* @throws SignatureException
* @throws UnsupportedEncodingException
*/
private static byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
}
}
public static void main(String[] args) {
String str= "abc" ;
String md5 = md5Encode(str);
System.out.println(md5);
}
}
| UTF-8 | Java | 2,971 | java | MD5Util.java | Java | [] | null | [] | package com.sanbang.utils;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MD5Util {
private static Logger logger = LoggerFactory.getLogger(MD5Util.class);
/***
* MD5加密 生成32位md5码
*
* @param 待加密字符串
* @return 返回32位md5码
*/
public static String md5Encode(String inStr) {
return encrypt(inStr, "");
}
private static String encrypt(String inputText, String algorithmName) {
if (inputText == null || "".equals(inputText.trim())) {
throw new IllegalArgumentException("请输入要加密的内容");
}
if (algorithmName == null || "".equals(algorithmName.trim())) {
algorithmName = "md5";
}
String encryptText = null;
try {
MessageDigest m = MessageDigest.getInstance(algorithmName);
m.update(inputText.getBytes("UTF8"));
byte s[] = m.digest();
// m.digest(inputText.getBytes("UTF8"));
return hex(s);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return encryptText;
}
// 返回十六进制字符串
private static String hex(byte[] arr) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; ++i) {
sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1,
3));
}
return sb.toString();
}
/**
* 签名字符串
*
* @param text
* 需要签名的字符串
* @param sign
* 签名结果
* @param key
* 密钥
* @param input_charset
* 编码格式
* @return 签名结果
*/
public static boolean verify(String text, String sign, String key, String charset) throws Exception {
text = text + key;
String mysign = DigestUtils.md5Hex(getContentBytes(text, charset));
if (mysign.equals(sign)) {
return true;
} else {
return false;
}
}
/**
* @param content
* @param charset
* @return
* @throws SignatureException
* @throws UnsupportedEncodingException
*/
private static byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
}
}
public static void main(String[] args) {
String str= "abc" ;
String md5 = md5Encode(str);
System.out.println(md5);
}
}
| 2,971 | 0.599284 | 0.589624 | 103 | 25.135921 | 21.826788 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.485437 | false | false | 4 |
d9ff5510100616362c2c29132aced8f48564a09c | 22,703,197,159,076 | e340cbcf9abda621c0a5ae8d1faf1c90aef91bbc | /Genetic/src/main/java/GeneticAlg/EvolutionAlg/EvoAlg.java | 232f69b7c69ee98882a7abab80e0091ee70063ed | [] | no_license | minority4u/MLE | https://github.com/minority4u/MLE | 928570eabd5f01d9f36e288098d81584a041d3c4 | 95960b780be02354568f2ff7ee4ea98e22ca9753 | refs/heads/master | 2021-03-19T08:30:09.212000 | 2020-12-07T10:02:49 | 2020-12-07T10:02:49 | 89,502,618 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package GeneticAlg.EvolutionAlg;
import GeneticAlg.OpcodeLoader;
import GeneticAlg.VM;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import static GeneticAlg.Constants.*;
/**
* Created by minority on 12.10.16.
*/
public class EvoAlg extends Thread {
// for multithreaded evolutions
int ID;
// current generation of this population
int generation;
// size of this population (p)
int populationSize;
// percentagePartForCrossover (r) - single point crossover
double percentagePartForCrossover;
// mutation percentage rate (m), the index for mutation is random.
double percentagePartForMutation;
double maxFitness;
double fitnessThreshold;
double sumOfAllFitnesses;
int lenOfBestHyp;
int averageOpcodeLength;
int vmOperationsOfBestHyp;
ArrayList<Hypothesis> currentPopulation;
ArrayList<Hypothesis> nextGeneration;
// helper objects
// necessary to load an existing opcode into a new evolution
OpcodeLoader opcodeLoader;
// necessary to simulate each opcode and evaluate
VM vm;
// new population with random hypothesis
public EvoAlg() {
this.opcodeLoader = null;
initializeParams();
initializePopulation();
evaluateAndSortPopulation();
}
// new population with hypothesis from loaded opcode
public EvoAlg(String path) {
this.opcodeLoader = new OpcodeLoader(path);
initializeParams();
initializePopulationWithOpcode();
evaluateAndSortPopulation();
}
// initialize half of the population with the loaded opcode
// the others will be initialized to include new gens
private void initializePopulationWithOpcode() {
// TODO: define the percent part for the loaded opcode in Constants
// actually its 1 %
for (int i = 0; i < populationSize; i++) {
if (currentPopulation.size() < populationSize * PERCENTPARTOFLOADEDOPCODE) {
currentPopulation.add(new Hypothesis(opcodeLoader.getOpCode()));
} else {
currentPopulation.add(new Hypothesis());
}
}
}
// initialize the starting population with new random hypotheses
private void initializePopulation() {
for (int i = 0; i < populationSize; i++) {
currentPopulation.add(new Hypothesis());
}
}
private void initializeParams() {
// initialize objects
this.vm = new VM();
this.currentPopulation = new ArrayList<Hypothesis>();
this.nextGeneration = new ArrayList<Hypothesis>();
this.ID = random.nextInt(1000);
this.generation = 0;
this.sumOfAllFitnesses = 0;
this.fitnessThreshold = FITNESSGOAL;
this.maxFitness = 0;
this.lenOfBestHyp = 0;
this.percentagePartForCrossover = PERCENTPARTFORCROSSOVER;
this.percentagePartForMutation = PERCENTPARTFORMUTATION;
this.populationSize = POPULATIONSIZE;
// flexible populationsize for multithreaded testing
//this.populationSize = POPULATIONSIZE - random.nextInt(POPULATIONSIZE) + 20;
}
// Start the evolution algorithm for this population
public void run() {
// print a short overview vor each population (multithreaded) at the beginning
printPopulationOverview();
//printHypotheses();
while (this.maxFitness < this.fitnessThreshold
&& generation < MAXGENERATION) {
// print a short overview about this population for each generation
printPopulationOverview();
// selection, selected hyp will be added to nextGeneration
selection();
// crossover, children will be added to nextGeneration
crossover();
// mutate nextGeneration
mutate();
// update the next generation as current population
update();
// rise the population counter
generation++;
// calculate and sort the new population
evaluateAndSortPopulation();
}
System.out.println("\nEvolution no." + this.ID + " done... \n");
//printTheBestHyp();
saveTheBestOpcodeToFile();
//printHypotheses();
}
public void printPopulationOverview() {
System.out.println("Evolution-ID: " + this.ID);
System.out.println("Generation: " + this.generation);
System.out.println("Max fitness: " + this.maxFitness);
System.out.println("Length of the best Hyp: " + this.lenOfBestHyp);
System.out.println("VM-Operations of the best Hyp: : " + this.vmOperationsOfBestHyp);
System.out.println("Fitness sum: " + this.sumOfAllFitnesses);
System.out.println("Average Hyp length: " + this.averageOpcodeLength);
System.out.println("Fitness threshold: " + this.fitnessThreshold);
System.out.println("Population size: " + this.currentPopulation.size());
//printHypotheses();
System.out.println("......................................");
}
// prints all hypotheses of this population
public void printHypotheses() {
for (Hypothesis hyp : currentPopulation) {
System.out.println(hyp.toString());
}
}
// sorts all hypotheses desc by probability and prints the best hypothese
public void printTheBestHyp() {
System.out.println(currentPopulation.get(0));
System.out.println();
}
public void printStack(Hypothesis hypothesis) {
System.out.println("The Stack of this hypothesis: ");
vm.setMemAndResizeMAX(hypothesis.opCode);
vm.simulate();
//vm.printStack();
}
// sum the fitness of all hyp and save the highest fitness in the maxFitness variable
private void calculateFitnessAndProbabilityForAllHyp() {
this.sumOfAllFitnesses = 0;
this.maxFitness = 0;
int lengthSum = 0;
for (Hypothesis hyp : currentPopulation) {
this.sumOfAllFitnesses += hyp.calcFitness(vm);
lengthSum += hyp.hypotheseSize;
if (hyp.fitness >= this.maxFitness) {
this.lenOfBestHyp = hyp.hypotheseSize;
this.maxFitness = hyp.fitness;
this.vmOperationsOfBestHyp = hyp.vmOperations;
}
}
// calculate the probability, fitness must be calculated before
for (Hypothesis hyp : currentPopulation) {
hyp.probability = (hyp.fitness) / sumOfAllFitnesses;
}
this.averageOpcodeLength = lengthSum / populationSize;
}
// stores the best hyp at project directory dir = PATHTOSAVETHEBESTOPCODE for later reuse
private void saveTheBestOpcodeToFile() {
Hypothesis bestHyp;
Collections.sort(currentPopulation);
bestHyp = currentPopulation.get(0);
try {
String filename = PATHTOSAVETHEBESTOPCODE +
(int) bestHyp.fitness +
"_Len" + bestHyp.opCode.length +
"_Gen" + generation +
"_Id" + this.ID +
".txt";
PrintWriter writer = new PrintWriter(filename, "UTF-8");
writer.println(bestHyp);
writer.close();
} catch (Exception e) {
// do something
}
}
// second idea, rank selection
private void selection() {
int numberOfSelectedHyp = (int) ((1 - this.percentagePartForCrossover) * this.populationSize);
// as long as we dont have enough hyp in our selected list we add the best from actual population
for (Hypothesis hyp : currentPopulation) {
if (this.nextGeneration.size() < numberOfSelectedHyp) {
// our list is sorted by probability, therefore we take the first elements, rank selection
this.nextGeneration.add(hyp);
} else {
break;
}
}
}
// TODO: after n generations population is dominated by the best?
// second idea, the probability is a direct selector
private void crossover() {
int numberOfCrossoverHypPairs = (int) ((this.percentagePartForCrossover * this.populationSize));
ArrayList pairsOfParents = new ArrayList<>();
// select the best parents for crossover
for (Hypothesis hyp : currentPopulation) {
// Our population is sorted by probability, we only take the best
if (pairsOfParents.size() < numberOfCrossoverHypPairs) {
pairsOfParents.add(hyp);
} else {
break;
}
}
// cross each parent-pair and add the new pair of children to the next generation
// cut and splice crossover
int randomCrossoverPartnerIndex;
Hypothesis fatherHyp, motherHyp;
// create two children for each couple and add them to the new population
while (pairsOfParents.size() > 1) {
randomCrossoverPartnerIndex = random.nextInt(pairsOfParents.size());
fatherHyp = (Hypothesis) pairsOfParents.remove(randomCrossoverPartnerIndex);
motherHyp = (Hypothesis) pairsOfParents.remove(0);
this.nextGeneration.addAll(cross(motherHyp, fatherHyp));
}
}
// returns an arraylist with two hyp children single point crossed out of each parent pair hyp
// single point crossover
// cut and slice
private ArrayList<Hypothesis> cross(Hypothesis father, Hypothesis mother) {
int minSizeOfParents;
int crossoverIndex;
int[] fatherFront, fatherBack, motherFront, motherBack;
ArrayList<Hypothesis> childrens = new ArrayList();
// get a random index for single point crossover between 0 and min(parents.opCode.length)
// childrens length = crossoverIndex + (parent.length - crossoverIndex)
minSizeOfParents = Math.min(father.opCode.length, mother.opCode.length);
crossoverIndex = random.nextInt(minSizeOfParents);
// cuts the parents in two new code sequences each
motherFront = Arrays.copyOfRange(mother.opCode, 0, crossoverIndex);
fatherFront = Arrays.copyOfRange(father.opCode, 0, crossoverIndex);
motherBack = Arrays.copyOfRange(mother.opCode, crossoverIndex, mother.hypotheseSize);
fatherBack = Arrays.copyOfRange(father.opCode, crossoverIndex, father.hypotheseSize);
// creates two new Hypotheses
childrens.add(new Hypothesis(motherFront, fatherBack));
childrens.add(new Hypothesis(fatherFront, motherBack));
return childrens;
}
// returns an arraylist with two hyp children single point crossed out of each parent pair hyp
// single point crossover, but children length could cut the parents gene
private ArrayList<Hypothesis> crossOld(Hypothesis father, Hypothesis mother) {
int minSizeOfParents;
int minSizeOfChildren;
int minSizeOfChildrenAndParents;
int crossoverIndex;
ArrayList<Hypothesis> children = new ArrayList();
Hypothesis child1 = new Hypothesis();
Hypothesis child2 = new Hypothesis();
// get a random index for single point crossover between 0 and min(opCode.length)
minSizeOfParents = Math.min(father.opCode.length, mother.opCode.length);
minSizeOfChildren = Math.min(child1.opCode.length, child2.opCode.length);
minSizeOfChildrenAndParents = Math.min(minSizeOfParents, minSizeOfChildren);
crossoverIndex = random.nextInt(minSizeOfChildrenAndParents);
for (int i = 0; i < minSizeOfChildrenAndParents; i++) {
if (i < crossoverIndex) {
child1.opCode[i] = father.opCode[i];
child2.opCode[i] = mother.opCode[i];
} else {
child1.opCode[i] = mother.opCode[i];
child2.opCode[i] = father.opCode[i];
}
}
children.add(child1);
children.add(child2);
return children;
}
private void mutate() {
// TODO: survivor?
int Low = (int) (PERCENTPARTMUTATIONSURVIVORS * populationSize);
//int Low = (int) MUTATIONSURVIVOR;
int High = nextGeneration.size();
int mutations = (int) (percentagePartForMutation * nextGeneration.size());
int index;
Hypothesis hypToMutate;
for (int i = 0; i < mutations; i++) {
// dont mutate the best
// we dont create the smallest indexes (the best are at the front part of the list)
index = random.nextInt(High - Low) + Low;
// replace mutated
hypToMutate = nextGeneration.remove(index);
// add Hyp at last position
nextGeneration.add(nextGeneration.size() - 1, hypToMutate.mutate());
}
}
// set the next generation as current generation
private void update() {
this.currentPopulation = nextGeneration;
this.populationSize = nextGeneration.size();
this.nextGeneration = new ArrayList<>();
}
private void evaluateAndSortPopulation() {
calculateFitnessAndProbabilityForAllHyp();
Collections.sort(currentPopulation);
}
}
| UTF-8 | Java | 13,328 | java | EvoAlg.java | Java | [
{
"context": " static GeneticAlg.Constants.*;\n\n/**\n * Created by minority on 12.10.16.\n */\npublic class EvoAlg extends Thre",
"end": 267,
"score": 0.999589204788208,
"start": 259,
"tag": "USERNAME",
"value": "minority"
}
] | null | [] | package GeneticAlg.EvolutionAlg;
import GeneticAlg.OpcodeLoader;
import GeneticAlg.VM;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import static GeneticAlg.Constants.*;
/**
* Created by minority on 12.10.16.
*/
public class EvoAlg extends Thread {
// for multithreaded evolutions
int ID;
// current generation of this population
int generation;
// size of this population (p)
int populationSize;
// percentagePartForCrossover (r) - single point crossover
double percentagePartForCrossover;
// mutation percentage rate (m), the index for mutation is random.
double percentagePartForMutation;
double maxFitness;
double fitnessThreshold;
double sumOfAllFitnesses;
int lenOfBestHyp;
int averageOpcodeLength;
int vmOperationsOfBestHyp;
ArrayList<Hypothesis> currentPopulation;
ArrayList<Hypothesis> nextGeneration;
// helper objects
// necessary to load an existing opcode into a new evolution
OpcodeLoader opcodeLoader;
// necessary to simulate each opcode and evaluate
VM vm;
// new population with random hypothesis
public EvoAlg() {
this.opcodeLoader = null;
initializeParams();
initializePopulation();
evaluateAndSortPopulation();
}
// new population with hypothesis from loaded opcode
public EvoAlg(String path) {
this.opcodeLoader = new OpcodeLoader(path);
initializeParams();
initializePopulationWithOpcode();
evaluateAndSortPopulation();
}
// initialize half of the population with the loaded opcode
// the others will be initialized to include new gens
private void initializePopulationWithOpcode() {
// TODO: define the percent part for the loaded opcode in Constants
// actually its 1 %
for (int i = 0; i < populationSize; i++) {
if (currentPopulation.size() < populationSize * PERCENTPARTOFLOADEDOPCODE) {
currentPopulation.add(new Hypothesis(opcodeLoader.getOpCode()));
} else {
currentPopulation.add(new Hypothesis());
}
}
}
// initialize the starting population with new random hypotheses
private void initializePopulation() {
for (int i = 0; i < populationSize; i++) {
currentPopulation.add(new Hypothesis());
}
}
private void initializeParams() {
// initialize objects
this.vm = new VM();
this.currentPopulation = new ArrayList<Hypothesis>();
this.nextGeneration = new ArrayList<Hypothesis>();
this.ID = random.nextInt(1000);
this.generation = 0;
this.sumOfAllFitnesses = 0;
this.fitnessThreshold = FITNESSGOAL;
this.maxFitness = 0;
this.lenOfBestHyp = 0;
this.percentagePartForCrossover = PERCENTPARTFORCROSSOVER;
this.percentagePartForMutation = PERCENTPARTFORMUTATION;
this.populationSize = POPULATIONSIZE;
// flexible populationsize for multithreaded testing
//this.populationSize = POPULATIONSIZE - random.nextInt(POPULATIONSIZE) + 20;
}
// Start the evolution algorithm for this population
public void run() {
// print a short overview vor each population (multithreaded) at the beginning
printPopulationOverview();
//printHypotheses();
while (this.maxFitness < this.fitnessThreshold
&& generation < MAXGENERATION) {
// print a short overview about this population for each generation
printPopulationOverview();
// selection, selected hyp will be added to nextGeneration
selection();
// crossover, children will be added to nextGeneration
crossover();
// mutate nextGeneration
mutate();
// update the next generation as current population
update();
// rise the population counter
generation++;
// calculate and sort the new population
evaluateAndSortPopulation();
}
System.out.println("\nEvolution no." + this.ID + " done... \n");
//printTheBestHyp();
saveTheBestOpcodeToFile();
//printHypotheses();
}
public void printPopulationOverview() {
System.out.println("Evolution-ID: " + this.ID);
System.out.println("Generation: " + this.generation);
System.out.println("Max fitness: " + this.maxFitness);
System.out.println("Length of the best Hyp: " + this.lenOfBestHyp);
System.out.println("VM-Operations of the best Hyp: : " + this.vmOperationsOfBestHyp);
System.out.println("Fitness sum: " + this.sumOfAllFitnesses);
System.out.println("Average Hyp length: " + this.averageOpcodeLength);
System.out.println("Fitness threshold: " + this.fitnessThreshold);
System.out.println("Population size: " + this.currentPopulation.size());
//printHypotheses();
System.out.println("......................................");
}
// prints all hypotheses of this population
public void printHypotheses() {
for (Hypothesis hyp : currentPopulation) {
System.out.println(hyp.toString());
}
}
// sorts all hypotheses desc by probability and prints the best hypothese
public void printTheBestHyp() {
System.out.println(currentPopulation.get(0));
System.out.println();
}
public void printStack(Hypothesis hypothesis) {
System.out.println("The Stack of this hypothesis: ");
vm.setMemAndResizeMAX(hypothesis.opCode);
vm.simulate();
//vm.printStack();
}
// sum the fitness of all hyp and save the highest fitness in the maxFitness variable
private void calculateFitnessAndProbabilityForAllHyp() {
this.sumOfAllFitnesses = 0;
this.maxFitness = 0;
int lengthSum = 0;
for (Hypothesis hyp : currentPopulation) {
this.sumOfAllFitnesses += hyp.calcFitness(vm);
lengthSum += hyp.hypotheseSize;
if (hyp.fitness >= this.maxFitness) {
this.lenOfBestHyp = hyp.hypotheseSize;
this.maxFitness = hyp.fitness;
this.vmOperationsOfBestHyp = hyp.vmOperations;
}
}
// calculate the probability, fitness must be calculated before
for (Hypothesis hyp : currentPopulation) {
hyp.probability = (hyp.fitness) / sumOfAllFitnesses;
}
this.averageOpcodeLength = lengthSum / populationSize;
}
// stores the best hyp at project directory dir = PATHTOSAVETHEBESTOPCODE for later reuse
private void saveTheBestOpcodeToFile() {
Hypothesis bestHyp;
Collections.sort(currentPopulation);
bestHyp = currentPopulation.get(0);
try {
String filename = PATHTOSAVETHEBESTOPCODE +
(int) bestHyp.fitness +
"_Len" + bestHyp.opCode.length +
"_Gen" + generation +
"_Id" + this.ID +
".txt";
PrintWriter writer = new PrintWriter(filename, "UTF-8");
writer.println(bestHyp);
writer.close();
} catch (Exception e) {
// do something
}
}
// second idea, rank selection
private void selection() {
int numberOfSelectedHyp = (int) ((1 - this.percentagePartForCrossover) * this.populationSize);
// as long as we dont have enough hyp in our selected list we add the best from actual population
for (Hypothesis hyp : currentPopulation) {
if (this.nextGeneration.size() < numberOfSelectedHyp) {
// our list is sorted by probability, therefore we take the first elements, rank selection
this.nextGeneration.add(hyp);
} else {
break;
}
}
}
// TODO: after n generations population is dominated by the best?
// second idea, the probability is a direct selector
private void crossover() {
int numberOfCrossoverHypPairs = (int) ((this.percentagePartForCrossover * this.populationSize));
ArrayList pairsOfParents = new ArrayList<>();
// select the best parents for crossover
for (Hypothesis hyp : currentPopulation) {
// Our population is sorted by probability, we only take the best
if (pairsOfParents.size() < numberOfCrossoverHypPairs) {
pairsOfParents.add(hyp);
} else {
break;
}
}
// cross each parent-pair and add the new pair of children to the next generation
// cut and splice crossover
int randomCrossoverPartnerIndex;
Hypothesis fatherHyp, motherHyp;
// create two children for each couple and add them to the new population
while (pairsOfParents.size() > 1) {
randomCrossoverPartnerIndex = random.nextInt(pairsOfParents.size());
fatherHyp = (Hypothesis) pairsOfParents.remove(randomCrossoverPartnerIndex);
motherHyp = (Hypothesis) pairsOfParents.remove(0);
this.nextGeneration.addAll(cross(motherHyp, fatherHyp));
}
}
// returns an arraylist with two hyp children single point crossed out of each parent pair hyp
// single point crossover
// cut and slice
private ArrayList<Hypothesis> cross(Hypothesis father, Hypothesis mother) {
int minSizeOfParents;
int crossoverIndex;
int[] fatherFront, fatherBack, motherFront, motherBack;
ArrayList<Hypothesis> childrens = new ArrayList();
// get a random index for single point crossover between 0 and min(parents.opCode.length)
// childrens length = crossoverIndex + (parent.length - crossoverIndex)
minSizeOfParents = Math.min(father.opCode.length, mother.opCode.length);
crossoverIndex = random.nextInt(minSizeOfParents);
// cuts the parents in two new code sequences each
motherFront = Arrays.copyOfRange(mother.opCode, 0, crossoverIndex);
fatherFront = Arrays.copyOfRange(father.opCode, 0, crossoverIndex);
motherBack = Arrays.copyOfRange(mother.opCode, crossoverIndex, mother.hypotheseSize);
fatherBack = Arrays.copyOfRange(father.opCode, crossoverIndex, father.hypotheseSize);
// creates two new Hypotheses
childrens.add(new Hypothesis(motherFront, fatherBack));
childrens.add(new Hypothesis(fatherFront, motherBack));
return childrens;
}
// returns an arraylist with two hyp children single point crossed out of each parent pair hyp
// single point crossover, but children length could cut the parents gene
private ArrayList<Hypothesis> crossOld(Hypothesis father, Hypothesis mother) {
int minSizeOfParents;
int minSizeOfChildren;
int minSizeOfChildrenAndParents;
int crossoverIndex;
ArrayList<Hypothesis> children = new ArrayList();
Hypothesis child1 = new Hypothesis();
Hypothesis child2 = new Hypothesis();
// get a random index for single point crossover between 0 and min(opCode.length)
minSizeOfParents = Math.min(father.opCode.length, mother.opCode.length);
minSizeOfChildren = Math.min(child1.opCode.length, child2.opCode.length);
minSizeOfChildrenAndParents = Math.min(minSizeOfParents, minSizeOfChildren);
crossoverIndex = random.nextInt(minSizeOfChildrenAndParents);
for (int i = 0; i < minSizeOfChildrenAndParents; i++) {
if (i < crossoverIndex) {
child1.opCode[i] = father.opCode[i];
child2.opCode[i] = mother.opCode[i];
} else {
child1.opCode[i] = mother.opCode[i];
child2.opCode[i] = father.opCode[i];
}
}
children.add(child1);
children.add(child2);
return children;
}
private void mutate() {
// TODO: survivor?
int Low = (int) (PERCENTPARTMUTATIONSURVIVORS * populationSize);
//int Low = (int) MUTATIONSURVIVOR;
int High = nextGeneration.size();
int mutations = (int) (percentagePartForMutation * nextGeneration.size());
int index;
Hypothesis hypToMutate;
for (int i = 0; i < mutations; i++) {
// dont mutate the best
// we dont create the smallest indexes (the best are at the front part of the list)
index = random.nextInt(High - Low) + Low;
// replace mutated
hypToMutate = nextGeneration.remove(index);
// add Hyp at last position
nextGeneration.add(nextGeneration.size() - 1, hypToMutate.mutate());
}
}
// set the next generation as current generation
private void update() {
this.currentPopulation = nextGeneration;
this.populationSize = nextGeneration.size();
this.nextGeneration = new ArrayList<>();
}
private void evaluateAndSortPopulation() {
calculateFitnessAndProbabilityForAllHyp();
Collections.sort(currentPopulation);
}
}
| 13,328 | 0.634979 | 0.631603 | 369 | 35.11924 | 27.859051 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.525745 | false | false | 4 |
9a17cf0c192151daad46dc318bfc5d0d129d19a6 | 3,315,714,768,163 | ae522a18c923c016b2f25a6da9b35dfc0a105483 | /FINAL_V10_GUI/src/AppKickstarter/misc/Ticket.java | 41d3dd572ff40834b665f9fd93c9f0474f882637 | [] | no_license | MaureenZOU/COMP4007_Group2_Phase2 | https://github.com/MaureenZOU/COMP4007_Group2_Phase2 | dbae29ffe4af9daa429b22b93e57437c6712334d | 9d6bbfb2b4cc9892aa51a234930744f0c3128660 | refs/heads/master | 2021-08-23T08:42:51.697000 | 2017-12-04T10:34:38 | 2017-12-04T10:34:38 | 112,908,084 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package AppKickstarter.misc;
public class Ticket {
public int ticketNo;
public boolean isACKed;
public String cid;
public int nPersons;
public Ticket(int ticketNo, String cid, int nPersons, boolean isACKed){
this.ticketNo = ticketNo;
this.isACKed = isACKed;
this.cid = cid;
this.nPersons = nPersons;
}
}
| UTF-8 | Java | 361 | java | Ticket.java | Java | [] | null | [] | package AppKickstarter.misc;
public class Ticket {
public int ticketNo;
public boolean isACKed;
public String cid;
public int nPersons;
public Ticket(int ticketNo, String cid, int nPersons, boolean isACKed){
this.ticketNo = ticketNo;
this.isACKed = isACKed;
this.cid = cid;
this.nPersons = nPersons;
}
}
| 361 | 0.65374 | 0.65374 | 14 | 24.785715 | 17.542515 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.857143 | false | false | 4 |
73602d7b9e9468355e10be19ea9b6b5c4cf5878d | 27,075,473,874,508 | d3c2494fc3816a586e682b220d2ad8a96c42158c | /linkedlistChalenge/src/com/okeino2/Main.java | bb86d7a22e1aadae65de21902f82f9d913df2866 | [] | no_license | okeino/JAVA-sandbox | https://github.com/okeino/JAVA-sandbox | de3b868a73ee212cb7cddd7a15a40c471b13aa77 | cb9811599b06158bd8ac1ee2b53e6e60ec0362e0 | refs/heads/master | 2020-04-08T13:10:38.423000 | 2018-11-27T18:16:02 | 2018-11-27T18:16:02 | 159,378,704 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.okeino2;
import com.Album;
import java.util.*;
public class Main {
private static ArrayList<Album> myAlbum = new ArrayList<>();
public static void main(String[] args) {
// write your code here
Album albums = new Album("Kings rock","ACE");
albums.newSong("Rock",3.59);
albums.newSong("Rockers rock",5.59);
albums.newSong("Rocky nuk",3.59);
albums.newSong("Rocks love",2.59);
myAlbum.add(albums);
albums = new Album("New Beats","ACE Mac");
albums.newSong("Funk one",3.59);
albums.newSong("Free flow",5.29);
albums.newSong("Luv nuk",3.59);
albums.newSong("love",7.59);
myAlbum.add(albums);
LinkedList<Song> playList = new LinkedList<>();
myAlbum.get(0).addToPlayList("Rock",playList);
myAlbum.get(0).addToPlayList("Rocks love",playList);
myAlbum.get(0).addToPlayList("nuk",playList);// does not work
myAlbum.get(0).addToPlayList(3,playList);
myAlbum.get(1).addToPlayList(4,playList);
myAlbum.get(1).addToPlayList(2,playList);
myAlbum.get(1).addToPlayList(1,playList);
myAlbum.get(1).addToPlayList(3,playList);
myAlbum.get(1).addToPlayList(12,playList); // there is no track 12
play(playList);
}
private static void play(LinkedList<Song> playList){
Scanner scanner =new Scanner(System.in);
boolean quit = false;
boolean forward = true;
ListIterator<Song> listIterator = playList.listIterator();
if(playList.size() == 0){
System.out.println("No songs in playList");
return;
}
else{
System.out.println("Now playing "+ listIterator.next().toString());
printMenu();
}
while (!quit){
int action = scanner.nextInt();
scanner.nextLine();
switch (action){
case 0:
System.out.println("Playlist complete.");
quit = true;
break;
case 1:
if( !forward){
if(listIterator.hasNext()){
listIterator.next();
}
forward = true;
}
if (listIterator.hasNext()){
System.out.println("Now playing "+ listIterator.next().toString());
}else{
System.out.println("We have reached the end of the playlist");
forward = false;
}
break;
case 2:
if(forward){
if(listIterator.hasPrevious()){
listIterator.previous();
}
forward=false;
}
if(listIterator.hasPrevious()){
System.out.println("Now playing "+listIterator.previous().toString());
}else{
System.out.println("We are at the start of the playlist");
forward = true;
}
break;
case 3:
if(forward){
if(listIterator.hasPrevious()){
System.out.println("Now replaying "+ listIterator.previous().toString());
forward = false;
}else{
System.out.println("We are at the start of the list");
}
}else {
if(listIterator.hasNext()){
System.out.println("Now replaying "+listIterator.next().toString());
forward = true;
}else{
System.out.println("We have reached the end of the list");
}
}
break;
case 4:
printList(playList);
break;
case 5:
printMenu();
break;
case 6:
if(playList.size()>0){
listIterator.remove();
if(listIterator.hasNext()){
System.out.println("Now playing"+ listIterator.next());
}else if(listIterator.hasPrevious()){
System.out.println("Now playing"+ listIterator.previous());
}
}
break;
}
}
}
private static void printMenu(){
System.out.println("Available actions:\npress ");
System.out.println("0 to quit\n"+
"1 - to play next song\n"+
"2 - to play previous song\n"+
"3 - to replay the current song\n"+
"4 - list songs in the playlist\n"+
"5 - print available actions.\n"+
"6 - delete current song from playlist");
}
private static void printList(LinkedList<Song> playList){
Iterator<Song> iterator = playList.iterator();
System.out.println("=============================");
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println("=============================");
}
}
| UTF-8 | Java | 5,609 | java | Main.java | Java | [] | null | [] | package com.okeino2;
import com.Album;
import java.util.*;
public class Main {
private static ArrayList<Album> myAlbum = new ArrayList<>();
public static void main(String[] args) {
// write your code here
Album albums = new Album("Kings rock","ACE");
albums.newSong("Rock",3.59);
albums.newSong("Rockers rock",5.59);
albums.newSong("Rocky nuk",3.59);
albums.newSong("Rocks love",2.59);
myAlbum.add(albums);
albums = new Album("New Beats","ACE Mac");
albums.newSong("Funk one",3.59);
albums.newSong("Free flow",5.29);
albums.newSong("Luv nuk",3.59);
albums.newSong("love",7.59);
myAlbum.add(albums);
LinkedList<Song> playList = new LinkedList<>();
myAlbum.get(0).addToPlayList("Rock",playList);
myAlbum.get(0).addToPlayList("Rocks love",playList);
myAlbum.get(0).addToPlayList("nuk",playList);// does not work
myAlbum.get(0).addToPlayList(3,playList);
myAlbum.get(1).addToPlayList(4,playList);
myAlbum.get(1).addToPlayList(2,playList);
myAlbum.get(1).addToPlayList(1,playList);
myAlbum.get(1).addToPlayList(3,playList);
myAlbum.get(1).addToPlayList(12,playList); // there is no track 12
play(playList);
}
private static void play(LinkedList<Song> playList){
Scanner scanner =new Scanner(System.in);
boolean quit = false;
boolean forward = true;
ListIterator<Song> listIterator = playList.listIterator();
if(playList.size() == 0){
System.out.println("No songs in playList");
return;
}
else{
System.out.println("Now playing "+ listIterator.next().toString());
printMenu();
}
while (!quit){
int action = scanner.nextInt();
scanner.nextLine();
switch (action){
case 0:
System.out.println("Playlist complete.");
quit = true;
break;
case 1:
if( !forward){
if(listIterator.hasNext()){
listIterator.next();
}
forward = true;
}
if (listIterator.hasNext()){
System.out.println("Now playing "+ listIterator.next().toString());
}else{
System.out.println("We have reached the end of the playlist");
forward = false;
}
break;
case 2:
if(forward){
if(listIterator.hasPrevious()){
listIterator.previous();
}
forward=false;
}
if(listIterator.hasPrevious()){
System.out.println("Now playing "+listIterator.previous().toString());
}else{
System.out.println("We are at the start of the playlist");
forward = true;
}
break;
case 3:
if(forward){
if(listIterator.hasPrevious()){
System.out.println("Now replaying "+ listIterator.previous().toString());
forward = false;
}else{
System.out.println("We are at the start of the list");
}
}else {
if(listIterator.hasNext()){
System.out.println("Now replaying "+listIterator.next().toString());
forward = true;
}else{
System.out.println("We have reached the end of the list");
}
}
break;
case 4:
printList(playList);
break;
case 5:
printMenu();
break;
case 6:
if(playList.size()>0){
listIterator.remove();
if(listIterator.hasNext()){
System.out.println("Now playing"+ listIterator.next());
}else if(listIterator.hasPrevious()){
System.out.println("Now playing"+ listIterator.previous());
}
}
break;
}
}
}
private static void printMenu(){
System.out.println("Available actions:\npress ");
System.out.println("0 to quit\n"+
"1 - to play next song\n"+
"2 - to play previous song\n"+
"3 - to replay the current song\n"+
"4 - list songs in the playlist\n"+
"5 - print available actions.\n"+
"6 - delete current song from playlist");
}
private static void printList(LinkedList<Song> playList){
Iterator<Song> iterator = playList.iterator();
System.out.println("=============================");
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println("=============================");
}
}
| 5,609 | 0.449456 | 0.438937 | 171 | 31.80117 | 24.924828 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.54386 | false | false | 4 |
74831c810038d656d9f874a8f7fbb13382dca681 | 27,865,747,846,164 | 57e618385e1fda43b551b9fedc8d5082f7f8f426 | /ProfitApp/src/main/java/bsu/fpmi/profit/CheckServlet.java | c38722579f0cf20fdae906601ff75e811076fa10 | [] | no_license | klopotuk1136/UP | https://github.com/klopotuk1136/UP | 1982bb486e4e6d449c2420d6d79169f95c2cdd0f | 5391c995e5d5c3d6a6404e114d521ff216e91db8 | refs/heads/master | 2023-05-02T18:49:32.843000 | 2021-05-25T10:34:15 | 2021-05-25T10:34:15 | 337,687,115 | 0 | 1 | null | false | 2021-05-25T10:35:48 | 2021-02-10T10:20:05 | 2021-05-25T10:34:18 | 2021-05-25T10:34:15 | 1,506 | 0 | 1 | 4 | HTML | false | false | package bsu.fpmi.profit;
import java.io.*;
import javax.servlet.http.*;
public class CheckServlet extends HttpServlet {
private static final String JSON = "{\"success\" :\"true\"}";
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("json");
PrintWriter pw = response.getWriter();
pw.println(JSON);
}
} | UTF-8 | Java | 465 | java | CheckServlet.java | Java | [] | null | [] | package bsu.fpmi.profit;
import java.io.*;
import javax.servlet.http.*;
public class CheckServlet extends HttpServlet {
private static final String JSON = "{\"success\" :\"true\"}";
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("json");
PrintWriter pw = response.getWriter();
pw.println(JSON);
}
} | 465 | 0.643011 | 0.643011 | 15 | 30.066668 | 29.196957 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.533333 | false | false | 4 |
5cd1dbdcddd4b9aec95920c5303d51439de25c95 | 21,904,333,254,328 | daf5013dac63ebce2e64ae04a3babfdbedbdc349 | /src/main/java/me/gking2224/model/execution/groovy/GroovyClassLoaderScriptV1.java | c88358779bd5ab55e727a589c49af10835232e89 | [] | no_license | gking2224/modelserver | https://github.com/gking2224/modelserver | d380e580c5b1e1d0e23b079c2d21bd6f887f875d | 36036e488861d44ff12ba572d4c47cc41a2fa356 | refs/heads/master | 2020-02-26T14:25:54.878000 | 2016-08-06T17:26:33 | 2016-08-06T17:26:33 | 64,286,083 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.gking2224.model.execution.groovy;
public interface GroovyClassLoaderScriptV1 {
void execute();
}
| UTF-8 | Java | 114 | java | GroovyClassLoaderScriptV1.java | Java | [
{
"context": "package me.gking2224.model.execution.groovy;\n\npublic interface GroovyC",
"end": 20,
"score": 0.8092653155326843,
"start": 12,
"tag": "USERNAME",
"value": "king2224"
}
] | null | [] | package me.gking2224.model.execution.groovy;
public interface GroovyClassLoaderScriptV1 {
void execute();
}
| 114 | 0.780702 | 0.736842 | 6 | 18 | 19.536291 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 4 |
fdca65996a3fa2e820305595dc6a2bfd9acc6650 | 21,904,333,257,295 | 3cd38b3b7691a1541873a19b6e35802f35249c49 | /Mindstorm Toopers/src/vision/gui/DotsThresholder.java | a10ee7b79f2d67e8b0a9ab2742b58f941d6636f8 | [] | no_license | kubabuk/sdp | https://github.com/kubabuk/sdp | 59f493fde6c20b98c8aed44aa617e7c710d61b2c | d6f73a3f9b1369ed0943b8df4508547b115c2cf1 | refs/heads/master | 2021-05-28T02:48:26.764000 | 2014-03-31T11:28:53 | 2014-03-31T11:28:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package vision.gui;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import vision.ImageProcessor;
import vision.PitchConstants;
public class DotsThresholder extends JPanel implements ItemListener, ChangeListener {
private ImageProcessor imageProcessor;
private JCheckBox chk_showLocation;
private JCheckBox chk_showDirection;
private JCheckBox chk_showPixels;
private ThresholdsPanel thresholds;
private PitchConstants pitchConstants;
public DotsThresholder(ImageProcessor imageProcessor, PitchConstants pitchConstants){
this.imageProcessor = imageProcessor;
this.pitchConstants = pitchConstants;
chk_showLocation = new JCheckBox("Show Dots Location");
chk_showLocation.addItemListener(this);
this.add(chk_showLocation);
chk_showDirection = new JCheckBox("Show Robot Directions");
chk_showDirection.addItemListener(this);
this.add(chk_showDirection);
chk_showPixels = new JCheckBox("Show detected pixels");
chk_showPixels.addItemListener(this);
this.add(chk_showPixels);
thresholds = new ThresholdsPanel();
thresholds.setRedSliderChangeListener(this);
thresholds.setBlueSliderChangeListener(this);
thresholds.setGreenSliderChangeListener(this);
thresholds.setHueSliderChangeListener(this);
thresholds.setSaturationSliderChangeListener(this);
thresholds.setValueSliderChangeListener(this);
updateNewValues();
this.add(thresholds);
}
public void updateNewValues(){
thresholds.setRedSliderValues(pitchConstants.getRedLower(pitchConstants.GREY), pitchConstants.getRedUpper(pitchConstants.GREY));
thresholds.setBlueSliderValues(pitchConstants.getBlueLower(pitchConstants.GREY), pitchConstants.getBlueUpper(pitchConstants.GREY));
thresholds.setGreenSliderValues(pitchConstants.getGreenLower(pitchConstants.GREY), pitchConstants.getGreenUpper(pitchConstants.GREY));
thresholds.setHueSliderValues(pitchConstants.getHueLower(pitchConstants.GREY), pitchConstants.getHueUpper(pitchConstants.GREY));
thresholds.setValueSliderValues(pitchConstants.getValueLower(pitchConstants.GREY), pitchConstants.getValueUpper(pitchConstants.GREY));
thresholds.setSaturationSliderValues(pitchConstants.getSaturationLower(pitchConstants.GREY), pitchConstants.getSaturationUpper(pitchConstants.GREY));
}
@Override
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
if (source == chk_showLocation){
if (chk_showLocation.isSelected()){
System.out.println("Marking the dots.");
imageProcessor.showDots(true);
} else {
System.out.println("Not marking the dots.");
imageProcessor.showDots(false);
}
} else if (source == chk_showPixels){
if (chk_showPixels.isSelected()){
System.out.println("Showing dots pixels.");
imageProcessor.showDotsPixels(true);
} else {
System.out.println("Not showing dots pixels.");
imageProcessor.showDotsPixels(false);
}
} else if (source == chk_showDirection){
if (chk_showDirection.isSelected()){
System.out.println("Showing robot directions.");
imageProcessor.showDirections(true);
} else {
System.out.println("Not showing robot directions.");
imageProcessor.showDirections(false);
}
}
}
@Override
public void stateChanged(ChangeEvent arg0) {
if (arg0.getSource().equals(thresholds.getRedSlider())){
RangeSlider source = (RangeSlider) arg0.getSource();
imageProcessor.setDotsMinRed(source.getLowerValue());
imageProcessor.setDotsMaxRed(source.getUpperValue());
pitchConstants.setRedLower(pitchConstants.GREY, source.getLowerValue());
pitchConstants.setRedUpper(pitchConstants.GREY, source.getUpperValue());
} else if (arg0.getSource().equals(thresholds.getBlueSlider())){
RangeSlider source = (RangeSlider) arg0.getSource();
imageProcessor.setDotsMinBlue(source.getLowerValue());
imageProcessor.setDotsMaxBlue(source.getUpperValue());
pitchConstants.setBlueLower(pitchConstants.GREY, source.getLowerValue());
pitchConstants.setBlueUpper(pitchConstants.GREY, source.getUpperValue());
} else if (arg0.getSource().equals(thresholds.getGreenSlider())){
RangeSlider source = (RangeSlider) arg0.getSource();
imageProcessor.setDotsMinGreen(source.getLowerValue());
imageProcessor.setDotsMaxGreen(source.getUpperValue());
pitchConstants.setGreenLower(pitchConstants.GREY, source.getLowerValue());
pitchConstants.setGreenUpper(pitchConstants.GREY, source.getUpperValue());
} else if (arg0.getSource().equals(thresholds.getHueSlider())){
RangeSlider source = (RangeSlider) arg0.getSource();
imageProcessor.setDotsMinHue(source.getLowerValue());
imageProcessor.setDotsMaxHue(source.getUpperValue());
pitchConstants.setHueLower(pitchConstants.GREY, source.getLowerValue());
pitchConstants.setHueUpper(pitchConstants.GREY, source.getUpperValue());
} else if (arg0.getSource().equals(thresholds.getSaturationSlider())){
RangeSlider source = (RangeSlider) arg0.getSource();
imageProcessor.setDotsMinSaturation(source.getLowerValue());
imageProcessor.setDotsMaxSaturation(source.getUpperValue());
pitchConstants.setSaturationLower(pitchConstants.GREY, source.getLowerValue());
pitchConstants.setSaturationUpper(pitchConstants.GREY, source.getUpperValue());
} else if (arg0.getSource().equals(thresholds.getValueSlider())){
RangeSlider source = (RangeSlider) arg0.getSource();
imageProcessor.setDotsMinValue(source.getLowerValue());
imageProcessor.setDotsMaxValue(source.getUpperValue());
pitchConstants.setValueLower(pitchConstants.GREY, source.getLowerValue());
pitchConstants.setValueUpper(pitchConstants.GREY, source.getUpperValue());
}
}
}
| UTF-8 | Java | 5,820 | java | DotsThresholder.java | Java | [] | null | [] | package vision.gui;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import vision.ImageProcessor;
import vision.PitchConstants;
public class DotsThresholder extends JPanel implements ItemListener, ChangeListener {
private ImageProcessor imageProcessor;
private JCheckBox chk_showLocation;
private JCheckBox chk_showDirection;
private JCheckBox chk_showPixels;
private ThresholdsPanel thresholds;
private PitchConstants pitchConstants;
public DotsThresholder(ImageProcessor imageProcessor, PitchConstants pitchConstants){
this.imageProcessor = imageProcessor;
this.pitchConstants = pitchConstants;
chk_showLocation = new JCheckBox("Show Dots Location");
chk_showLocation.addItemListener(this);
this.add(chk_showLocation);
chk_showDirection = new JCheckBox("Show Robot Directions");
chk_showDirection.addItemListener(this);
this.add(chk_showDirection);
chk_showPixels = new JCheckBox("Show detected pixels");
chk_showPixels.addItemListener(this);
this.add(chk_showPixels);
thresholds = new ThresholdsPanel();
thresholds.setRedSliderChangeListener(this);
thresholds.setBlueSliderChangeListener(this);
thresholds.setGreenSliderChangeListener(this);
thresholds.setHueSliderChangeListener(this);
thresholds.setSaturationSliderChangeListener(this);
thresholds.setValueSliderChangeListener(this);
updateNewValues();
this.add(thresholds);
}
public void updateNewValues(){
thresholds.setRedSliderValues(pitchConstants.getRedLower(pitchConstants.GREY), pitchConstants.getRedUpper(pitchConstants.GREY));
thresholds.setBlueSliderValues(pitchConstants.getBlueLower(pitchConstants.GREY), pitchConstants.getBlueUpper(pitchConstants.GREY));
thresholds.setGreenSliderValues(pitchConstants.getGreenLower(pitchConstants.GREY), pitchConstants.getGreenUpper(pitchConstants.GREY));
thresholds.setHueSliderValues(pitchConstants.getHueLower(pitchConstants.GREY), pitchConstants.getHueUpper(pitchConstants.GREY));
thresholds.setValueSliderValues(pitchConstants.getValueLower(pitchConstants.GREY), pitchConstants.getValueUpper(pitchConstants.GREY));
thresholds.setSaturationSliderValues(pitchConstants.getSaturationLower(pitchConstants.GREY), pitchConstants.getSaturationUpper(pitchConstants.GREY));
}
@Override
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
if (source == chk_showLocation){
if (chk_showLocation.isSelected()){
System.out.println("Marking the dots.");
imageProcessor.showDots(true);
} else {
System.out.println("Not marking the dots.");
imageProcessor.showDots(false);
}
} else if (source == chk_showPixels){
if (chk_showPixels.isSelected()){
System.out.println("Showing dots pixels.");
imageProcessor.showDotsPixels(true);
} else {
System.out.println("Not showing dots pixels.");
imageProcessor.showDotsPixels(false);
}
} else if (source == chk_showDirection){
if (chk_showDirection.isSelected()){
System.out.println("Showing robot directions.");
imageProcessor.showDirections(true);
} else {
System.out.println("Not showing robot directions.");
imageProcessor.showDirections(false);
}
}
}
@Override
public void stateChanged(ChangeEvent arg0) {
if (arg0.getSource().equals(thresholds.getRedSlider())){
RangeSlider source = (RangeSlider) arg0.getSource();
imageProcessor.setDotsMinRed(source.getLowerValue());
imageProcessor.setDotsMaxRed(source.getUpperValue());
pitchConstants.setRedLower(pitchConstants.GREY, source.getLowerValue());
pitchConstants.setRedUpper(pitchConstants.GREY, source.getUpperValue());
} else if (arg0.getSource().equals(thresholds.getBlueSlider())){
RangeSlider source = (RangeSlider) arg0.getSource();
imageProcessor.setDotsMinBlue(source.getLowerValue());
imageProcessor.setDotsMaxBlue(source.getUpperValue());
pitchConstants.setBlueLower(pitchConstants.GREY, source.getLowerValue());
pitchConstants.setBlueUpper(pitchConstants.GREY, source.getUpperValue());
} else if (arg0.getSource().equals(thresholds.getGreenSlider())){
RangeSlider source = (RangeSlider) arg0.getSource();
imageProcessor.setDotsMinGreen(source.getLowerValue());
imageProcessor.setDotsMaxGreen(source.getUpperValue());
pitchConstants.setGreenLower(pitchConstants.GREY, source.getLowerValue());
pitchConstants.setGreenUpper(pitchConstants.GREY, source.getUpperValue());
} else if (arg0.getSource().equals(thresholds.getHueSlider())){
RangeSlider source = (RangeSlider) arg0.getSource();
imageProcessor.setDotsMinHue(source.getLowerValue());
imageProcessor.setDotsMaxHue(source.getUpperValue());
pitchConstants.setHueLower(pitchConstants.GREY, source.getLowerValue());
pitchConstants.setHueUpper(pitchConstants.GREY, source.getUpperValue());
} else if (arg0.getSource().equals(thresholds.getSaturationSlider())){
RangeSlider source = (RangeSlider) arg0.getSource();
imageProcessor.setDotsMinSaturation(source.getLowerValue());
imageProcessor.setDotsMaxSaturation(source.getUpperValue());
pitchConstants.setSaturationLower(pitchConstants.GREY, source.getLowerValue());
pitchConstants.setSaturationUpper(pitchConstants.GREY, source.getUpperValue());
} else if (arg0.getSource().equals(thresholds.getValueSlider())){
RangeSlider source = (RangeSlider) arg0.getSource();
imageProcessor.setDotsMinValue(source.getLowerValue());
imageProcessor.setDotsMaxValue(source.getUpperValue());
pitchConstants.setValueLower(pitchConstants.GREY, source.getLowerValue());
pitchConstants.setValueUpper(pitchConstants.GREY, source.getUpperValue());
}
}
}
| 5,820 | 0.788488 | 0.786254 | 129 | 44.11628 | 31.126804 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.875969 | false | false | 4 |
c3ff96921795acea5f97480e864735239b177f10 | 2,156,073,600,998 | a2c8932f4275af22bac7d247cb23be8db90495e9 | /src/main/java/org/apache/accumulo/core/client/admin/TableOperations.java | 1b822ae3504fcbc22bacaa7aed41de6618c710d6 | [] | no_license | jstoneham/accumulo-cloudbase-shim | https://github.com/jstoneham/accumulo-cloudbase-shim | cfeac497cc6a1aa3f40fead7dc2803adbc0a1970 | 0a7368b28de6fe7edb0f8372ff6cff56f44a6f6a | refs/heads/master | 2020-05-18T04:17:46.750000 | 2013-07-25T15:40:24 | 2013-07-25T15:40:24 | 8,102,700 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.core.client.admin;
import org.apache.accumulo.core.client.*;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.iterators.IteratorUtil;
import org.apache.accumulo.core.util.BulkImportHelper;
import org.apache.hadoop.io.Text;
import java.io.IOException;
import java.util.*;
public interface TableOperations {
public SortedSet<String> list();
public boolean exists(String tableName);
public void create(String tableName) throws AccumuloException, AccumuloSecurityException, TableExistsException;
public void create(String tableName, boolean versioningIter, TimeType timeType) throws AccumuloException, AccumuloSecurityException, TableExistsException;
public void addSplits(String tableName, SortedSet<Text> partitionKeys) throws TableNotFoundException, AccumuloException, AccumuloSecurityException;
public Collection<Text> getSplits(String tableName) throws TableNotFoundException;
public Collection<Text> getSplits(String tableName, int maxSplits) throws TableNotFoundException;
public void compact(String tableName, Text start, Text end, boolean flush, boolean wait) throws AccumuloSecurityException, TableNotFoundException,
AccumuloException;
public void delete(String tableName) throws AccumuloException, AccumuloSecurityException, TableNotFoundException;
public void rename(String oldTableName, String newTableName) throws AccumuloSecurityException, TableNotFoundException, AccumuloException,
TableExistsException;
public void flush(String tableName) throws AccumuloException, AccumuloSecurityException;
public void setProperty(String tableName, String property, String value) throws AccumuloException, AccumuloSecurityException;
public void removeProperty(String tableName, String property) throws AccumuloException, AccumuloSecurityException;
public Iterable<Map.Entry<String, String>> getProperties(String tableName) throws AccumuloException, TableNotFoundException;
public void setLocalityGroups(String tableName, Map<String, Set<Text>> groups) throws AccumuloException, AccumuloSecurityException, TableNotFoundException;
public Map<String, Set<Text>> getLocalityGroups(String tableName) throws AccumuloException, TableNotFoundException;
public Set<Range> splitRangeByTablets(String tableName, Range range, int maxSplits) throws AccumuloException, AccumuloSecurityException,
TableNotFoundException;
public void importDirectory(String tableName, String dir, String failureDir, boolean setTime) throws TableNotFoundException, IOException, AccumuloException,
AccumuloSecurityException;
public BulkImportHelper.AssignmentStats importDirectory(String tableName, String dir, String failureDir, int numThreads, int numAssignThreads, boolean disableGC)
throws IOException, AccumuloException, AccumuloSecurityException;
public void offline(String tableName) throws AccumuloSecurityException, AccumuloException, TableNotFoundException;
public void online(String tableName) throws AccumuloSecurityException, AccumuloException, TableNotFoundException;
public void clearLocatorCache(String tableName) throws TableNotFoundException;
public Map<String, String> tableIdMap();
public void attachIterator(String tableName, IteratorSetting setting) throws AccumuloSecurityException, AccumuloException, TableNotFoundException;
public void attachIterator(String tableName, IteratorSetting setting, EnumSet<IteratorUtil.IteratorScope> scopes) throws AccumuloSecurityException, AccumuloException,
TableNotFoundException;
public void removeIterator(String tableName, String name, EnumSet<IteratorUtil.IteratorScope> scopes) throws AccumuloSecurityException, AccumuloException,
TableNotFoundException;
public IteratorSetting getIteratorSetting(String tableName, String name, IteratorUtil.IteratorScope scope) throws AccumuloSecurityException, AccumuloException,
TableNotFoundException;
public Map<String, EnumSet<IteratorUtil.IteratorScope>> listIterators(String tableName) throws AccumuloSecurityException, AccumuloException, TableNotFoundException;
public void checkIteratorConflicts(String tableName, IteratorSetting setting, EnumSet<IteratorUtil.IteratorScope> scopes) throws AccumuloException, TableNotFoundException;
}
| UTF-8 | Java | 5,198 | java | TableOperations.java | Java | [] | null | [] | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.core.client.admin;
import org.apache.accumulo.core.client.*;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.iterators.IteratorUtil;
import org.apache.accumulo.core.util.BulkImportHelper;
import org.apache.hadoop.io.Text;
import java.io.IOException;
import java.util.*;
public interface TableOperations {
public SortedSet<String> list();
public boolean exists(String tableName);
public void create(String tableName) throws AccumuloException, AccumuloSecurityException, TableExistsException;
public void create(String tableName, boolean versioningIter, TimeType timeType) throws AccumuloException, AccumuloSecurityException, TableExistsException;
public void addSplits(String tableName, SortedSet<Text> partitionKeys) throws TableNotFoundException, AccumuloException, AccumuloSecurityException;
public Collection<Text> getSplits(String tableName) throws TableNotFoundException;
public Collection<Text> getSplits(String tableName, int maxSplits) throws TableNotFoundException;
public void compact(String tableName, Text start, Text end, boolean flush, boolean wait) throws AccumuloSecurityException, TableNotFoundException,
AccumuloException;
public void delete(String tableName) throws AccumuloException, AccumuloSecurityException, TableNotFoundException;
public void rename(String oldTableName, String newTableName) throws AccumuloSecurityException, TableNotFoundException, AccumuloException,
TableExistsException;
public void flush(String tableName) throws AccumuloException, AccumuloSecurityException;
public void setProperty(String tableName, String property, String value) throws AccumuloException, AccumuloSecurityException;
public void removeProperty(String tableName, String property) throws AccumuloException, AccumuloSecurityException;
public Iterable<Map.Entry<String, String>> getProperties(String tableName) throws AccumuloException, TableNotFoundException;
public void setLocalityGroups(String tableName, Map<String, Set<Text>> groups) throws AccumuloException, AccumuloSecurityException, TableNotFoundException;
public Map<String, Set<Text>> getLocalityGroups(String tableName) throws AccumuloException, TableNotFoundException;
public Set<Range> splitRangeByTablets(String tableName, Range range, int maxSplits) throws AccumuloException, AccumuloSecurityException,
TableNotFoundException;
public void importDirectory(String tableName, String dir, String failureDir, boolean setTime) throws TableNotFoundException, IOException, AccumuloException,
AccumuloSecurityException;
public BulkImportHelper.AssignmentStats importDirectory(String tableName, String dir, String failureDir, int numThreads, int numAssignThreads, boolean disableGC)
throws IOException, AccumuloException, AccumuloSecurityException;
public void offline(String tableName) throws AccumuloSecurityException, AccumuloException, TableNotFoundException;
public void online(String tableName) throws AccumuloSecurityException, AccumuloException, TableNotFoundException;
public void clearLocatorCache(String tableName) throws TableNotFoundException;
public Map<String, String> tableIdMap();
public void attachIterator(String tableName, IteratorSetting setting) throws AccumuloSecurityException, AccumuloException, TableNotFoundException;
public void attachIterator(String tableName, IteratorSetting setting, EnumSet<IteratorUtil.IteratorScope> scopes) throws AccumuloSecurityException, AccumuloException,
TableNotFoundException;
public void removeIterator(String tableName, String name, EnumSet<IteratorUtil.IteratorScope> scopes) throws AccumuloSecurityException, AccumuloException,
TableNotFoundException;
public IteratorSetting getIteratorSetting(String tableName, String name, IteratorUtil.IteratorScope scope) throws AccumuloSecurityException, AccumuloException,
TableNotFoundException;
public Map<String, EnumSet<IteratorUtil.IteratorScope>> listIterators(String tableName) throws AccumuloSecurityException, AccumuloException, TableNotFoundException;
public void checkIteratorConflicts(String tableName, IteratorSetting setting, EnumSet<IteratorUtil.IteratorScope> scopes) throws AccumuloException, TableNotFoundException;
}
| 5,198 | 0.811274 | 0.810504 | 95 | 53.71579 | 57.074959 | 175 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.273684 | false | false | 4 |
e6399ade9f08052a18ef5d0addf3acedd5c714cc | 15,857,019,295,483 | c98c1db695e4b18a8236fefb185748c350ae32f8 | /src/main/java/com/zhangkm/spider/frame/G.java | fb3d7731b6147bfe7a3c9530141f7c7310b11868 | [] | no_license | yxzkm/zkm-home | https://github.com/yxzkm/zkm-home | df63d519e6fe8fd4fef0599163ec9d9849ee17f9 | 8a8055b78741dcadf8fd14c8cc5e75237f46d4f5 | refs/heads/master | 2021-07-16T00:29:39.842000 | 2017-12-19T11:09:12 | 2017-12-19T11:09:12 | 96,161,399 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zhangkm.spider.frame;
import org.apache.http.client.HttpClient;
public class G {
public static final String QUEUE_JOB_CATCHER = "QUEUE:JOB_CATCHER";
public static final String QUEUE_LINK_SPIDER = "QUEUE:LINK_SPIDER";
public static final String QUEUE_LINK_CHECKER = "QUEUE:LINK_CHECKER";
public static final String QUEUE_PAGE_SPIDER = "QUEUE:PAGE_SPIDER";
public static final String QUEUE_TEXT_EXTRACTOR = "QUEUE:TEXT_EXTRACTOR";
public static final String QUEUE_BASIC_FILTER = "QUEUE:BASIC_FILTER";
public static final String QUEUE_INDUSTRY_FILTER = "QUEUE:INDUSTRY_FILTER";
public static final String QUEUE_REGION_FILTER = "QUEUE:REGION_FILTER";
public static final String QUEUE_MONGO_WRITER = "QUEUE:MONGO_WRITER";
public static final String QUEUE_SOLR_WRITER = "QUEUE:SOLR_WRITER";
public static String LOCAL_FILE_PATH;
public static String JCRB_CHANNEL_ID;
}
| UTF-8 | Java | 919 | java | G.java | Java | [] | null | [] | package com.zhangkm.spider.frame;
import org.apache.http.client.HttpClient;
public class G {
public static final String QUEUE_JOB_CATCHER = "QUEUE:JOB_CATCHER";
public static final String QUEUE_LINK_SPIDER = "QUEUE:LINK_SPIDER";
public static final String QUEUE_LINK_CHECKER = "QUEUE:LINK_CHECKER";
public static final String QUEUE_PAGE_SPIDER = "QUEUE:PAGE_SPIDER";
public static final String QUEUE_TEXT_EXTRACTOR = "QUEUE:TEXT_EXTRACTOR";
public static final String QUEUE_BASIC_FILTER = "QUEUE:BASIC_FILTER";
public static final String QUEUE_INDUSTRY_FILTER = "QUEUE:INDUSTRY_FILTER";
public static final String QUEUE_REGION_FILTER = "QUEUE:REGION_FILTER";
public static final String QUEUE_MONGO_WRITER = "QUEUE:MONGO_WRITER";
public static final String QUEUE_SOLR_WRITER = "QUEUE:SOLR_WRITER";
public static String LOCAL_FILE_PATH;
public static String JCRB_CHANNEL_ID;
}
| 919 | 0.751904 | 0.751904 | 22 | 39.772728 | 31.016026 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.181818 | false | false | 4 |
14f048c67d6f69dd54e401e33c52f712a69baa1b | 30,434,138,317,164 | d044ba6c2565c611b6efeafd3bbb25bac85834ab | /Beta-project/app/src/main/java/com/example/alpha_test/UploadPictures.java | 3a0e337478edaec52e47e4c1bf4dd891d287a1ce | [] | no_license | OmerHikly/BigProject | https://github.com/OmerHikly/BigProject | 70d9c65fe1602f72397ecff6ca1e0c88cdcd9113 | a02370eee2db78d82f7682f0e241d7b64b61c498 | refs/heads/master | 2022-06-21T10:00:47.132000 | 2020-05-08T09:22:07 | 2020-05-08T09:22:07 | 261,565,696 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.alpha_test;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
public class UploadPictures extends AppCompatActivity {
ImageView img;
Button ch;
Context ctx=this;
StorageReference mStorageRef;
private StorageTask<UploadTask.TaskSnapshot> uploadTask;
public Uri imguri;
public static final int IMAGE_PICK_CODE=1000;
public static final int PERMISSION_CODE=1001;
public static StorageReference Ref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_pictures);
mStorageRef = FirebaseStorage.getInstance().getReference();
img = findViewById(R.id.iv);
ch = findViewById(R.id.Chs);
}
public void FileChooser(View view) {//Check the permission and the sdk number of the device
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
requestPermissions(permissions,PERMISSION_CODE);
} else {
pickFromGallery();
}
} else {
pickFromGallery();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case PERMISSION_CODE:{
if (grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
pickFromGallery();
}
else{
Toast.makeText(this,"Permission denied",Toast.LENGTH_SHORT).show();
}
}
}
}
private void pickFromGallery() {//Choose the image,saves the image you clicked on
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, IMAGE_PICK_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {//checking that an image have picked and that the image url and data is fine
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_PICK_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
imguri = data.getData();
upload();
}
}
private String getExtension(Uri uri){//This method gets the extension of the file that have been picked (png,jpg,jpeg)
ContentResolver cr=getContentResolver();
MimeTypeMap mimeTypeMap=MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(cr.getType(uri));
}
public void upload() {//This method doing the service action of uploading the file.
Toast.makeText(this,"We are uploading your file...",Toast.LENGTH_SHORT).show();
Ref=mStorageRef.child("Images").child(System.currentTimeMillis()+"."+getExtension(imguri));//
//the line above keeps the extension of the file and name it with his millis since the the UNIX epoch: (1970-01-01 00:00:00 UTC) a date
// That makes sure that the first file that was uploaded will always remain the first and won't mix by the firebase order
uploadTask=Ref.putFile(imguri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {//If the reference is right do:
// Get a URL to the uploaded content
Toast.makeText(getApplicationContext(), "Image uploaded successfully", Toast.LENGTH_SHORT).show();
DownloadImg();
}
})
.addOnFailureListener(new OnFailureListener() {//if the reference is wrong:
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
private void DownloadImg() {// a method that downloads the url of the last added image
Ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>(){
@Override
public void onSuccess(Uri uri) {
Picasso.with(ctx).load(uri).fit().centerCrop().into(img);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
public void AuthScreen(MenuItem item) {
Intent t = new Intent(this, MainActivity.class);
startActivity(t);
}
public void RemoveScreen(MenuItem item) {
Intent t = new Intent(this, AddData.class);
startActivity(t);
}
public void ImageScreen(MenuItem item) {
Intent t = new Intent(this, UploadPictures.class);
startActivity(t);
}
public void ScanScreen(MenuItem item) {
Intent t = new Intent(this, BarcodeScan.class);
startActivity(t);
}
}
| UTF-8 | Java | 6,505 | java | UploadPictures.java | Java | [] | null | [] | package com.example.alpha_test;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
public class UploadPictures extends AppCompatActivity {
ImageView img;
Button ch;
Context ctx=this;
StorageReference mStorageRef;
private StorageTask<UploadTask.TaskSnapshot> uploadTask;
public Uri imguri;
public static final int IMAGE_PICK_CODE=1000;
public static final int PERMISSION_CODE=1001;
public static StorageReference Ref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_pictures);
mStorageRef = FirebaseStorage.getInstance().getReference();
img = findViewById(R.id.iv);
ch = findViewById(R.id.Chs);
}
public void FileChooser(View view) {//Check the permission and the sdk number of the device
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
requestPermissions(permissions,PERMISSION_CODE);
} else {
pickFromGallery();
}
} else {
pickFromGallery();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case PERMISSION_CODE:{
if (grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
pickFromGallery();
}
else{
Toast.makeText(this,"Permission denied",Toast.LENGTH_SHORT).show();
}
}
}
}
private void pickFromGallery() {//Choose the image,saves the image you clicked on
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, IMAGE_PICK_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {//checking that an image have picked and that the image url and data is fine
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_PICK_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
imguri = data.getData();
upload();
}
}
private String getExtension(Uri uri){//This method gets the extension of the file that have been picked (png,jpg,jpeg)
ContentResolver cr=getContentResolver();
MimeTypeMap mimeTypeMap=MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(cr.getType(uri));
}
public void upload() {//This method doing the service action of uploading the file.
Toast.makeText(this,"We are uploading your file...",Toast.LENGTH_SHORT).show();
Ref=mStorageRef.child("Images").child(System.currentTimeMillis()+"."+getExtension(imguri));//
//the line above keeps the extension of the file and name it with his millis since the the UNIX epoch: (1970-01-01 00:00:00 UTC) a date
// That makes sure that the first file that was uploaded will always remain the first and won't mix by the firebase order
uploadTask=Ref.putFile(imguri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {//If the reference is right do:
// Get a URL to the uploaded content
Toast.makeText(getApplicationContext(), "Image uploaded successfully", Toast.LENGTH_SHORT).show();
DownloadImg();
}
})
.addOnFailureListener(new OnFailureListener() {//if the reference is wrong:
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
private void DownloadImg() {// a method that downloads the url of the last added image
Ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>(){
@Override
public void onSuccess(Uri uri) {
Picasso.with(ctx).load(uri).fit().centerCrop().into(img);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
public void AuthScreen(MenuItem item) {
Intent t = new Intent(this, MainActivity.class);
startActivity(t);
}
public void RemoveScreen(MenuItem item) {
Intent t = new Intent(this, AddData.class);
startActivity(t);
}
public void ImageScreen(MenuItem item) {
Intent t = new Intent(this, UploadPictures.class);
startActivity(t);
}
public void ScanScreen(MenuItem item) {
Intent t = new Intent(this, BarcodeScan.class);
startActivity(t);
}
}
| 6,505 | 0.648117 | 0.644427 | 197 | 32.015228 | 33.780041 | 169 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.497462 | false | false | 4 |
3de2b646c5879e5a1213dd3a9738b044afb808d0 | 32,040,456,071,922 | 2112597843a5ddbc0e1a19b11bcfca5bf7cb3df5 | /src/test/java/tmproject/Controller/HomeControllerTest.java | 9a1ad263b5ba9e8f29405c43e287bdca60f64e66 | [] | no_license | danielpall/tmproject | https://github.com/danielpall/tmproject | 7399b472ae2f9b71ca5d25786bf37bf9067178b1 | ad8fbdf56e98a09c4f5857478e470373bf173ef4 | refs/heads/master | 2016-06-07T07:56:06.855000 | 2015-11-23T10:27:59 | 2015-11-23T10:27:59 | 46,531,772 | 0 | 0 | null | false | 2015-11-23T10:27:59 | 2015-11-20T01:40:49 | 2015-11-20T14:08:04 | 2015-11-23T10:27:59 | 26 | 0 | 0 | 0 | Java | null | null | package tmproject.Controller;
import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import tmproject.Service.StringManipulationService;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
public class HomeControllerTest {
@Test
public void testFrontpage() throws Exception {
StringManipulationService mockService = mock(StringManipulationService.class);
HomeController homeController = new HomeController(mockService);
MockMvc mockMvc = standaloneSetup(homeController).build();
mockMvc.perform(get("/"))
.andExpect(view().name("Index"));
}
} | UTF-8 | Java | 918 | java | HomeControllerTest.java | Java | [] | null | [] | package tmproject.Controller;
import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import tmproject.Service.StringManipulationService;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
public class HomeControllerTest {
@Test
public void testFrontpage() throws Exception {
StringManipulationService mockService = mock(StringManipulationService.class);
HomeController homeController = new HomeController(mockService);
MockMvc mockMvc = standaloneSetup(homeController).build();
mockMvc.perform(get("/"))
.andExpect(view().name("Index"));
}
} | 918 | 0.772331 | 0.772331 | 29 | 30.689655 | 31.398554 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.448276 | false | false | 4 |
b476db72206ca4868510ad9264b8975db7053828 | 18,073,222,423,589 | 2dae59b741ff18c5c99f4dcab19292deeacf3525 | /app/src/main/java/com/elpuig/ejercicio1realm/MostrarPersonas.java | 4f56fe048f56e6152b66f90501d9b2e20c5f4e06 | [] | no_license | Doble-De/Ejercicio2Realm | https://github.com/Doble-De/Ejercicio2Realm | 51e8862926f64008ed4048d8ddb13c0a16ee4583 | 551db5555affac40a2cbd0986369fc755e4ed1c6 | refs/heads/master | 2020-05-23T09:23:28.682000 | 2019-05-14T21:59:02 | 2019-05-14T21:59:02 | 186,705,974 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.elpuig.ejercicio1realm;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import io.realm.Realm;
import io.realm.RealmResults;
public class MostrarPersonas extends AppCompatActivity {
TextView textView, id;
String idm, nombreCompleto, genero, edad;
int ide;
boolean encontrado;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mostrar_personas);
Realm.init(this);
textView = findViewById(R.id.mostrar);
id = findViewById(R.id.idm);
listarPersonas();
findViewById(R.id.modificar).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println(idm+" "+nombreCompleto+" "+genero+" "+ edad);
if (buscarid() != null){
Intent intent = new Intent(MostrarPersonas.this, ModifPersonas.class);
intent.putExtra("id",idm);
intent.putExtra("name",nombreCompleto);
intent.putExtra("age",edad);
intent.putExtra("gender",genero);
startActivity(intent);
onDestroy();
}
}
});
findViewById(R.id.eliminar).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ide = buscarid().getId();
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
RealmResults<Persona> delete = realm.where(Persona.class)
.equalTo("id", ide)
.findAll();
delete.deleteAllFromRealm();
realm.commitTransaction();
listarPersonas();
}
});
}
public final List<Persona> listarPersonas(){
Realm realm = Realm.getDefaultInstance();
RealmResults<Persona> personas = realm.where(Persona.class).findAll();
String lista = "";
for (Persona persona : personas){
lista += "Id: " + persona.getId() + " Nombre Apellido: " + persona.getNombreCompleto() +" Edad: " + persona.getEdad() + " Genero: " + persona.getSexo() +"\n";
}
textView.setText(lista);
return personas;
}
public Persona buscarid(){
encontrado = false;
Realm realm = Realm.getDefaultInstance();
RealmResults<Persona> personas = realm.where(Persona.class).findAll();
int temp = Integer.parseInt((id.getText().toString()));
for (Persona persona : personas){
if (temp == persona.getId()){
idm = String.valueOf(persona.getId());
nombreCompleto = persona.getNombreCompleto();
edad = String.valueOf(persona.getEdad());
genero = persona.getSexo();
return persona;
}
}
return null;
}
}
| UTF-8 | Java | 3,224 | java | MostrarPersonas.java | Java | [] | null | [] | package com.elpuig.ejercicio1realm;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import io.realm.Realm;
import io.realm.RealmResults;
public class MostrarPersonas extends AppCompatActivity {
TextView textView, id;
String idm, nombreCompleto, genero, edad;
int ide;
boolean encontrado;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mostrar_personas);
Realm.init(this);
textView = findViewById(R.id.mostrar);
id = findViewById(R.id.idm);
listarPersonas();
findViewById(R.id.modificar).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println(idm+" "+nombreCompleto+" "+genero+" "+ edad);
if (buscarid() != null){
Intent intent = new Intent(MostrarPersonas.this, ModifPersonas.class);
intent.putExtra("id",idm);
intent.putExtra("name",nombreCompleto);
intent.putExtra("age",edad);
intent.putExtra("gender",genero);
startActivity(intent);
onDestroy();
}
}
});
findViewById(R.id.eliminar).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ide = buscarid().getId();
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
RealmResults<Persona> delete = realm.where(Persona.class)
.equalTo("id", ide)
.findAll();
delete.deleteAllFromRealm();
realm.commitTransaction();
listarPersonas();
}
});
}
public final List<Persona> listarPersonas(){
Realm realm = Realm.getDefaultInstance();
RealmResults<Persona> personas = realm.where(Persona.class).findAll();
String lista = "";
for (Persona persona : personas){
lista += "Id: " + persona.getId() + " Nombre Apellido: " + persona.getNombreCompleto() +" Edad: " + persona.getEdad() + " Genero: " + persona.getSexo() +"\n";
}
textView.setText(lista);
return personas;
}
public Persona buscarid(){
encontrado = false;
Realm realm = Realm.getDefaultInstance();
RealmResults<Persona> personas = realm.where(Persona.class).findAll();
int temp = Integer.parseInt((id.getText().toString()));
for (Persona persona : personas){
if (temp == persona.getId()){
idm = String.valueOf(persona.getId());
nombreCompleto = persona.getNombreCompleto();
edad = String.valueOf(persona.getEdad());
genero = persona.getSexo();
return persona;
}
}
return null;
}
}
| 3,224 | 0.572581 | 0.57196 | 97 | 32.237114 | 27.131514 | 170 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.649485 | false | false | 4 |
ae0a496a358462a4b4ea10633c1779ce87efe3a9 | 9,191,230,067,472 | ffc4aaa94f18d074ac6c8692cdeacc6410381de9 | /ActivitiServiceTest.java | 241bfb63629fadd8ca60f2b7ed5f1cfb07070d6e | [] | no_license | wangwenjie666/activiti-api | https://github.com/wangwenjie666/activiti-api | e4bacdb8adbe55ce74d8ecab3f6fd91c1d04ef23 | 6aa12b0461586d9048eb75ce4bc84b44eeac9469 | refs/heads/master | 2020-12-14T10:18:02.435000 | 2020-01-18T11:42:39 | 2020-01-18T11:42:39 | 234,708,637 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.imooc.activiti.helloworld;
import com.google.common.collect.Maps;
import org.activiti.engine.*;
import org.activiti.engine.history.*;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceBuilder;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
/**
* @Description: 基本 api 使用
* @Auther: wangwenjie
* @CreateTime: 2020-01-18
*/
public class ActivitiServiceTest {
private static Logger LOGGER = LoggerFactory.getLogger(ActivitiServiceTest.class);
private static final ProcessEngine processEngine = HelloWorld.getProcessEngine();
RuntimeService runtimeService = processEngine.getRuntimeService();
TaskService taskService = processEngine.getTaskService();
HistoryService historyService = processEngine.getHistoryService();
private ProcessDefinition processDefinition;
@Before
public void before() {
processDefinition = HelloWorld.getProcessDefinition(processEngine);
}
//通过key定义流程
@Test
public void createProcessByKey() {
//开始流程实例
Map<String, Object> map = Maps.newHashMap();
map.put("key1", "value1");
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("second_approve", map);
LOGGER.info("processInstance = {}", processInstance); //ProcessInstance[5]
}
//通过流程实例id 开启
@Test
public void createProcessById() {
ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId());
LOGGER.info("processInstance = {}", processInstance); //ProcessInstance[5]
}
//通过builder定义流程
@Test
public void createProcessByBuilder() {
//开始流程实例
Map<String, Object> map = Maps.newHashMap();
map.put("key1", "value1");
ProcessInstance processInstance = runtimeService.createProcessInstanceBuilder()
.businessKey("order001")
.processDefinitionKey(processDefinition.getKey())
.variables(map)
.start();
LOGGER.info("processInstance = {}", processInstance); //processInstance = ProcessInstance[5]
//设置变量
runtimeService.setVariable(processInstance.getId(), "key1", "value1111");
//获取创建流程中的参数
Map<String, Object> variables = runtimeService.getVariables(processInstance.getId());
LOGGER.info("variables = {}", variables);
}
//查询流程实例
@Test
public void queryProcessInstance() {
//开始流程实例
Map<String, Object> map = Maps.newHashMap();
map.put("key1", "value1");
ProcessInstance processInstance = runtimeService.createProcessInstanceBuilder()
.businessKey("order001")
.processDefinitionKey(processDefinition.getKey())
.variables(map)
.start();
LOGGER.info("processInstance = {}", processInstance); //processInstance = ProcessInstance[5]
//通过实例id查询
ProcessInstance processInstance1 = runtimeService.createProcessInstanceQuery()
.processInstanceId(processInstance.getId())
.singleResult();
//通过业务单号
ProcessInstance order1Instance = runtimeService.createProcessInstanceQuery()
.processInstanceBusinessKey("order001")
.singleResult();
LOGGER.info("query instance = {} , by businesskey = {}", processInstance1, order1Instance);
//获取执行器信息
List<Execution> executions = runtimeService.createExecutionQuery()
.listPage(0, 100);
for (Execution execution : executions) {
LOGGER.info("获取的执行器信息 {}", execution);
//获取的执行器信息 ProcessInstance[5]
//获取的执行器信息 Execution[ id '7' ] - activity 'submitForm - parent '5'
}
/**
* ProcessInstance表示一次工作流业务的实体数据
* Execution表示流程实例中的具体执行路径
*/
}
@Test
public void testTaskService() {
ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId());
Task task = taskService.createTaskQuery().singleResult();
LOGGER.info("task = {}", ToStringBuilder.reflectionToString(task, ToStringStyle.DEFAULT_STYLE));
}
@Test
public void testHistoryService() {
//发布流程
Deployment deploy = processEngine.getRepositoryService().createDeployment()
.addClasspathResource("one_process.bpmn")
.deploy();
//开启流程定义builder
Map<String, Object> variables = Maps.newHashMap();
Map<String, Object> transientVariables = Maps.newHashMap();
variables.put("key1", "value1");
variables.put("key2", "value2");
transientVariables.put("trans1", "transValue");
ProcessInstanceBuilder builder = processEngine.getRuntimeService().createProcessInstanceBuilder();
//开启的流程实例
ProcessInstance processInstance = builder.processDefinitionKey("one_process")
.variables(variables)
.transientVariables(transientVariables)
.start();
runtimeService.setVariable(processInstance.getId(), "key1", "value_1_1");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
//formSerivce 完成task
FormService formService = processEngine.getFormService();
Map<String, Object> properties = Maps.newHashMap();
properties.put("formkey1", "formValue1");
properties.put("key2", "value2_2");
properties.put("description", "同意");
// taskService.complete(task.getId(), properties);
// formService.submitTaskFormData(task.getId(), properties);
//historyService 流程实例
List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().list();
for (HistoricProcessInstance historicProcessInstance : list) {
LOGGER.info("historicProcessInstance = {}", ToStringBuilder.reflectionToString(historicProcessInstance));
}
//流程执行节点
List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery().list();
for (HistoricActivityInstance historicActivityInstance : historicActivityInstances) {
LOGGER.info("historicActivityInstance = {}", historicActivityInstance);
//HistoricActivityInstanceEntity[id=13, activityId=startevent1, activityName=开始]
//HistoricActivityInstanceEntity[id=14, activityId=approve, activityName=老板审批]
//HistoricActivityInstanceEntity[id=19, activityId=endevent1, activityName=结束]
}
//流程任务
List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery().list();
for (HistoricTaskInstance historicTaskInstance : historicTaskInstances) {
Map<String, Object> taskLocalVariables = historicTaskInstance.getTaskLocalVariables();
Map<String, Object> processVariables = historicTaskInstance.getProcessVariables();
LOGGER.info(" processVariables = {}", processVariables);
LOGGER.info(" taskLocalVariables = {}", taskLocalVariables);
LOGGER.info(" historicTaskInstance= {}", ToStringBuilder.reflectionToString(historicTaskInstance));
}
//变量
List<HistoricVariableInstance> historicVariableInstances = historyService.createHistoricVariableInstanceQuery().list();
for (HistoricVariableInstance historicVariableInstance : historicVariableInstances) {
LOGGER.info("historicVariableInstance = {}", ToStringBuilder.reflectionToString(historicVariableInstance));
}
//历史详情
List<HistoricDetail> historicDetails = historyService.createHistoricDetailQuery().listPage(0, 100);
for (HistoricDetail historicDetail : historicDetails) {
LOGGER.info("historicDetail = {}", ToStringBuilder.reflectionToString(historicDetail));
}
//log
ProcessInstanceHistoryLog processInstanceHistoryLog = historyService.createProcessInstanceHistoryLogQuery(processInstance.getId())
.includeActivities()
.includeComments()
.includeFormProperties()
.includeTasks()
.includeVariables()
.includeVariableUpdates()
.singleResult();
List<HistoricData> historicData = processInstanceHistoryLog.getHistoricData();
for (HistoricData historicDatum : historicData) {
LOGGER.info(" historicDatum= {}", ToStringBuilder.reflectionToString(historicDatum));
}
//删除流程实例
historyService.deleteHistoricProcessInstance(processInstance.getId());
HistoricProcessInstance historyInstanceQuery = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).singleResult();
LOGGER.info("historyInstanceQuery = {}", historyInstanceQuery);
}
}
| UTF-8 | Java | 9,779 | java | ActivitiServiceTest.java | Java | [
{
"context": "l.Map;\n\n/**\n * @Description: 基本 api 使用\n * @Auther: wangwenjie\n * @CreateTime: 2020-01-18\n */\npublic class Activ",
"end": 766,
"score": 0.9996404647827148,
"start": 756,
"tag": "USERNAME",
"value": "wangwenjie"
},
{
"context": "ssInstanceBuilder()\n .businessKey(\"order001\")\n .processDefinitionKey(processDe",
"end": 2325,
"score": 0.9687556028366089,
"start": 2317,
"tag": "KEY",
"value": "order001"
},
{
"context": "ssInstanceBuilder()\n .businessKey(\"order001\")\n .processDefinitionKey(processDe",
"end": 3122,
"score": 0.9600096940994263,
"start": 3114,
"tag": "KEY",
"value": "order001"
},
{
"context": "ry()\n .processInstanceBusinessKey(\"order001\")\n .singleResult();\n LOGGER",
"end": 3707,
"score": 0.7276961207389832,
"start": 3699,
"tag": "KEY",
"value": "order001"
},
{
"context": "\", \"value1\");\n variables.put(\"key2\", \"value2\");\n\n transientVariables.put(\"trans1\", \"tra",
"end": 5110,
"score": 0.7939693927764893,
"start": 5109,
"tag": "KEY",
"value": "2"
},
{
"context": "\", \"formValue1\");\n properties.put(\"key2\", \"value2_2\");\n properties.put(\"description\", \"同意\");\n/",
"end": 5940,
"score": 0.8447964787483215,
"start": 5932,
"tag": "KEY",
"value": "value2_2"
}
] | null | [] | package com.imooc.activiti.helloworld;
import com.google.common.collect.Maps;
import org.activiti.engine.*;
import org.activiti.engine.history.*;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceBuilder;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
/**
* @Description: 基本 api 使用
* @Auther: wangwenjie
* @CreateTime: 2020-01-18
*/
public class ActivitiServiceTest {
private static Logger LOGGER = LoggerFactory.getLogger(ActivitiServiceTest.class);
private static final ProcessEngine processEngine = HelloWorld.getProcessEngine();
RuntimeService runtimeService = processEngine.getRuntimeService();
TaskService taskService = processEngine.getTaskService();
HistoryService historyService = processEngine.getHistoryService();
private ProcessDefinition processDefinition;
@Before
public void before() {
processDefinition = HelloWorld.getProcessDefinition(processEngine);
}
//通过key定义流程
@Test
public void createProcessByKey() {
//开始流程实例
Map<String, Object> map = Maps.newHashMap();
map.put("key1", "value1");
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("second_approve", map);
LOGGER.info("processInstance = {}", processInstance); //ProcessInstance[5]
}
//通过流程实例id 开启
@Test
public void createProcessById() {
ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId());
LOGGER.info("processInstance = {}", processInstance); //ProcessInstance[5]
}
//通过builder定义流程
@Test
public void createProcessByBuilder() {
//开始流程实例
Map<String, Object> map = Maps.newHashMap();
map.put("key1", "value1");
ProcessInstance processInstance = runtimeService.createProcessInstanceBuilder()
.businessKey("order001")
.processDefinitionKey(processDefinition.getKey())
.variables(map)
.start();
LOGGER.info("processInstance = {}", processInstance); //processInstance = ProcessInstance[5]
//设置变量
runtimeService.setVariable(processInstance.getId(), "key1", "value1111");
//获取创建流程中的参数
Map<String, Object> variables = runtimeService.getVariables(processInstance.getId());
LOGGER.info("variables = {}", variables);
}
//查询流程实例
@Test
public void queryProcessInstance() {
//开始流程实例
Map<String, Object> map = Maps.newHashMap();
map.put("key1", "value1");
ProcessInstance processInstance = runtimeService.createProcessInstanceBuilder()
.businessKey("order001")
.processDefinitionKey(processDefinition.getKey())
.variables(map)
.start();
LOGGER.info("processInstance = {}", processInstance); //processInstance = ProcessInstance[5]
//通过实例id查询
ProcessInstance processInstance1 = runtimeService.createProcessInstanceQuery()
.processInstanceId(processInstance.getId())
.singleResult();
//通过业务单号
ProcessInstance order1Instance = runtimeService.createProcessInstanceQuery()
.processInstanceBusinessKey("order001")
.singleResult();
LOGGER.info("query instance = {} , by businesskey = {}", processInstance1, order1Instance);
//获取执行器信息
List<Execution> executions = runtimeService.createExecutionQuery()
.listPage(0, 100);
for (Execution execution : executions) {
LOGGER.info("获取的执行器信息 {}", execution);
//获取的执行器信息 ProcessInstance[5]
//获取的执行器信息 Execution[ id '7' ] - activity 'submitForm - parent '5'
}
/**
* ProcessInstance表示一次工作流业务的实体数据
* Execution表示流程实例中的具体执行路径
*/
}
@Test
public void testTaskService() {
ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId());
Task task = taskService.createTaskQuery().singleResult();
LOGGER.info("task = {}", ToStringBuilder.reflectionToString(task, ToStringStyle.DEFAULT_STYLE));
}
@Test
public void testHistoryService() {
//发布流程
Deployment deploy = processEngine.getRepositoryService().createDeployment()
.addClasspathResource("one_process.bpmn")
.deploy();
//开启流程定义builder
Map<String, Object> variables = Maps.newHashMap();
Map<String, Object> transientVariables = Maps.newHashMap();
variables.put("key1", "value1");
variables.put("key2", "value2");
transientVariables.put("trans1", "transValue");
ProcessInstanceBuilder builder = processEngine.getRuntimeService().createProcessInstanceBuilder();
//开启的流程实例
ProcessInstance processInstance = builder.processDefinitionKey("one_process")
.variables(variables)
.transientVariables(transientVariables)
.start();
runtimeService.setVariable(processInstance.getId(), "key1", "value_1_1");
Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
//formSerivce 完成task
FormService formService = processEngine.getFormService();
Map<String, Object> properties = Maps.newHashMap();
properties.put("formkey1", "formValue1");
properties.put("key2", "value2_2");
properties.put("description", "同意");
// taskService.complete(task.getId(), properties);
// formService.submitTaskFormData(task.getId(), properties);
//historyService 流程实例
List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().list();
for (HistoricProcessInstance historicProcessInstance : list) {
LOGGER.info("historicProcessInstance = {}", ToStringBuilder.reflectionToString(historicProcessInstance));
}
//流程执行节点
List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery().list();
for (HistoricActivityInstance historicActivityInstance : historicActivityInstances) {
LOGGER.info("historicActivityInstance = {}", historicActivityInstance);
//HistoricActivityInstanceEntity[id=13, activityId=startevent1, activityName=开始]
//HistoricActivityInstanceEntity[id=14, activityId=approve, activityName=老板审批]
//HistoricActivityInstanceEntity[id=19, activityId=endevent1, activityName=结束]
}
//流程任务
List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery().list();
for (HistoricTaskInstance historicTaskInstance : historicTaskInstances) {
Map<String, Object> taskLocalVariables = historicTaskInstance.getTaskLocalVariables();
Map<String, Object> processVariables = historicTaskInstance.getProcessVariables();
LOGGER.info(" processVariables = {}", processVariables);
LOGGER.info(" taskLocalVariables = {}", taskLocalVariables);
LOGGER.info(" historicTaskInstance= {}", ToStringBuilder.reflectionToString(historicTaskInstance));
}
//变量
List<HistoricVariableInstance> historicVariableInstances = historyService.createHistoricVariableInstanceQuery().list();
for (HistoricVariableInstance historicVariableInstance : historicVariableInstances) {
LOGGER.info("historicVariableInstance = {}", ToStringBuilder.reflectionToString(historicVariableInstance));
}
//历史详情
List<HistoricDetail> historicDetails = historyService.createHistoricDetailQuery().listPage(0, 100);
for (HistoricDetail historicDetail : historicDetails) {
LOGGER.info("historicDetail = {}", ToStringBuilder.reflectionToString(historicDetail));
}
//log
ProcessInstanceHistoryLog processInstanceHistoryLog = historyService.createProcessInstanceHistoryLogQuery(processInstance.getId())
.includeActivities()
.includeComments()
.includeFormProperties()
.includeTasks()
.includeVariables()
.includeVariableUpdates()
.singleResult();
List<HistoricData> historicData = processInstanceHistoryLog.getHistoricData();
for (HistoricData historicDatum : historicData) {
LOGGER.info(" historicDatum= {}", ToStringBuilder.reflectionToString(historicDatum));
}
//删除流程实例
historyService.deleteHistoricProcessInstance(processInstance.getId());
HistoricProcessInstance historyInstanceQuery = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).singleResult();
LOGGER.info("historyInstanceQuery = {}", historyInstanceQuery);
}
}
| 9,779 | 0.683186 | 0.675529 | 223 | 41.16592 | 36.188648 | 165 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.627803 | false | false | 4 |
dad06eb9bb0d192bf76158a4c1837d6eb2ff0f61 | 17,952,963,317,316 | 0b24cf99612ce74f354f2af5274888fc32b47e7b | /springboot-slice-upload/src/main/java/com/github/lybgeek/upload/strategy/SliceUploadStrategy.java | 48be1b87787a38f894311c02833ac577a42a565f | [] | no_license | lyb-geek/springboot-learning | https://github.com/lyb-geek/springboot-learning | 9c90706ffe4af8f14485d043c52bbb795f366bc0 | d441036b5969a8023b92b4c40b8a915cf524dba6 | refs/heads/master | 2023-07-25T13:43:46.685000 | 2023-07-22T12:41:42 | 2023-07-22T12:41:42 | 195,616,981 | 544 | 395 | null | false | 2023-03-11T02:17:31 | 2019-07-07T06:13:03 | 2023-03-07T10:00:13 | 2023-03-11T02:17:27 | 2,973 | 423 | 355 | 19 | Java | false | false | package com.github.lybgeek.upload.strategy;
import com.github.lybgeek.upload.dto.FileUploadDTO;
import com.github.lybgeek.upload.dto.FileUploadRequestDTO;
public interface SliceUploadStrategy {
FileUploadDTO sliceUpload(FileUploadRequestDTO param);
}
| UTF-8 | Java | 256 | java | SliceUploadStrategy.java | Java | [
{
"context": "package com.github.lybgeek.upload.strategy;\n\nimport com.github.lybgeek.uploa",
"end": 26,
"score": 0.9389718174934387,
"start": 19,
"tag": "USERNAME",
"value": "lybgeek"
},
{
"context": "ithub.lybgeek.upload.strategy;\n\nimport com.github.lybgeek.upload.dto.FileUploadDTO;\nimport com.github.lybge",
"end": 70,
"score": 0.9356439709663391,
"start": 63,
"tag": "USERNAME",
"value": "lybgeek"
},
{
"context": "bgeek.upload.dto.FileUploadDTO;\nimport com.github.lybgeek.upload.dto.FileUploadRequestDTO;\n\npublic interfac",
"end": 122,
"score": 0.930227518081665,
"start": 115,
"tag": "USERNAME",
"value": "lybgeek"
}
] | null | [] | package com.github.lybgeek.upload.strategy;
import com.github.lybgeek.upload.dto.FileUploadDTO;
import com.github.lybgeek.upload.dto.FileUploadRequestDTO;
public interface SliceUploadStrategy {
FileUploadDTO sliceUpload(FileUploadRequestDTO param);
}
| 256 | 0.839844 | 0.839844 | 9 | 27.444445 | 24.980486 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 4 |
14415596d391ea75a0578b581335018666b7dbaf | 24,979,529,846,568 | eae93a8069547c21dd764365ee6511d9fd0245de | /xdftest/src/main/java/com/android/xdftest/TemperatureTest.java | 003532c0a0be050ecdfe982daeb1ada4f1340565 | [] | no_license | lanzwu/AppTest | https://github.com/lanzwu/AppTest | 9414bc77e818dab2b45f9d0853012fbe59d5be27 | 8a3486981cdcffbba6f2b793c0505d56fc529bd1 | refs/heads/master | 2020-03-11T23:54:26.595000 | 2018-06-25T08:52:43 | 2018-06-25T08:52:43 | 130,335,196 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.android.xdftest;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;
import utils.BaseActivity;
import utils.TestConstants;
/**
* Created by zhouxiangyu on 2018/1/3.
*/
public class TemperatureTest extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.refresh_test);
showPresentation();
presentation.autoChangePicture(TestConstants.res,false, 1000);
RadioGroup modes = findViewById(R.id.modes);
modes.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (i){
case R.id.mode1:
okayManager.setEinkMode(1);
break;
case R.id.mode2:
okayManager.setEinkMode(2);
break;
case R.id.mode5:
okayManager.setEinkMode(5);
break;
case R.id.mode6:
//优化从GC16切换到A2头几张图片模糊的问题
okayManager.setEinkMode(6);
presentation.autoChangePicture(TestConstants.res,true, 0);
presentation.drawColor(Color.BLACK);
refresh();
break;
}
}
});
}
public void refresh() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
presentation.autoChangePicture(TestConstants.res,false, 1000);
}
},800);
}
public void exit(View view){
Log.d("zhouxiangyu","TemperatureTest exit");
okayManager.setEinkMode(1);
presentation.autoChangePicture(TestConstants.res,true, 0);
presentation.drawColor(Color.BLACK);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
TemperatureTest.this.finish();
}
},500);
}
}
| UTF-8 | Java | 2,343 | java | TemperatureTest.java | Java | [
{
"context": "ty;\nimport utils.TestConstants;\n\n/**\n * Created by zhouxiangyu on 2018/1/3.\n */\n\npublic class TemperatureTest ex",
"end": 284,
"score": 0.9995670318603516,
"start": 273,
"tag": "USERNAME",
"value": "zhouxiangyu"
}
] | null | [] | package com.android.xdftest;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;
import utils.BaseActivity;
import utils.TestConstants;
/**
* Created by zhouxiangyu on 2018/1/3.
*/
public class TemperatureTest extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.refresh_test);
showPresentation();
presentation.autoChangePicture(TestConstants.res,false, 1000);
RadioGroup modes = findViewById(R.id.modes);
modes.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (i){
case R.id.mode1:
okayManager.setEinkMode(1);
break;
case R.id.mode2:
okayManager.setEinkMode(2);
break;
case R.id.mode5:
okayManager.setEinkMode(5);
break;
case R.id.mode6:
//优化从GC16切换到A2头几张图片模糊的问题
okayManager.setEinkMode(6);
presentation.autoChangePicture(TestConstants.res,true, 0);
presentation.drawColor(Color.BLACK);
refresh();
break;
}
}
});
}
public void refresh() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
presentation.autoChangePicture(TestConstants.res,false, 1000);
}
},800);
}
public void exit(View view){
Log.d("zhouxiangyu","TemperatureTest exit");
okayManager.setEinkMode(1);
presentation.autoChangePicture(TestConstants.res,true, 0);
presentation.drawColor(Color.BLACK);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
TemperatureTest.this.finish();
}
},500);
}
}
| 2,343 | 0.551277 | 0.536564 | 73 | 30.657534 | 21.380583 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.630137 | false | false | 4 |
537f09a33de863e49cbfdf434d5b54428c646a37 | 15,891,379,004,579 | b404fba95bea8832edc91b853be71653f21aae4a | /src/isw24u/controller/GestoreAmministratore.java | e26b1f0611e65976e5118f28a94afe18faec2ee2 | [] | no_license | OmarPani93/ProgettoISW | https://github.com/OmarPani93/ProgettoISW | 3d3e44d5b98c7cf8b68f04c1ccbc190d0ddaa9f5 | ad6c29e898618de23a88b0a34afefef96a62db42 | refs/heads/master | 2020-02-26T00:19:14.808000 | 2016-07-26T20:20:42 | 2016-07-26T20:20:42 | 64,007,199 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package isw24u.controller;
import java.util.Date;
import isw24u.model.ContenutoMultimediale;
import isw24u.model.Database;
import isw24u.model.UtenteRegistrato;
public class GestoreAmministratore
{
public static boolean permaBanUtente(UtenteRegistrato amministratore, UtenteRegistrato utente)
{
if(amministratore == null || utente == null)
{
throw new IllegalArgumentException("Parametro/i non valido/i.");
}
if(!amministratore.isAdministrator() || amministratore.equals(utente))
{
return false;
}
/*
* La data di inizio e quella di fine ban vengone settate a null
* perché il ban è permanente
*/
utente.setInizioBan(new Date());
utente.setFineBan(null);
utente.setBanned(true);
utente.setBanPermanent(true);
return true;
}
public static boolean banUtente(UtenteRegistrato amministratore, UtenteRegistrato utente, Date fineBan)
{
if(amministratore == null || utente == null || fineBan == null)
{
throw new IllegalArgumentException("Parametro/i non valido/i.");
}
if(!amministratore.isAdministrator() || amministratore.equals(utente))
{
return false;
}
utente.setBanned(true);
utente.setBanPermanent(false);
utente.setInizioBan(new Date()); //L'inizio del ban viene settato con data e ora corrente
utente.setFineBan(fineBan);
return true;
}
public static boolean unBan(UtenteRegistrato amministratore, UtenteRegistrato utente)
{
if(amministratore == null || utente == null)
{
throw new IllegalArgumentException("Parametro/i non valido/i.");
}
if(!amministratore.isAdministrator() || amministratore.equals(utente))
{
return false;
}
utente.setBanned(false);
utente.setBanPermanent(false);
utente.setInizioBan(null);
utente.setFineBan(null);
return true;
}
public static boolean rimuoviPost(UtenteRegistrato amministratore, ContenutoMultimediale contenuto)
{
if(amministratore == null || contenuto == null)
{
throw new IllegalArgumentException("Parametro/i non valido/i.");
}
if(!amministratore.isAdministrator())
{
return false;
}
return Database.rimuoviContenuto(contenuto.getAutore(), contenuto);
}
}
| ISO-8859-1 | Java | 2,143 | java | GestoreAmministratore.java | Java | [] | null | [] | package isw24u.controller;
import java.util.Date;
import isw24u.model.ContenutoMultimediale;
import isw24u.model.Database;
import isw24u.model.UtenteRegistrato;
public class GestoreAmministratore
{
public static boolean permaBanUtente(UtenteRegistrato amministratore, UtenteRegistrato utente)
{
if(amministratore == null || utente == null)
{
throw new IllegalArgumentException("Parametro/i non valido/i.");
}
if(!amministratore.isAdministrator() || amministratore.equals(utente))
{
return false;
}
/*
* La data di inizio e quella di fine ban vengone settate a null
* perché il ban è permanente
*/
utente.setInizioBan(new Date());
utente.setFineBan(null);
utente.setBanned(true);
utente.setBanPermanent(true);
return true;
}
public static boolean banUtente(UtenteRegistrato amministratore, UtenteRegistrato utente, Date fineBan)
{
if(amministratore == null || utente == null || fineBan == null)
{
throw new IllegalArgumentException("Parametro/i non valido/i.");
}
if(!amministratore.isAdministrator() || amministratore.equals(utente))
{
return false;
}
utente.setBanned(true);
utente.setBanPermanent(false);
utente.setInizioBan(new Date()); //L'inizio del ban viene settato con data e ora corrente
utente.setFineBan(fineBan);
return true;
}
public static boolean unBan(UtenteRegistrato amministratore, UtenteRegistrato utente)
{
if(amministratore == null || utente == null)
{
throw new IllegalArgumentException("Parametro/i non valido/i.");
}
if(!amministratore.isAdministrator() || amministratore.equals(utente))
{
return false;
}
utente.setBanned(false);
utente.setBanPermanent(false);
utente.setInizioBan(null);
utente.setFineBan(null);
return true;
}
public static boolean rimuoviPost(UtenteRegistrato amministratore, ContenutoMultimediale contenuto)
{
if(amministratore == null || contenuto == null)
{
throw new IllegalArgumentException("Parametro/i non valido/i.");
}
if(!amministratore.isAdministrator())
{
return false;
}
return Database.rimuoviContenuto(contenuto.getAutore(), contenuto);
}
}
| 2,143 | 0.733769 | 0.730033 | 79 | 26.101265 | 28.668156 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.278481 | false | false | 4 |
5adba9107ba992f698e18ab257ab9ca5feb647fa | 8,564,164,845,785 | 9533317822e004f352b53437e43e0e317c116eab | /WinesOfCrete/src/main/java/com/cs360/winesofcrete/server/Home.java | 5ab132d639d30d023214e5e15c87760812c0734b | [] | no_license | Sundorius/Wines-Of-Crete | https://github.com/Sundorius/Wines-Of-Crete | 07b87dd2d7595a1f3a031d02fa26673c8a202f43 | 159f6b50f5040a15504d7c6cb5018407b63adb2d | refs/heads/main | 2023-01-03T13:09:01.044000 | 2020-10-21T16:12:51 | 2020-10-21T16:12:51 | 305,977,255 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
@file: Home.java
*/
package com.cs360.winesofcrete.server;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author manos katsifarakis <csd3195@csd.uoc.gr>
*/
@WebServlet(name = "Home",urlPatterns ={"/Home"})
public class Home extends HttpServlet
{
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
HttpSession session = request.getSession(false);
if (session == null)
{
response.setStatus(401);
return;
}
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter())
{
out.println("<!DOCTYPE html>\n"
+ "<html>\n"
+ " <head>\n"
+ " <title>Wines of Crete</title>\n"
+ " <meta charset=\"UTF-8\">\n"
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n"
+ "\n"
+ " <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css\" crossorigin=\"anonymous\">\n"
+ " <link rel=\"stylesheet\" type=\"text/css\" href=\"css/base.css\">\n"
+ "\n"
+ " <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" crossorigin=\"anonymous\"></script>\n"
+ " <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js\" crossorigin=\"anonymous\"></script>\n"
+ " <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js\" crossorigin=\"anonymous\"></script>\n"
+ " </head>\n"
+ " <body>\n"
+ " <nav class=\"navbar navbar-dark bg-dark navbar-fixed-top\">\n"
+ " <div class=\"container-fluid\">\n"
+ " <div class=\"navbar-header\">\n"
+ " <label class=\"navbar-brand\">Wines of Crete</label>\n"
+ " </div>\n"
+ " <div class=\"navbar-right\">\n"
+ " <ul class=\"nav\">\n"
+ " <li class=\"nav-item space-after\">\n"
+ " <a class=\"navbar-brand\" href=\"#\" onclick=\"getUserOrders()\">\n"
+ " <div id=\"username_holder\" class=\"username_holder\">"
+ session.getAttribute("username").toString()
+ " </div>\n"
+ " </a>\n"
+ " </li>\n"
+ " <li class=\"nav-item space-after\">\n"
+ " <a class=\"navbar-brand\" href=\"#\" onclick=\"showAllProducts()\">All Products</a>\n"
+ " </li>\n"
+ " <li class=\"nav-item\">\n"
+ " <a class=\"navbar-brand\" href=\"#\" onclick=\"logOut()\">Logout</a>\n"
+ " </li>\n"
+ " </ul>\n"
+ " </div>\n"
+ " </nav>\n"
+ " <div class=\"row\">\n"
+ " <div class=\"col-sm-2 sidebar my-sidebar\">\n"
+ " <ul class=\"nav-sidebar\" >\n"
+ " <li class=\"active\">\n"
+ " <a href=\"#\" onclick=\"showAllProducts()\">All Products</a>\n"
+ " </li>\n"
+ " <li>\n"
+ " <a href=\"#\" onclick=\"showTopProducts()\">Top 10 Products - Wineries </a>\n"
+ " </li>\n"
+ " <li>\n"
+ " <a href=\"#\" onclick=\"showBadCustomers()\">Bad Customers</a>\n"
+ " </li>\n"
+ " <li>\n"
+ " <a href=\"#\" onclick=\"showGoodCustomers()\">Good Customers</a>\n"
+ " </li>\n"
+ " <li>\n"
+ " <a href=\"#\" onclick=\"showTransactions()\">Show Transactions History</a>\n"
+ " </li>\n"
+ " <li>\n"
+ " <a href=\"#\" onclick=\"changeUserInformation()\">Change Personsal Information</a>\n"
+ " </li>\n"
+ " </ul>\n"
+ " </div>\n"
+ " <div id=\"main_div\" class=\"col-sm-8 main\" style=\"text-align: left;\">"
// TODO fill main div!!
+ " </div>\n"
+ " <div id=\"right_div\" class=\"col-sm-2 sidebar my-sidebar col-right\">"
+ " <ul id=\"inner_right_div\">\n"
+ " <li>"
+ " <a onclick=\"showBasket()\" href=\"#\">Basket</a>\n"
+ " </li>"
+ " <li>"
+ " <a onclick=\"getUserOrders()\" href=\"#\">Show Orders</a>\n"
+ " </li>"
+ " <li>"
+ " <a onclick=\"returnProductOrder()\" href=\"#\">Return Product-Order</a>\n"
+ " </li>"
+ " <li>"
+ " <a onclick=\"deleteAccount()\" href=\"#\">Delete Account</a>\n"
+ " </li>"
+ " </ul>"
+ " </div>"
+ " </div>\n"
+ "\n"
// TODO ADD ALL THE NECESSARY .js FILED BELOW!!!
+ " <script src=\"js/account.js\"></script>\n"
+ " <script src=\"js/basket.js\"></script>\n"
+ " <script src=\"js/orders.js\"></script>\n"
+ " <script src=\"js/logout.js\"></script>\n"
+ " <script src=\"js/payOrder.js\"></script>\n"
+ " <script src=\"js/showAllProducts.js\"></script>\n"
+ " <script src=\"js/showBadCustomers.js\"></script>\n"
+ " <script src=\"js/showGoodCustomers.js\"></script>\n"
+ " <script src=\"js/showProductsOfSelection.js\"></script>\n"
+ " <script src=\"js/showTopProducts.js\"></script>\n"
+ " <script src=\"js/showTransactions.js\"></script>\n"
+ " <script src=\"js/changeUserInformation.js\"></script>\n"
+ " <script src=\"js/updateUserInformation.js\"></script>\n"
+ "\n"
+ " </body>\n"
+ "</html>\n"
);
}
response.setStatus(200);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| UTF-8 | Java | 9,419 | java | Home.java | Java | [
{
"context": "javax.servlet.http.HttpSession;\n\n/**\n *\n * @author manos katsifarakis <csd3195@csd.uoc.gr>\n */\n@WebServlet(name = \"Home",
"end": 413,
"score": 0.9998001456260681,
"start": 395,
"tag": "NAME",
"value": "manos katsifarakis"
},
{
"context": "tpSession;\n\n/**\n *\n * @author manos katsifarakis <csd3195@csd.uoc.gr>\n */\n@WebServlet(name = \"Home\",urlPatterns ={\"/Ho",
"end": 433,
"score": 0.9999306797981262,
"start": 415,
"tag": "EMAIL",
"value": "csd3195@csd.uoc.gr"
},
{
"context": " + \" <div id=\\\"username_holder\\\" class=\\\"username_holder\\\">\"\n + s",
"end": 3197,
"score": 0.9955458045005798,
"start": 3182,
"tag": "USERNAME",
"value": "username_holder"
},
{
"context": " <div id=\\\"username_holder\\\" class=\\\"username_holder\\\">\"\n + session.getAttribute(\"usern",
"end": 3223,
"score": 0.9743270874023438,
"start": 3208,
"tag": "USERNAME",
"value": "username_holder"
},
{
"context": "older\\\">\"\n + session.getAttribute(\"username\").toString()\n + \" ",
"end": 3276,
"score": 0.6501211524009705,
"start": 3268,
"tag": "USERNAME",
"value": "username"
}
] | null | [] | /*
@file: Home.java
*/
package com.cs360.winesofcrete.server;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author <NAME> <<EMAIL>>
*/
@WebServlet(name = "Home",urlPatterns ={"/Home"})
public class Home extends HttpServlet
{
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
HttpSession session = request.getSession(false);
if (session == null)
{
response.setStatus(401);
return;
}
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter())
{
out.println("<!DOCTYPE html>\n"
+ "<html>\n"
+ " <head>\n"
+ " <title>Wines of Crete</title>\n"
+ " <meta charset=\"UTF-8\">\n"
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n"
+ "\n"
+ " <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css\" crossorigin=\"anonymous\">\n"
+ " <link rel=\"stylesheet\" type=\"text/css\" href=\"css/base.css\">\n"
+ "\n"
+ " <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" crossorigin=\"anonymous\"></script>\n"
+ " <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js\" crossorigin=\"anonymous\"></script>\n"
+ " <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js\" crossorigin=\"anonymous\"></script>\n"
+ " </head>\n"
+ " <body>\n"
+ " <nav class=\"navbar navbar-dark bg-dark navbar-fixed-top\">\n"
+ " <div class=\"container-fluid\">\n"
+ " <div class=\"navbar-header\">\n"
+ " <label class=\"navbar-brand\">Wines of Crete</label>\n"
+ " </div>\n"
+ " <div class=\"navbar-right\">\n"
+ " <ul class=\"nav\">\n"
+ " <li class=\"nav-item space-after\">\n"
+ " <a class=\"navbar-brand\" href=\"#\" onclick=\"getUserOrders()\">\n"
+ " <div id=\"username_holder\" class=\"username_holder\">"
+ session.getAttribute("username").toString()
+ " </div>\n"
+ " </a>\n"
+ " </li>\n"
+ " <li class=\"nav-item space-after\">\n"
+ " <a class=\"navbar-brand\" href=\"#\" onclick=\"showAllProducts()\">All Products</a>\n"
+ " </li>\n"
+ " <li class=\"nav-item\">\n"
+ " <a class=\"navbar-brand\" href=\"#\" onclick=\"logOut()\">Logout</a>\n"
+ " </li>\n"
+ " </ul>\n"
+ " </div>\n"
+ " </nav>\n"
+ " <div class=\"row\">\n"
+ " <div class=\"col-sm-2 sidebar my-sidebar\">\n"
+ " <ul class=\"nav-sidebar\" >\n"
+ " <li class=\"active\">\n"
+ " <a href=\"#\" onclick=\"showAllProducts()\">All Products</a>\n"
+ " </li>\n"
+ " <li>\n"
+ " <a href=\"#\" onclick=\"showTopProducts()\">Top 10 Products - Wineries </a>\n"
+ " </li>\n"
+ " <li>\n"
+ " <a href=\"#\" onclick=\"showBadCustomers()\">Bad Customers</a>\n"
+ " </li>\n"
+ " <li>\n"
+ " <a href=\"#\" onclick=\"showGoodCustomers()\">Good Customers</a>\n"
+ " </li>\n"
+ " <li>\n"
+ " <a href=\"#\" onclick=\"showTransactions()\">Show Transactions History</a>\n"
+ " </li>\n"
+ " <li>\n"
+ " <a href=\"#\" onclick=\"changeUserInformation()\">Change Personsal Information</a>\n"
+ " </li>\n"
+ " </ul>\n"
+ " </div>\n"
+ " <div id=\"main_div\" class=\"col-sm-8 main\" style=\"text-align: left;\">"
// TODO fill main div!!
+ " </div>\n"
+ " <div id=\"right_div\" class=\"col-sm-2 sidebar my-sidebar col-right\">"
+ " <ul id=\"inner_right_div\">\n"
+ " <li>"
+ " <a onclick=\"showBasket()\" href=\"#\">Basket</a>\n"
+ " </li>"
+ " <li>"
+ " <a onclick=\"getUserOrders()\" href=\"#\">Show Orders</a>\n"
+ " </li>"
+ " <li>"
+ " <a onclick=\"returnProductOrder()\" href=\"#\">Return Product-Order</a>\n"
+ " </li>"
+ " <li>"
+ " <a onclick=\"deleteAccount()\" href=\"#\">Delete Account</a>\n"
+ " </li>"
+ " </ul>"
+ " </div>"
+ " </div>\n"
+ "\n"
// TODO ADD ALL THE NECESSARY .js FILED BELOW!!!
+ " <script src=\"js/account.js\"></script>\n"
+ " <script src=\"js/basket.js\"></script>\n"
+ " <script src=\"js/orders.js\"></script>\n"
+ " <script src=\"js/logout.js\"></script>\n"
+ " <script src=\"js/payOrder.js\"></script>\n"
+ " <script src=\"js/showAllProducts.js\"></script>\n"
+ " <script src=\"js/showBadCustomers.js\"></script>\n"
+ " <script src=\"js/showGoodCustomers.js\"></script>\n"
+ " <script src=\"js/showProductsOfSelection.js\"></script>\n"
+ " <script src=\"js/showTopProducts.js\"></script>\n"
+ " <script src=\"js/showTransactions.js\"></script>\n"
+ " <script src=\"js/changeUserInformation.js\"></script>\n"
+ " <script src=\"js/updateUserInformation.js\"></script>\n"
+ "\n"
+ " </body>\n"
+ "</html>\n"
);
}
response.setStatus(200);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| 9,396 | 0.420851 | 0.416923 | 193 | 47.803108 | 35.520302 | 167 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.15544 | false | false | 4 |
8ca405ca3e6855595e7230eb4996cee9ac970fd5 | 17,059,610,168,958 | 1378a7442ee574872e894ede362b211f81f7effe | /src/com/iotek/github/Git2.java | 4c2be8e646cfeb4bd5de2b782292a5b71a6fbfc5 | [] | no_license | DANDANQAQ/eclipsegithub1228 | https://github.com/DANDANQAQ/eclipsegithub1228 | 699f0ac1d4677c948f42853da6e1e0b58d03ce2b | 29073967ef1a2f06c9ff393d8650846d015ec902 | refs/heads/master | 2021-09-01T17:17:18.236000 | 2017-12-28T02:53:23 | 2017-12-28T02:53:23 | 115,577,243 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.iotek.github;
public class Git2 {
}
| UTF-8 | Java | 55 | java | Git2.java | Java | [] | null | [] | package com.iotek.github;
public class Git2 {
}
| 55 | 0.654545 | 0.636364 | 5 | 9 | 10.788883 | 25 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 4 |
60e893eca043cb498f0cf912cc8c71747bb396e9 | 2,637,109,964,400 | a3a48bef46b31fcdd914f8ab67f5282f560d5c28 | /hipparchus-migration/src/main/java/org/hipparchus/migration/ode/JacobianMatrices.java | 72f554c93a4a7d869d9e7fd2d0f7383798c9ec1a | [
"BSD-3-Clause",
"Minpack",
"Apache-2.0",
"MIT",
"GPL-2.0-only",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-generic-cla"
] | permissive | Hipparchus-Math/hipparchus | https://github.com/Hipparchus-Math/hipparchus | f88ebc1e4a9ab8cd698f258564ecfcda75a389a6 | fc5af4e976fb48de690c6670b0bc0214d0b095db | refs/heads/master | 2023-09-04T12:34:51.209000 | 2023-09-01T17:26:49 | 2023-09-01T17:26:49 | 60,063,484 | 114 | 41 | Apache-2.0 | false | 2023-08-19T10:30:33 | 2016-05-31T06:24:32 | 2023-07-17T06:49:12 | 2023-08-19T10:30:30 | 30,047 | 113 | 41 | 21 | Java | false | false | /*
* 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.
*/
/*
* This is not the original file distributed by the Apache Software Foundation
* It has been modified by the Hipparchus project
*/
package org.hipparchus.migration.ode;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.hipparchus.exception.LocalizedCoreFormats;
import org.hipparchus.exception.MathIllegalArgumentException;
import org.hipparchus.exception.MathIllegalStateException;
import org.hipparchus.ode.ExpandableODE;
import org.hipparchus.ode.LocalizedODEFormats;
import org.hipparchus.ode.NamedParameterJacobianProvider;
import org.hipparchus.ode.ODEState;
import org.hipparchus.ode.OrdinaryDifferentialEquation;
import org.hipparchus.ode.ParameterConfiguration;
import org.hipparchus.ode.ParametersController;
import org.hipparchus.ode.SecondaryODE;
/**
* This class defines a set of {@link SecondaryODE secondary equations} to
* compute the Jacobian matrices with respect to the initial state vector and, if
* any, to some parameters of the primary ODE set.
* <p>
* It is intended to be packed into an {@link ExpandableODE}
* in conjunction with a primary set of ODE, which may be:</p>
* <ul>
* <li>a {@link FirstOrderDifferentialEquations}</li>
* <li>a {@link MainStateJacobianProvider}</li>
* </ul>
* <p>In order to compute Jacobian matrices with respect to some parameters of the
* primary ODE set, the following parameter Jacobian providers may be set:</p>
* <ul>
* <li>a {@link ParametersController}</li>
* </ul>
*
* @see ExpandableODE
* @see FirstOrderDifferentialEquations
* @see MainStateJacobianProvider
* @see NamedParameterJacobianProvider
* @see ParametersController
* @deprecated as of 1.0, replaced with {@link org.hipparchus.ode.VariationalEquation}
*/
@Deprecated
public class JacobianMatrices {
/** Expandable first order differential equation. */
private ExpandableODE efode;
/** Index of the instance in the expandable set. */
private int index;
/** FODE with exact primary Jacobian computation skill. */
private MainStateJacobianProvider jode;
/** FODE without exact parameter Jacobian computation skill. */
private ParametersController parametersController;
/** Primary state vector dimension. */
private int stateDim;
/** Selected parameters for parameter Jacobian computation. */
private MutableParameterConfiguration[] selectedParameters;
/** FODE with exact parameter Jacobian computation skill. */
private List<NamedParameterJacobianProvider> jacobianProviders;
/** Parameters dimension. */
private int paramDim;
/** Boolean for selected parameters consistency. */
private boolean dirtyParameter;
/** State and parameters Jacobian matrices in a row. */
private double[] matricesData;
/** Simple constructor for a secondary equations set computing Jacobian matrices.
* <p>
* Parameters must belong to the supported ones given by {@link
* org.hipparchus.ode.Parameterizable#getParametersNames()}, so the primary set of differential
* equations must be {@link org.hipparchus.ode.Parameterizable}.
* </p>
* <p>Note that each selection clears the previous selected parameters.</p>
*
* @param fode the primary first order differential equations set to extend
* @param hY step used for finite difference computation with respect to state vector
* @param parameters parameters to consider for Jacobian matrices processing
* (may be null if parameters Jacobians is not desired)
* @exception MathIllegalArgumentException if there is a dimension mismatch between
* the steps array {@code hY} and the equation dimension
*/
public JacobianMatrices(final OrdinaryDifferentialEquation fode, final double[] hY,
final String... parameters)
throws MathIllegalArgumentException {
this(new MainStateJacobianWrapper(fode, hY), parameters);
}
/** Simple constructor for a secondary equations set computing Jacobian matrices.
* <p>
* Parameters must belong to the supported ones given by {@link
* org.hipparchus.ode.Parameterizable#getParametersNames()}, so the primary set of differential
* equations must be {@link org.hipparchus.ode.Parameterizable}.
* </p>
* <p>Note that each selection clears the previous selected parameters.</p>
*
* @param jode the primary first order differential equations set to extend
* @param parameters parameters to consider for Jacobian matrices processing
* (may be null if parameters Jacobians is not desired)
*/
public JacobianMatrices(final MainStateJacobianProvider jode,
final String... parameters) {
this.efode = null;
this.index = -1;
this.jode = jode;
this.parametersController = null;
this.stateDim = jode.getDimension();
if (parameters == null) {
selectedParameters = null;
paramDim = 0;
} else {
this.selectedParameters = new MutableParameterConfiguration[parameters.length];
for (int i = 0; i < parameters.length; ++i) {
selectedParameters[i] = new MutableParameterConfiguration(parameters[i], Double.NaN);
}
paramDim = parameters.length;
}
this.dirtyParameter = false;
this.jacobianProviders = new ArrayList<>();
// set the default initial state Jacobian to the identity
// and the default initial parameters Jacobian to the null matrix
matricesData = new double[(stateDim + paramDim) * stateDim];
for (int i = 0; i < stateDim; ++i) {
matricesData[i * (stateDim + 1)] = 1.0;
}
}
/** Register the variational equations for the Jacobians matrices to the expandable set.
* <p>
* This method must be called <em>before {@link #setUpInitialState(ODEState)}</em>
* </p>
* @param expandable expandable set into which variational equations should be registered
* @throws MathIllegalArgumentException if the dimension of the partial state does not
* match the selected equations set dimension
* @exception MismatchedEquations if the primary set of the expandable set does
* not match the one used to build the instance
* @see ExpandableODE#addSecondaryEquations(SecondaryODE)
* @see #setUpInitialState(ODEState)
*/
public void registerVariationalEquations(final ExpandableODE expandable)
throws MathIllegalArgumentException, MismatchedEquations {
// safety checks
final OrdinaryDifferentialEquation ode = (jode instanceof MainStateJacobianWrapper) ?
((MainStateJacobianWrapper) jode).ode :
jode;
if (expandable.getPrimary() != ode) {
throw new MismatchedEquations();
}
efode = expandable;
index = efode.addSecondaryEquations(new JacobiansSecondaryODE());
}
/** Set up initial state.
* <p>
* This method inserts the initial Jacobian matrices data into
* an {@link ODEState ODE state} by overriding the additional
* state components corresponding to the instance. It must be
* called prior to integrate the equations.
* </p>
* <p>
* This method must be called <em>after</em> {@link
* #registerVariationalEquations(ExpandableODE)},
* {@link #setInitialMainStateJacobian(double[][])} and
* {@link #setInitialParameterJacobian(String, double[])}.
* </p>
* @param initialState initial state, without the initial Jacobians
* matrices
* @return a new instance of initial state, with the initial Jacobians
* matrices properly initialized
*/
public ODEState setUpInitialState(final ODEState initialState) { // NOPMD - PMD false positive
// insert the matrices data into secondary states
final double[][] secondary = new double[efode.getMapper().getNumberOfEquations() - 1][];
for (int i = 0; i < initialState.getNumberOfSecondaryStates(); ++i) {
if (i + 1 != index) {
secondary[i] = initialState.getSecondaryState(i + 1);
}
}
secondary[index - 1] = matricesData;
// create an updated initial state
return new ODEState(initialState.getTime(), initialState.getPrimaryState(), secondary);
}
/** Add a parameter Jacobian provider.
* @param provider the parameter Jacobian provider to compute exactly the parameter Jacobian matrix
*/
public void addParameterJacobianProvider(final NamedParameterJacobianProvider provider) {
jacobianProviders.add(provider);
}
/** Set a parameter Jacobian provider.
* @param pc the controller to compute the parameter Jacobian matrix using finite differences
* @deprecated as of 1.0, replaced with {@link #setParametersController(ParametersController)}
*/
@Deprecated
public void setParameterizedODE(final ParametersController pc) {
setParametersController(pc);
}
/** Set a parameter Jacobian provider.
* @param parametersController the controller to compute the parameter Jacobian matrix using finite differences
*/
public void setParametersController(final ParametersController parametersController) {
this.parametersController = parametersController;
dirtyParameter = true;
}
/** Set the step associated to a parameter in order to compute by finite
* difference the Jacobian matrix.
* <p>
* Needed if and only if the primary ODE set is a {@link ParametersController}.
* </p>
* <p>
* Given a non zero parameter value pval for the parameter, a reasonable value
* for such a step is {@code pval * FastMath.sqrt(Precision.EPSILON)}.
* </p>
* <p>
* A zero value for such a step doesn't enable to compute the parameter Jacobian matrix.
* </p>
* @param parameter parameter to consider for Jacobian processing
* @param hP step for Jacobian finite difference computation w.r.t. the specified parameter
* @see ParametersController
* @exception MathIllegalArgumentException if the parameter is not supported
*/
public void setParameterStep(final String parameter, final double hP)
throws MathIllegalArgumentException {
for (MutableParameterConfiguration param: selectedParameters) {
if (parameter.equals(param.getParameterName())) {
param.setHP(hP);
dirtyParameter = true;
return;
}
}
throw new MathIllegalArgumentException(LocalizedODEFormats.UNKNOWN_PARAMETER, parameter);
}
/** Set the initial value of the Jacobian matrix with respect to state.
* <p>
* If this method is not called, the initial value of the Jacobian
* matrix with respect to state is set to identity.
* </p>
* <p>
* This method must be called <em>before {@link #setUpInitialState(ODEState)}</em>
* </p>
* @param dYdY0 initial Jacobian matrix w.r.t. state
* @exception MathIllegalArgumentException if matrix dimensions are incorrect
*/
public void setInitialMainStateJacobian(final double[][] dYdY0)
throws MathIllegalArgumentException {
// Check dimensions
checkDimension(stateDim, dYdY0);
checkDimension(stateDim, dYdY0[0]);
// store the matrix in row major order as a single dimension array
int i = 0;
for (final double[] row : dYdY0) {
System.arraycopy(row, 0, matricesData, i, stateDim);
i += stateDim;
}
}
/** Set the initial value of a column of the Jacobian matrix with respect to one parameter.
* <p>
* If this method is not called for some parameter, the initial value of
* the column of the Jacobian matrix with respect to this parameter is set to zero.
* </p>
* <p>
* This method must be called <em>before {@link #setUpInitialState(ODEState)}</em>
* </p>
* @param pName parameter name
* @param dYdP initial Jacobian column vector with respect to the parameter
* @exception MathIllegalArgumentException if a parameter is not supported
* @throws MathIllegalArgumentException if the column vector does not match state dimension
*/
public void setInitialParameterJacobian(final String pName, final double[] dYdP)
throws MathIllegalArgumentException {
// Check dimensions
checkDimension(stateDim, dYdP);
// store the column in a global single dimension array
int i = stateDim * stateDim;
for (MutableParameterConfiguration param: selectedParameters) {
if (pName.equals(param.getParameterName())) {
System.arraycopy(dYdP, 0, matricesData, i, stateDim);
return;
}
i += stateDim;
}
throw new MathIllegalArgumentException(LocalizedODEFormats.UNKNOWN_PARAMETER, pName);
}
/** Extract the Jacobian matrix with respect to state.
* @param state state from which to extract Jacobian matrix
* @return Jacobian matrix dY/dY0 with respect to state.
*/
public double[][] extractMainSetJacobian(final ODEState state) {
// get current state for this set of equations from the expandable fode
final double[] p = state.getSecondaryState(index);
final double[][] dYdY0 = new double[stateDim][stateDim];
int j = 0;
for (int i = 0; i < stateDim; i++) {
System.arraycopy(p, j, dYdY0[i], 0, stateDim);
j += stateDim;
}
return dYdY0;
}
/** Extract the Jacobian matrix with respect to one parameter.
* @param state state from which to extract Jacobian matrix
* @param pName name of the parameter for the computed Jacobian matrix
* @return Jacobian matrix dY/dP with respect to the named parameter
*/
public double[] extractParameterJacobian(final ODEState state, final String pName) {
// get current state for this set of equations from the expandable fode
final double[] p = state.getSecondaryState(index);
final double[] dYdP = new double[stateDim];
int i = stateDim * stateDim;
for (MutableParameterConfiguration param: selectedParameters) {
if (param.getParameterName().equals(pName)) {
System.arraycopy(p, i, dYdP, 0, stateDim);
break;
}
i += stateDim;
}
return dYdP;
}
/** Check array dimensions.
* @param expected expected dimension
* @param array (may be null if expected is 0)
* @throws MathIllegalArgumentException if the array dimension does not match the expected one
*/
private void checkDimension(final int expected, final Object array)
throws MathIllegalArgumentException {
int arrayDimension = (array == null) ? 0 : Array.getLength(array);
if (arrayDimension != expected) {
throw new MathIllegalArgumentException(LocalizedCoreFormats.DIMENSIONS_MISMATCH,
arrayDimension, expected);
}
}
/** Local implementation of secondary equations.
* <p>
* This class is an inner class to ensure proper scheduling of calls
* by forcing the use of {@link JacobianMatrices#registerVariationalEquations(ExpandableODE)}.
* </p>
*/
private class JacobiansSecondaryODE implements SecondaryODE {
/** {@inheritDoc} */
@Override
public int getDimension() {
return stateDim * (stateDim + paramDim);
}
/** {@inheritDoc} */
@Override
public double[] computeDerivatives(final double t, final double[] y, final double[] yDot,
final double[] z)
throws MathIllegalArgumentException, MathIllegalStateException {
try {
// Lazy initialization
Constructor<ParameterConfiguration> configCtr =
ParameterConfiguration.class.getDeclaredConstructor(String.class, Double.TYPE);
configCtr.setAccessible(true);
@SuppressWarnings("unchecked")
Constructor<NamedParameterJacobianProvider> providerCtr =
(Constructor<NamedParameterJacobianProvider>)
Class.forName("org.hipparchus.ode.ParameterJacobianWrapper").getDeclaredConstructor(OrdinaryDifferentialEquation.class,
double[].class,
ParametersController.class,
ParameterConfiguration[].class);
providerCtr.setAccessible(true);
if (dirtyParameter && (paramDim != 0)) {
ParameterConfiguration [] immutable = new ParameterConfiguration[selectedParameters.length];
for (int i = 0; i < selectedParameters.length; ++i) {
immutable[i] = configCtr.newInstance(selectedParameters[i].getParameterName(),
selectedParameters[i].getHP());
}
jacobianProviders.add(providerCtr.newInstance(jode, new double[jode.getDimension()],
parametersController, immutable));
dirtyParameter = false;
}
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException |
InvocationTargetException | NoSuchMethodException | SecurityException | ClassNotFoundException e) {
throw new MathIllegalStateException(e, LocalizedCoreFormats.SIMPLE_MESSAGE, e.getLocalizedMessage());
}
// variational equations:
// from d[dy/dt]/dy0 and d[dy/dt]/dp to d[dy/dy0]/dt and d[dy/dp]/dt
// compute Jacobian matrix with respect to primary state
double[][] dFdY = jode.computeMainStateJacobian(t, y, yDot);
// Dispatch Jacobian matrix in the compound secondary state vector
final double[] zDot = new double[z.length];
for (int i = 0; i < stateDim; ++i) {
final double[] dFdYi = dFdY[i];
for (int j = 0; j < stateDim; ++j) {
double s = 0;
final int startIndex = j;
int zIndex = startIndex;
for (int l = 0; l < stateDim; ++l) {
s += dFdYi[l] * z[zIndex];
zIndex += stateDim;
}
zDot[startIndex + i * stateDim] = s;
}
}
if (paramDim != 0) {
// compute Jacobian matrices with respect to parameters
int startIndex = stateDim * stateDim;
for (MutableParameterConfiguration param: selectedParameters) {
boolean found = false;
for (int k = 0 ; (!found) && (k < jacobianProviders.size()); ++k) {
final NamedParameterJacobianProvider provider = jacobianProviders.get(k);
if (provider.isSupported(param.getParameterName())) {
final double[] dFdP =
provider.computeParameterJacobian(t, y, yDot,
param.getParameterName());
for (int i = 0; i < stateDim; ++i) {
final double[] dFdYi = dFdY[i];
int zIndex = startIndex;
double s = dFdP[i];
for (int l = 0; l < stateDim; ++l) {
s += dFdYi[l] * z[zIndex];
zIndex++;
}
zDot[startIndex + i] = s;
}
found = true;
}
}
if (! found) {
Arrays.fill(zDot, startIndex, startIndex + stateDim, 0.0);
}
startIndex += stateDim;
}
}
return zDot;
}
}
/** Wrapper class to compute jacobian matrices by finite differences for ODE
* which do not compute them by themselves.
*/
private static class MainStateJacobianWrapper implements MainStateJacobianProvider {
/** Raw ODE without jacobians computation skill to be wrapped into a MainStateJacobianProvider. */
private final OrdinaryDifferentialEquation ode;
/** Steps for finite difference computation of the jacobian df/dy w.r.t. state. */
private final double[] hY;
/** Wrap a {@link FirstOrderDifferentialEquations} into a {@link MainStateJacobianProvider}.
* @param ode original ODE problem, without jacobians computation skill
* @param hY step sizes to compute the jacobian df/dy
* @exception MathIllegalArgumentException if there is a dimension mismatch between
* the steps array {@code hY} and the equation dimension
*/
MainStateJacobianWrapper(final OrdinaryDifferentialEquation ode,
final double[] hY)
throws MathIllegalArgumentException {
this.ode = ode;
this.hY = hY.clone();
if (hY.length != ode.getDimension()) {
throw new MathIllegalArgumentException(LocalizedCoreFormats.DIMENSIONS_MISMATCH,
ode.getDimension(), hY.length);
}
}
/** {@inheritDoc} */
@Override
public int getDimension() {
return ode.getDimension();
}
/** {@inheritDoc} */
@Override
public double[] computeDerivatives(double t, double[] y)
throws MathIllegalArgumentException, MathIllegalStateException {
return ode.computeDerivatives(t, y);
}
/** {@inheritDoc} */
@Override
public double[][] computeMainStateJacobian(double t, double[] y, double[] yDot)
throws MathIllegalArgumentException, MathIllegalStateException {
final int n = ode.getDimension();
final double[][] dFdY = new double[n][n];
for (int j = 0; j < n; ++j) {
final double savedYj = y[j];
y[j] += hY[j];
final double[] tmpDot = ode.computeDerivatives(t, y);
for (int i = 0; i < n; ++i) {
dFdY[i][j] = (tmpDot[i] - yDot[i]) / hY[j];
}
y[j] = savedYj;
}
return dFdY;
}
}
/**
* Special exception for equations mismatch.
*/
public static class MismatchedEquations extends MathIllegalArgumentException {
/** Serializable UID. */
private static final long serialVersionUID = 20120902L;
/** Simple constructor. */
public MismatchedEquations() {
super(LocalizedODEFormats.UNMATCHED_ODE_IN_EXPANDED_SET);
}
}
/** Selected parameter for parameter Jacobian computation. */
private static class MutableParameterConfiguration {
/** Parameter name. */
private String parameterName;
/** Parameter step for finite difference computation. */
private double hP;
/** Parameter name and step pair constructor.
* @param parameterName parameter name
* @param hP parameter step
*/
MutableParameterConfiguration(final String parameterName, final double hP) {
this.parameterName = parameterName;
this.hP = hP;
}
/** Get parameter name.
* @return parameterName parameter name
*/
public String getParameterName() {
return parameterName;
}
/** Get parameter step.
* @return hP parameter step
*/
public double getHP() {
return hP;
}
/** Set parameter step.
* @param hParam parameter step
*/
public void setHP(final double hParam) {
this.hP = hParam;
}
}
}
| UTF-8 | Java | 25,790 | java | JacobianMatrices.java | Java | [] | null | [] | /*
* 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.
*/
/*
* This is not the original file distributed by the Apache Software Foundation
* It has been modified by the Hipparchus project
*/
package org.hipparchus.migration.ode;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.hipparchus.exception.LocalizedCoreFormats;
import org.hipparchus.exception.MathIllegalArgumentException;
import org.hipparchus.exception.MathIllegalStateException;
import org.hipparchus.ode.ExpandableODE;
import org.hipparchus.ode.LocalizedODEFormats;
import org.hipparchus.ode.NamedParameterJacobianProvider;
import org.hipparchus.ode.ODEState;
import org.hipparchus.ode.OrdinaryDifferentialEquation;
import org.hipparchus.ode.ParameterConfiguration;
import org.hipparchus.ode.ParametersController;
import org.hipparchus.ode.SecondaryODE;
/**
* This class defines a set of {@link SecondaryODE secondary equations} to
* compute the Jacobian matrices with respect to the initial state vector and, if
* any, to some parameters of the primary ODE set.
* <p>
* It is intended to be packed into an {@link ExpandableODE}
* in conjunction with a primary set of ODE, which may be:</p>
* <ul>
* <li>a {@link FirstOrderDifferentialEquations}</li>
* <li>a {@link MainStateJacobianProvider}</li>
* </ul>
* <p>In order to compute Jacobian matrices with respect to some parameters of the
* primary ODE set, the following parameter Jacobian providers may be set:</p>
* <ul>
* <li>a {@link ParametersController}</li>
* </ul>
*
* @see ExpandableODE
* @see FirstOrderDifferentialEquations
* @see MainStateJacobianProvider
* @see NamedParameterJacobianProvider
* @see ParametersController
* @deprecated as of 1.0, replaced with {@link org.hipparchus.ode.VariationalEquation}
*/
@Deprecated
public class JacobianMatrices {
/** Expandable first order differential equation. */
private ExpandableODE efode;
/** Index of the instance in the expandable set. */
private int index;
/** FODE with exact primary Jacobian computation skill. */
private MainStateJacobianProvider jode;
/** FODE without exact parameter Jacobian computation skill. */
private ParametersController parametersController;
/** Primary state vector dimension. */
private int stateDim;
/** Selected parameters for parameter Jacobian computation. */
private MutableParameterConfiguration[] selectedParameters;
/** FODE with exact parameter Jacobian computation skill. */
private List<NamedParameterJacobianProvider> jacobianProviders;
/** Parameters dimension. */
private int paramDim;
/** Boolean for selected parameters consistency. */
private boolean dirtyParameter;
/** State and parameters Jacobian matrices in a row. */
private double[] matricesData;
/** Simple constructor for a secondary equations set computing Jacobian matrices.
* <p>
* Parameters must belong to the supported ones given by {@link
* org.hipparchus.ode.Parameterizable#getParametersNames()}, so the primary set of differential
* equations must be {@link org.hipparchus.ode.Parameterizable}.
* </p>
* <p>Note that each selection clears the previous selected parameters.</p>
*
* @param fode the primary first order differential equations set to extend
* @param hY step used for finite difference computation with respect to state vector
* @param parameters parameters to consider for Jacobian matrices processing
* (may be null if parameters Jacobians is not desired)
* @exception MathIllegalArgumentException if there is a dimension mismatch between
* the steps array {@code hY} and the equation dimension
*/
public JacobianMatrices(final OrdinaryDifferentialEquation fode, final double[] hY,
final String... parameters)
throws MathIllegalArgumentException {
this(new MainStateJacobianWrapper(fode, hY), parameters);
}
/** Simple constructor for a secondary equations set computing Jacobian matrices.
* <p>
* Parameters must belong to the supported ones given by {@link
* org.hipparchus.ode.Parameterizable#getParametersNames()}, so the primary set of differential
* equations must be {@link org.hipparchus.ode.Parameterizable}.
* </p>
* <p>Note that each selection clears the previous selected parameters.</p>
*
* @param jode the primary first order differential equations set to extend
* @param parameters parameters to consider for Jacobian matrices processing
* (may be null if parameters Jacobians is not desired)
*/
public JacobianMatrices(final MainStateJacobianProvider jode,
final String... parameters) {
this.efode = null;
this.index = -1;
this.jode = jode;
this.parametersController = null;
this.stateDim = jode.getDimension();
if (parameters == null) {
selectedParameters = null;
paramDim = 0;
} else {
this.selectedParameters = new MutableParameterConfiguration[parameters.length];
for (int i = 0; i < parameters.length; ++i) {
selectedParameters[i] = new MutableParameterConfiguration(parameters[i], Double.NaN);
}
paramDim = parameters.length;
}
this.dirtyParameter = false;
this.jacobianProviders = new ArrayList<>();
// set the default initial state Jacobian to the identity
// and the default initial parameters Jacobian to the null matrix
matricesData = new double[(stateDim + paramDim) * stateDim];
for (int i = 0; i < stateDim; ++i) {
matricesData[i * (stateDim + 1)] = 1.0;
}
}
/** Register the variational equations for the Jacobians matrices to the expandable set.
* <p>
* This method must be called <em>before {@link #setUpInitialState(ODEState)}</em>
* </p>
* @param expandable expandable set into which variational equations should be registered
* @throws MathIllegalArgumentException if the dimension of the partial state does not
* match the selected equations set dimension
* @exception MismatchedEquations if the primary set of the expandable set does
* not match the one used to build the instance
* @see ExpandableODE#addSecondaryEquations(SecondaryODE)
* @see #setUpInitialState(ODEState)
*/
public void registerVariationalEquations(final ExpandableODE expandable)
throws MathIllegalArgumentException, MismatchedEquations {
// safety checks
final OrdinaryDifferentialEquation ode = (jode instanceof MainStateJacobianWrapper) ?
((MainStateJacobianWrapper) jode).ode :
jode;
if (expandable.getPrimary() != ode) {
throw new MismatchedEquations();
}
efode = expandable;
index = efode.addSecondaryEquations(new JacobiansSecondaryODE());
}
/** Set up initial state.
* <p>
* This method inserts the initial Jacobian matrices data into
* an {@link ODEState ODE state} by overriding the additional
* state components corresponding to the instance. It must be
* called prior to integrate the equations.
* </p>
* <p>
* This method must be called <em>after</em> {@link
* #registerVariationalEquations(ExpandableODE)},
* {@link #setInitialMainStateJacobian(double[][])} and
* {@link #setInitialParameterJacobian(String, double[])}.
* </p>
* @param initialState initial state, without the initial Jacobians
* matrices
* @return a new instance of initial state, with the initial Jacobians
* matrices properly initialized
*/
public ODEState setUpInitialState(final ODEState initialState) { // NOPMD - PMD false positive
// insert the matrices data into secondary states
final double[][] secondary = new double[efode.getMapper().getNumberOfEquations() - 1][];
for (int i = 0; i < initialState.getNumberOfSecondaryStates(); ++i) {
if (i + 1 != index) {
secondary[i] = initialState.getSecondaryState(i + 1);
}
}
secondary[index - 1] = matricesData;
// create an updated initial state
return new ODEState(initialState.getTime(), initialState.getPrimaryState(), secondary);
}
/** Add a parameter Jacobian provider.
* @param provider the parameter Jacobian provider to compute exactly the parameter Jacobian matrix
*/
public void addParameterJacobianProvider(final NamedParameterJacobianProvider provider) {
jacobianProviders.add(provider);
}
/** Set a parameter Jacobian provider.
* @param pc the controller to compute the parameter Jacobian matrix using finite differences
* @deprecated as of 1.0, replaced with {@link #setParametersController(ParametersController)}
*/
@Deprecated
public void setParameterizedODE(final ParametersController pc) {
setParametersController(pc);
}
/** Set a parameter Jacobian provider.
* @param parametersController the controller to compute the parameter Jacobian matrix using finite differences
*/
public void setParametersController(final ParametersController parametersController) {
this.parametersController = parametersController;
dirtyParameter = true;
}
/** Set the step associated to a parameter in order to compute by finite
* difference the Jacobian matrix.
* <p>
* Needed if and only if the primary ODE set is a {@link ParametersController}.
* </p>
* <p>
* Given a non zero parameter value pval for the parameter, a reasonable value
* for such a step is {@code pval * FastMath.sqrt(Precision.EPSILON)}.
* </p>
* <p>
* A zero value for such a step doesn't enable to compute the parameter Jacobian matrix.
* </p>
* @param parameter parameter to consider for Jacobian processing
* @param hP step for Jacobian finite difference computation w.r.t. the specified parameter
* @see ParametersController
* @exception MathIllegalArgumentException if the parameter is not supported
*/
public void setParameterStep(final String parameter, final double hP)
throws MathIllegalArgumentException {
for (MutableParameterConfiguration param: selectedParameters) {
if (parameter.equals(param.getParameterName())) {
param.setHP(hP);
dirtyParameter = true;
return;
}
}
throw new MathIllegalArgumentException(LocalizedODEFormats.UNKNOWN_PARAMETER, parameter);
}
/** Set the initial value of the Jacobian matrix with respect to state.
* <p>
* If this method is not called, the initial value of the Jacobian
* matrix with respect to state is set to identity.
* </p>
* <p>
* This method must be called <em>before {@link #setUpInitialState(ODEState)}</em>
* </p>
* @param dYdY0 initial Jacobian matrix w.r.t. state
* @exception MathIllegalArgumentException if matrix dimensions are incorrect
*/
public void setInitialMainStateJacobian(final double[][] dYdY0)
throws MathIllegalArgumentException {
// Check dimensions
checkDimension(stateDim, dYdY0);
checkDimension(stateDim, dYdY0[0]);
// store the matrix in row major order as a single dimension array
int i = 0;
for (final double[] row : dYdY0) {
System.arraycopy(row, 0, matricesData, i, stateDim);
i += stateDim;
}
}
/** Set the initial value of a column of the Jacobian matrix with respect to one parameter.
* <p>
* If this method is not called for some parameter, the initial value of
* the column of the Jacobian matrix with respect to this parameter is set to zero.
* </p>
* <p>
* This method must be called <em>before {@link #setUpInitialState(ODEState)}</em>
* </p>
* @param pName parameter name
* @param dYdP initial Jacobian column vector with respect to the parameter
* @exception MathIllegalArgumentException if a parameter is not supported
* @throws MathIllegalArgumentException if the column vector does not match state dimension
*/
public void setInitialParameterJacobian(final String pName, final double[] dYdP)
throws MathIllegalArgumentException {
// Check dimensions
checkDimension(stateDim, dYdP);
// store the column in a global single dimension array
int i = stateDim * stateDim;
for (MutableParameterConfiguration param: selectedParameters) {
if (pName.equals(param.getParameterName())) {
System.arraycopy(dYdP, 0, matricesData, i, stateDim);
return;
}
i += stateDim;
}
throw new MathIllegalArgumentException(LocalizedODEFormats.UNKNOWN_PARAMETER, pName);
}
/** Extract the Jacobian matrix with respect to state.
* @param state state from which to extract Jacobian matrix
* @return Jacobian matrix dY/dY0 with respect to state.
*/
public double[][] extractMainSetJacobian(final ODEState state) {
// get current state for this set of equations from the expandable fode
final double[] p = state.getSecondaryState(index);
final double[][] dYdY0 = new double[stateDim][stateDim];
int j = 0;
for (int i = 0; i < stateDim; i++) {
System.arraycopy(p, j, dYdY0[i], 0, stateDim);
j += stateDim;
}
return dYdY0;
}
/** Extract the Jacobian matrix with respect to one parameter.
* @param state state from which to extract Jacobian matrix
* @param pName name of the parameter for the computed Jacobian matrix
* @return Jacobian matrix dY/dP with respect to the named parameter
*/
public double[] extractParameterJacobian(final ODEState state, final String pName) {
// get current state for this set of equations from the expandable fode
final double[] p = state.getSecondaryState(index);
final double[] dYdP = new double[stateDim];
int i = stateDim * stateDim;
for (MutableParameterConfiguration param: selectedParameters) {
if (param.getParameterName().equals(pName)) {
System.arraycopy(p, i, dYdP, 0, stateDim);
break;
}
i += stateDim;
}
return dYdP;
}
/** Check array dimensions.
* @param expected expected dimension
* @param array (may be null if expected is 0)
* @throws MathIllegalArgumentException if the array dimension does not match the expected one
*/
private void checkDimension(final int expected, final Object array)
throws MathIllegalArgumentException {
int arrayDimension = (array == null) ? 0 : Array.getLength(array);
if (arrayDimension != expected) {
throw new MathIllegalArgumentException(LocalizedCoreFormats.DIMENSIONS_MISMATCH,
arrayDimension, expected);
}
}
/** Local implementation of secondary equations.
* <p>
* This class is an inner class to ensure proper scheduling of calls
* by forcing the use of {@link JacobianMatrices#registerVariationalEquations(ExpandableODE)}.
* </p>
*/
private class JacobiansSecondaryODE implements SecondaryODE {
/** {@inheritDoc} */
@Override
public int getDimension() {
return stateDim * (stateDim + paramDim);
}
/** {@inheritDoc} */
@Override
public double[] computeDerivatives(final double t, final double[] y, final double[] yDot,
final double[] z)
throws MathIllegalArgumentException, MathIllegalStateException {
try {
// Lazy initialization
Constructor<ParameterConfiguration> configCtr =
ParameterConfiguration.class.getDeclaredConstructor(String.class, Double.TYPE);
configCtr.setAccessible(true);
@SuppressWarnings("unchecked")
Constructor<NamedParameterJacobianProvider> providerCtr =
(Constructor<NamedParameterJacobianProvider>)
Class.forName("org.hipparchus.ode.ParameterJacobianWrapper").getDeclaredConstructor(OrdinaryDifferentialEquation.class,
double[].class,
ParametersController.class,
ParameterConfiguration[].class);
providerCtr.setAccessible(true);
if (dirtyParameter && (paramDim != 0)) {
ParameterConfiguration [] immutable = new ParameterConfiguration[selectedParameters.length];
for (int i = 0; i < selectedParameters.length; ++i) {
immutable[i] = configCtr.newInstance(selectedParameters[i].getParameterName(),
selectedParameters[i].getHP());
}
jacobianProviders.add(providerCtr.newInstance(jode, new double[jode.getDimension()],
parametersController, immutable));
dirtyParameter = false;
}
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException |
InvocationTargetException | NoSuchMethodException | SecurityException | ClassNotFoundException e) {
throw new MathIllegalStateException(e, LocalizedCoreFormats.SIMPLE_MESSAGE, e.getLocalizedMessage());
}
// variational equations:
// from d[dy/dt]/dy0 and d[dy/dt]/dp to d[dy/dy0]/dt and d[dy/dp]/dt
// compute Jacobian matrix with respect to primary state
double[][] dFdY = jode.computeMainStateJacobian(t, y, yDot);
// Dispatch Jacobian matrix in the compound secondary state vector
final double[] zDot = new double[z.length];
for (int i = 0; i < stateDim; ++i) {
final double[] dFdYi = dFdY[i];
for (int j = 0; j < stateDim; ++j) {
double s = 0;
final int startIndex = j;
int zIndex = startIndex;
for (int l = 0; l < stateDim; ++l) {
s += dFdYi[l] * z[zIndex];
zIndex += stateDim;
}
zDot[startIndex + i * stateDim] = s;
}
}
if (paramDim != 0) {
// compute Jacobian matrices with respect to parameters
int startIndex = stateDim * stateDim;
for (MutableParameterConfiguration param: selectedParameters) {
boolean found = false;
for (int k = 0 ; (!found) && (k < jacobianProviders.size()); ++k) {
final NamedParameterJacobianProvider provider = jacobianProviders.get(k);
if (provider.isSupported(param.getParameterName())) {
final double[] dFdP =
provider.computeParameterJacobian(t, y, yDot,
param.getParameterName());
for (int i = 0; i < stateDim; ++i) {
final double[] dFdYi = dFdY[i];
int zIndex = startIndex;
double s = dFdP[i];
for (int l = 0; l < stateDim; ++l) {
s += dFdYi[l] * z[zIndex];
zIndex++;
}
zDot[startIndex + i] = s;
}
found = true;
}
}
if (! found) {
Arrays.fill(zDot, startIndex, startIndex + stateDim, 0.0);
}
startIndex += stateDim;
}
}
return zDot;
}
}
/** Wrapper class to compute jacobian matrices by finite differences for ODE
* which do not compute them by themselves.
*/
private static class MainStateJacobianWrapper implements MainStateJacobianProvider {
/** Raw ODE without jacobians computation skill to be wrapped into a MainStateJacobianProvider. */
private final OrdinaryDifferentialEquation ode;
/** Steps for finite difference computation of the jacobian df/dy w.r.t. state. */
private final double[] hY;
/** Wrap a {@link FirstOrderDifferentialEquations} into a {@link MainStateJacobianProvider}.
* @param ode original ODE problem, without jacobians computation skill
* @param hY step sizes to compute the jacobian df/dy
* @exception MathIllegalArgumentException if there is a dimension mismatch between
* the steps array {@code hY} and the equation dimension
*/
MainStateJacobianWrapper(final OrdinaryDifferentialEquation ode,
final double[] hY)
throws MathIllegalArgumentException {
this.ode = ode;
this.hY = hY.clone();
if (hY.length != ode.getDimension()) {
throw new MathIllegalArgumentException(LocalizedCoreFormats.DIMENSIONS_MISMATCH,
ode.getDimension(), hY.length);
}
}
/** {@inheritDoc} */
@Override
public int getDimension() {
return ode.getDimension();
}
/** {@inheritDoc} */
@Override
public double[] computeDerivatives(double t, double[] y)
throws MathIllegalArgumentException, MathIllegalStateException {
return ode.computeDerivatives(t, y);
}
/** {@inheritDoc} */
@Override
public double[][] computeMainStateJacobian(double t, double[] y, double[] yDot)
throws MathIllegalArgumentException, MathIllegalStateException {
final int n = ode.getDimension();
final double[][] dFdY = new double[n][n];
for (int j = 0; j < n; ++j) {
final double savedYj = y[j];
y[j] += hY[j];
final double[] tmpDot = ode.computeDerivatives(t, y);
for (int i = 0; i < n; ++i) {
dFdY[i][j] = (tmpDot[i] - yDot[i]) / hY[j];
}
y[j] = savedYj;
}
return dFdY;
}
}
/**
* Special exception for equations mismatch.
*/
public static class MismatchedEquations extends MathIllegalArgumentException {
/** Serializable UID. */
private static final long serialVersionUID = 20120902L;
/** Simple constructor. */
public MismatchedEquations() {
super(LocalizedODEFormats.UNMATCHED_ODE_IN_EXPANDED_SET);
}
}
/** Selected parameter for parameter Jacobian computation. */
private static class MutableParameterConfiguration {
/** Parameter name. */
private String parameterName;
/** Parameter step for finite difference computation. */
private double hP;
/** Parameter name and step pair constructor.
* @param parameterName parameter name
* @param hP parameter step
*/
MutableParameterConfiguration(final String parameterName, final double hP) {
this.parameterName = parameterName;
this.hP = hP;
}
/** Get parameter name.
* @return parameterName parameter name
*/
public String getParameterName() {
return parameterName;
}
/** Get parameter step.
* @return hP parameter step
*/
public double getHP() {
return hP;
}
/** Set parameter step.
* @param hParam parameter step
*/
public void setHP(final double hParam) {
this.hP = hParam;
}
}
}
| 25,790 | 0.615781 | 0.613339 | 629 | 40 | 31.915379 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.419714 | false | false | 4 |
790f2ee6fbcb2bb97ef8ce025067fb3fcdbd323c | 5,257,039,980,119 | 3710f8a8785675e41cdf32d15b0036888692a4b8 | /IHM/src/Modele/Personne.java | 5a8e2484116c4e040cc93313b6f4954eae77deac | [] | no_license | GDubuisson/IHM | https://github.com/GDubuisson/IHM | 007a708c2de40d220465b851f577cf4e3c5340c0 | 5b8ec49b27b148f0301ffcb1116a01c7363e8e77 | refs/heads/master | 2021-04-03T08:18:18.185000 | 2018-04-02T22:56:14 | 2018-04-02T22:56:14 | 124,085,641 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 Modele;
import static ihm.SQLiteConnection.connect;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author popor
*/
public class Personne {
private int idPersonne;
private String Nom;
private String Prenom;
private String Mdp;
private boolean Enseignant;
private Classe classe;
private ArrayList<Personne> listP;
public Personne() {
}
public Personne(int idPersonne, String Nom, String Prenom, Classe Classe, String Mdp, boolean Enseignant) {
this.idPersonne = idPersonne;
this.Nom = Nom;
this.Prenom = Prenom;
this.classe = Classe;
this.Mdp = Mdp;
this.Enseignant = Enseignant;
}
public Personne(int idPersonne, String Nom, String Prenom) {
this.idPersonne = idPersonne;
this.Nom = Nom;
this.Prenom = Prenom;
//this.classe = Classe;
}
public Personne(int idPersonne, String nom, String prenom, String mdp, boolean ens) {
this.idPersonne = idPersonne;
this.Nom = nom;
this.Prenom = prenom;
this.Mdp = mdp;
this.Enseignant = ens;
//this.classe = Classe;
}
public Personne(int idPersonne, String Nom, String Prenom, Classe classe) {
this.idPersonne = idPersonne;
this.Nom = Nom;
this.Prenom = Prenom;
this.classe = classe;
}
public int getIdPersonne() {
return idPersonne;
}
public void setIdPersonne(int idPersonne) {
this.idPersonne = idPersonne;
}
public String getNom() {
return Nom;
}
public void setNom(String Nom) {
this.Nom = Nom;
}
public String getPrenom() {
return Prenom;
}
public void setPrenom(String Prenom) {
this.Prenom = Prenom;
}
public Classe getNomClasse() {
return classe;
}
public void setClasse(Classe classe) {
this.classe = classe;
}
public String getMdp() {
return Mdp;
}
public void setMdp(String Mdp) {
this.Mdp = Mdp;
}
public boolean isEnseignant() {
return Enseignant;
}
public void setEnseignant(boolean Enseignant) {
this.Enseignant = Enseignant;
}
public String Info(){
return this.getIdPersonne()+" "+this.getPrenom()+" "+this.getNom()+" "+this.getNomClasse()+ " enseignant : "+this.isEnseignant();
}
}
| UTF-8 | Java | 2,865 | java | Personne.java | Java | [
{
"context": "st;\r\nimport java.util.List;\r\n\r\n/**\r\n *\r\n * @author popor\r\n */\r\npublic class Personne {\r\n private int idPe",
"end": 450,
"score": 0.9208393096923828,
"start": 445,
"tag": "USERNAME",
"value": "popor"
}
] | null | [] | /*
* 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 Modele;
import static ihm.SQLiteConnection.connect;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author popor
*/
public class Personne {
private int idPersonne;
private String Nom;
private String Prenom;
private String Mdp;
private boolean Enseignant;
private Classe classe;
private ArrayList<Personne> listP;
public Personne() {
}
public Personne(int idPersonne, String Nom, String Prenom, Classe Classe, String Mdp, boolean Enseignant) {
this.idPersonne = idPersonne;
this.Nom = Nom;
this.Prenom = Prenom;
this.classe = Classe;
this.Mdp = Mdp;
this.Enseignant = Enseignant;
}
public Personne(int idPersonne, String Nom, String Prenom) {
this.idPersonne = idPersonne;
this.Nom = Nom;
this.Prenom = Prenom;
//this.classe = Classe;
}
public Personne(int idPersonne, String nom, String prenom, String mdp, boolean ens) {
this.idPersonne = idPersonne;
this.Nom = nom;
this.Prenom = prenom;
this.Mdp = mdp;
this.Enseignant = ens;
//this.classe = Classe;
}
public Personne(int idPersonne, String Nom, String Prenom, Classe classe) {
this.idPersonne = idPersonne;
this.Nom = Nom;
this.Prenom = Prenom;
this.classe = classe;
}
public int getIdPersonne() {
return idPersonne;
}
public void setIdPersonne(int idPersonne) {
this.idPersonne = idPersonne;
}
public String getNom() {
return Nom;
}
public void setNom(String Nom) {
this.Nom = Nom;
}
public String getPrenom() {
return Prenom;
}
public void setPrenom(String Prenom) {
this.Prenom = Prenom;
}
public Classe getNomClasse() {
return classe;
}
public void setClasse(Classe classe) {
this.classe = classe;
}
public String getMdp() {
return Mdp;
}
public void setMdp(String Mdp) {
this.Mdp = Mdp;
}
public boolean isEnseignant() {
return Enseignant;
}
public void setEnseignant(boolean Enseignant) {
this.Enseignant = Enseignant;
}
public String Info(){
return this.getIdPersonne()+" "+this.getPrenom()+" "+this.getNom()+" "+this.getNomClasse()+ " enseignant : "+this.isEnseignant();
}
}
| 2,865 | 0.58918 | 0.58918 | 117 | 22.487179 | 22.488218 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 4 |
9484dc4b97417ff1187ac614ad7d9c248a24bff3 | 20,418,274,571,061 | 2694879fd793bbb48cc909f545d79c74c96998aa | /src/main/java/com/zipcodewilmington/scientificcalculator/Calculator.java | 6f582bbb0b42a6c87283f1a92fe0fcdd9beee689 | [] | no_license | Git-Leon/Maven.ScientificCalculator | https://github.com/Git-Leon/Maven.ScientificCalculator | 812314ba6ecd7da8659dba8420dd011bdcad3ecf | 88017eb438499bf9b17a4ad87eab30ef735aab5b | refs/heads/master | 2021-07-15T17:44:28.943000 | 2019-10-21T00:55:31 | 2019-10-21T00:55:31 | 216,440,958 | 0 | 0 | null | false | 2020-10-13T16:51:49 | 2019-10-20T23:24:42 | 2019-10-21T00:55:37 | 2020-10-13T16:51:48 | 94 | 0 | 0 | 1 | Java | false | false | package com.zipcodewilmington.scientificcalculator;
import com.zipcodewilmington.scientificcalculator.operations.*;
import java.util.Arrays;
import java.util.List;
class Calculator {
private List<String> unaryOperators = Arrays.asList(
"square",
"sqrt",
"factorial",
"inverse",
"invert",
"sine",
"cosine",
"tangent",
"inversesine",
"inversecosine",
"logarithm",
"inverselogarithm",
"naturallogarithm",
"inversenaturallogarithm");
private List<String> binaryOperators = Arrays.asList(
"division",
"subtraction",
"multiplication",
"addition",
"exponent");
private List<String> nullaryOperators = Arrays.asList(
"options",
"exit");
void run() {
String userInput = null;
while(!"exit".equals(userInput)) {
displayOptions();
userInput = Console.getStringInput("\nSelect any of the above options.").toLowerCase();
if (!binaryOperators.contains(userInput)) { // not binary operator
if (!unaryOperators.contains(userInput)) { // not unary operator
if (!nullaryOperators.contains(userInput)) { // invalid operator
Console.println("Invalid user input!");
Console.println("Please try again!");
run();
} else { // run nullary operators
if("options".equals(userInput)) {
displayOptions();
} else {
break;
}
}
} else { // run unary operators
Double value1 = Console.getDoubleInput("Enter first value: ");
runUnaryOperator(userInput, value1);
}
} else { // run binary operators
Double value1 = Console.getDoubleInput("Enter first value: ");
Double value2 = Console.getDoubleInput("Enter second value: ");
runBinaryOperator(userInput, value1, value2);
}
}
}
private void runUnaryOperator(String operator, Double value) {
switch (operator) {
case "square":
new Squared().display(value);
break;
case "sqrt":
new Sqrt().display(value);
break;
case "factorial":
new Factorial().display(value);
break;
case "inverse":
new Inverse().display(value);
break;
case "invert":
new Invert().display(value);
break;
case "sine":
new Sine().display(value);
break;
case "cosine":
new Cosine().display(value);
break;
case "tan":
new Tangent().display(value);
break;
case "inversesine":
new InverseSine().display(value);
break;
case "inversecosine":
new InverseCosine().display(value);
break;
case "inversetangent":
new InverseTangent().display(value);
break;
case "logarithm":
new Logarithm().display(value);
break;
case "inverselogarithm":
new InverseLogarithm().display(value);
break;
case "naturallogarithm":
new NaturalLogarithm().display(value);
break;
case "inversenaturallogarithm":
new InverseNaturalLogarithm().display(value);
break;
}
}
private void runBinaryOperator(String operator, Double value1, Double value2) {
switch (operator) {
case "add":
new Addition().display(value1, value2);
break;
case "subtract":
new Subtraction().display(value1, value2);
break;
case "multiply":
new Multiplication().display(value1, value2);
break;
case "divide":
new Division().display(value1, value2);
break;
case "exponent":
new Exponent().display(value1, value2);
break;
}
}
private void displayOptions() {
Console.println("\n-------------------------------------------------------------------");
Console.println("Welcome to the operator-selector menu!");
Console.println(unaryOperators.toString());
Console.println(binaryOperators.toString());
Console.println(nullaryOperators.toString());
}
} | UTF-8 | Java | 4,995 | java | Calculator.java | Java | [] | null | [] | package com.zipcodewilmington.scientificcalculator;
import com.zipcodewilmington.scientificcalculator.operations.*;
import java.util.Arrays;
import java.util.List;
class Calculator {
private List<String> unaryOperators = Arrays.asList(
"square",
"sqrt",
"factorial",
"inverse",
"invert",
"sine",
"cosine",
"tangent",
"inversesine",
"inversecosine",
"logarithm",
"inverselogarithm",
"naturallogarithm",
"inversenaturallogarithm");
private List<String> binaryOperators = Arrays.asList(
"division",
"subtraction",
"multiplication",
"addition",
"exponent");
private List<String> nullaryOperators = Arrays.asList(
"options",
"exit");
void run() {
String userInput = null;
while(!"exit".equals(userInput)) {
displayOptions();
userInput = Console.getStringInput("\nSelect any of the above options.").toLowerCase();
if (!binaryOperators.contains(userInput)) { // not binary operator
if (!unaryOperators.contains(userInput)) { // not unary operator
if (!nullaryOperators.contains(userInput)) { // invalid operator
Console.println("Invalid user input!");
Console.println("Please try again!");
run();
} else { // run nullary operators
if("options".equals(userInput)) {
displayOptions();
} else {
break;
}
}
} else { // run unary operators
Double value1 = Console.getDoubleInput("Enter first value: ");
runUnaryOperator(userInput, value1);
}
} else { // run binary operators
Double value1 = Console.getDoubleInput("Enter first value: ");
Double value2 = Console.getDoubleInput("Enter second value: ");
runBinaryOperator(userInput, value1, value2);
}
}
}
private void runUnaryOperator(String operator, Double value) {
switch (operator) {
case "square":
new Squared().display(value);
break;
case "sqrt":
new Sqrt().display(value);
break;
case "factorial":
new Factorial().display(value);
break;
case "inverse":
new Inverse().display(value);
break;
case "invert":
new Invert().display(value);
break;
case "sine":
new Sine().display(value);
break;
case "cosine":
new Cosine().display(value);
break;
case "tan":
new Tangent().display(value);
break;
case "inversesine":
new InverseSine().display(value);
break;
case "inversecosine":
new InverseCosine().display(value);
break;
case "inversetangent":
new InverseTangent().display(value);
break;
case "logarithm":
new Logarithm().display(value);
break;
case "inverselogarithm":
new InverseLogarithm().display(value);
break;
case "naturallogarithm":
new NaturalLogarithm().display(value);
break;
case "inversenaturallogarithm":
new InverseNaturalLogarithm().display(value);
break;
}
}
private void runBinaryOperator(String operator, Double value1, Double value2) {
switch (operator) {
case "add":
new Addition().display(value1, value2);
break;
case "subtract":
new Subtraction().display(value1, value2);
break;
case "multiply":
new Multiplication().display(value1, value2);
break;
case "divide":
new Division().display(value1, value2);
break;
case "exponent":
new Exponent().display(value1, value2);
break;
}
}
private void displayOptions() {
Console.println("\n-------------------------------------------------------------------");
Console.println("Welcome to the operator-selector menu!");
Console.println(unaryOperators.toString());
Console.println(binaryOperators.toString());
Console.println(nullaryOperators.toString());
}
} | 4,995 | 0.479279 | 0.475676 | 143 | 33.937061 | 21.193487 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.657343 | false | false | 4 |
8b177204767a0d002071f759f4b6a10875ed7f75 | 14,113,262,597,771 | ef69284c83d2c95c15b00643486486ee3a59ebf1 | /app/src/main/java/im/tny/segvault/disturbances/MainService.java | 6f502fd0553dc20f82a2c86db8c8dbdcbd6458c2 | [
"Apache-2.0"
] | permissive | ABCRic/underlx | https://github.com/ABCRic/underlx | 440cfa8ce0ffa60bbf4a3cb5df9876d1bfc3548f | 3c6d7b3953236a00bdf4b20a611c91cfd14fa0e8 | refs/heads/master | 2021-08-16T02:40:27.696000 | 2017-11-18T21:11:06 | 2017-11-18T21:11:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package im.tny.segvault.disturbances;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import com.evernote.android.job.Job;
import com.evernote.android.job.JobCreator;
import com.evernote.android.job.JobRequest;
import com.google.firebase.messaging.FirebaseMessaging;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import im.tny.segvault.disturbances.exception.APIException;
import im.tny.segvault.disturbances.exception.CacheException;
import im.tny.segvault.disturbances.model.Feedback;
import im.tny.segvault.disturbances.model.RStation;
import im.tny.segvault.disturbances.model.StationUse;
import im.tny.segvault.disturbances.model.Trip;
import im.tny.segvault.s2ls.InNetworkState;
import im.tny.segvault.s2ls.NearNetworkState;
import im.tny.segvault.s2ls.OffNetworkState;
import im.tny.segvault.s2ls.Path;
import im.tny.segvault.s2ls.S2LS;
import im.tny.segvault.s2ls.State;
import im.tny.segvault.s2ls.routing.ChangeLineStep;
import im.tny.segvault.s2ls.routing.ConnectionWeighter;
import im.tny.segvault.s2ls.routing.EnterStep;
import im.tny.segvault.s2ls.routing.ExitStep;
import im.tny.segvault.s2ls.routing.Route;
import im.tny.segvault.s2ls.routing.Step;
import im.tny.segvault.s2ls.wifi.BSSID;
import im.tny.segvault.s2ls.wifi.WiFiLocator;
import im.tny.segvault.subway.Connection;
import im.tny.segvault.subway.Line;
import im.tny.segvault.subway.Network;
import im.tny.segvault.subway.Station;
import im.tny.segvault.subway.Stop;
import im.tny.segvault.subway.Zone;
import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmResults;
public class MainService extends Service {
public static final String PRIMARY_NETWORK_ID = "pt-ml";
private API api;
private ConnectionWeighter cweighter = new DisturbanceAwareWeighter(this);
private WiFiChecker wfc;
private LineStatusCache lineStatusCache = new LineStatusCache(this);
private StatsCache statsCache = new StatsCache(this);
private PairManager pairManager;
private Synchronizer synchronizer;
private final Object lock = new Object();
private Map<String, Network> networks = new HashMap<>();
private Map<String, S2LS> locServices = new HashMap<>();
private Date creationDate = null;
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
private Handler stateTickHandler = null;
private Realm realmForListeners;
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
MainService getService() {
// Return this instance of MainService so clients can call public methods
return MainService.this;
}
}
public MainService() {
}
private void putNetwork(final Network net) {
synchronized (lock) {
// create Realm stations for the network if they don't exist already
Realm realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
for (Station s : net.getStations()) {
if (realm.where(RStation.class).equalTo("id", s.getId()).count() == 0) {
RStation rs = new RStation();
rs.setStop(s);
rs.setNetwork(net.getId());
realm.copyToRealm(rs);
}
}
}
});
net.setEdgeWeighter(cweighter);
networks.put(net.getId(), net);
S2LS loc = new S2LS(net, new S2LSChangeListener());
locServices.put(net.getId(), loc);
WiFiLocator wl = new WiFiLocator(net);
wfc.setLocatorForNetwork(net, wl);
loc.addNetworkDetector(wl);
loc.addProximityDetector(wl);
loc.addLocator(wl);
}
}
@Override
public void onCreate() {
creationDate = new Date();
stateTickHandler = new Handler();
PreferenceManager.setDefaultValues(this.getApplicationContext(), R.xml.notif_settings, false);
api = API.getInstance();
wfc = new WiFiChecker(this, (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE));
wfc.setScanInterval(10000);
if (networks.size() == 0) {
loadNetworks();
}
SharedPreferences sharedPref = getSharedPreferences("settings", MODE_PRIVATE);
sharedPref.registerOnSharedPreferenceChangeListener(generalPrefsListener);
if (new Date().getTime() - sharedPref.getLong("pref_last_auto_topology_update_check", 0) > TimeUnit.HOURS.toMillis(2)) {
SharedPreferences.Editor e = sharedPref.edit();
e.putLong("pref_last_auto_topology_update_check", new Date().getTime());
e.apply();
checkForTopologyUpdates();
}
realmForListeners = Realm.getDefaultInstance();
tripRealmResults = realmForListeners.where(Trip.class).findAll();
tripRealmResults.addChangeListener(tripRealmChangeListener);
feedbackRealmResults = realmForListeners.where(Feedback.class).findAll();
feedbackRealmResults.addChangeListener(feedbackRealmChangeListener);
pairManager = new PairManager(getApplicationContext());
//pairManager.unpair();
API.getInstance().setPairManager(pairManager);
if (!pairManager.isPaired()) {
pairManager.pairAsync();
}
synchronizer = new Synchronizer(getApplicationContext());
}
@Override
public void onDestroy() {
wfc.stopScanning();
SharedPreferences sharedPref = getSharedPreferences("settings", MODE_PRIVATE);
sharedPref.unregisterOnSharedPreferenceChangeListener(generalPrefsListener);
tripRealmResults.removeChangeListener(tripRealmChangeListener);
feedbackRealmResults.removeChangeListener(feedbackRealmChangeListener);
realmForListeners.close();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (networks.size() == 0) {
loadNetworks();
}
if (intent != null && intent.getAction() != null) {
switch (intent.getAction()) {
case ACTION_CHECK_TOPOLOGY_UPDATES:
Log.d("MainService", "onStartCommand CheckUpdates");
if (new Date().getTime() - creationDate.getTime() < TimeUnit.SECONDS.toMillis(10)) {
// service started less than 10 seconds ago, no need to check again
break;
}
checkForTopologyUpdates(true);
Log.d("MainService", "onStartCommand updates checked");
break;
case ACTION_SYNC_TRIPS:
Log.d("MainService", "onStartCommand SyncTrips");
synchronizer.attemptSync();
break;
case ACTION_DISTURBANCE_NOTIFICATION: {
final String network = intent.getStringExtra(EXTRA_DISTURBANCE_NETWORK);
final String line = intent.getStringExtra(EXTRA_DISTURBANCE_LINE);
final String id = intent.getStringExtra(EXTRA_DISTURBANCE_ID);
final String status = intent.getStringExtra(EXTRA_DISTURBANCE_STATUS);
final boolean downtime = intent.getBooleanExtra(EXTRA_DISTURBANCE_DOWNTIME, false);
final long msgtime = intent.getLongExtra(EXTRA_DISTURBANCE_MSGTIME, 0);
handleDisturbanceNotification(network, line, id, status, downtime, msgtime);
break;
}
case ACTION_ANNOUNCEMENT_NOTIFICATION: {
final String network = intent.getStringExtra(EXTRA_ANNOUNCEMENT_NETWORK);
final String title = intent.getStringExtra(EXTRA_ANNOUNCEMENT_TITLE);
final String body = intent.getStringExtra(EXTRA_ANNOUNCEMENT_BODY);
final String url = intent.getStringExtra(EXTRA_ANNOUNCEMENT_URL);
final String source = intent.getStringExtra(EXTRA_ANNOUNCEMENT_SOURCE);
final long msgtime = intent.getLongExtra(EXTRA_ANNOUNCEMENT_MSGTIME, 0);
handleAnnouncementNotification(network, title, body, url, source, msgtime);
break;
}
case ACTION_END_TRIP: {
final String network = intent.getStringExtra(EXTRA_TRIP_NETWORK);
S2LS loc;
synchronized (lock) {
loc = locServices.get(network);
}
if (loc != null) {
loc.endCurrentTrip();
}
break;
}
case ACTION_END_NAVIGATION: {
final String network = intent.getStringExtra(EXTRA_NAVIGATION_NETWORK);
S2LS loc;
synchronized (lock) {
loc = locServices.get(network);
}
if (loc != null) {
loc.setCurrentTargetRoute(null, false);
}
break;
}
}
}
reloadFCMsubscriptions();
UpdateTopologyJob.schedule();
SyncTripsJob.schedule();
return Service.START_STICKY;
}
private void loadNetworks() {
synchronized (lock) {
try {
Network net = TopologyCache.loadNetwork(this, PRIMARY_NETWORK_ID, api.getEndpoint().toString());
putNetwork(net);
S2LS loc = locServices.get(PRIMARY_NETWORK_ID);
Log.d("loadNetworks", String.format("In network? %b", loc.inNetwork()));
Log.d("loadNetworks", String.format("Near network? %b", loc.nearNetwork()));
Zone z = loc.getLocation();
for (Stop s : z.vertexSet()) {
Log.d("loadNetworks", String.format("May be in station %s", s));
}
} catch (CacheException e) {
// cache invalid, attempt to reload topology
updateTopology();
}
}
}
public void reloadFCMsubscriptions() {
FirebaseMessaging fcm = FirebaseMessaging.getInstance();
SharedPreferences sharedPref = getSharedPreferences("notifsettings", MODE_PRIVATE);
Set<String> linePref = sharedPref.getStringSet("pref_notifs_lines", null);
if (linePref != null && linePref.size() != 0) {
fcm.subscribeToTopic("disturbances");
if (BuildConfig.DEBUG) {
fcm.subscribeToTopic("disturbances-debug");
}
} else {
fcm.unsubscribeFromTopic("disturbances");
fcm.unsubscribeFromTopic("disturbances-debug");
}
Set<String> sourcePref = sharedPref.getStringSet("pref_notifs_announcement_sources", null);
for (Announcement.Source possibleSource : Announcement.getSources()) {
if (sourcePref != null && sourcePref.contains(possibleSource.id)) {
fcm.subscribeToTopic("announcements-" + possibleSource.id);
if (BuildConfig.DEBUG) {
fcm.subscribeToTopic("announcements-debug-" + possibleSource.id);
}
} else {
fcm.unsubscribeFromTopic("announcements-" + possibleSource.id);
fcm.unsubscribeFromTopic("announcements-debug-" + possibleSource.id);
}
}
}
public void updateTopology() {
if (!isTopologyUpdateInProgress()) {
synchronized (lock) {
cancelTopologyUpdate();
currentUpdateTopologyTask = new UpdateTopologyTask();
currentUpdateTopologyTask.executeOnExecutor(Util.LARGE_STACK_THREAD_POOL_EXECUTOR, PRIMARY_NETWORK_ID);
}
}
}
public void updateTopology(String... network_ids) {
if (!isTopologyUpdateInProgress()) {
synchronized (lock) {
cancelTopologyUpdate();
currentUpdateTopologyTask = new UpdateTopologyTask();
currentUpdateTopologyTask.executeOnExecutor(Util.LARGE_STACK_THREAD_POOL_EXECUTOR, network_ids);
}
}
}
public void cancelTopologyUpdate() {
synchronized (lock) {
if (currentUpdateTopologyTask != null) {
currentUpdateTopologyTask.cancel(true);
}
}
}
public boolean isTopologyUpdateInProgress() {
return currentUpdateTopologyTask != null;
}
public void checkForTopologyUpdates() {
if (!isTopologyUpdateInProgress()) {
synchronized (lock) {
currentCheckTopologyUpdatesTask = new CheckTopologyUpdatesTask();
currentCheckTopologyUpdatesTask.execute(Connectivity.isConnectedWifi(this));
}
}
}
public void checkForTopologyUpdates(boolean autoUpdate) {
if (!isTopologyUpdateInProgress()) {
synchronized (lock) {
currentCheckTopologyUpdatesTask = new CheckTopologyUpdatesTask();
currentCheckTopologyUpdatesTask.execute(autoUpdate);
}
}
}
public Collection<Network> getNetworks() {
synchronized (lock) {
return networks.values();
}
}
public Network getNetwork(String id) {
synchronized (lock) {
return networks.get(id);
}
}
public S2LS getS2LS(String networkId) {
synchronized (lock) {
return locServices.get(networkId);
}
}
public List<Station> getAllStations() {
List<Station> stations = new ArrayList<>();
synchronized (lock) {
for (Network n : networks.values()) {
stations.addAll(n.getStations());
}
}
return stations;
}
public List<Line> getAllLines() {
List<Line> lines = new ArrayList<>();
synchronized (lock) {
for (Network n : networks.values()) {
lines.addAll(n.getLines());
}
}
return lines;
}
public LineStatusCache getLineStatusCache() {
return lineStatusCache;
}
public StatsCache getStatsCache() {
return statsCache;
}
public Stop getLikelyNextExit(List<Connection> path, double threshold) {
if (path.size() == 0) {
return null;
}
// get the line for the latest connection
Connection last = path.get(path.size() - 1);
Line line = null;
for (Line l : getAllLines()) {
if (l.edgeSet().contains(last)) {
line = l;
break;
}
}
if (line == null) {
return null;
}
Set<Stop> alreadyVisited = new HashSet<>();
for (Connection c : path) {
alreadyVisited.add(c.getSource());
alreadyVisited.add(c.getTarget());
}
// get all the stops till the end of the line, after the given connection
// (or in the case of circular lines, all stops of the line)
Stop maxStop = null;
double max = 0;
Set<Stop> stops = new HashSet<>();
while (stops.add(last.getSource())) {
Stop curStop = last.getTarget();
if (!alreadyVisited.contains(curStop)) {
double r = getLeaveTrainFactorForStop(curStop);
if (maxStop == null || r > max) {
maxStop = curStop;
max = r;
}
}
if (line.outDegreeOf(curStop) == 1) {
break;
}
for (Connection outedge : line.outgoingEdgesOf(curStop)) {
if (!stops.contains(outedge.getTarget())) {
last = outedge;
break;
}
}
}
if (max < threshold) {
// most relevant station is not relevant enough
return null;
}
return maxStop;
}
public double getLeaveTrainFactorForStop(Stop stop) {
Realm realm = Realm.getDefaultInstance();
long entryCount = realm.where(StationUse.class).equalTo("station.id", stop.getStation().getId()).equalTo("type", StationUse.UseType.NETWORK_ENTRY.name()).count();
long exitCount = realm.where(StationUse.class).equalTo("station.id", stop.getStation().getId()).equalTo("type", StationUse.UseType.NETWORK_EXIT.name()).count();
// number of times user left at this stop to transfer to another line
long transferCount = realm.where(StationUse.class).equalTo("station.id", stop.getStation().getId()).equalTo("sourceLine", stop.getLine().getId()).equalTo("type", StationUse.UseType.INTERCHANGE.name()).count();
realm.close();
return entryCount * 0.3 + exitCount + transferCount;
}
public List<ScanResult> getLastWiFiScanResults() {
return wfc.getLastScanResults();
}
public void mockLocation(Station station) {
if (BuildConfig.DEBUG && station.getStops().size() > 0) {
List<BSSID> bssids = new ArrayList<>();
for (Stop s : station.getStops()) {
bssids.addAll(WiFiLocator.getBSSIDsForStop(s));
}
wfc.updateBSSIDsDebug(bssids);
}
}
// DEBUG:
protected String dumpDebugInfo() {
String s = "Service created on " + creationDate.toString();
s += (wfc.isScanning() ? String.format(". WFC scanning every %d s", wfc.getScanInterval() / 1000) : ". WFC not scanning") + "\n";
for (Network n : getNetworks()) {
S2LS loc;
synchronized (lock) {
loc = locServices.get(n.getId());
}
s += "Network " + n.getName() + "\n";
s += "State machine: " + loc.getState().toString() + "\n";
s += String.format("\tIn network? %b\n\tNear network? %b\n", loc.inNetwork(), loc.nearNetwork());
if (loc.getState() instanceof InNetworkState) {
s += "\tPossible stops:\n";
for (Stop stop : loc.getLocation().vertexSet()) {
s += String.format("\t\t%s (%s)\n", stop.getStation().getName(), stop.getLine().getName());
}
s += "\tPath:\n";
if (loc.getCurrentTrip() != null) {
for (Connection c : loc.getCurrentTrip().getEdgeList()) {
s += String.format("\t\t%s -> %s\n", c.getSource().toString(), c.getTarget().toString());
}
if (loc.getCurrentTargetRoute() != null) {
s += String.format("\t\tCurrent path complies? %b\n",
loc.getCurrentTargetRoute().checkPathCompliance(loc.getCurrentTrip()));
}
}
}
}
try {
API.AuthTest authTest = API.getInstance().getAuthTest();
s += "API auth test result: " + authTest.result + "\n";
s += "API key as perceived by server: " + authTest.key + "\n";
} catch (APIException e) {
e.printStackTrace();
s += "Error testing API authentication\n";
}
synchronizer.attemptSync();
return s;
}
// END OF DEBUG
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private UpdateTopologyTask currentUpdateTopologyTask = null;
private class UpdateTopologyTask extends AsyncTask<String, Integer, Boolean> {
protected Boolean doInBackground(String... networkIds) {
int net_count = networkIds.length;
publishProgress(0);
try {
for (int cur_net = 0; cur_net < net_count; cur_net++) {
API.Network n = api.getNetwork(networkIds[cur_net]);
publishProgress(5);
if (isCancelled()) break;
float netPart = (float) (cur_net + 1) / (float) net_count;
Log.d("UpdateTopologyTask", "Updating network " + n.id);
HashMap<String, API.Station> apiStations = new HashMap<>();
for (API.Station s : api.getStations()) {
if (s.network.equals(n.id)) {
apiStations.put(s.id, s);
}
}
publishProgress(20);
if (isCancelled()) break;
HashMap<String, API.Lobby> apiLobbies = new HashMap<>();
for (API.Lobby l : api.getLobbies()) {
if (l.network.equals(n.id)) {
apiLobbies.put(l.id, l);
}
}
publishProgress(40);
if (isCancelled()) break;
int line_count = n.lines.size();
int cur_line = 0;
HashMap<String, API.Line> apiLines = new HashMap<>();
for (String lineid : n.lines) {
API.Line l = api.getLine(lineid);
apiLines.put(lineid, l);
cur_line++;
publishProgress(40 + (int) (((cur_line / (float) (line_count)) * netPart) * 20));
if (cur_line < line_count) {
cur_line++;
}
if (isCancelled()) break;
}
if (isCancelled()) break;
List<API.Connection> connections = api.getConnections();
publishProgress(80);
if (isCancelled()) break;
List<API.Transfer> transfers = api.getTransfers();
publishProgress(100);
API.DatasetInfo info = api.getDatasetInfo(n.id);
lineStatusCache.clear();
statsCache.clear();
TopologyCache.saveNetwork(MainService.this, n, apiStations, apiLobbies, apiLines, connections, transfers, info);
putNetwork(TopologyCache.loadNetwork(MainService.this, n.id, api.getEndpoint().toString()));
if (isCancelled()) break;
}
} catch (APIException e) {
return false;
} catch (CacheException e) {
return false;
}
return true;
}
protected void onProgressUpdate(Integer... progress) {
Intent intent = new Intent(ACTION_UPDATE_TOPOLOGY_PROGRESS);
intent.putExtra(EXTRA_UPDATE_TOPOLOGY_PROGRESS, progress[0]);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
protected void onPostExecute(Boolean result) {
Log.d("UpdateTopologyTask", result.toString());
currentUpdateTopologyTask = null;
Intent intent = new Intent(ACTION_UPDATE_TOPOLOGY_FINISHED);
intent.putExtra(EXTRA_UPDATE_TOPOLOGY_FINISHED, result);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
@Override
protected void onCancelled() {
Log.d("UpdateTopologyTask", "onCancelled");
currentUpdateTopologyTask = null;
Intent intent = new Intent(ACTION_UPDATE_TOPOLOGY_CANCELLED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
}
private CheckTopologyUpdatesTask currentCheckTopologyUpdatesTask = null;
private class CheckTopologyUpdatesTask extends AsyncTask<Boolean, Integer, Boolean> {
// returns true if there are updates, false if not
private boolean autoUpdate;
protected Boolean doInBackground(Boolean... autoUpdate) {
this.autoUpdate = autoUpdate[0];
Log.d("MainService", "CheckTopologyUpdatesTask");
try {
List<API.DatasetInfo> datasetInfos = api.getDatasetInfos();
synchronized (lock) {
for (API.DatasetInfo di : datasetInfos) {
if (!networks.containsKey(di.network)) {
return true;
}
Network net = networks.get(di.network);
if (!di.version.equals(net.getDatasetVersion())) {
return true;
}
}
}
return false;
} catch (APIException e) {
return false;
}
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Boolean result) {
if (result) {
if (autoUpdate) {
updateTopology();
} else {
Intent intent = new Intent(ACTION_TOPOLOGY_UPDATE_AVAILABLE);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
}
currentCheckTopologyUpdatesTask = null;
}
}
public static final String ACTION_UPDATE_TOPOLOGY_PROGRESS = "im.tny.segvault.disturbances.action.topology.update.progress";
public static final String EXTRA_UPDATE_TOPOLOGY_PROGRESS = "im.tny.segvault.disturbances.extra.topology.update.progress";
public static final String ACTION_UPDATE_TOPOLOGY_FINISHED = "im.tny.segvault.disturbances.action.topology.update.finished";
public static final String EXTRA_UPDATE_TOPOLOGY_FINISHED = "im.tny.segvault.disturbances.extra.topology.update.finished";
public static final String ACTION_UPDATE_TOPOLOGY_CANCELLED = "im.tny.segvault.disturbances.action.topology.update.cancelled";
public static final String ACTION_TOPOLOGY_UPDATE_AVAILABLE = "im.tny.segvault.disturbances.action.topology.update.available";
public static final String ACTION_CHECK_TOPOLOGY_UPDATES = "im.tny.segvault.disturbances.action.checkTopologyUpdates";
public static final String ACTION_SYNC_TRIPS = "im.tny.segvault.disturbances.action.syncTrips";
public static final String ACTION_CURRENT_TRIP_UPDATED = "im.tny.segvault.disturbances.action.trip.current.updated";
public static final String ACTION_CURRENT_TRIP_ENDED = "im.tny.segvault.disturbances.action.trip.current.ended";
public static final String ACTION_S2LS_STATUS_CHANGED = "im.tny.segvault.disturbances.action.s2ls.status.changed";
public static final String ACTION_CACHE_EXTRAS_PROGRESS = "im.tny.segvault.disturbances.action.cacheextras.progress";
public static final String EXTRA_CACHE_EXTRAS_PROGRESS_CURRENT = "im.tny.segvault.disturbances.extra.cacheextras.progress.current";
public static final String EXTRA_CACHE_EXTRAS_PROGRESS_TOTAL = "im.tny.segvault.disturbances.extra.cacheextras.progress.total";
public static final String ACTION_CACHE_EXTRAS_FINISHED = "im.tny.segvault.disturbances.action.cacheextras.finished";
public static final String EXTRA_CACHE_EXTRAS_FINISHED = "im.tny.segvault.disturbances.extra.cacheextras.finished";
public static class LocationJobCreator implements JobCreator {
@Override
public Job create(String tag) {
switch (tag) {
case UpdateTopologyJob.TAG:
return new UpdateTopologyJob();
case SyncTripsJob.TAG:
return new SyncTripsJob();
default:
return null;
}
}
}
public static class UpdateTopologyJob extends Job {
public static final String TAG = "job_update_topology";
@Override
@NonNull
protected Result onRunJob(Params params) {
Intent intent = new Intent(getContext(), MainService.class).setAction(ACTION_CHECK_TOPOLOGY_UPDATES);
getContext().startService(intent);
return Result.SUCCESS;
}
public static void schedule() {
schedule(true);
}
public static void schedule(boolean updateCurrent) {
new JobRequest.Builder(UpdateTopologyJob.TAG)
.setExecutionWindow(TimeUnit.HOURS.toMillis(12), TimeUnit.HOURS.toMillis(36))
.setBackoffCriteria(TimeUnit.MINUTES.toMillis(30), JobRequest.BackoffPolicy.EXPONENTIAL)
.setRequiredNetworkType(JobRequest.NetworkType.UNMETERED)
.setPersisted(true)
.setUpdateCurrent(updateCurrent)
.build()
.schedule();
}
}
public static class SyncTripsJob extends Job {
public static final String TAG = "job_sync_trips";
@Override
@NonNull
protected Result onRunJob(Params params) {
Intent intent = new Intent(getContext(), MainService.class).setAction(ACTION_SYNC_TRIPS);
getContext().startService(intent);
return Result.SUCCESS;
}
public static void schedule() {
schedule(true);
}
public static void schedule(boolean updateCurrent) {
new JobRequest.Builder(SyncTripsJob.TAG)
.setExecutionWindow(TimeUnit.HOURS.toMillis(24), TimeUnit.HOURS.toMillis(48))
.setBackoffCriteria(TimeUnit.HOURS.toMillis(1), JobRequest.BackoffPolicy.EXPONENTIAL)
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setPersisted(true)
.setUpdateCurrent(updateCurrent)
.build()
.schedule();
}
}
private static final String ACTION_DISTURBANCE_NOTIFICATION = "im.tny.segvault.disturbances.action.notification.disturbance";
private static final String EXTRA_DISTURBANCE_NETWORK = "im.tny.segvault.disturbances.extra.notification.disturbance.network";
private static final String EXTRA_DISTURBANCE_LINE = "im.tny.segvault.disturbances.extra.notification.disturbance.line";
private static final String EXTRA_DISTURBANCE_ID = "im.tny.segvault.disturbances.extra.notification.disturbance.id";
private static final String EXTRA_DISTURBANCE_STATUS = "im.tny.segvault.disturbances.extra.notification.disturbance.status";
private static final String EXTRA_DISTURBANCE_DOWNTIME = "im.tny.segvault.disturbances.extra.notification.disturbance.downtime";
private static final String EXTRA_DISTURBANCE_MSGTIME = "im.tny.segvault.disturbances.extra.notification.disturbance.msgtime";
public static void startForDisturbanceNotification(Context context, String network, String line,
String id, String status, boolean downtime, long messageTime) {
Intent intent = new Intent(context, MainService.class);
intent.setAction(ACTION_DISTURBANCE_NOTIFICATION);
intent.putExtra(EXTRA_DISTURBANCE_NETWORK, network);
intent.putExtra(EXTRA_DISTURBANCE_LINE, line);
intent.putExtra(EXTRA_DISTURBANCE_ID, id);
intent.putExtra(EXTRA_DISTURBANCE_STATUS, status);
intent.putExtra(EXTRA_DISTURBANCE_DOWNTIME, downtime);
intent.putExtra(EXTRA_DISTURBANCE_MSGTIME, messageTime);
context.startService(intent);
}
private void handleDisturbanceNotification(String network, String line,
String id, String status, boolean downtime,
long msgtime) {
Log.d("MainService", "handleDisturbanceNotification");
SharedPreferences sharedPref = getSharedPreferences("notifsettings", MODE_PRIVATE);
Set<String> linePref = sharedPref.getStringSet("pref_notifs_lines", null);
Network snetwork;
synchronized (lock) {
if (!networks.containsKey(network)) {
return;
}
snetwork = networks.get(network);
}
Line sline = snetwork.getLine(line);
if (sline == null) {
return;
}
if (downtime) {
lineStatusCache.markLineAsDown(sline, new Date(msgtime));
} else {
lineStatusCache.markLineAsUp(sline);
}
if (linePref != null && !linePref.contains(line)) {
// notifications disabled for this line
return;
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (!downtime && !sharedPref.getBoolean("pref_notifs_service_resumed", true)) {
// notifications for normal service resumed disabled
notificationManager.cancel(id.hashCode());
return;
}
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(MainActivity.EXTRA_INITIAL_FRAGMENT, "nav_disturbances");
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
String title = String.format(getString(R.string.notif_disturbance_title), sline.getName());
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.setBigContentTitle(title);
bigTextStyle.bigText(status);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setStyle(bigTextStyle)
.setSmallIcon(R.drawable.ic_disturbance_notif)
.setColor(sline.getColor())
.setContentTitle(title)
.setContentText(status)
.setAutoCancel(true)
.setWhen(msgtime)
.setSound(Uri.parse(sharedPref.getString(downtime ? "pref_notifs_ringtone" : "pref_notifs_regularization_ringtone", "content://settings/system/notification_sound")))
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setContentIntent(pendingIntent);
if (sharedPref.getBoolean(downtime ? "pref_notifs_vibrate" : "pref_notifs_regularization_vibrate", false)) {
notificationBuilder.setVibrate(new long[]{0, 100, 100, 150, 150, 200});
} else {
notificationBuilder.setVibrate(new long[]{0l});
}
notificationManager.notify(id.hashCode(), notificationBuilder.build());
}
private static final String ACTION_ANNOUNCEMENT_NOTIFICATION = "im.tny.segvault.disturbances.action.notification.announcement";
private static final String EXTRA_ANNOUNCEMENT_NETWORK = "im.tny.segvault.disturbances.extra.notification.announcement.network";
private static final String EXTRA_ANNOUNCEMENT_TITLE = "im.tny.segvault.disturbances.extra.notification.announcement.title";
private static final String EXTRA_ANNOUNCEMENT_BODY = "im.tny.segvault.disturbances.extra.notification.announcement.body";
private static final String EXTRA_ANNOUNCEMENT_URL = "im.tny.segvault.disturbances.extra.notification.announcement.url";
private static final String EXTRA_ANNOUNCEMENT_SOURCE = "im.tny.segvault.disturbances.extra.notification.announcement.source";
private static final String EXTRA_ANNOUNCEMENT_MSGTIME = "im.tny.segvault.disturbances.extra.notification.announcement.msgtime";
public static void startForAnnouncementNotification(Context context, String network, String title,
String body, String url, String source, long messageTime) {
Intent intent = new Intent(context, MainService.class);
intent.setAction(ACTION_ANNOUNCEMENT_NOTIFICATION);
intent.putExtra(EXTRA_ANNOUNCEMENT_NETWORK, network);
intent.putExtra(EXTRA_ANNOUNCEMENT_TITLE, title);
intent.putExtra(EXTRA_ANNOUNCEMENT_BODY, body);
intent.putExtra(EXTRA_ANNOUNCEMENT_URL, url);
intent.putExtra(EXTRA_ANNOUNCEMENT_SOURCE, source);
intent.putExtra(EXTRA_ANNOUNCEMENT_MSGTIME, messageTime);
context.startService(intent);
}
private void handleAnnouncementNotification(String network, String title,
String body, String url, String sourceId,
long msgtime) {
Log.d("MainService", "handleAnnouncementNotification");
SharedPreferences sharedPref = getSharedPreferences("notifsettings", MODE_PRIVATE);
Set<String> sourcePref = sharedPref.getStringSet("pref_notifs_announcement_sources", null);
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse(url));
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Announcement.Source source = Announcement.getSource(sourceId);
if (source == null) {
return;
}
if (title.isEmpty()) {
title = String.format(getString(R.string.notif_announcement_alt_title), getString(source.nameResourceId));
}
if (body.isEmpty()) {
body = getString(R.string.frag_announcement_no_text);
}
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.setBigContentTitle(title);
bigTextStyle.bigText(body);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setStyle(bigTextStyle)
.setSmallIcon(R.drawable.ic_pt_ml_notif)
.setColor(source.color)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setWhen(msgtime)
.setSound(Uri.parse(sharedPref.getString("pref_notifs_announcement_ringtone", "content://settings/system/notification_sound")))
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setContentIntent(contentIntent);
if (sharedPref.getBoolean("pref_notifs_announcement_vibrate", false)) {
notificationBuilder.setVibrate(new long[]{0, 100, 100, 150, 150, 200});
} else {
notificationBuilder.setVibrate(new long[]{0l});
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(url.hashCode(), notificationBuilder.build());
}
private static final int ROUTE_NOTIFICATION_ID = -100;
public static final String ACTION_END_NAVIGATION = "im.tny.segvault.disturbances.action.route.current.end";
public static final String EXTRA_NAVIGATION_NETWORK = "im.tny.segvault.disturbances.extra.route.current.end.network";
public static final String ACTION_END_TRIP = "im.tny.segvault.disturbances.action.trip.current.end";
public static final String EXTRA_TRIP_NETWORK = "im.tny.segvault.disturbances.extra.trip.current.end.network";
private void updateRouteNotification(S2LS loc) {
updateRouteNotification(loc, false);
}
private void updateRouteNotification(S2LS loc, boolean highPriorityNotification) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(MainActivity.EXTRA_INITIAL_FRAGMENT, "nav_home");
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
intent, 0);
Path currentPath = loc.getCurrentTrip();
Route currentRoute = loc.getCurrentTargetRoute();
if (currentPath == null && currentRoute == null) {
Log.e("MainService", "Attempt to create notification when there's no path or planned route");
return;
}
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
CharSequence title = "";
List<CharSequence> statusLines = new ArrayList<>();
int color = -1;
if (currentRoute != null) {
inboxStyle.setSummaryText(String.format(getString(R.string.notif_route_navigating_status), currentRoute.getTarget().getStation().getName()));
Step nextStep = currentRoute.getNextStep(currentPath);
if (nextStep instanceof EnterStep) {
if (currentPath != null && currentPath.getCurrentStop() != null && currentRoute.checkPathStartsRoute(currentPath)) {
title = String.format(getString(R.string.notif_route_catch_train_title), ((EnterStep) nextStep).getDirection().getName(12));
} else {
title = String.format(getString(R.string.notif_route_enter_station_title), nextStep.getStation().getName(15));
}
// TODO: show "encurtamentos" warnings here if applicable
statusLines.add(String.format(getString(R.string.notif_route_catch_train_status), ((EnterStep) nextStep).getDirection().getName()));
color = currentRoute.getSource().getLine().getColor();
} else if (nextStep instanceof ChangeLineStep) {
ChangeLineStep clStep = (ChangeLineStep) nextStep;
String lineName = clStep.getTarget().getName();
String titleStr;
if (currentPath != null && currentPath.getCurrentStop() != null && currentPath.getCurrentStop().getStation() == nextStep.getStation()) {
titleStr = String.format(getString(R.string.notif_route_catch_train_line_change_title),
clStep.getTarget().getName());
} else {
titleStr = String.format(getString(R.string.notif_route_line_change_title),
nextStep.getStation().getName(10),
lineName);
}
int lStart = titleStr.indexOf(lineName);
int lEnd = lStart + lineName.length();
Spannable sb = new SpannableString(titleStr);
sb.setSpan(new ForegroundColorSpan(clStep.getTarget().getColor()), lStart, lEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
title = sb;
// TODO: show "encurtamentos" warnings here if applicable
sb = new SpannableString(
String.format(getString(R.string.notif_route_catch_train_status),
clStep.getDirection().getName())
);
sb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
statusLines.add(sb);
color = clStep.getTarget().getColor();
} else if (nextStep instanceof ExitStep) {
if (currentPath != null &&
new Date().getTime() - currentPath.getCurrentStopEntryTime().getTime() > 30 * 1000 &&
nextStep.getStation() == currentPath.getNextStop().getStation()) {
title = getString(R.string.notif_route_leave_train_next);
} else if (currentPath != null && currentPath.getCurrentStop().getStation() == nextStep.getStation()) {
title = getString(R.string.notif_route_leave_train_now);
} else {
title = String.format(getString(R.string.notif_route_leave_train), nextStep.getStation().getName(20));
}
}
}
if (currentPath != null) {
Stop curStop = currentPath.getCurrentStop();
if (color == -1) {
color = curStop.getLine().getColor();
}
if (currentRoute != null) {
statusLines.add(String.format(getString(R.string.notif_route_current_station), curStop.getStation().getName()));
} else {
title = curStop.getStation().getName();
}
if (currentPath.isWaitingFirstTrain()) {
statusLines.add(getString(R.string.notif_route_waiting));
} else {
Stop direction = currentPath.getDirection();
Stop next = currentPath.getNextStop();
if (direction != null && next != null) {
statusLines.add(String.format(getString(R.string.notif_route_next_station), next.getStation().getName()));
if (currentRoute == null) {
statusLines.add(String.format(getString(R.string.notif_route_direction), direction.getStation().getName()));
}
} else {
statusLines.add(getString(R.string.notif_route_left_station));
}
}
}
CharSequence singleLineStatus = "";
for (CharSequence s : statusLines) {
inboxStyle.addLine(s);
singleLineStatus = TextUtils.concat(singleLineStatus, s) + " | ";
}
singleLineStatus = singleLineStatus.subSequence(0, singleLineStatus.length() - 3);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setStyle(inboxStyle)
.setColor(color)
.setContentTitle(title)
.setContentText(singleLineStatus)
.setAutoCancel(false)
.setContentIntent(pendingIntent)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setOngoing(true);
if (highPriorityNotification) {
stopForeground(true);
notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
notificationBuilder.setDefaults(NotificationCompat.DEFAULT_VIBRATE);
}
if (currentRoute != null) {
notificationBuilder.setSmallIcon(R.drawable.ic_navigation_white_24dp);
Intent stopIntent = new Intent(this, MainService.class);
stopIntent.setAction(ACTION_END_NAVIGATION);
stopIntent.putExtra(EXTRA_NAVIGATION_NETWORK, loc.getNetwork().getId());
PendingIntent pendingStopIntent = PendingIntent.getService(this, (int) System.currentTimeMillis(),
stopIntent, 0);
notificationBuilder.addAction(R.drawable.ic_close_black_24dp, getString(R.string.notif_route_end_navigation), pendingStopIntent);
} else {
notificationBuilder.setSmallIcon(R.drawable.ic_trip_notif);
if (loc.canRequestEndOfTrip()) {
Intent stopIntent = new Intent(this, MainService.class);
stopIntent.setAction(ACTION_END_TRIP);
stopIntent.putExtra(EXTRA_TRIP_NETWORK, loc.getNetwork().getId());
PendingIntent pendingStopIntent = PendingIntent.getService(this, (int) System.currentTimeMillis(),
stopIntent, 0);
notificationBuilder.addAction(R.drawable.ic_stop_black_24dp, getString(R.string.notif_route_end_trip), pendingStopIntent);
}
}
startForeground(ROUTE_NOTIFICATION_ID, notificationBuilder.build());
}
public class S2LSChangeListener implements S2LS.EventListener {
@Override
public void onStateChanged(final S2LS loc) {
Log.d("onStateChanged", "State changed");
stateTickHandler.removeCallbacksAndMessages(null);
if (loc.getState().getPreferredTickIntervalMillis() != 0) {
doTick(loc.getState());
}
SharedPreferences sharedPref = getSharedPreferences("settings", MODE_PRIVATE);
boolean locationEnabled = sharedPref.getBoolean("pref_location_enable", true);
if (loc.getState() instanceof InNetworkState) {
wfc.setScanInterval(TimeUnit.SECONDS.toMillis(10));
if (locationEnabled) {
wfc.startScanning();
}
if (loc.getCurrentTrip() != null) {
updateRouteNotification(loc);
}
} else if (loc.getState() instanceof NearNetworkState) {
wfc.setScanInterval(TimeUnit.MINUTES.toMillis(1));
if (locationEnabled)
wfc.startScanningIfWiFiEnabled();
checkStopForeground(loc);
} else if (loc.getState() instanceof OffNetworkState) {
// wfc.stopScanning(); // TODO only enable this when there are locators besides WiFi
wfc.setScanInterval(TimeUnit.MINUTES.toMillis(1));
if (locationEnabled)
wfc.startScanningIfWiFiEnabled();
checkStopForeground(loc);
}
Intent intent = new Intent(ACTION_S2LS_STATUS_CHANGED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
@Override
public void onTripStarted(final S2LS s2ls) {
Path path = s2ls.getCurrentTrip();
path.addPathChangedListener(new Path.OnPathChangedListener() {
private Station prevEndStation = null;
@Override
public void onPathChanged(Path path) {
Log.d("onPathChanged", "Path changed");
Intent intent = new Intent(ACTION_CURRENT_TRIP_UPDATED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
boolean highPrioNotif = false;
if (s2ls.getCurrentTargetRoute() != null) {
Step nextStep = s2ls.getCurrentTargetRoute().getNextStep(path);
highPrioNotif = path.getEndVertex().getStation() != prevEndStation &&
path.getEndVertex().getStation() == nextStep.getStation() &&
!(nextStep instanceof EnterStep);
}
prevEndStation = path.getEndVertex().getStation();
updateRouteNotification(s2ls, highPrioNotif);
}
});
updateRouteNotification(s2ls);
}
@Override
public void onTripEnded(S2LS s2ls, Path path) {
String tripId = Trip.persistConnectionPath(path);
Intent intent = new Intent(ACTION_CURRENT_TRIP_ENDED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
if (!checkStopForeground(s2ls)) {
updateRouteNotification(s2ls);
}
SharedPreferences sharedPref = getSharedPreferences("settings", MODE_PRIVATE);
boolean openTripCorrection = sharedPref.getBoolean("pref_auto_open_trip_correction", false);
boolean openVisitCorrection = sharedPref.getBoolean("pref_auto_open_visit_correction", false);
if (openTripCorrection && (path.getEdgeList().size() > 0 || openVisitCorrection)) {
intent = new Intent(getApplicationContext(), TripCorrectionActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(TripCorrectionActivity.EXTRA_NETWORK_ID, s2ls.getNetwork().getId());
intent.putExtra(TripCorrectionActivity.EXTRA_TRIP_ID, tripId);
intent.putExtra(TripCorrectionActivity.EXTRA_IS_STANDALONE, true);
startActivity(intent);
}
}
@Override
public void onRouteProgrammed(S2LS s2ls, Route route) {
updateRouteNotification(s2ls);
}
@Override
public void onRouteStarted(S2LS s2ls, Path path, Route route) {
Log.d("onRouteStarted", "Route started");
if (!checkStopForeground(s2ls)) {
updateRouteNotification(s2ls);
}
}
@Override
public void onRouteMistake(S2LS s2ls, Path path, Route route) {
Log.d("onRouteMistake", "Route mistake");
// recalculate route with current station as origin station
s2ls.setCurrentTargetRoute(
Route.calculate(
s2ls.getNetwork(),
path.getEndVertex().getStation(),
route.getTarget().getStation()), true);
if (!checkStopForeground(s2ls)) {
updateRouteNotification(s2ls);
}
}
@Override
public void onRouteCancelled(S2LS s2ls, Route route) {
Log.d("onRouteCancelled", "Route cancelled");
if (!checkStopForeground(s2ls)) {
updateRouteNotification(s2ls);
}
}
@Override
public void onRouteCompleted(S2LS s2ls, Path path, Route route) {
Log.d("onRouteCompleted", "Route completed");
if (!checkStopForeground(s2ls)) {
updateRouteNotification(s2ls);
}
}
private void doTick(final State state) {
stateTickHandler.postDelayed(new Runnable() {
@Override
public void run() {
doTick(state);
state.tick();
}
}, state.getPreferredTickIntervalMillis());
}
private boolean checkStopForeground(S2LS loc) {
if (loc.getCurrentTargetRoute() == null && !(loc.getState() instanceof InNetworkState)) {
stopForeground(true);
return true;
}
return false;
}
}
public void cacheAllExtras(String... network_ids) {
ExtraContentCache.clearAllCachedExtras(this);
for (String id : network_ids) {
Network network = getNetwork(id);
ExtraContentCache.cacheAllExtras(this, new ExtraContentCache.OnCacheAllListener() {
@Override
public void onSuccess() {
Intent intent = new Intent(ACTION_CACHE_EXTRAS_FINISHED);
intent.putExtra(EXTRA_CACHE_EXTRAS_FINISHED, true);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
@Override
public void onProgress(int current, int total) {
Intent intent = new Intent(ACTION_CACHE_EXTRAS_PROGRESS);
intent.putExtra(EXTRA_CACHE_EXTRAS_PROGRESS_CURRENT, current);
intent.putExtra(EXTRA_CACHE_EXTRAS_PROGRESS_TOTAL, total);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
@Override
public void onFailure() {
Intent intent = new Intent(ACTION_CACHE_EXTRAS_FINISHED);
intent.putExtra(EXTRA_CACHE_EXTRAS_FINISHED, false);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
}, network);
}
}
private SharedPreferences.OnSharedPreferenceChangeListener generalPrefsListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("pref_location_enable")) {
if (prefs.getBoolean("pref_location_enable", true))
wfc.startScanningIfWiFiEnabled();
else
wfc.stopScanning();
}
}
};
public static final String ACTION_TRIP_REALM_UPDATED = "im.tny.segvault.disturbances.action.realm.trip.updated";
private RealmResults<Trip> tripRealmResults;
private final RealmChangeListener<RealmResults<Trip>> tripRealmChangeListener = new RealmChangeListener<RealmResults<Trip>>() {
@Override
public void onChange(RealmResults<Trip> element) {
Intent intent = new Intent(ACTION_TRIP_REALM_UPDATED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
};
public static final String ACTION_FEEDBACK_REALM_UPDATED = "im.tny.segvault.disturbances.action.realm.feedback.updated";
private RealmResults<Feedback> feedbackRealmResults;
private final RealmChangeListener<RealmResults<Feedback>> feedbackRealmChangeListener = new RealmChangeListener<RealmResults<Feedback>>() {
@Override
public void onChange(RealmResults<Feedback> element) {
Intent intent = new Intent(ACTION_FEEDBACK_REALM_UPDATED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
};
}
| UTF-8 | Java | 58,502 | java | MainService.java | Java | [] | null | [] | package im.tny.segvault.disturbances;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import com.evernote.android.job.Job;
import com.evernote.android.job.JobCreator;
import com.evernote.android.job.JobRequest;
import com.google.firebase.messaging.FirebaseMessaging;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import im.tny.segvault.disturbances.exception.APIException;
import im.tny.segvault.disturbances.exception.CacheException;
import im.tny.segvault.disturbances.model.Feedback;
import im.tny.segvault.disturbances.model.RStation;
import im.tny.segvault.disturbances.model.StationUse;
import im.tny.segvault.disturbances.model.Trip;
import im.tny.segvault.s2ls.InNetworkState;
import im.tny.segvault.s2ls.NearNetworkState;
import im.tny.segvault.s2ls.OffNetworkState;
import im.tny.segvault.s2ls.Path;
import im.tny.segvault.s2ls.S2LS;
import im.tny.segvault.s2ls.State;
import im.tny.segvault.s2ls.routing.ChangeLineStep;
import im.tny.segvault.s2ls.routing.ConnectionWeighter;
import im.tny.segvault.s2ls.routing.EnterStep;
import im.tny.segvault.s2ls.routing.ExitStep;
import im.tny.segvault.s2ls.routing.Route;
import im.tny.segvault.s2ls.routing.Step;
import im.tny.segvault.s2ls.wifi.BSSID;
import im.tny.segvault.s2ls.wifi.WiFiLocator;
import im.tny.segvault.subway.Connection;
import im.tny.segvault.subway.Line;
import im.tny.segvault.subway.Network;
import im.tny.segvault.subway.Station;
import im.tny.segvault.subway.Stop;
import im.tny.segvault.subway.Zone;
import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmResults;
public class MainService extends Service {
public static final String PRIMARY_NETWORK_ID = "pt-ml";
private API api;
private ConnectionWeighter cweighter = new DisturbanceAwareWeighter(this);
private WiFiChecker wfc;
private LineStatusCache lineStatusCache = new LineStatusCache(this);
private StatsCache statsCache = new StatsCache(this);
private PairManager pairManager;
private Synchronizer synchronizer;
private final Object lock = new Object();
private Map<String, Network> networks = new HashMap<>();
private Map<String, S2LS> locServices = new HashMap<>();
private Date creationDate = null;
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
private Handler stateTickHandler = null;
private Realm realmForListeners;
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
MainService getService() {
// Return this instance of MainService so clients can call public methods
return MainService.this;
}
}
public MainService() {
}
private void putNetwork(final Network net) {
synchronized (lock) {
// create Realm stations for the network if they don't exist already
Realm realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
for (Station s : net.getStations()) {
if (realm.where(RStation.class).equalTo("id", s.getId()).count() == 0) {
RStation rs = new RStation();
rs.setStop(s);
rs.setNetwork(net.getId());
realm.copyToRealm(rs);
}
}
}
});
net.setEdgeWeighter(cweighter);
networks.put(net.getId(), net);
S2LS loc = new S2LS(net, new S2LSChangeListener());
locServices.put(net.getId(), loc);
WiFiLocator wl = new WiFiLocator(net);
wfc.setLocatorForNetwork(net, wl);
loc.addNetworkDetector(wl);
loc.addProximityDetector(wl);
loc.addLocator(wl);
}
}
@Override
public void onCreate() {
creationDate = new Date();
stateTickHandler = new Handler();
PreferenceManager.setDefaultValues(this.getApplicationContext(), R.xml.notif_settings, false);
api = API.getInstance();
wfc = new WiFiChecker(this, (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE));
wfc.setScanInterval(10000);
if (networks.size() == 0) {
loadNetworks();
}
SharedPreferences sharedPref = getSharedPreferences("settings", MODE_PRIVATE);
sharedPref.registerOnSharedPreferenceChangeListener(generalPrefsListener);
if (new Date().getTime() - sharedPref.getLong("pref_last_auto_topology_update_check", 0) > TimeUnit.HOURS.toMillis(2)) {
SharedPreferences.Editor e = sharedPref.edit();
e.putLong("pref_last_auto_topology_update_check", new Date().getTime());
e.apply();
checkForTopologyUpdates();
}
realmForListeners = Realm.getDefaultInstance();
tripRealmResults = realmForListeners.where(Trip.class).findAll();
tripRealmResults.addChangeListener(tripRealmChangeListener);
feedbackRealmResults = realmForListeners.where(Feedback.class).findAll();
feedbackRealmResults.addChangeListener(feedbackRealmChangeListener);
pairManager = new PairManager(getApplicationContext());
//pairManager.unpair();
API.getInstance().setPairManager(pairManager);
if (!pairManager.isPaired()) {
pairManager.pairAsync();
}
synchronizer = new Synchronizer(getApplicationContext());
}
@Override
public void onDestroy() {
wfc.stopScanning();
SharedPreferences sharedPref = getSharedPreferences("settings", MODE_PRIVATE);
sharedPref.unregisterOnSharedPreferenceChangeListener(generalPrefsListener);
tripRealmResults.removeChangeListener(tripRealmChangeListener);
feedbackRealmResults.removeChangeListener(feedbackRealmChangeListener);
realmForListeners.close();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (networks.size() == 0) {
loadNetworks();
}
if (intent != null && intent.getAction() != null) {
switch (intent.getAction()) {
case ACTION_CHECK_TOPOLOGY_UPDATES:
Log.d("MainService", "onStartCommand CheckUpdates");
if (new Date().getTime() - creationDate.getTime() < TimeUnit.SECONDS.toMillis(10)) {
// service started less than 10 seconds ago, no need to check again
break;
}
checkForTopologyUpdates(true);
Log.d("MainService", "onStartCommand updates checked");
break;
case ACTION_SYNC_TRIPS:
Log.d("MainService", "onStartCommand SyncTrips");
synchronizer.attemptSync();
break;
case ACTION_DISTURBANCE_NOTIFICATION: {
final String network = intent.getStringExtra(EXTRA_DISTURBANCE_NETWORK);
final String line = intent.getStringExtra(EXTRA_DISTURBANCE_LINE);
final String id = intent.getStringExtra(EXTRA_DISTURBANCE_ID);
final String status = intent.getStringExtra(EXTRA_DISTURBANCE_STATUS);
final boolean downtime = intent.getBooleanExtra(EXTRA_DISTURBANCE_DOWNTIME, false);
final long msgtime = intent.getLongExtra(EXTRA_DISTURBANCE_MSGTIME, 0);
handleDisturbanceNotification(network, line, id, status, downtime, msgtime);
break;
}
case ACTION_ANNOUNCEMENT_NOTIFICATION: {
final String network = intent.getStringExtra(EXTRA_ANNOUNCEMENT_NETWORK);
final String title = intent.getStringExtra(EXTRA_ANNOUNCEMENT_TITLE);
final String body = intent.getStringExtra(EXTRA_ANNOUNCEMENT_BODY);
final String url = intent.getStringExtra(EXTRA_ANNOUNCEMENT_URL);
final String source = intent.getStringExtra(EXTRA_ANNOUNCEMENT_SOURCE);
final long msgtime = intent.getLongExtra(EXTRA_ANNOUNCEMENT_MSGTIME, 0);
handleAnnouncementNotification(network, title, body, url, source, msgtime);
break;
}
case ACTION_END_TRIP: {
final String network = intent.getStringExtra(EXTRA_TRIP_NETWORK);
S2LS loc;
synchronized (lock) {
loc = locServices.get(network);
}
if (loc != null) {
loc.endCurrentTrip();
}
break;
}
case ACTION_END_NAVIGATION: {
final String network = intent.getStringExtra(EXTRA_NAVIGATION_NETWORK);
S2LS loc;
synchronized (lock) {
loc = locServices.get(network);
}
if (loc != null) {
loc.setCurrentTargetRoute(null, false);
}
break;
}
}
}
reloadFCMsubscriptions();
UpdateTopologyJob.schedule();
SyncTripsJob.schedule();
return Service.START_STICKY;
}
private void loadNetworks() {
synchronized (lock) {
try {
Network net = TopologyCache.loadNetwork(this, PRIMARY_NETWORK_ID, api.getEndpoint().toString());
putNetwork(net);
S2LS loc = locServices.get(PRIMARY_NETWORK_ID);
Log.d("loadNetworks", String.format("In network? %b", loc.inNetwork()));
Log.d("loadNetworks", String.format("Near network? %b", loc.nearNetwork()));
Zone z = loc.getLocation();
for (Stop s : z.vertexSet()) {
Log.d("loadNetworks", String.format("May be in station %s", s));
}
} catch (CacheException e) {
// cache invalid, attempt to reload topology
updateTopology();
}
}
}
public void reloadFCMsubscriptions() {
FirebaseMessaging fcm = FirebaseMessaging.getInstance();
SharedPreferences sharedPref = getSharedPreferences("notifsettings", MODE_PRIVATE);
Set<String> linePref = sharedPref.getStringSet("pref_notifs_lines", null);
if (linePref != null && linePref.size() != 0) {
fcm.subscribeToTopic("disturbances");
if (BuildConfig.DEBUG) {
fcm.subscribeToTopic("disturbances-debug");
}
} else {
fcm.unsubscribeFromTopic("disturbances");
fcm.unsubscribeFromTopic("disturbances-debug");
}
Set<String> sourcePref = sharedPref.getStringSet("pref_notifs_announcement_sources", null);
for (Announcement.Source possibleSource : Announcement.getSources()) {
if (sourcePref != null && sourcePref.contains(possibleSource.id)) {
fcm.subscribeToTopic("announcements-" + possibleSource.id);
if (BuildConfig.DEBUG) {
fcm.subscribeToTopic("announcements-debug-" + possibleSource.id);
}
} else {
fcm.unsubscribeFromTopic("announcements-" + possibleSource.id);
fcm.unsubscribeFromTopic("announcements-debug-" + possibleSource.id);
}
}
}
public void updateTopology() {
if (!isTopologyUpdateInProgress()) {
synchronized (lock) {
cancelTopologyUpdate();
currentUpdateTopologyTask = new UpdateTopologyTask();
currentUpdateTopologyTask.executeOnExecutor(Util.LARGE_STACK_THREAD_POOL_EXECUTOR, PRIMARY_NETWORK_ID);
}
}
}
public void updateTopology(String... network_ids) {
if (!isTopologyUpdateInProgress()) {
synchronized (lock) {
cancelTopologyUpdate();
currentUpdateTopologyTask = new UpdateTopologyTask();
currentUpdateTopologyTask.executeOnExecutor(Util.LARGE_STACK_THREAD_POOL_EXECUTOR, network_ids);
}
}
}
public void cancelTopologyUpdate() {
synchronized (lock) {
if (currentUpdateTopologyTask != null) {
currentUpdateTopologyTask.cancel(true);
}
}
}
public boolean isTopologyUpdateInProgress() {
return currentUpdateTopologyTask != null;
}
public void checkForTopologyUpdates() {
if (!isTopologyUpdateInProgress()) {
synchronized (lock) {
currentCheckTopologyUpdatesTask = new CheckTopologyUpdatesTask();
currentCheckTopologyUpdatesTask.execute(Connectivity.isConnectedWifi(this));
}
}
}
public void checkForTopologyUpdates(boolean autoUpdate) {
if (!isTopologyUpdateInProgress()) {
synchronized (lock) {
currentCheckTopologyUpdatesTask = new CheckTopologyUpdatesTask();
currentCheckTopologyUpdatesTask.execute(autoUpdate);
}
}
}
public Collection<Network> getNetworks() {
synchronized (lock) {
return networks.values();
}
}
public Network getNetwork(String id) {
synchronized (lock) {
return networks.get(id);
}
}
public S2LS getS2LS(String networkId) {
synchronized (lock) {
return locServices.get(networkId);
}
}
public List<Station> getAllStations() {
List<Station> stations = new ArrayList<>();
synchronized (lock) {
for (Network n : networks.values()) {
stations.addAll(n.getStations());
}
}
return stations;
}
public List<Line> getAllLines() {
List<Line> lines = new ArrayList<>();
synchronized (lock) {
for (Network n : networks.values()) {
lines.addAll(n.getLines());
}
}
return lines;
}
public LineStatusCache getLineStatusCache() {
return lineStatusCache;
}
public StatsCache getStatsCache() {
return statsCache;
}
public Stop getLikelyNextExit(List<Connection> path, double threshold) {
if (path.size() == 0) {
return null;
}
// get the line for the latest connection
Connection last = path.get(path.size() - 1);
Line line = null;
for (Line l : getAllLines()) {
if (l.edgeSet().contains(last)) {
line = l;
break;
}
}
if (line == null) {
return null;
}
Set<Stop> alreadyVisited = new HashSet<>();
for (Connection c : path) {
alreadyVisited.add(c.getSource());
alreadyVisited.add(c.getTarget());
}
// get all the stops till the end of the line, after the given connection
// (or in the case of circular lines, all stops of the line)
Stop maxStop = null;
double max = 0;
Set<Stop> stops = new HashSet<>();
while (stops.add(last.getSource())) {
Stop curStop = last.getTarget();
if (!alreadyVisited.contains(curStop)) {
double r = getLeaveTrainFactorForStop(curStop);
if (maxStop == null || r > max) {
maxStop = curStop;
max = r;
}
}
if (line.outDegreeOf(curStop) == 1) {
break;
}
for (Connection outedge : line.outgoingEdgesOf(curStop)) {
if (!stops.contains(outedge.getTarget())) {
last = outedge;
break;
}
}
}
if (max < threshold) {
// most relevant station is not relevant enough
return null;
}
return maxStop;
}
public double getLeaveTrainFactorForStop(Stop stop) {
Realm realm = Realm.getDefaultInstance();
long entryCount = realm.where(StationUse.class).equalTo("station.id", stop.getStation().getId()).equalTo("type", StationUse.UseType.NETWORK_ENTRY.name()).count();
long exitCount = realm.where(StationUse.class).equalTo("station.id", stop.getStation().getId()).equalTo("type", StationUse.UseType.NETWORK_EXIT.name()).count();
// number of times user left at this stop to transfer to another line
long transferCount = realm.where(StationUse.class).equalTo("station.id", stop.getStation().getId()).equalTo("sourceLine", stop.getLine().getId()).equalTo("type", StationUse.UseType.INTERCHANGE.name()).count();
realm.close();
return entryCount * 0.3 + exitCount + transferCount;
}
public List<ScanResult> getLastWiFiScanResults() {
return wfc.getLastScanResults();
}
public void mockLocation(Station station) {
if (BuildConfig.DEBUG && station.getStops().size() > 0) {
List<BSSID> bssids = new ArrayList<>();
for (Stop s : station.getStops()) {
bssids.addAll(WiFiLocator.getBSSIDsForStop(s));
}
wfc.updateBSSIDsDebug(bssids);
}
}
// DEBUG:
protected String dumpDebugInfo() {
String s = "Service created on " + creationDate.toString();
s += (wfc.isScanning() ? String.format(". WFC scanning every %d s", wfc.getScanInterval() / 1000) : ". WFC not scanning") + "\n";
for (Network n : getNetworks()) {
S2LS loc;
synchronized (lock) {
loc = locServices.get(n.getId());
}
s += "Network " + n.getName() + "\n";
s += "State machine: " + loc.getState().toString() + "\n";
s += String.format("\tIn network? %b\n\tNear network? %b\n", loc.inNetwork(), loc.nearNetwork());
if (loc.getState() instanceof InNetworkState) {
s += "\tPossible stops:\n";
for (Stop stop : loc.getLocation().vertexSet()) {
s += String.format("\t\t%s (%s)\n", stop.getStation().getName(), stop.getLine().getName());
}
s += "\tPath:\n";
if (loc.getCurrentTrip() != null) {
for (Connection c : loc.getCurrentTrip().getEdgeList()) {
s += String.format("\t\t%s -> %s\n", c.getSource().toString(), c.getTarget().toString());
}
if (loc.getCurrentTargetRoute() != null) {
s += String.format("\t\tCurrent path complies? %b\n",
loc.getCurrentTargetRoute().checkPathCompliance(loc.getCurrentTrip()));
}
}
}
}
try {
API.AuthTest authTest = API.getInstance().getAuthTest();
s += "API auth test result: " + authTest.result + "\n";
s += "API key as perceived by server: " + authTest.key + "\n";
} catch (APIException e) {
e.printStackTrace();
s += "Error testing API authentication\n";
}
synchronizer.attemptSync();
return s;
}
// END OF DEBUG
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private UpdateTopologyTask currentUpdateTopologyTask = null;
private class UpdateTopologyTask extends AsyncTask<String, Integer, Boolean> {
protected Boolean doInBackground(String... networkIds) {
int net_count = networkIds.length;
publishProgress(0);
try {
for (int cur_net = 0; cur_net < net_count; cur_net++) {
API.Network n = api.getNetwork(networkIds[cur_net]);
publishProgress(5);
if (isCancelled()) break;
float netPart = (float) (cur_net + 1) / (float) net_count;
Log.d("UpdateTopologyTask", "Updating network " + n.id);
HashMap<String, API.Station> apiStations = new HashMap<>();
for (API.Station s : api.getStations()) {
if (s.network.equals(n.id)) {
apiStations.put(s.id, s);
}
}
publishProgress(20);
if (isCancelled()) break;
HashMap<String, API.Lobby> apiLobbies = new HashMap<>();
for (API.Lobby l : api.getLobbies()) {
if (l.network.equals(n.id)) {
apiLobbies.put(l.id, l);
}
}
publishProgress(40);
if (isCancelled()) break;
int line_count = n.lines.size();
int cur_line = 0;
HashMap<String, API.Line> apiLines = new HashMap<>();
for (String lineid : n.lines) {
API.Line l = api.getLine(lineid);
apiLines.put(lineid, l);
cur_line++;
publishProgress(40 + (int) (((cur_line / (float) (line_count)) * netPart) * 20));
if (cur_line < line_count) {
cur_line++;
}
if (isCancelled()) break;
}
if (isCancelled()) break;
List<API.Connection> connections = api.getConnections();
publishProgress(80);
if (isCancelled()) break;
List<API.Transfer> transfers = api.getTransfers();
publishProgress(100);
API.DatasetInfo info = api.getDatasetInfo(n.id);
lineStatusCache.clear();
statsCache.clear();
TopologyCache.saveNetwork(MainService.this, n, apiStations, apiLobbies, apiLines, connections, transfers, info);
putNetwork(TopologyCache.loadNetwork(MainService.this, n.id, api.getEndpoint().toString()));
if (isCancelled()) break;
}
} catch (APIException e) {
return false;
} catch (CacheException e) {
return false;
}
return true;
}
protected void onProgressUpdate(Integer... progress) {
Intent intent = new Intent(ACTION_UPDATE_TOPOLOGY_PROGRESS);
intent.putExtra(EXTRA_UPDATE_TOPOLOGY_PROGRESS, progress[0]);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
protected void onPostExecute(Boolean result) {
Log.d("UpdateTopologyTask", result.toString());
currentUpdateTopologyTask = null;
Intent intent = new Intent(ACTION_UPDATE_TOPOLOGY_FINISHED);
intent.putExtra(EXTRA_UPDATE_TOPOLOGY_FINISHED, result);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
@Override
protected void onCancelled() {
Log.d("UpdateTopologyTask", "onCancelled");
currentUpdateTopologyTask = null;
Intent intent = new Intent(ACTION_UPDATE_TOPOLOGY_CANCELLED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
}
private CheckTopologyUpdatesTask currentCheckTopologyUpdatesTask = null;
private class CheckTopologyUpdatesTask extends AsyncTask<Boolean, Integer, Boolean> {
// returns true if there are updates, false if not
private boolean autoUpdate;
protected Boolean doInBackground(Boolean... autoUpdate) {
this.autoUpdate = autoUpdate[0];
Log.d("MainService", "CheckTopologyUpdatesTask");
try {
List<API.DatasetInfo> datasetInfos = api.getDatasetInfos();
synchronized (lock) {
for (API.DatasetInfo di : datasetInfos) {
if (!networks.containsKey(di.network)) {
return true;
}
Network net = networks.get(di.network);
if (!di.version.equals(net.getDatasetVersion())) {
return true;
}
}
}
return false;
} catch (APIException e) {
return false;
}
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Boolean result) {
if (result) {
if (autoUpdate) {
updateTopology();
} else {
Intent intent = new Intent(ACTION_TOPOLOGY_UPDATE_AVAILABLE);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
}
currentCheckTopologyUpdatesTask = null;
}
}
public static final String ACTION_UPDATE_TOPOLOGY_PROGRESS = "im.tny.segvault.disturbances.action.topology.update.progress";
public static final String EXTRA_UPDATE_TOPOLOGY_PROGRESS = "im.tny.segvault.disturbances.extra.topology.update.progress";
public static final String ACTION_UPDATE_TOPOLOGY_FINISHED = "im.tny.segvault.disturbances.action.topology.update.finished";
public static final String EXTRA_UPDATE_TOPOLOGY_FINISHED = "im.tny.segvault.disturbances.extra.topology.update.finished";
public static final String ACTION_UPDATE_TOPOLOGY_CANCELLED = "im.tny.segvault.disturbances.action.topology.update.cancelled";
public static final String ACTION_TOPOLOGY_UPDATE_AVAILABLE = "im.tny.segvault.disturbances.action.topology.update.available";
public static final String ACTION_CHECK_TOPOLOGY_UPDATES = "im.tny.segvault.disturbances.action.checkTopologyUpdates";
public static final String ACTION_SYNC_TRIPS = "im.tny.segvault.disturbances.action.syncTrips";
public static final String ACTION_CURRENT_TRIP_UPDATED = "im.tny.segvault.disturbances.action.trip.current.updated";
public static final String ACTION_CURRENT_TRIP_ENDED = "im.tny.segvault.disturbances.action.trip.current.ended";
public static final String ACTION_S2LS_STATUS_CHANGED = "im.tny.segvault.disturbances.action.s2ls.status.changed";
public static final String ACTION_CACHE_EXTRAS_PROGRESS = "im.tny.segvault.disturbances.action.cacheextras.progress";
public static final String EXTRA_CACHE_EXTRAS_PROGRESS_CURRENT = "im.tny.segvault.disturbances.extra.cacheextras.progress.current";
public static final String EXTRA_CACHE_EXTRAS_PROGRESS_TOTAL = "im.tny.segvault.disturbances.extra.cacheextras.progress.total";
public static final String ACTION_CACHE_EXTRAS_FINISHED = "im.tny.segvault.disturbances.action.cacheextras.finished";
public static final String EXTRA_CACHE_EXTRAS_FINISHED = "im.tny.segvault.disturbances.extra.cacheextras.finished";
public static class LocationJobCreator implements JobCreator {
@Override
public Job create(String tag) {
switch (tag) {
case UpdateTopologyJob.TAG:
return new UpdateTopologyJob();
case SyncTripsJob.TAG:
return new SyncTripsJob();
default:
return null;
}
}
}
public static class UpdateTopologyJob extends Job {
public static final String TAG = "job_update_topology";
@Override
@NonNull
protected Result onRunJob(Params params) {
Intent intent = new Intent(getContext(), MainService.class).setAction(ACTION_CHECK_TOPOLOGY_UPDATES);
getContext().startService(intent);
return Result.SUCCESS;
}
public static void schedule() {
schedule(true);
}
public static void schedule(boolean updateCurrent) {
new JobRequest.Builder(UpdateTopologyJob.TAG)
.setExecutionWindow(TimeUnit.HOURS.toMillis(12), TimeUnit.HOURS.toMillis(36))
.setBackoffCriteria(TimeUnit.MINUTES.toMillis(30), JobRequest.BackoffPolicy.EXPONENTIAL)
.setRequiredNetworkType(JobRequest.NetworkType.UNMETERED)
.setPersisted(true)
.setUpdateCurrent(updateCurrent)
.build()
.schedule();
}
}
public static class SyncTripsJob extends Job {
public static final String TAG = "job_sync_trips";
@Override
@NonNull
protected Result onRunJob(Params params) {
Intent intent = new Intent(getContext(), MainService.class).setAction(ACTION_SYNC_TRIPS);
getContext().startService(intent);
return Result.SUCCESS;
}
public static void schedule() {
schedule(true);
}
public static void schedule(boolean updateCurrent) {
new JobRequest.Builder(SyncTripsJob.TAG)
.setExecutionWindow(TimeUnit.HOURS.toMillis(24), TimeUnit.HOURS.toMillis(48))
.setBackoffCriteria(TimeUnit.HOURS.toMillis(1), JobRequest.BackoffPolicy.EXPONENTIAL)
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setPersisted(true)
.setUpdateCurrent(updateCurrent)
.build()
.schedule();
}
}
private static final String ACTION_DISTURBANCE_NOTIFICATION = "im.tny.segvault.disturbances.action.notification.disturbance";
private static final String EXTRA_DISTURBANCE_NETWORK = "im.tny.segvault.disturbances.extra.notification.disturbance.network";
private static final String EXTRA_DISTURBANCE_LINE = "im.tny.segvault.disturbances.extra.notification.disturbance.line";
private static final String EXTRA_DISTURBANCE_ID = "im.tny.segvault.disturbances.extra.notification.disturbance.id";
private static final String EXTRA_DISTURBANCE_STATUS = "im.tny.segvault.disturbances.extra.notification.disturbance.status";
private static final String EXTRA_DISTURBANCE_DOWNTIME = "im.tny.segvault.disturbances.extra.notification.disturbance.downtime";
private static final String EXTRA_DISTURBANCE_MSGTIME = "im.tny.segvault.disturbances.extra.notification.disturbance.msgtime";
public static void startForDisturbanceNotification(Context context, String network, String line,
String id, String status, boolean downtime, long messageTime) {
Intent intent = new Intent(context, MainService.class);
intent.setAction(ACTION_DISTURBANCE_NOTIFICATION);
intent.putExtra(EXTRA_DISTURBANCE_NETWORK, network);
intent.putExtra(EXTRA_DISTURBANCE_LINE, line);
intent.putExtra(EXTRA_DISTURBANCE_ID, id);
intent.putExtra(EXTRA_DISTURBANCE_STATUS, status);
intent.putExtra(EXTRA_DISTURBANCE_DOWNTIME, downtime);
intent.putExtra(EXTRA_DISTURBANCE_MSGTIME, messageTime);
context.startService(intent);
}
private void handleDisturbanceNotification(String network, String line,
String id, String status, boolean downtime,
long msgtime) {
Log.d("MainService", "handleDisturbanceNotification");
SharedPreferences sharedPref = getSharedPreferences("notifsettings", MODE_PRIVATE);
Set<String> linePref = sharedPref.getStringSet("pref_notifs_lines", null);
Network snetwork;
synchronized (lock) {
if (!networks.containsKey(network)) {
return;
}
snetwork = networks.get(network);
}
Line sline = snetwork.getLine(line);
if (sline == null) {
return;
}
if (downtime) {
lineStatusCache.markLineAsDown(sline, new Date(msgtime));
} else {
lineStatusCache.markLineAsUp(sline);
}
if (linePref != null && !linePref.contains(line)) {
// notifications disabled for this line
return;
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (!downtime && !sharedPref.getBoolean("pref_notifs_service_resumed", true)) {
// notifications for normal service resumed disabled
notificationManager.cancel(id.hashCode());
return;
}
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(MainActivity.EXTRA_INITIAL_FRAGMENT, "nav_disturbances");
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
String title = String.format(getString(R.string.notif_disturbance_title), sline.getName());
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.setBigContentTitle(title);
bigTextStyle.bigText(status);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setStyle(bigTextStyle)
.setSmallIcon(R.drawable.ic_disturbance_notif)
.setColor(sline.getColor())
.setContentTitle(title)
.setContentText(status)
.setAutoCancel(true)
.setWhen(msgtime)
.setSound(Uri.parse(sharedPref.getString(downtime ? "pref_notifs_ringtone" : "pref_notifs_regularization_ringtone", "content://settings/system/notification_sound")))
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setContentIntent(pendingIntent);
if (sharedPref.getBoolean(downtime ? "pref_notifs_vibrate" : "pref_notifs_regularization_vibrate", false)) {
notificationBuilder.setVibrate(new long[]{0, 100, 100, 150, 150, 200});
} else {
notificationBuilder.setVibrate(new long[]{0l});
}
notificationManager.notify(id.hashCode(), notificationBuilder.build());
}
private static final String ACTION_ANNOUNCEMENT_NOTIFICATION = "im.tny.segvault.disturbances.action.notification.announcement";
private static final String EXTRA_ANNOUNCEMENT_NETWORK = "im.tny.segvault.disturbances.extra.notification.announcement.network";
private static final String EXTRA_ANNOUNCEMENT_TITLE = "im.tny.segvault.disturbances.extra.notification.announcement.title";
private static final String EXTRA_ANNOUNCEMENT_BODY = "im.tny.segvault.disturbances.extra.notification.announcement.body";
private static final String EXTRA_ANNOUNCEMENT_URL = "im.tny.segvault.disturbances.extra.notification.announcement.url";
private static final String EXTRA_ANNOUNCEMENT_SOURCE = "im.tny.segvault.disturbances.extra.notification.announcement.source";
private static final String EXTRA_ANNOUNCEMENT_MSGTIME = "im.tny.segvault.disturbances.extra.notification.announcement.msgtime";
public static void startForAnnouncementNotification(Context context, String network, String title,
String body, String url, String source, long messageTime) {
Intent intent = new Intent(context, MainService.class);
intent.setAction(ACTION_ANNOUNCEMENT_NOTIFICATION);
intent.putExtra(EXTRA_ANNOUNCEMENT_NETWORK, network);
intent.putExtra(EXTRA_ANNOUNCEMENT_TITLE, title);
intent.putExtra(EXTRA_ANNOUNCEMENT_BODY, body);
intent.putExtra(EXTRA_ANNOUNCEMENT_URL, url);
intent.putExtra(EXTRA_ANNOUNCEMENT_SOURCE, source);
intent.putExtra(EXTRA_ANNOUNCEMENT_MSGTIME, messageTime);
context.startService(intent);
}
private void handleAnnouncementNotification(String network, String title,
String body, String url, String sourceId,
long msgtime) {
Log.d("MainService", "handleAnnouncementNotification");
SharedPreferences sharedPref = getSharedPreferences("notifsettings", MODE_PRIVATE);
Set<String> sourcePref = sharedPref.getStringSet("pref_notifs_announcement_sources", null);
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse(url));
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Announcement.Source source = Announcement.getSource(sourceId);
if (source == null) {
return;
}
if (title.isEmpty()) {
title = String.format(getString(R.string.notif_announcement_alt_title), getString(source.nameResourceId));
}
if (body.isEmpty()) {
body = getString(R.string.frag_announcement_no_text);
}
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.setBigContentTitle(title);
bigTextStyle.bigText(body);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setStyle(bigTextStyle)
.setSmallIcon(R.drawable.ic_pt_ml_notif)
.setColor(source.color)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setWhen(msgtime)
.setSound(Uri.parse(sharedPref.getString("pref_notifs_announcement_ringtone", "content://settings/system/notification_sound")))
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setContentIntent(contentIntent);
if (sharedPref.getBoolean("pref_notifs_announcement_vibrate", false)) {
notificationBuilder.setVibrate(new long[]{0, 100, 100, 150, 150, 200});
} else {
notificationBuilder.setVibrate(new long[]{0l});
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(url.hashCode(), notificationBuilder.build());
}
private static final int ROUTE_NOTIFICATION_ID = -100;
public static final String ACTION_END_NAVIGATION = "im.tny.segvault.disturbances.action.route.current.end";
public static final String EXTRA_NAVIGATION_NETWORK = "im.tny.segvault.disturbances.extra.route.current.end.network";
public static final String ACTION_END_TRIP = "im.tny.segvault.disturbances.action.trip.current.end";
public static final String EXTRA_TRIP_NETWORK = "im.tny.segvault.disturbances.extra.trip.current.end.network";
private void updateRouteNotification(S2LS loc) {
updateRouteNotification(loc, false);
}
private void updateRouteNotification(S2LS loc, boolean highPriorityNotification) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(MainActivity.EXTRA_INITIAL_FRAGMENT, "nav_home");
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
intent, 0);
Path currentPath = loc.getCurrentTrip();
Route currentRoute = loc.getCurrentTargetRoute();
if (currentPath == null && currentRoute == null) {
Log.e("MainService", "Attempt to create notification when there's no path or planned route");
return;
}
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
CharSequence title = "";
List<CharSequence> statusLines = new ArrayList<>();
int color = -1;
if (currentRoute != null) {
inboxStyle.setSummaryText(String.format(getString(R.string.notif_route_navigating_status), currentRoute.getTarget().getStation().getName()));
Step nextStep = currentRoute.getNextStep(currentPath);
if (nextStep instanceof EnterStep) {
if (currentPath != null && currentPath.getCurrentStop() != null && currentRoute.checkPathStartsRoute(currentPath)) {
title = String.format(getString(R.string.notif_route_catch_train_title), ((EnterStep) nextStep).getDirection().getName(12));
} else {
title = String.format(getString(R.string.notif_route_enter_station_title), nextStep.getStation().getName(15));
}
// TODO: show "encurtamentos" warnings here if applicable
statusLines.add(String.format(getString(R.string.notif_route_catch_train_status), ((EnterStep) nextStep).getDirection().getName()));
color = currentRoute.getSource().getLine().getColor();
} else if (nextStep instanceof ChangeLineStep) {
ChangeLineStep clStep = (ChangeLineStep) nextStep;
String lineName = clStep.getTarget().getName();
String titleStr;
if (currentPath != null && currentPath.getCurrentStop() != null && currentPath.getCurrentStop().getStation() == nextStep.getStation()) {
titleStr = String.format(getString(R.string.notif_route_catch_train_line_change_title),
clStep.getTarget().getName());
} else {
titleStr = String.format(getString(R.string.notif_route_line_change_title),
nextStep.getStation().getName(10),
lineName);
}
int lStart = titleStr.indexOf(lineName);
int lEnd = lStart + lineName.length();
Spannable sb = new SpannableString(titleStr);
sb.setSpan(new ForegroundColorSpan(clStep.getTarget().getColor()), lStart, lEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
title = sb;
// TODO: show "encurtamentos" warnings here if applicable
sb = new SpannableString(
String.format(getString(R.string.notif_route_catch_train_status),
clStep.getDirection().getName())
);
sb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
statusLines.add(sb);
color = clStep.getTarget().getColor();
} else if (nextStep instanceof ExitStep) {
if (currentPath != null &&
new Date().getTime() - currentPath.getCurrentStopEntryTime().getTime() > 30 * 1000 &&
nextStep.getStation() == currentPath.getNextStop().getStation()) {
title = getString(R.string.notif_route_leave_train_next);
} else if (currentPath != null && currentPath.getCurrentStop().getStation() == nextStep.getStation()) {
title = getString(R.string.notif_route_leave_train_now);
} else {
title = String.format(getString(R.string.notif_route_leave_train), nextStep.getStation().getName(20));
}
}
}
if (currentPath != null) {
Stop curStop = currentPath.getCurrentStop();
if (color == -1) {
color = curStop.getLine().getColor();
}
if (currentRoute != null) {
statusLines.add(String.format(getString(R.string.notif_route_current_station), curStop.getStation().getName()));
} else {
title = curStop.getStation().getName();
}
if (currentPath.isWaitingFirstTrain()) {
statusLines.add(getString(R.string.notif_route_waiting));
} else {
Stop direction = currentPath.getDirection();
Stop next = currentPath.getNextStop();
if (direction != null && next != null) {
statusLines.add(String.format(getString(R.string.notif_route_next_station), next.getStation().getName()));
if (currentRoute == null) {
statusLines.add(String.format(getString(R.string.notif_route_direction), direction.getStation().getName()));
}
} else {
statusLines.add(getString(R.string.notif_route_left_station));
}
}
}
CharSequence singleLineStatus = "";
for (CharSequence s : statusLines) {
inboxStyle.addLine(s);
singleLineStatus = TextUtils.concat(singleLineStatus, s) + " | ";
}
singleLineStatus = singleLineStatus.subSequence(0, singleLineStatus.length() - 3);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setStyle(inboxStyle)
.setColor(color)
.setContentTitle(title)
.setContentText(singleLineStatus)
.setAutoCancel(false)
.setContentIntent(pendingIntent)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setOngoing(true);
if (highPriorityNotification) {
stopForeground(true);
notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
notificationBuilder.setDefaults(NotificationCompat.DEFAULT_VIBRATE);
}
if (currentRoute != null) {
notificationBuilder.setSmallIcon(R.drawable.ic_navigation_white_24dp);
Intent stopIntent = new Intent(this, MainService.class);
stopIntent.setAction(ACTION_END_NAVIGATION);
stopIntent.putExtra(EXTRA_NAVIGATION_NETWORK, loc.getNetwork().getId());
PendingIntent pendingStopIntent = PendingIntent.getService(this, (int) System.currentTimeMillis(),
stopIntent, 0);
notificationBuilder.addAction(R.drawable.ic_close_black_24dp, getString(R.string.notif_route_end_navigation), pendingStopIntent);
} else {
notificationBuilder.setSmallIcon(R.drawable.ic_trip_notif);
if (loc.canRequestEndOfTrip()) {
Intent stopIntent = new Intent(this, MainService.class);
stopIntent.setAction(ACTION_END_TRIP);
stopIntent.putExtra(EXTRA_TRIP_NETWORK, loc.getNetwork().getId());
PendingIntent pendingStopIntent = PendingIntent.getService(this, (int) System.currentTimeMillis(),
stopIntent, 0);
notificationBuilder.addAction(R.drawable.ic_stop_black_24dp, getString(R.string.notif_route_end_trip), pendingStopIntent);
}
}
startForeground(ROUTE_NOTIFICATION_ID, notificationBuilder.build());
}
public class S2LSChangeListener implements S2LS.EventListener {
@Override
public void onStateChanged(final S2LS loc) {
Log.d("onStateChanged", "State changed");
stateTickHandler.removeCallbacksAndMessages(null);
if (loc.getState().getPreferredTickIntervalMillis() != 0) {
doTick(loc.getState());
}
SharedPreferences sharedPref = getSharedPreferences("settings", MODE_PRIVATE);
boolean locationEnabled = sharedPref.getBoolean("pref_location_enable", true);
if (loc.getState() instanceof InNetworkState) {
wfc.setScanInterval(TimeUnit.SECONDS.toMillis(10));
if (locationEnabled) {
wfc.startScanning();
}
if (loc.getCurrentTrip() != null) {
updateRouteNotification(loc);
}
} else if (loc.getState() instanceof NearNetworkState) {
wfc.setScanInterval(TimeUnit.MINUTES.toMillis(1));
if (locationEnabled)
wfc.startScanningIfWiFiEnabled();
checkStopForeground(loc);
} else if (loc.getState() instanceof OffNetworkState) {
// wfc.stopScanning(); // TODO only enable this when there are locators besides WiFi
wfc.setScanInterval(TimeUnit.MINUTES.toMillis(1));
if (locationEnabled)
wfc.startScanningIfWiFiEnabled();
checkStopForeground(loc);
}
Intent intent = new Intent(ACTION_S2LS_STATUS_CHANGED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
@Override
public void onTripStarted(final S2LS s2ls) {
Path path = s2ls.getCurrentTrip();
path.addPathChangedListener(new Path.OnPathChangedListener() {
private Station prevEndStation = null;
@Override
public void onPathChanged(Path path) {
Log.d("onPathChanged", "Path changed");
Intent intent = new Intent(ACTION_CURRENT_TRIP_UPDATED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
boolean highPrioNotif = false;
if (s2ls.getCurrentTargetRoute() != null) {
Step nextStep = s2ls.getCurrentTargetRoute().getNextStep(path);
highPrioNotif = path.getEndVertex().getStation() != prevEndStation &&
path.getEndVertex().getStation() == nextStep.getStation() &&
!(nextStep instanceof EnterStep);
}
prevEndStation = path.getEndVertex().getStation();
updateRouteNotification(s2ls, highPrioNotif);
}
});
updateRouteNotification(s2ls);
}
@Override
public void onTripEnded(S2LS s2ls, Path path) {
String tripId = Trip.persistConnectionPath(path);
Intent intent = new Intent(ACTION_CURRENT_TRIP_ENDED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
if (!checkStopForeground(s2ls)) {
updateRouteNotification(s2ls);
}
SharedPreferences sharedPref = getSharedPreferences("settings", MODE_PRIVATE);
boolean openTripCorrection = sharedPref.getBoolean("pref_auto_open_trip_correction", false);
boolean openVisitCorrection = sharedPref.getBoolean("pref_auto_open_visit_correction", false);
if (openTripCorrection && (path.getEdgeList().size() > 0 || openVisitCorrection)) {
intent = new Intent(getApplicationContext(), TripCorrectionActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(TripCorrectionActivity.EXTRA_NETWORK_ID, s2ls.getNetwork().getId());
intent.putExtra(TripCorrectionActivity.EXTRA_TRIP_ID, tripId);
intent.putExtra(TripCorrectionActivity.EXTRA_IS_STANDALONE, true);
startActivity(intent);
}
}
@Override
public void onRouteProgrammed(S2LS s2ls, Route route) {
updateRouteNotification(s2ls);
}
@Override
public void onRouteStarted(S2LS s2ls, Path path, Route route) {
Log.d("onRouteStarted", "Route started");
if (!checkStopForeground(s2ls)) {
updateRouteNotification(s2ls);
}
}
@Override
public void onRouteMistake(S2LS s2ls, Path path, Route route) {
Log.d("onRouteMistake", "Route mistake");
// recalculate route with current station as origin station
s2ls.setCurrentTargetRoute(
Route.calculate(
s2ls.getNetwork(),
path.getEndVertex().getStation(),
route.getTarget().getStation()), true);
if (!checkStopForeground(s2ls)) {
updateRouteNotification(s2ls);
}
}
@Override
public void onRouteCancelled(S2LS s2ls, Route route) {
Log.d("onRouteCancelled", "Route cancelled");
if (!checkStopForeground(s2ls)) {
updateRouteNotification(s2ls);
}
}
@Override
public void onRouteCompleted(S2LS s2ls, Path path, Route route) {
Log.d("onRouteCompleted", "Route completed");
if (!checkStopForeground(s2ls)) {
updateRouteNotification(s2ls);
}
}
private void doTick(final State state) {
stateTickHandler.postDelayed(new Runnable() {
@Override
public void run() {
doTick(state);
state.tick();
}
}, state.getPreferredTickIntervalMillis());
}
private boolean checkStopForeground(S2LS loc) {
if (loc.getCurrentTargetRoute() == null && !(loc.getState() instanceof InNetworkState)) {
stopForeground(true);
return true;
}
return false;
}
}
public void cacheAllExtras(String... network_ids) {
ExtraContentCache.clearAllCachedExtras(this);
for (String id : network_ids) {
Network network = getNetwork(id);
ExtraContentCache.cacheAllExtras(this, new ExtraContentCache.OnCacheAllListener() {
@Override
public void onSuccess() {
Intent intent = new Intent(ACTION_CACHE_EXTRAS_FINISHED);
intent.putExtra(EXTRA_CACHE_EXTRAS_FINISHED, true);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
@Override
public void onProgress(int current, int total) {
Intent intent = new Intent(ACTION_CACHE_EXTRAS_PROGRESS);
intent.putExtra(EXTRA_CACHE_EXTRAS_PROGRESS_CURRENT, current);
intent.putExtra(EXTRA_CACHE_EXTRAS_PROGRESS_TOTAL, total);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
@Override
public void onFailure() {
Intent intent = new Intent(ACTION_CACHE_EXTRAS_FINISHED);
intent.putExtra(EXTRA_CACHE_EXTRAS_FINISHED, false);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
}, network);
}
}
private SharedPreferences.OnSharedPreferenceChangeListener generalPrefsListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("pref_location_enable")) {
if (prefs.getBoolean("pref_location_enable", true))
wfc.startScanningIfWiFiEnabled();
else
wfc.stopScanning();
}
}
};
public static final String ACTION_TRIP_REALM_UPDATED = "im.tny.segvault.disturbances.action.realm.trip.updated";
private RealmResults<Trip> tripRealmResults;
private final RealmChangeListener<RealmResults<Trip>> tripRealmChangeListener = new RealmChangeListener<RealmResults<Trip>>() {
@Override
public void onChange(RealmResults<Trip> element) {
Intent intent = new Intent(ACTION_TRIP_REALM_UPDATED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
};
public static final String ACTION_FEEDBACK_REALM_UPDATED = "im.tny.segvault.disturbances.action.realm.feedback.updated";
private RealmResults<Feedback> feedbackRealmResults;
private final RealmChangeListener<RealmResults<Feedback>> feedbackRealmChangeListener = new RealmChangeListener<RealmResults<Feedback>>() {
@Override
public void onChange(RealmResults<Feedback> element) {
Intent intent = new Intent(ACTION_FEEDBACK_REALM_UPDATED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(MainService.this);
bm.sendBroadcast(intent);
}
};
}
| 58,502 | 0.602441 | 0.598971 | 1,313 | 43.555977 | 34.720276 | 217 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.651942 | false | false | 4 |
b07bcdfb0ef2caf3ed1083eef180f000b711a529 | 31,353,261,320,214 | dad0e2234283b7c2c52b5c215ca0756fa4d838bc | /app/src/main/java/com/andreimesina/kitesurfingworldwide/activity/list/SpotViewHolder.java | b905e93881ea0c5fa64a3b2f741eed1bdda28306 | [] | no_license | andreimesina/KitesurfingWorldwide | https://github.com/andreimesina/KitesurfingWorldwide | d50ee6e3ab028489fed4af1ac0c4e7535b06b994 | b8445b73887d5cf358cf788c7f466703e1ffa9c7 | refs/heads/master | 2020-05-22T02:33:16.370000 | 2019-06-02T19:37:05 | 2019-06-02T19:37:05 | 186,200,327 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.andreimesina.kitesurfingworldwide.activity.list;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.andreimesina.kitesurfingworldwide.R;
public class SpotViewHolder extends RecyclerView.ViewHolder {
private TextView textViewName;
private TextView textViewCountry;
public SpotViewHolder(@NonNull View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.textView_name_item);
textViewCountry = itemView.findViewById(R.id.textView_country_item);
}
}
| UTF-8 | Java | 628 | java | SpotViewHolder.java | Java | [] | null | [] | package com.andreimesina.kitesurfingworldwide.activity.list;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.andreimesina.kitesurfingworldwide.R;
public class SpotViewHolder extends RecyclerView.ViewHolder {
private TextView textViewName;
private TextView textViewCountry;
public SpotViewHolder(@NonNull View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.textView_name_item);
textViewCountry = itemView.findViewById(R.id.textView_country_item);
}
}
| 628 | 0.780255 | 0.780255 | 22 | 27.545454 | 25.631527 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
336daf7631fcf3bcda132eff779af494645ff521 | 23,854,248,428,718 | 0e7a63030067a747716ef5f8f2aeef860c013c66 | /103-04/src/_16.java | 1f136ccef96e51c151e5e9cb4cffbe63eff8d4f9 | [] | no_license | e1018e1018/Coding365 | https://github.com/e1018e1018/Coding365 | c1a9294d5f73b34cbba13a3cacac100c63a8c1ad | cc25d09fc82589a0978a8a3d4c6c1668c425a926 | refs/heads/master | 2020-03-23T02:57:27.341000 | 2018-08-08T16:40:36 | 2018-08-08T16:40:36 | 140,801,851 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
public class _16 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String _1 = input.next();
String _2 = input.next();
if(_1.length() > 59 || _2.length() > 59) {
System.exit(1);
}
ArrayList<Integer> plus = new ArrayList<Integer>();
ArrayList<Integer> minus = new ArrayList<Integer>();
int[] multiply = new int[_1.length() + _2.length() + Math.abs(_1.length() - _2.length())];
String zero = "";
int add_1 = 0, add_2 = 0;
boolean negative = false;
String[] _01Split = _1.split("");
String[] _02Split = _2.split("");
String tempString;
int zeroCount = 0;
int _1Length = _1.length();
int _2Length = _2.length();
if(_01Split[0].equals("-")) {
_1Length--;
for(int a = 1; a < _01Split.length; a++) {
add_1 += Integer.parseInt(_01Split[a]);
}
}else {
for(int a = 0; a < _01Split.length; a++) {
add_1 += Integer.parseInt(_01Split[a]);
}
}
if(_02Split[0].equals("-")) {
_2Length--;
for(int b = 1; b < _02Split.length; b++) {
add_2 += Integer.parseInt(_02Split[b]);
}
}else {
for(int b = 0; b < _02Split.length; b++) {
add_2 += Integer.parseInt(_02Split[b]);
}
}
for(int z = 0; z < Math.abs(_1Length - _2Length); z++) {
zero += "0";
zeroCount++;
}
if(_1Length < _2Length) {
_1 = zero + _1;
tempString = _1;
_1 = _2;
_2 = tempString;
negative = true;
}else
if(_1Length > _2Length){
_2 = zero + _2;
}else {
if(add_1 < add_2) {
tempString = _1;
_1 = _2;
_2 = tempString;
negative = true;
}
}
String[] _1Split = _1.split("");
String[] _2Split = _2.split("");
int digit = 0;
for(int i = _1.length() - 1; i >= 0; i--) {
int temp = Integer.parseInt(_1Split[i]) + Integer.parseInt(_2Split[i]);
if(temp > 9) {
temp %= 10;
plus.add(digit + temp);
digit = 0;
digit++;
}else {
if(digit + temp > 9) {
plus.add(0);
digit = 0;
digit++;
}else {
plus.add(digit + temp);
digit = 0;
}
}
}
if(digit == 1) {
System.out.print(digit);
digit = 0;
for(int k = plus.size() - 1; k >= 0; k--) {
System.out.print(plus.get(k));
}
}else {
for(int k = plus.size() - 1; k >= 0; k--) {
System.out.print(plus.get(k));
}
}
System.out.print("\n");
for(int i = _1.length() - 1; i >= 0; i--) {
int temp = Integer.parseInt(_1Split[i]) - Integer.parseInt(_2Split[i]) + digit;
if(temp < 0) {
temp += 10;
minus.add(temp);
digit = 0;
digit--;
}else {
minus.add(temp);
digit = 0;
}
}
if(_1.equals(_2)) {
System.out.print(0);
}else {
if(negative) {
System.out.print("-");
for(int k = minus.size() -1 ; k >= 0; k--) {
System.out.print(minus.get(k));
}
}else {
for(int k = minus.size() -1 ; k >= 0; k--) {
System.out.print(minus.get(k));
}
}
}
System.out.print("\n");
for(int i =0 ; i < _1.length(); i++){
for(int j =0; j < _2.length(); j++){
multiply[i + j] += Integer.parseInt(_1Split[i]) * Integer.parseInt(_2Split[j]);
}
}
for(int i =multiply.length - 1; i > 0 ;i--){
multiply[i - 1] += multiply[i] / 10;
multiply[i] = multiply[i] % 10;
}
if(add_1 == 0 || add_2 == 0) {
System.out.print(0);
}
else {
int m;
for(m = 0; m < multiply.length -1; m++) {
if(multiply[m] != 0) {
break;
}
}
for(int k = m; k < multiply.length -1 ; k++) {
System.out.print(multiply[k]);
}
}
}
} | UTF-8 | Java | 3,749 | java | _16.java | Java | [] | null | [] | import java.util.*;
public class _16 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String _1 = input.next();
String _2 = input.next();
if(_1.length() > 59 || _2.length() > 59) {
System.exit(1);
}
ArrayList<Integer> plus = new ArrayList<Integer>();
ArrayList<Integer> minus = new ArrayList<Integer>();
int[] multiply = new int[_1.length() + _2.length() + Math.abs(_1.length() - _2.length())];
String zero = "";
int add_1 = 0, add_2 = 0;
boolean negative = false;
String[] _01Split = _1.split("");
String[] _02Split = _2.split("");
String tempString;
int zeroCount = 0;
int _1Length = _1.length();
int _2Length = _2.length();
if(_01Split[0].equals("-")) {
_1Length--;
for(int a = 1; a < _01Split.length; a++) {
add_1 += Integer.parseInt(_01Split[a]);
}
}else {
for(int a = 0; a < _01Split.length; a++) {
add_1 += Integer.parseInt(_01Split[a]);
}
}
if(_02Split[0].equals("-")) {
_2Length--;
for(int b = 1; b < _02Split.length; b++) {
add_2 += Integer.parseInt(_02Split[b]);
}
}else {
for(int b = 0; b < _02Split.length; b++) {
add_2 += Integer.parseInt(_02Split[b]);
}
}
for(int z = 0; z < Math.abs(_1Length - _2Length); z++) {
zero += "0";
zeroCount++;
}
if(_1Length < _2Length) {
_1 = zero + _1;
tempString = _1;
_1 = _2;
_2 = tempString;
negative = true;
}else
if(_1Length > _2Length){
_2 = zero + _2;
}else {
if(add_1 < add_2) {
tempString = _1;
_1 = _2;
_2 = tempString;
negative = true;
}
}
String[] _1Split = _1.split("");
String[] _2Split = _2.split("");
int digit = 0;
for(int i = _1.length() - 1; i >= 0; i--) {
int temp = Integer.parseInt(_1Split[i]) + Integer.parseInt(_2Split[i]);
if(temp > 9) {
temp %= 10;
plus.add(digit + temp);
digit = 0;
digit++;
}else {
if(digit + temp > 9) {
plus.add(0);
digit = 0;
digit++;
}else {
plus.add(digit + temp);
digit = 0;
}
}
}
if(digit == 1) {
System.out.print(digit);
digit = 0;
for(int k = plus.size() - 1; k >= 0; k--) {
System.out.print(plus.get(k));
}
}else {
for(int k = plus.size() - 1; k >= 0; k--) {
System.out.print(plus.get(k));
}
}
System.out.print("\n");
for(int i = _1.length() - 1; i >= 0; i--) {
int temp = Integer.parseInt(_1Split[i]) - Integer.parseInt(_2Split[i]) + digit;
if(temp < 0) {
temp += 10;
minus.add(temp);
digit = 0;
digit--;
}else {
minus.add(temp);
digit = 0;
}
}
if(_1.equals(_2)) {
System.out.print(0);
}else {
if(negative) {
System.out.print("-");
for(int k = minus.size() -1 ; k >= 0; k--) {
System.out.print(minus.get(k));
}
}else {
for(int k = minus.size() -1 ; k >= 0; k--) {
System.out.print(minus.get(k));
}
}
}
System.out.print("\n");
for(int i =0 ; i < _1.length(); i++){
for(int j =0; j < _2.length(); j++){
multiply[i + j] += Integer.parseInt(_1Split[i]) * Integer.parseInt(_2Split[j]);
}
}
for(int i =multiply.length - 1; i > 0 ;i--){
multiply[i - 1] += multiply[i] / 10;
multiply[i] = multiply[i] % 10;
}
if(add_1 == 0 || add_2 == 0) {
System.out.print(0);
}
else {
int m;
for(m = 0; m < multiply.length -1; m++) {
if(multiply[m] != 0) {
break;
}
}
for(int k = m; k < multiply.length -1 ; k++) {
System.out.print(multiply[k]);
}
}
}
} | 3,749 | 0.480128 | 0.440918 | 163 | 22.006134 | 18.395617 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.02454 | false | false | 4 |
2f2c9ea752ef50430b659aa7bd2f85a205f3f5a6 | 17,978,733,145,246 | d0a7e6b37d20ff653e6daefe4984240c18269641 | /acfun5_7/src/main/java/com/baidu/speech/AuthEasrHelper.java | 803b08d6d452aea644c11bc9270b3122d58e5e77 | [] | no_license | HubertYoung/AcFun | https://github.com/HubertYoung/AcFun | 3fbecdec57becae32b7cd917e4c15f16aeab95e8 | e83c4a821e1dbeb7843af09d59755f3cd833e83a | refs/heads/master | 2018-11-18T03:53:57.159000 | 2018-10-29T15:01:55 | 2018-10-29T15:02:01 | 146,857,138 | 6 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.baidu.speech;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.text.TextUtils;
import com.baidu.speech.easr.EasrFactory;
import com.baidu.speech.easr.EasrJniInterface;
import com.baidu.speech.easr.EasrNativeJniInterface;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.logging.Logger;
import org.json.JSONObject;
public class AuthEasrHelper {
public static final int a = 0;
public static final int b = 8000;
public static final int c = 8001;
public static final int d = 8002;
public static final int e = 8003;
public static final int f = 8004;
public static final int g = 8005;
public static final int h = 8007;
public static final int i = 9000;
private static final String j = "AuthEasrHelper";
private static final Logger k = Logger.getLogger(j);
private static final EasrNativeJniInterface l = EasrFactory.b();
private static final EasrJniInterface m = EasrFactory.a();
private static String n = null;
private static boolean o = true;
private static String p = "";
private static boolean q = false;
private static final String r = "[百度语音试用服务%d天后到期]";
private static final String s = "[百度语音试用服务已经到期,请及时更新授权]";
private static final String t = "bds-easr-license.lic";
public static synchronized void a(EventContext eventContext, JSONObject jSONObject) throws Exception {
synchronized (AuthEasrHelper.class) {
if (l.k()) {
return;
}
String optString = jSONObject.optString("license", jSONObject.optString("license-file-path"));
Object optString2 = jSONObject.optString("appid");
if (TextUtils.isEmpty(optString2)) {
ApplicationInfo applicationInfo = eventContext.getPackageManager().getApplicationInfo(eventContext.getPackageName(), 128);
if (!(applicationInfo == null || applicationInfo.metaData == null)) {
Object obj = applicationInfo.metaData.get("com.baidu.speech.APP_ID");
if (obj != null) {
optString2 = obj.toString();
}
}
}
Integer valueOf = TextUtils.isEmpty(optString2) ? null : Integer.valueOf(Integer.parseInt(optString2));
try {
a(eventContext, optString, valueOf);
} catch (Throwable e) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("bad license! license=");
stringBuilder.append(optString);
stringBuilder.append(", appid=");
stringBuilder.append(valueOf);
throw new Exception(stringBuilder.toString(), e);
}
}
}
private static synchronized void a(EventContext eventContext, String str, Integer num) throws IOException {
synchronized (AuthEasrHelper.class) {
Logger logger = k;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("easr auth: licenseUri=");
stringBuilder.append(str);
stringBuilder.append(", appid=");
stringBuilder.append(num);
logger.info(stringBuilder.toString());
if (TextUtils.isEmpty(str) || !str.matches("^\\w+?://.*") || str.startsWith("file://")) {
a((Context) eventContext, num, str);
} else {
logger = k;
stringBuilder = new StringBuilder();
stringBuilder.append("easr auth: copy to writable path if not exist!, licenseUri=");
stringBuilder.append(str);
logger.info(stringBuilder.toString());
byte[] d = eventContext.d(str);
stringBuilder = new StringBuilder();
stringBuilder.append("easr-");
stringBuilder.append(Integer.toHexString(Arrays.toString(d).hashCode()));
stringBuilder.append(".lic");
File fileStreamPath = eventContext.getFileStreamPath(stringBuilder.toString());
if (!fileStreamPath.exists()) {
Logger logger2 = k;
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append("easr auth: copy license ");
stringBuilder2.append(str);
stringBuilder2.append("->");
stringBuilder2.append(fileStreamPath);
logger2.info(stringBuilder2.toString());
FileOutputStream fileOutputStream = new FileOutputStream(fileStreamPath);
fileOutputStream.write(d);
fileOutputStream.close();
}
a((Context) eventContext, num, fileStreamPath.getAbsolutePath());
}
}
}
private static int b(Context context, Integer num, String str, String str2, String str3) {
int a = l.a(context, num == null ? "" : num.toString(), str, str2, str3);
Logger logger = k;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("GetLicense getLicenseRet ");
stringBuilder.append(a);
stringBuilder.append(", licensePath: ");
stringBuilder.append(str3);
stringBuilder.append(", appid: ");
stringBuilder.append(num);
logger.info(stringBuilder.toString());
Logger logger2 = k;
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append("cuid: ");
stringBuilder2.append(str);
stringBuilder2.append(", stat: ");
stringBuilder2.append(str2);
logger2.info(stringBuilder2.toString());
if (a < 0) {
int a2 = l.a(context, "", str, str2, str3);
logger2 = k;
stringBuilder2 = new StringBuilder();
stringBuilder2.append("GetLicense getLicenseRet ");
stringBuilder2.append(a2);
stringBuilder2.append(", licensePath: ");
stringBuilder2.append(str3);
stringBuilder2.append(", appid: ");
stringBuilder2.append("");
logger2.info(stringBuilder2.toString());
logger2 = k;
StringBuilder stringBuilder3 = new StringBuilder();
stringBuilder3.append("cuid: ");
stringBuilder3.append(str);
stringBuilder3.append(", stat: ");
stringBuilder3.append(str2);
logger2.info(stringBuilder3.toString());
if (a2 >= 0) {
return a2;
}
}
return a;
}
private static int a(Context context, Integer num, String str, byte[] bArr, int i, byte[] bArr2, String str2) {
String num2 = num == null ? "" : num.toString();
String str3 = new String(bArr);
if (context.getPackageName().equals("com.baidu.speech.recognizerdemo") && str3.contains("acfcb9c8b0260") && str3.contains("24a04d595472216df3905965643a36bdaffeedcfc0b35")) {
num2 = "1111";
}
int a = l.a(context, num2, str, bArr, i, bArr2, str2);
if (a >= 0) {
return a;
}
return l.a(context, "", str, bArr, i, bArr2, str2);
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
private static synchronized int a(android.content.Context r18, java.lang.Integer r19, java.lang.String r20) {
/*
r8 = r18;
r9 = r19;
r10 = com.baidu.speech.AuthEasrHelper.class;
monitor-enter(r10);
r1 = "bds-easr-license.lic";
r1 = r8.getFileStreamPath(r1); Catch:{ all -> 0x022a }
r1 = r1.getAbsolutePath(); Catch:{ all -> 0x022a }
n = r1; Catch:{ all -> 0x022a }
if (r20 == 0) goto L_0x0026;
L_0x0015:
r2 = new java.io.File; Catch:{ all -> 0x022a }
r3 = n; Catch:{ all -> 0x022a }
r2.<init>(r3); Catch:{ all -> 0x022a }
r2 = r2.exists(); Catch:{ all -> 0x022a }
if (r2 == 0) goto L_0x0023;
L_0x0022:
goto L_0x0026;
L_0x0023:
r1 = r20;
goto L_0x0028;
L_0x0026:
r1 = n; Catch:{ all -> 0x022a }
L_0x0028:
r2 = k; Catch:{ all -> 0x022a }
r3 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r3.<init>(); Catch:{ all -> 0x022a }
r4 = "licensePath: ";
r3.append(r4); Catch:{ all -> 0x022a }
r3.append(r1); Catch:{ all -> 0x022a }
r3 = r3.toString(); Catch:{ all -> 0x022a }
r2.info(r3); Catch:{ all -> 0x022a }
r11 = com.baidu.speech.easr.Utility.c(r18); Catch:{ all -> 0x022a }
r2 = new java.io.File; Catch:{ all -> 0x022a }
r2.<init>(r1); Catch:{ all -> 0x022a }
r2 = r2.exists(); Catch:{ all -> 0x022a }
r12 = 0;
if (r2 != 0) goto L_0x00ad;
L_0x004e:
r2 = new java.io.File; Catch:{ all -> 0x022a }
r2.<init>(r1); Catch:{ all -> 0x022a }
r2 = r2.canWrite(); Catch:{ all -> 0x022a }
if (r2 != 0) goto L_0x005b;
L_0x0059:
r1 = n; Catch:{ all -> 0x022a }
L_0x005b:
r2 = com.baidu.speech.easr.stat.StatHelper.a(r8, r12); Catch:{ all -> 0x022a }
r3 = b(r8, r9, r11, r2, r1); Catch:{ all -> 0x022a }
r4 = k; Catch:{ all -> 0x022a }
r5 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r5.<init>(); Catch:{ all -> 0x022a }
r6 = "GetLicense getLicenseRet ";
r5.append(r6); Catch:{ all -> 0x022a }
r5.append(r3); Catch:{ all -> 0x022a }
r6 = ", licensePath: ";
r5.append(r6); Catch:{ all -> 0x022a }
r5.append(r1); Catch:{ all -> 0x022a }
r5 = r5.toString(); Catch:{ all -> 0x022a }
r4.info(r5); Catch:{ all -> 0x022a }
r4 = k; Catch:{ all -> 0x022a }
r5 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r5.<init>(); Catch:{ all -> 0x022a }
r6 = "cuid: ";
r5.append(r6); Catch:{ all -> 0x022a }
r5.append(r11); Catch:{ all -> 0x022a }
r6 = ", stat: ";
r5.append(r6); Catch:{ all -> 0x022a }
r5.append(r2); Catch:{ all -> 0x022a }
r2 = r5.toString(); Catch:{ all -> 0x022a }
r4.info(r2); Catch:{ all -> 0x022a }
if (r3 >= 0) goto L_0x00ad;
L_0x00a1:
r1 = "";
p = r1; Catch:{ all -> 0x022a }
r1 = java.lang.Math.abs(r3); Catch:{ all -> 0x022a }
r1 = r1 + 9000;
monitor-exit(r10);
return r1;
L_0x00ad:
r13 = r1;
r1 = 32;
r14 = new byte[r1]; Catch:{ all -> 0x022a }
r1 = 1024; // 0x400 float:1.435E-42 double:5.06E-321;
r15 = new byte[r1]; Catch:{ all -> 0x022a }
r5 = com.baidu.speech.easr.Utility.a(r13, r15); Catch:{ all -> 0x022a }
r1 = r18.getFilesDir(); Catch:{ all -> 0x022a }
r7 = r1.getAbsolutePath(); Catch:{ all -> 0x022a }
r1 = k; Catch:{ all -> 0x022a }
r2 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r2.<init>(); Catch:{ all -> 0x022a }
r3 = "logDir: ";
r2.append(r3); Catch:{ all -> 0x022a }
r2.append(r7); Catch:{ all -> 0x022a }
r2 = r2.toString(); Catch:{ all -> 0x022a }
r1.info(r2); Catch:{ all -> 0x022a }
r1 = r8;
r2 = r9;
r3 = r11;
r4 = r15;
r6 = r14;
r16 = r7;
r1 = a(r1, r2, r3, r4, r5, r6, r7); Catch:{ all -> 0x022a }
r2 = new java.lang.String; Catch:{ all -> 0x022a }
r2.<init>(r14); Catch:{ all -> 0x022a }
r3 = "end";
r3 = r2.indexOf(r3); Catch:{ all -> 0x022a }
r4 = -1;
r7 = 0;
if (r3 == r4) goto L_0x00fe;
L_0x00f2:
r3 = r2.substring(r7, r3); Catch:{ all -> 0x022a }
r4 = new com.baidu.speech.easr.stat.StatThread; Catch:{ all -> 0x022a }
r4.<init>(r8, r3); Catch:{ all -> 0x022a }
r4.start(); Catch:{ all -> 0x022a }
L_0x00fe:
r3 = k; Catch:{ all -> 0x022a }
r4 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r4.<init>(); Catch:{ all -> 0x022a }
r5 = "VerifyLicense authRet ";
r4.append(r5); Catch:{ all -> 0x022a }
r4.append(r1); Catch:{ all -> 0x022a }
r4 = r4.toString(); Catch:{ all -> 0x022a }
r3.info(r4); Catch:{ all -> 0x022a }
r3 = k; Catch:{ all -> 0x022a }
r4 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r4.<init>(); Catch:{ all -> 0x022a }
r5 = "appIdStr: ";
r4.append(r5); Catch:{ all -> 0x022a }
r4.append(r2); Catch:{ all -> 0x022a }
r2 = r4.toString(); Catch:{ all -> 0x022a }
r3.info(r2); Catch:{ all -> 0x022a }
r2 = l; Catch:{ all -> 0x022a }
r6 = 1;
r5 = 1000; // 0x3e8 float:1.401E-42 double:4.94E-321;
if (r1 < 0) goto L_0x0155;
L_0x0131:
r2 = l; Catch:{ all -> 0x022a }
if (r1 >= r5) goto L_0x013c;
L_0x0135:
o = r7; Catch:{ all -> 0x022a }
r1 = "";
p = r1; Catch:{ all -> 0x022a }
goto L_0x0153;
L_0x013c:
o = r6; Catch:{ all -> 0x022a }
r2 = java.util.Locale.US; Catch:{ all -> 0x022a }
r3 = "[百度语音试用服务%d天后到期]";
r4 = new java.lang.Object[r6]; Catch:{ all -> 0x022a }
r6 = l; Catch:{ all -> 0x022a }
r1 = r1 - r5;
r1 = java.lang.Integer.valueOf(r1); Catch:{ all -> 0x022a }
r4[r7] = r1; Catch:{ all -> 0x022a }
r1 = java.lang.String.format(r2, r3, r4); Catch:{ all -> 0x022a }
p = r1; Catch:{ all -> 0x022a }
L_0x0153:
monitor-exit(r10);
return r7;
L_0x0155:
r2 = l; Catch:{ all -> 0x022a }
r4 = -6;
if (r1 != r4) goto L_0x016d;
L_0x015a:
r1 = q; Catch:{ all -> 0x022a }
if (r1 != 0) goto L_0x016b;
L_0x015e:
r1 = new java.lang.Thread; Catch:{ all -> 0x022a }
r2 = new com.baidu.speech.AuthEasrHelper$1; Catch:{ all -> 0x022a }
r2.<init>(r13, r8, r9, r11); Catch:{ all -> 0x022a }
r1.<init>(r2); Catch:{ all -> 0x022a }
r1.start(); Catch:{ all -> 0x022a }
L_0x016b:
monitor-exit(r10);
return r7;
L_0x016d:
r1 = com.baidu.speech.easr.stat.StatHelper.a(r8, r12); Catch:{ all -> 0x022a }
r2 = new java.io.File; Catch:{ all -> 0x022a }
r2.<init>(r13); Catch:{ all -> 0x022a }
r2 = r2.canWrite(); Catch:{ all -> 0x022a }
if (r2 != 0) goto L_0x017e;
L_0x017c:
r13 = n; Catch:{ all -> 0x022a }
L_0x017e:
r2 = b(r8, r9, r11, r1, r13); Catch:{ all -> 0x022a }
r3 = k; Catch:{ all -> 0x022a }
r12 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r12.<init>(); Catch:{ all -> 0x022a }
r4 = "GetLicense getLicenseRet ";
r12.append(r4); Catch:{ all -> 0x022a }
r12.append(r2); Catch:{ all -> 0x022a }
r4 = ", licensePath: ";
r12.append(r4); Catch:{ all -> 0x022a }
r12.append(r13); Catch:{ all -> 0x022a }
r4 = r12.toString(); Catch:{ all -> 0x022a }
r3.info(r4); Catch:{ all -> 0x022a }
r3 = k; Catch:{ all -> 0x022a }
r4 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r4.<init>(); Catch:{ all -> 0x022a }
r12 = "cuid: ";
r4.append(r12); Catch:{ all -> 0x022a }
r4.append(r11); Catch:{ all -> 0x022a }
r12 = ", stat: ";
r4.append(r12); Catch:{ all -> 0x022a }
r4.append(r1); Catch:{ all -> 0x022a }
r1 = r4.toString(); Catch:{ all -> 0x022a }
r3.info(r1); Catch:{ all -> 0x022a }
if (r2 <= 0) goto L_0x021e;
L_0x01c0:
r12 = com.baidu.speech.easr.Utility.a(r13, r15); Catch:{ all -> 0x022a }
r1 = r8;
r2 = r9;
r3 = r11;
r8 = -6;
r4 = r15;
r9 = 1000; // 0x3e8 float:1.401E-42 double:4.94E-321;
r5 = r12;
r11 = 1;
r6 = r14;
r12 = 0;
r7 = r16;
r1 = a(r1, r2, r3, r4, r5, r6, r7); Catch:{ all -> 0x022a }
r2 = k; Catch:{ all -> 0x022a }
r3 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r3.<init>(); Catch:{ all -> 0x022a }
r4 = "VerifyLicense authRet ";
r3.append(r4); Catch:{ all -> 0x022a }
r3.append(r1); Catch:{ all -> 0x022a }
r3 = r3.toString(); Catch:{ all -> 0x022a }
r2.info(r3); Catch:{ all -> 0x022a }
r2 = l; Catch:{ all -> 0x022a }
if (r1 >= 0) goto L_0x01fa;
L_0x01ef:
r2 = l; Catch:{ all -> 0x022a }
if (r1 != r8) goto L_0x01f4;
L_0x01f3:
goto L_0x01fa;
L_0x01f4:
r2 = "[百度语音试用服务已经到期,请及时更新授权]";
p = r2; Catch:{ all -> 0x022a }
monitor-exit(r10);
return r1;
L_0x01fa:
r2 = l; Catch:{ all -> 0x022a }
if (r1 >= r9) goto L_0x0205;
L_0x01fe:
o = r12; Catch:{ all -> 0x022a }
r1 = "";
p = r1; Catch:{ all -> 0x022a }
goto L_0x021c;
L_0x0205:
o = r11; Catch:{ all -> 0x022a }
r2 = java.util.Locale.US; Catch:{ all -> 0x022a }
r3 = "[百度语音试用服务%d天后到期]";
r4 = new java.lang.Object[r11]; Catch:{ all -> 0x022a }
r5 = l; Catch:{ all -> 0x022a }
r1 = r1 - r9;
r1 = java.lang.Integer.valueOf(r1); Catch:{ all -> 0x022a }
r4[r12] = r1; Catch:{ all -> 0x022a }
r1 = java.lang.String.format(r2, r3, r4); Catch:{ all -> 0x022a }
p = r1; Catch:{ all -> 0x022a }
L_0x021c:
monitor-exit(r10);
return r12;
L_0x021e:
r1 = "[百度语音试用服务已经到期,请及时更新授权]";
p = r1; Catch:{ all -> 0x022a }
r1 = java.lang.Math.abs(r2); Catch:{ all -> 0x022a }
r1 = r1 + 9000;
monitor-exit(r10);
return r1;
L_0x022a:
r0 = move-exception;
r1 = r0;
monitor-exit(r10);
throw r1;
*/
throw new UnsupportedOperationException("Method not decompiled: com.baidu.speech.AuthEasrHelper.a(android.content.Context, java.lang.Integer, java.lang.String):int");
}
}
| UTF-8 | Java | 18,593 | java | AuthEasrHelper.java | Java | [] | null | [] | package com.baidu.speech;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.text.TextUtils;
import com.baidu.speech.easr.EasrFactory;
import com.baidu.speech.easr.EasrJniInterface;
import com.baidu.speech.easr.EasrNativeJniInterface;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.logging.Logger;
import org.json.JSONObject;
public class AuthEasrHelper {
public static final int a = 0;
public static final int b = 8000;
public static final int c = 8001;
public static final int d = 8002;
public static final int e = 8003;
public static final int f = 8004;
public static final int g = 8005;
public static final int h = 8007;
public static final int i = 9000;
private static final String j = "AuthEasrHelper";
private static final Logger k = Logger.getLogger(j);
private static final EasrNativeJniInterface l = EasrFactory.b();
private static final EasrJniInterface m = EasrFactory.a();
private static String n = null;
private static boolean o = true;
private static String p = "";
private static boolean q = false;
private static final String r = "[百度语音试用服务%d天后到期]";
private static final String s = "[百度语音试用服务已经到期,请及时更新授权]";
private static final String t = "bds-easr-license.lic";
public static synchronized void a(EventContext eventContext, JSONObject jSONObject) throws Exception {
synchronized (AuthEasrHelper.class) {
if (l.k()) {
return;
}
String optString = jSONObject.optString("license", jSONObject.optString("license-file-path"));
Object optString2 = jSONObject.optString("appid");
if (TextUtils.isEmpty(optString2)) {
ApplicationInfo applicationInfo = eventContext.getPackageManager().getApplicationInfo(eventContext.getPackageName(), 128);
if (!(applicationInfo == null || applicationInfo.metaData == null)) {
Object obj = applicationInfo.metaData.get("com.baidu.speech.APP_ID");
if (obj != null) {
optString2 = obj.toString();
}
}
}
Integer valueOf = TextUtils.isEmpty(optString2) ? null : Integer.valueOf(Integer.parseInt(optString2));
try {
a(eventContext, optString, valueOf);
} catch (Throwable e) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("bad license! license=");
stringBuilder.append(optString);
stringBuilder.append(", appid=");
stringBuilder.append(valueOf);
throw new Exception(stringBuilder.toString(), e);
}
}
}
private static synchronized void a(EventContext eventContext, String str, Integer num) throws IOException {
synchronized (AuthEasrHelper.class) {
Logger logger = k;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("easr auth: licenseUri=");
stringBuilder.append(str);
stringBuilder.append(", appid=");
stringBuilder.append(num);
logger.info(stringBuilder.toString());
if (TextUtils.isEmpty(str) || !str.matches("^\\w+?://.*") || str.startsWith("file://")) {
a((Context) eventContext, num, str);
} else {
logger = k;
stringBuilder = new StringBuilder();
stringBuilder.append("easr auth: copy to writable path if not exist!, licenseUri=");
stringBuilder.append(str);
logger.info(stringBuilder.toString());
byte[] d = eventContext.d(str);
stringBuilder = new StringBuilder();
stringBuilder.append("easr-");
stringBuilder.append(Integer.toHexString(Arrays.toString(d).hashCode()));
stringBuilder.append(".lic");
File fileStreamPath = eventContext.getFileStreamPath(stringBuilder.toString());
if (!fileStreamPath.exists()) {
Logger logger2 = k;
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append("easr auth: copy license ");
stringBuilder2.append(str);
stringBuilder2.append("->");
stringBuilder2.append(fileStreamPath);
logger2.info(stringBuilder2.toString());
FileOutputStream fileOutputStream = new FileOutputStream(fileStreamPath);
fileOutputStream.write(d);
fileOutputStream.close();
}
a((Context) eventContext, num, fileStreamPath.getAbsolutePath());
}
}
}
private static int b(Context context, Integer num, String str, String str2, String str3) {
int a = l.a(context, num == null ? "" : num.toString(), str, str2, str3);
Logger logger = k;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("GetLicense getLicenseRet ");
stringBuilder.append(a);
stringBuilder.append(", licensePath: ");
stringBuilder.append(str3);
stringBuilder.append(", appid: ");
stringBuilder.append(num);
logger.info(stringBuilder.toString());
Logger logger2 = k;
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append("cuid: ");
stringBuilder2.append(str);
stringBuilder2.append(", stat: ");
stringBuilder2.append(str2);
logger2.info(stringBuilder2.toString());
if (a < 0) {
int a2 = l.a(context, "", str, str2, str3);
logger2 = k;
stringBuilder2 = new StringBuilder();
stringBuilder2.append("GetLicense getLicenseRet ");
stringBuilder2.append(a2);
stringBuilder2.append(", licensePath: ");
stringBuilder2.append(str3);
stringBuilder2.append(", appid: ");
stringBuilder2.append("");
logger2.info(stringBuilder2.toString());
logger2 = k;
StringBuilder stringBuilder3 = new StringBuilder();
stringBuilder3.append("cuid: ");
stringBuilder3.append(str);
stringBuilder3.append(", stat: ");
stringBuilder3.append(str2);
logger2.info(stringBuilder3.toString());
if (a2 >= 0) {
return a2;
}
}
return a;
}
private static int a(Context context, Integer num, String str, byte[] bArr, int i, byte[] bArr2, String str2) {
String num2 = num == null ? "" : num.toString();
String str3 = new String(bArr);
if (context.getPackageName().equals("com.baidu.speech.recognizerdemo") && str3.contains("acfcb9c8b0260") && str3.contains("24a04d595472216df3905965643a36bdaffeedcfc0b35")) {
num2 = "1111";
}
int a = l.a(context, num2, str, bArr, i, bArr2, str2);
if (a >= 0) {
return a;
}
return l.a(context, "", str, bArr, i, bArr2, str2);
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
private static synchronized int a(android.content.Context r18, java.lang.Integer r19, java.lang.String r20) {
/*
r8 = r18;
r9 = r19;
r10 = com.baidu.speech.AuthEasrHelper.class;
monitor-enter(r10);
r1 = "bds-easr-license.lic";
r1 = r8.getFileStreamPath(r1); Catch:{ all -> 0x022a }
r1 = r1.getAbsolutePath(); Catch:{ all -> 0x022a }
n = r1; Catch:{ all -> 0x022a }
if (r20 == 0) goto L_0x0026;
L_0x0015:
r2 = new java.io.File; Catch:{ all -> 0x022a }
r3 = n; Catch:{ all -> 0x022a }
r2.<init>(r3); Catch:{ all -> 0x022a }
r2 = r2.exists(); Catch:{ all -> 0x022a }
if (r2 == 0) goto L_0x0023;
L_0x0022:
goto L_0x0026;
L_0x0023:
r1 = r20;
goto L_0x0028;
L_0x0026:
r1 = n; Catch:{ all -> 0x022a }
L_0x0028:
r2 = k; Catch:{ all -> 0x022a }
r3 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r3.<init>(); Catch:{ all -> 0x022a }
r4 = "licensePath: ";
r3.append(r4); Catch:{ all -> 0x022a }
r3.append(r1); Catch:{ all -> 0x022a }
r3 = r3.toString(); Catch:{ all -> 0x022a }
r2.info(r3); Catch:{ all -> 0x022a }
r11 = com.baidu.speech.easr.Utility.c(r18); Catch:{ all -> 0x022a }
r2 = new java.io.File; Catch:{ all -> 0x022a }
r2.<init>(r1); Catch:{ all -> 0x022a }
r2 = r2.exists(); Catch:{ all -> 0x022a }
r12 = 0;
if (r2 != 0) goto L_0x00ad;
L_0x004e:
r2 = new java.io.File; Catch:{ all -> 0x022a }
r2.<init>(r1); Catch:{ all -> 0x022a }
r2 = r2.canWrite(); Catch:{ all -> 0x022a }
if (r2 != 0) goto L_0x005b;
L_0x0059:
r1 = n; Catch:{ all -> 0x022a }
L_0x005b:
r2 = com.baidu.speech.easr.stat.StatHelper.a(r8, r12); Catch:{ all -> 0x022a }
r3 = b(r8, r9, r11, r2, r1); Catch:{ all -> 0x022a }
r4 = k; Catch:{ all -> 0x022a }
r5 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r5.<init>(); Catch:{ all -> 0x022a }
r6 = "GetLicense getLicenseRet ";
r5.append(r6); Catch:{ all -> 0x022a }
r5.append(r3); Catch:{ all -> 0x022a }
r6 = ", licensePath: ";
r5.append(r6); Catch:{ all -> 0x022a }
r5.append(r1); Catch:{ all -> 0x022a }
r5 = r5.toString(); Catch:{ all -> 0x022a }
r4.info(r5); Catch:{ all -> 0x022a }
r4 = k; Catch:{ all -> 0x022a }
r5 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r5.<init>(); Catch:{ all -> 0x022a }
r6 = "cuid: ";
r5.append(r6); Catch:{ all -> 0x022a }
r5.append(r11); Catch:{ all -> 0x022a }
r6 = ", stat: ";
r5.append(r6); Catch:{ all -> 0x022a }
r5.append(r2); Catch:{ all -> 0x022a }
r2 = r5.toString(); Catch:{ all -> 0x022a }
r4.info(r2); Catch:{ all -> 0x022a }
if (r3 >= 0) goto L_0x00ad;
L_0x00a1:
r1 = "";
p = r1; Catch:{ all -> 0x022a }
r1 = java.lang.Math.abs(r3); Catch:{ all -> 0x022a }
r1 = r1 + 9000;
monitor-exit(r10);
return r1;
L_0x00ad:
r13 = r1;
r1 = 32;
r14 = new byte[r1]; Catch:{ all -> 0x022a }
r1 = 1024; // 0x400 float:1.435E-42 double:5.06E-321;
r15 = new byte[r1]; Catch:{ all -> 0x022a }
r5 = com.baidu.speech.easr.Utility.a(r13, r15); Catch:{ all -> 0x022a }
r1 = r18.getFilesDir(); Catch:{ all -> 0x022a }
r7 = r1.getAbsolutePath(); Catch:{ all -> 0x022a }
r1 = k; Catch:{ all -> 0x022a }
r2 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r2.<init>(); Catch:{ all -> 0x022a }
r3 = "logDir: ";
r2.append(r3); Catch:{ all -> 0x022a }
r2.append(r7); Catch:{ all -> 0x022a }
r2 = r2.toString(); Catch:{ all -> 0x022a }
r1.info(r2); Catch:{ all -> 0x022a }
r1 = r8;
r2 = r9;
r3 = r11;
r4 = r15;
r6 = r14;
r16 = r7;
r1 = a(r1, r2, r3, r4, r5, r6, r7); Catch:{ all -> 0x022a }
r2 = new java.lang.String; Catch:{ all -> 0x022a }
r2.<init>(r14); Catch:{ all -> 0x022a }
r3 = "end";
r3 = r2.indexOf(r3); Catch:{ all -> 0x022a }
r4 = -1;
r7 = 0;
if (r3 == r4) goto L_0x00fe;
L_0x00f2:
r3 = r2.substring(r7, r3); Catch:{ all -> 0x022a }
r4 = new com.baidu.speech.easr.stat.StatThread; Catch:{ all -> 0x022a }
r4.<init>(r8, r3); Catch:{ all -> 0x022a }
r4.start(); Catch:{ all -> 0x022a }
L_0x00fe:
r3 = k; Catch:{ all -> 0x022a }
r4 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r4.<init>(); Catch:{ all -> 0x022a }
r5 = "VerifyLicense authRet ";
r4.append(r5); Catch:{ all -> 0x022a }
r4.append(r1); Catch:{ all -> 0x022a }
r4 = r4.toString(); Catch:{ all -> 0x022a }
r3.info(r4); Catch:{ all -> 0x022a }
r3 = k; Catch:{ all -> 0x022a }
r4 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r4.<init>(); Catch:{ all -> 0x022a }
r5 = "appIdStr: ";
r4.append(r5); Catch:{ all -> 0x022a }
r4.append(r2); Catch:{ all -> 0x022a }
r2 = r4.toString(); Catch:{ all -> 0x022a }
r3.info(r2); Catch:{ all -> 0x022a }
r2 = l; Catch:{ all -> 0x022a }
r6 = 1;
r5 = 1000; // 0x3e8 float:1.401E-42 double:4.94E-321;
if (r1 < 0) goto L_0x0155;
L_0x0131:
r2 = l; Catch:{ all -> 0x022a }
if (r1 >= r5) goto L_0x013c;
L_0x0135:
o = r7; Catch:{ all -> 0x022a }
r1 = "";
p = r1; Catch:{ all -> 0x022a }
goto L_0x0153;
L_0x013c:
o = r6; Catch:{ all -> 0x022a }
r2 = java.util.Locale.US; Catch:{ all -> 0x022a }
r3 = "[百度语音试用服务%d天后到期]";
r4 = new java.lang.Object[r6]; Catch:{ all -> 0x022a }
r6 = l; Catch:{ all -> 0x022a }
r1 = r1 - r5;
r1 = java.lang.Integer.valueOf(r1); Catch:{ all -> 0x022a }
r4[r7] = r1; Catch:{ all -> 0x022a }
r1 = java.lang.String.format(r2, r3, r4); Catch:{ all -> 0x022a }
p = r1; Catch:{ all -> 0x022a }
L_0x0153:
monitor-exit(r10);
return r7;
L_0x0155:
r2 = l; Catch:{ all -> 0x022a }
r4 = -6;
if (r1 != r4) goto L_0x016d;
L_0x015a:
r1 = q; Catch:{ all -> 0x022a }
if (r1 != 0) goto L_0x016b;
L_0x015e:
r1 = new java.lang.Thread; Catch:{ all -> 0x022a }
r2 = new com.baidu.speech.AuthEasrHelper$1; Catch:{ all -> 0x022a }
r2.<init>(r13, r8, r9, r11); Catch:{ all -> 0x022a }
r1.<init>(r2); Catch:{ all -> 0x022a }
r1.start(); Catch:{ all -> 0x022a }
L_0x016b:
monitor-exit(r10);
return r7;
L_0x016d:
r1 = com.baidu.speech.easr.stat.StatHelper.a(r8, r12); Catch:{ all -> 0x022a }
r2 = new java.io.File; Catch:{ all -> 0x022a }
r2.<init>(r13); Catch:{ all -> 0x022a }
r2 = r2.canWrite(); Catch:{ all -> 0x022a }
if (r2 != 0) goto L_0x017e;
L_0x017c:
r13 = n; Catch:{ all -> 0x022a }
L_0x017e:
r2 = b(r8, r9, r11, r1, r13); Catch:{ all -> 0x022a }
r3 = k; Catch:{ all -> 0x022a }
r12 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r12.<init>(); Catch:{ all -> 0x022a }
r4 = "GetLicense getLicenseRet ";
r12.append(r4); Catch:{ all -> 0x022a }
r12.append(r2); Catch:{ all -> 0x022a }
r4 = ", licensePath: ";
r12.append(r4); Catch:{ all -> 0x022a }
r12.append(r13); Catch:{ all -> 0x022a }
r4 = r12.toString(); Catch:{ all -> 0x022a }
r3.info(r4); Catch:{ all -> 0x022a }
r3 = k; Catch:{ all -> 0x022a }
r4 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r4.<init>(); Catch:{ all -> 0x022a }
r12 = "cuid: ";
r4.append(r12); Catch:{ all -> 0x022a }
r4.append(r11); Catch:{ all -> 0x022a }
r12 = ", stat: ";
r4.append(r12); Catch:{ all -> 0x022a }
r4.append(r1); Catch:{ all -> 0x022a }
r1 = r4.toString(); Catch:{ all -> 0x022a }
r3.info(r1); Catch:{ all -> 0x022a }
if (r2 <= 0) goto L_0x021e;
L_0x01c0:
r12 = com.baidu.speech.easr.Utility.a(r13, r15); Catch:{ all -> 0x022a }
r1 = r8;
r2 = r9;
r3 = r11;
r8 = -6;
r4 = r15;
r9 = 1000; // 0x3e8 float:1.401E-42 double:4.94E-321;
r5 = r12;
r11 = 1;
r6 = r14;
r12 = 0;
r7 = r16;
r1 = a(r1, r2, r3, r4, r5, r6, r7); Catch:{ all -> 0x022a }
r2 = k; Catch:{ all -> 0x022a }
r3 = new java.lang.StringBuilder; Catch:{ all -> 0x022a }
r3.<init>(); Catch:{ all -> 0x022a }
r4 = "VerifyLicense authRet ";
r3.append(r4); Catch:{ all -> 0x022a }
r3.append(r1); Catch:{ all -> 0x022a }
r3 = r3.toString(); Catch:{ all -> 0x022a }
r2.info(r3); Catch:{ all -> 0x022a }
r2 = l; Catch:{ all -> 0x022a }
if (r1 >= 0) goto L_0x01fa;
L_0x01ef:
r2 = l; Catch:{ all -> 0x022a }
if (r1 != r8) goto L_0x01f4;
L_0x01f3:
goto L_0x01fa;
L_0x01f4:
r2 = "[百度语音试用服务已经到期,请及时更新授权]";
p = r2; Catch:{ all -> 0x022a }
monitor-exit(r10);
return r1;
L_0x01fa:
r2 = l; Catch:{ all -> 0x022a }
if (r1 >= r9) goto L_0x0205;
L_0x01fe:
o = r12; Catch:{ all -> 0x022a }
r1 = "";
p = r1; Catch:{ all -> 0x022a }
goto L_0x021c;
L_0x0205:
o = r11; Catch:{ all -> 0x022a }
r2 = java.util.Locale.US; Catch:{ all -> 0x022a }
r3 = "[百度语音试用服务%d天后到期]";
r4 = new java.lang.Object[r11]; Catch:{ all -> 0x022a }
r5 = l; Catch:{ all -> 0x022a }
r1 = r1 - r9;
r1 = java.lang.Integer.valueOf(r1); Catch:{ all -> 0x022a }
r4[r12] = r1; Catch:{ all -> 0x022a }
r1 = java.lang.String.format(r2, r3, r4); Catch:{ all -> 0x022a }
p = r1; Catch:{ all -> 0x022a }
L_0x021c:
monitor-exit(r10);
return r12;
L_0x021e:
r1 = "[百度语音试用服务已经到期,请及时更新授权]";
p = r1; Catch:{ all -> 0x022a }
r1 = java.lang.Math.abs(r2); Catch:{ all -> 0x022a }
r1 = r1 + 9000;
monitor-exit(r10);
return r1;
L_0x022a:
r0 = move-exception;
r1 = r0;
monitor-exit(r10);
throw r1;
*/
throw new UnsupportedOperationException("Method not decompiled: com.baidu.speech.AuthEasrHelper.a(android.content.Context, java.lang.Integer, java.lang.String):int");
}
}
| 18,593 | 0.531439 | 0.450302 | 444 | 40.443695 | 23.522062 | 181 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.371622 | false | false | 4 |
b196fe91cf074eb23b14fd667a57eb750df186e0 | 22,806,276,361,529 | a6fe66104b4a90bd5556279350cea53cca0f38c1 | /app/src/main/java/com/tsutsuku/artcollection/ui/base/BaseFragmentActivity.java | b2a1348393a669d670584a4fa8af6cc242294ad1 | [] | no_license | dengchaoAndroid/ArtCollection | https://github.com/dengchaoAndroid/ArtCollection | 986bcd71345519fe69e8a5347ec55988015b5fe8 | 1369f7c9ce7e7593b31dbeca7b6e90976aac31ee | refs/heads/master | 2021-07-24T04:43:31.666000 | 2017-11-03T09:27:05 | 2017-11-03T09:27:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tsutsuku.artcollection.ui.base;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.tsutsuku.artcollection.R;
import com.tsutsuku.artcollection.utils.TLog;
/**
* Created by tsutsuku on 2016/5/28.
*/
public abstract class BaseFragmentActivity extends FragmentActivity {
protected final String TAG = this.getClass().toString();
protected LinearLayout llBack;
protected TextView tvTitle;
protected TextView tvTitleButton;
protected ImageView ivTitleButton;
protected Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView();
initViews();
initListeners();
initData();
TLog.i("current activity is" + TAG);
}
protected abstract void setContentView();
protected abstract void initViews();
protected abstract void initListeners();
protected abstract void initData();
protected void initTitle(String title) {
llBack = (LinearLayout) findViewById(R.id.llBack);
llBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
closeKeyboard();
}
});
tvTitle = (TextView) findViewById(R.id.tvTitle);
tvTitle.setText(title);
}
protected void initTitle(int title) {
initTitle(getString(title));
}
protected void initTitle(String title, String btn) {
this.initTitle(title);
tvTitleButton = (TextView) findViewById(R.id.tvTitleButton);
tvTitleButton.setText(btn);
}
protected void initTitle(String title, int drawableId) {
this.initTitle(title);
ivTitleButton = (ImageView) findViewById(R.id.ivTitleButton);
ivTitleButton.setImageResource(drawableId);
}
protected void initTitle(int title, int ResId) {
this.initTitle(title);
if ("string".equals(getResources().getResourceTypeName(ResId))) {
tvTitleButton = (TextView) findViewById(R.id.tvTitleButton);
tvTitleButton.setText(ResId);
} else if ("drawable".equals(getResources().getResourceTypeName(ResId))) {
ivTitleButton = (ImageView) findViewById(R.id.ivTitleButton);
ivTitleButton.setImageResource(ResId);
} else if ("color".equals(getResources().getResourceTypeName(ResId))) {
ivTitleButton = (ImageView) findViewById(R.id.ivTitleButton);
ivTitleButton.setImageResource(ResId);
}
}
/**
* Close soft keyboard
*/
protected void closeKeyboard() {
View view = getWindow().peekDecorView();
if (view != null) {
InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
/**
* detect whether soft keyboard show
*
* @param rootView 根View
* @return
*/
protected boolean isKeyboardShow(View rootView) {
final int softKeyboardHeight = 100;
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
int heightDiff = rootView.getBottom() - r.bottom;
return heightDiff > softKeyboardHeight * dm.density;
}
}
| UTF-8 | Java | 3,764 | java | BaseFragmentActivity.java | Java | [
{
"context": "suku.artcollection.utils.TLog;\n\n\n/**\n * Created by tsutsuku on 2016/5/28.\n */\npublic abstract class BaseFragm",
"end": 508,
"score": 0.9991191029548645,
"start": 500,
"tag": "USERNAME",
"value": "tsutsuku"
}
] | null | [] | package com.tsutsuku.artcollection.ui.base;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.tsutsuku.artcollection.R;
import com.tsutsuku.artcollection.utils.TLog;
/**
* Created by tsutsuku on 2016/5/28.
*/
public abstract class BaseFragmentActivity extends FragmentActivity {
protected final String TAG = this.getClass().toString();
protected LinearLayout llBack;
protected TextView tvTitle;
protected TextView tvTitleButton;
protected ImageView ivTitleButton;
protected Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView();
initViews();
initListeners();
initData();
TLog.i("current activity is" + TAG);
}
protected abstract void setContentView();
protected abstract void initViews();
protected abstract void initListeners();
protected abstract void initData();
protected void initTitle(String title) {
llBack = (LinearLayout) findViewById(R.id.llBack);
llBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
closeKeyboard();
}
});
tvTitle = (TextView) findViewById(R.id.tvTitle);
tvTitle.setText(title);
}
protected void initTitle(int title) {
initTitle(getString(title));
}
protected void initTitle(String title, String btn) {
this.initTitle(title);
tvTitleButton = (TextView) findViewById(R.id.tvTitleButton);
tvTitleButton.setText(btn);
}
protected void initTitle(String title, int drawableId) {
this.initTitle(title);
ivTitleButton = (ImageView) findViewById(R.id.ivTitleButton);
ivTitleButton.setImageResource(drawableId);
}
protected void initTitle(int title, int ResId) {
this.initTitle(title);
if ("string".equals(getResources().getResourceTypeName(ResId))) {
tvTitleButton = (TextView) findViewById(R.id.tvTitleButton);
tvTitleButton.setText(ResId);
} else if ("drawable".equals(getResources().getResourceTypeName(ResId))) {
ivTitleButton = (ImageView) findViewById(R.id.ivTitleButton);
ivTitleButton.setImageResource(ResId);
} else if ("color".equals(getResources().getResourceTypeName(ResId))) {
ivTitleButton = (ImageView) findViewById(R.id.ivTitleButton);
ivTitleButton.setImageResource(ResId);
}
}
/**
* Close soft keyboard
*/
protected void closeKeyboard() {
View view = getWindow().peekDecorView();
if (view != null) {
InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
/**
* detect whether soft keyboard show
*
* @param rootView 根View
* @return
*/
protected boolean isKeyboardShow(View rootView) {
final int softKeyboardHeight = 100;
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
int heightDiff = rootView.getBottom() - r.bottom;
return heightDiff > softKeyboardHeight * dm.density;
}
}
| 3,764 | 0.667464 | 0.664274 | 115 | 31.713043 | 24.087797 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.547826 | false | false | 4 |
d4c51076acd14e576a5e8531934d47a88cc764e3 | 22,806,276,362,191 | fb916e95bebd1a1cb556e62d2f530d2fde10adf7 | /src/main/java/com/mint/core/web/front/FrontLocaleInterceptor.java | 6e8b86ead745df97333465fcadba48c2642f540d | [] | no_license | xrogzu/mint | https://github.com/xrogzu/mint | 9dfcdaf0ae4b8dcd3430025326fb2b16e4dab4f6 | d1595d8e826b751915ad95b95715326216b4500a | refs/heads/master | 2021-04-12T09:36:51.369000 | 2018-02-07T07:31:08 | 2018-02-07T07:31:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mint.core.web.front;
import com.mint.core.entity.Website;
import com.mint.core.web.SiteUtils;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.LocaleEditor;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.support.RequestContextUtils;
public class FrontLocaleInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj)
throws ServletException {
LocaleResolver localeresolver = RequestContextUtils.getLocaleResolver(request);
if (localeresolver == null) {
throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
}
Website website = SiteUtils.getWeb(request);
String s = website.getLocaleFront();
LocaleEditor localeeditor = new LocaleEditor();
localeeditor.setAsText(s);
localeresolver.setLocale(request, response, (Locale) localeeditor.getValue());
return true;
}
}
| UTF-8 | Java | 1,287 | java | FrontLocaleInterceptor.java | Java | [] | null | [] | package com.mint.core.web.front;
import com.mint.core.entity.Website;
import com.mint.core.web.SiteUtils;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.LocaleEditor;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.support.RequestContextUtils;
public class FrontLocaleInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj)
throws ServletException {
LocaleResolver localeresolver = RequestContextUtils.getLocaleResolver(request);
if (localeresolver == null) {
throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
}
Website website = SiteUtils.getWeb(request);
String s = website.getLocaleFront();
LocaleEditor localeeditor = new LocaleEditor();
localeeditor.setAsText(s);
localeresolver.setLocale(request, response, (Locale) localeeditor.getValue());
return true;
}
}
| 1,287 | 0.769231 | 0.769231 | 30 | 41.866665 | 30.021917 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.766667 | false | false | 4 |
8c036451bcbcb36a14a2d4b31620ff6139f196e8 | 24,326,694,834,396 | 0ef39091c0560f294dee8d818b6a4dbb3bec75de | /src/com/yunguanshi/utils/ModelUtil.java | b91a43e5c2727bdd253668b3a77b2f03a7fefc1a | [] | no_license | dounine/yunguanshi | https://github.com/dounine/yunguanshi | c35e930ca49c88c8d991b3d887483c709f618ab4 | 2637458a6e4467041c90c58f59d96bffdc4c9624 | refs/heads/master | 2021-01-12T15:41:26.230000 | 2015-11-25T10:00:32 | 2015-11-25T10:00:32 | 71,852,661 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yunguanshi.utils;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.yunguanshi.annotation.NodeType;
import com.yunguanshi.constant.TreeNodeType;
import com.yunguanshi.model.extjs.JsonTreeNode;
public class ModelUtil {
public static Map<String, Field[]> modelFields = new HashMap<String, Field[]>();
public static Map<String, String> modelFieldsJson = new HashMap<String,String>();
/**
* 得到类的属性集合
* @param c
* @param itself 是否是自身的字段
* @return
*/
public static Field[] getClassFields(Class<?> c, boolean itself){
if(itself){
if(modelFields.get(c.getName())!=null){
return modelFields.get(c.getName());
}else{
Field[] fields=c.getDeclaredFields();
modelFields.put(c.getName(), fields);
return fields;
}
}else{
if(modelFields.get(c.getName())!=null){
return modelFields.get(c.getName());
}else{
List<Field> fields=new ArrayList<Field>();
getAllDeclaredFields(c, fields);
Field[] fies=new Field[fields.size()];
fields.toArray(fies);
modelFields.put(c.getName(), fies);
return fies;
}
}
}
/**
* 从c类中取得全部字段,包括父类
* @param c
* @param fields
*/
public static void getAllDeclaredFields(Class<?> c, List<Field> fields){
Field[] fies=c.getDeclaredFields();
Collections.addAll(fields, fies);
Class<?> parent=c.getSuperclass();
if(parent!=Object.class){
getAllDeclaredFields(parent, fields);
}else{
return;
}
}
public static JsonTreeNode getJSONTreeNodeTemplate(Class<?> c){
Field[] fields = getClassFields(c, false);
JsonTreeNode template = new JsonTreeNode();
for(Field field : fields){
String value = field.getName();
NodeType nodeType = field.getAnnotation(NodeType.class);//获取注解类
if(nodeType==null){
continue;
}
TreeNodeType type = nodeType.type();//获取所注解的类型
if(TreeNodeType.ID.equalsType(type)){
template.setId(value);
}
if(TreeNodeType.TEXT.equalsType(type)){
template.setText(value);
}
if(TreeNodeType.CODE.equalsType(type)){
template.setCode(value);
}
if(TreeNodeType.ICON.equals(type)) {
template.setIcon(value);
}
if(TreeNodeType.NODEINFO.equals(type)) {
template.setNodeInfo(value);
}
if(TreeNodeType.NODEINFOTYPE.equals(type)) {
template.setNodeInfoType(value);
}
if(TreeNodeType.CLS.equals(type)) {
template.setCls(value);
}
if(TreeNodeType.LEAF.equals(type)) {
template.setNodeType(value);
}
if(TreeNodeType.PARENT.equals(type)) {
template.setParent(value);
}
if(TreeNodeType.DISABLED.equals(type)) {
template.setHref(value);
}
if(TreeNodeType.BIGICON.equals(type)) {
template.setBigIcon(value);
}
if(TreeNodeType.DESCRIPTION.equals(type)){
template.setDescription(value);
}
if(TreeNodeType.ORDERINDEX.equals(type)){
template.setOrderIndex(Integer.parseInt(value));
}
if(TreeNodeType.RESADD.equals(type)){
template.setResAdd(StringUtil.isNotEmpty(value)?true:null);
}
if(TreeNodeType.RESDELETE.equals(type)){
template.setResDelete(StringUtil.isNotEmpty(value)?true:null);
}
if(TreeNodeType.RESUPDATE.equals(type)){
template.setResUpdate(StringUtil.isNotEmpty(value)?true:null);
}
if(TreeNodeType.RESDELETE.equals(type)){
template.setResDelete(StringUtil.isNotEmpty(value)?true:null);
}
}
return template;
}
}
| UTF-8 | Java | 3,553 | java | ModelUtil.java | Java | [] | null | [] | package com.yunguanshi.utils;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.yunguanshi.annotation.NodeType;
import com.yunguanshi.constant.TreeNodeType;
import com.yunguanshi.model.extjs.JsonTreeNode;
public class ModelUtil {
public static Map<String, Field[]> modelFields = new HashMap<String, Field[]>();
public static Map<String, String> modelFieldsJson = new HashMap<String,String>();
/**
* 得到类的属性集合
* @param c
* @param itself 是否是自身的字段
* @return
*/
public static Field[] getClassFields(Class<?> c, boolean itself){
if(itself){
if(modelFields.get(c.getName())!=null){
return modelFields.get(c.getName());
}else{
Field[] fields=c.getDeclaredFields();
modelFields.put(c.getName(), fields);
return fields;
}
}else{
if(modelFields.get(c.getName())!=null){
return modelFields.get(c.getName());
}else{
List<Field> fields=new ArrayList<Field>();
getAllDeclaredFields(c, fields);
Field[] fies=new Field[fields.size()];
fields.toArray(fies);
modelFields.put(c.getName(), fies);
return fies;
}
}
}
/**
* 从c类中取得全部字段,包括父类
* @param c
* @param fields
*/
public static void getAllDeclaredFields(Class<?> c, List<Field> fields){
Field[] fies=c.getDeclaredFields();
Collections.addAll(fields, fies);
Class<?> parent=c.getSuperclass();
if(parent!=Object.class){
getAllDeclaredFields(parent, fields);
}else{
return;
}
}
public static JsonTreeNode getJSONTreeNodeTemplate(Class<?> c){
Field[] fields = getClassFields(c, false);
JsonTreeNode template = new JsonTreeNode();
for(Field field : fields){
String value = field.getName();
NodeType nodeType = field.getAnnotation(NodeType.class);//获取注解类
if(nodeType==null){
continue;
}
TreeNodeType type = nodeType.type();//获取所注解的类型
if(TreeNodeType.ID.equalsType(type)){
template.setId(value);
}
if(TreeNodeType.TEXT.equalsType(type)){
template.setText(value);
}
if(TreeNodeType.CODE.equalsType(type)){
template.setCode(value);
}
if(TreeNodeType.ICON.equals(type)) {
template.setIcon(value);
}
if(TreeNodeType.NODEINFO.equals(type)) {
template.setNodeInfo(value);
}
if(TreeNodeType.NODEINFOTYPE.equals(type)) {
template.setNodeInfoType(value);
}
if(TreeNodeType.CLS.equals(type)) {
template.setCls(value);
}
if(TreeNodeType.LEAF.equals(type)) {
template.setNodeType(value);
}
if(TreeNodeType.PARENT.equals(type)) {
template.setParent(value);
}
if(TreeNodeType.DISABLED.equals(type)) {
template.setHref(value);
}
if(TreeNodeType.BIGICON.equals(type)) {
template.setBigIcon(value);
}
if(TreeNodeType.DESCRIPTION.equals(type)){
template.setDescription(value);
}
if(TreeNodeType.ORDERINDEX.equals(type)){
template.setOrderIndex(Integer.parseInt(value));
}
if(TreeNodeType.RESADD.equals(type)){
template.setResAdd(StringUtil.isNotEmpty(value)?true:null);
}
if(TreeNodeType.RESDELETE.equals(type)){
template.setResDelete(StringUtil.isNotEmpty(value)?true:null);
}
if(TreeNodeType.RESUPDATE.equals(type)){
template.setResUpdate(StringUtil.isNotEmpty(value)?true:null);
}
if(TreeNodeType.RESDELETE.equals(type)){
template.setResDelete(StringUtil.isNotEmpty(value)?true:null);
}
}
return template;
}
}
| 3,553 | 0.69386 | 0.69386 | 129 | 25.891474 | 20.373734 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.891473 | false | false | 4 |
ee75f420110b851a1a6b06d1bd345cd812706eb3 | 18,863,496,370,290 | 368a33fba3c31c4c098cb6b880fe3efbf46bbb51 | /app/src/main/java/com/home/englishnote/views/fragments/WordsFragment.java | 4b9d328bdb2a8fd5a082941643f2d1a785989325 | [] | no_license | ssandy13862/Vocab-Notes-APP | https://github.com/ssandy13862/Vocab-Notes-APP | 23c2387c4d541778c6caeec019f9cb625f6489d9 | 1fd6549ab150290c8e7f72eb67ef4e0dcaba43ed | refs/heads/master | 2021-03-23T01:08:17.060000 | 2020-03-14T15:37:27 | 2020-03-14T15:37:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.home.englishnote.views.fragments;
import com.home.englishnote.models.entities.Word;
import com.home.englishnote.presenters.WordsPresenter.WordsView;
import com.home.englishnote.views.fragments.BaseFragment;
public class WordsFragment extends BaseFragment implements WordsView {
@Override
public void onGetWordSuccessfully(Word word) {
}
}
| UTF-8 | Java | 368 | java | WordsFragment.java | Java | [] | null | [] | package com.home.englishnote.views.fragments;
import com.home.englishnote.models.entities.Word;
import com.home.englishnote.presenters.WordsPresenter.WordsView;
import com.home.englishnote.views.fragments.BaseFragment;
public class WordsFragment extends BaseFragment implements WordsView {
@Override
public void onGetWordSuccessfully(Word word) {
}
}
| 368 | 0.807065 | 0.807065 | 14 | 25.285715 | 27.274866 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 4 |
692930c19dcddd3ff82b870dad6c9e036c738563 | 10,986,526,345,055 | 6b8b60b2e911582627e93b63b651b0e56cfa18eb | /spring-security-core/src/main/java/com/wayn/core/filter/ValidateCodeFilter.java | 0a203df305c007c312ee07e1aaa6f9bfb5ec1686 | [] | no_license | wayn-zhengda/spring-security-parent | https://github.com/wayn-zhengda/spring-security-parent | 50c0d932c022907daed6e32e5a6514c0e2993492 | 1cf351163287417b591001a5517ecfdf91a7853b | refs/heads/master | 2022-12-08T23:47:18.887000 | 2020-09-11T08:13:06 | 2020-09-11T08:13:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wayn.core.filter;
import com.wayn.core.constant.ValidateCodeConstant;
import com.wayn.core.exception.ValidataCodeException;
import com.wayn.core.validate.code.image.ImageCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
if (StringUtils.equals("/form/login", request.getRequestURI()) && StringUtils.endsWithIgnoreCase(request.getMethod(), "post")){
log.info("执行验证码校验");
try {
validateCode(new ServletWebRequest(request));
}catch (ValidataCodeException e){
log.error("验证码错误, {}", request.getRequestURL());
}
}
filterChain.doFilter(request, response);
}
private boolean validateCode(ServletWebRequest servletWebRequest) {
ImageCode imageCode = (ImageCode) sessionStrategy.getAttribute(servletWebRequest, ValidateCodeConstant.IMAGE_SESSION_KEY);
String matchCode = (String) servletWebRequest.getAttribute("code", 0);
if (imageCode.getCode().equals(matchCode)){
throw new ValidataCodeException("验证码错误");
}
return true;
}
}
| UTF-8 | Java | 2,012 | java | ValidateCodeFilter.java | Java | [] | null | [] | package com.wayn.core.filter;
import com.wayn.core.constant.ValidateCodeConstant;
import com.wayn.core.exception.ValidataCodeException;
import com.wayn.core.validate.code.image.ImageCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
if (StringUtils.equals("/form/login", request.getRequestURI()) && StringUtils.endsWithIgnoreCase(request.getMethod(), "post")){
log.info("执行验证码校验");
try {
validateCode(new ServletWebRequest(request));
}catch (ValidataCodeException e){
log.error("验证码错误, {}", request.getRequestURL());
}
}
filterChain.doFilter(request, response);
}
private boolean validateCode(ServletWebRequest servletWebRequest) {
ImageCode imageCode = (ImageCode) sessionStrategy.getAttribute(servletWebRequest, ValidateCodeConstant.IMAGE_SESSION_KEY);
String matchCode = (String) servletWebRequest.getAttribute("code", 0);
if (imageCode.getCode().equals(matchCode)){
throw new ValidataCodeException("验证码错误");
}
return true;
}
}
| 2,012 | 0.754297 | 0.751769 | 47 | 41.085106 | 35.749619 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.744681 | false | false | 4 |
1fbd1c398e3c0f6ff791fa973798ababfdb9a2a4 | 26,293,789,853,281 | c283e99f6f56dafe62e23bba88433ada4436ba37 | /integrationtesting/TestIntegrationHealthViewandGame.java | c1e1f96d4e1ea7f498d0e20bda9543307644b7d9 | [] | no_license | lwilli/DoS | https://github.com/lwilli/DoS | ef51868f70d9b60e2e546db628ad6c06139e4bdd | e63d5b9bea433bb5bba4fdffa2814d5044568982 | refs/heads/master | 2021-01-21T13:48:17.001000 | 2016-06-01T00:20:14 | 2016-06-01T00:20:14 | 55,737,082 | 0 | 0 | null | false | 2019-05-06T23:37:49 | 2016-04-08T00:24:35 | 2016-04-20T00:43:16 | 2016-06-01T00:20:16 | 4,657 | 0 | 0 | 0 | Java | false | false | package integrationtesting;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.Game;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import Model.HealthView;
/*Test by Juan Carlos Ferrel */
public class TestIntegrationHealthViewandGame {
public static int x = 0;
public static int y = 0;
public static int count = 0;
@Test
public void testGameOver() {
HealthView health = new HealthView();
try {
AppGameContainer app = new AppGameContainer(new BasicGame("Test") {
@Override
public void render(GameContainer container, Graphics g)
throws SlickException {
final Image image = new Image("res/Attack_Unit.png");
g.drawImage(image, x += 1, y);
}
@Override
public void update(GameContainer container, int delta)
throws SlickException {
if (x >= 750) {
health.decreaseHealth();
x = 0;
count++;
//container.exit();
}
/*Game Over*/
if (count == 4) {
System.out.println("I am here");
assertEquals(health.getGrade(), "F");
container.exit();
}
}
@Override
public void init(GameContainer container) throws SlickException {
x = 0;
y = 250;
count = 0;
}
});
app.start();
} catch (SlickException e) {
System.out.println("Error");
}
}
@Test
public void decreaseHealth() {
HealthView health = new HealthView();
try {
AppGameContainer app = new AppGameContainer(new BasicGame("Test") {
@Override
public void render(GameContainer container, Graphics g)
throws SlickException {
final Image image = new Image("res/Attack_Unit.png");
g.drawImage(image, x += 1, y);
}
@Override
public void update(GameContainer container, int delta)
throws SlickException {
if (x >= 750) {
health.decreaseHealth();
assertEquals(health.getGrade(), "B");
container.exit();
}
}
@Override
public void init(GameContainer container) throws SlickException {
x = 0;
y = 250;
}
});
app.start();
} catch (SlickException e) {
System.out.println("Error");
}
}
}
| UTF-8 | Java | 3,156 | java | TestIntegrationHealthViewandGame.java | Java | [
{
"context": "rg.junit.Test;\nimport Model.HealthView;\n\n/*Test by Juan Carlos Ferrel */\npublic class TestIntegrationHealthViewandGame ",
"end": 409,
"score": 0.9998263716697693,
"start": 391,
"tag": "NAME",
"value": "Juan Carlos Ferrel"
}
] | null | [] | package integrationtesting;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.Game;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import Model.HealthView;
/*Test by <NAME> */
public class TestIntegrationHealthViewandGame {
public static int x = 0;
public static int y = 0;
public static int count = 0;
@Test
public void testGameOver() {
HealthView health = new HealthView();
try {
AppGameContainer app = new AppGameContainer(new BasicGame("Test") {
@Override
public void render(GameContainer container, Graphics g)
throws SlickException {
final Image image = new Image("res/Attack_Unit.png");
g.drawImage(image, x += 1, y);
}
@Override
public void update(GameContainer container, int delta)
throws SlickException {
if (x >= 750) {
health.decreaseHealth();
x = 0;
count++;
//container.exit();
}
/*Game Over*/
if (count == 4) {
System.out.println("I am here");
assertEquals(health.getGrade(), "F");
container.exit();
}
}
@Override
public void init(GameContainer container) throws SlickException {
x = 0;
y = 250;
count = 0;
}
});
app.start();
} catch (SlickException e) {
System.out.println("Error");
}
}
@Test
public void decreaseHealth() {
HealthView health = new HealthView();
try {
AppGameContainer app = new AppGameContainer(new BasicGame("Test") {
@Override
public void render(GameContainer container, Graphics g)
throws SlickException {
final Image image = new Image("res/Attack_Unit.png");
g.drawImage(image, x += 1, y);
}
@Override
public void update(GameContainer container, int delta)
throws SlickException {
if (x >= 750) {
health.decreaseHealth();
assertEquals(health.getGrade(), "B");
container.exit();
}
}
@Override
public void init(GameContainer container) throws SlickException {
x = 0;
y = 250;
}
});
app.start();
} catch (SlickException e) {
System.out.println("Error");
}
}
}
| 3,144 | 0.478771 | 0.4718 | 107 | 28.495327 | 20.658041 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.429906 | false | false | 4 |
2751efc50979013d77628c345d0faa0cd3f77a30 | 10,101,763,082,603 | 483ed3c09da79bb93802a7d7bac3f2e477471081 | /backend/modules/party-service/src/main/java/org/serendipity/party/model/ElectoralDivisionModel.java | 5e7da6cb0254f925617594e0cd3add3e4cec3507 | [
"Apache-2.0"
] | permissive | Robinyo/serendipity | https://github.com/Robinyo/serendipity | bc1265b43153bc306acbdcb5c48492523db12bc5 | 64a24d91e462c79c3e25e9602d2e0ee17d55436b | refs/heads/main | 2023-01-27T20:27:32.560000 | 2021-12-20T20:30:05 | 2021-12-20T20:30:05 | 155,456,111 | 395 | 249 | Apache-2.0 | false | 2023-01-07T15:28:45 | 2018-10-30T21:05:02 | 2023-01-03T19:53:05 | 2023-01-07T15:28:44 | 33,874 | 358 | 215 | 27 | TypeScript | false | false | package org.serendipity.party.model;
import lombok.*;
import org.springframework.hateoas.RepresentationModel;
import java.util.Date;
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
public class ElectoralDivisionModel extends RepresentationModel<ElectoralDivisionModel> {
private Long id;
private String name;
private String nameDerivation;
private String state;
private String area;
private String locationDescription;
private Date dateGazetted;
private String latitude;
private String longitude;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ElectoralDivisionModel))
return false;
ElectoralDivisionModel other = (ElectoralDivisionModel) o;
return id != 0L && id.equals(other.getId());
}
@Override
public int hashCode() {
return 31;
}
}
| UTF-8 | Java | 871 | java | ElectoralDivisionModel.java | Java | [] | null | [] | package org.serendipity.party.model;
import lombok.*;
import org.springframework.hateoas.RepresentationModel;
import java.util.Date;
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
public class ElectoralDivisionModel extends RepresentationModel<ElectoralDivisionModel> {
private Long id;
private String name;
private String nameDerivation;
private String state;
private String area;
private String locationDescription;
private Date dateGazetted;
private String latitude;
private String longitude;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ElectoralDivisionModel))
return false;
ElectoralDivisionModel other = (ElectoralDivisionModel) o;
return id != 0L && id.equals(other.getId());
}
@Override
public int hashCode() {
return 31;
}
}
| 871 | 0.73938 | 0.735936 | 44 | 18.795454 | 19.28327 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.409091 | false | false | 4 |
24aaa1c577e2ef0a592fcd1531fb9e41d8a20cf1 | 16,836,271,852,693 | fc0288eb90ae604ea09e0f8ea4661f44497b6d93 | /dbupgrade-core/src/main/java/org/codehaus/mojo/dbupgrade/sqlexec/SQLExecConfig.java | bfb6d73386fa2a0e3d6b7c52a7924ad0b033bf8c | [] | no_license | mohanaraosv/dbupgrade | https://github.com/mohanaraosv/dbupgrade | 24326b4da6693ae5cb6593bb4f872ba508f35c0f | b77a6b27ad0d2ef7186dd87c1585f5f7a02db082 | refs/heads/master | 2021-01-17T06:29:37.416000 | 2014-09-30T23:23:18 | 2014-09-30T23:23:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.codehaus.mojo.dbupgrade.sqlexec;
import java.util.Properties;
import org.codehaus.mojo.dbupgrade.sqlexec.SQLExec.DelimiterType;
import org.codehaus.plexus.util.StringUtils;
/*
* Copyright 2000-2010 The Apache Software Foundation
*
* 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.
*/
public class SQLExecConfig
{
/**
* Call {@link #setOnError(String)} with this value to abort SQL command execution if an error is found.
*/
public static final String ON_ERROR_ABORT = "abort";
/**
* Call {@link #setOnError(String)} with this value to continue SQL command execution until all commands have been
* attempted, then abort the build if an SQL error occurred in any of the commands.
*/
public static final String ON_ERROR_ABORT_AFTER = "abortAfter";
/**
* Call {@link #setOnError(String)} with this value to continue SQL command execution if an error is found.
*/
public static final String ON_ERROR_CONTINUE = "continue";
/**
* Call {@link #setOrderFile(String)} with this value to sort in ascendant order the sql files.
*/
public static final String FILE_SORTING_ASC = "ascending";
/**
* Call {@link #setOrderFile(String)} with this value to sort in descendant order the sql files.
*/
public static final String FILE_SORTING_DSC = "descending";
// ////////////////////////// User Info ///////////////////////////////////
/**
* Database username. If not given, it will be looked up through <code>settings.xml</code>'s server with
* <code>${settingsKey}</code> as key.
*
* @since 1.0-beta-1
*/
private String username;
/**
* Database password. If not given, it will be looked up through <code>settings.xml</code>'s server with
* <code>${settingsKey}</code> as key.
*
* @since 1.0-beta-1
*/
private String password;
/**
* Ignore the password and use anonymous access. This may be useful for databases like MySQL which do not allow
* empty password parameters in the connection initialization.
*
* @since 1.0-beta-1
*/
private boolean enableAnonymousPassword;
/**
* Additional key=value pairs separated by comma(,) or semicolon(;) to be passed into JDBC driver.
*
* @since 1.0-beta-1
*/
private String driverProperties;
/**
* Skip execution when there is an error obtaining a connection. This is a special case to support databases, such
* as embedded Derby, that can shutdown the database via the URL (i.e. <code>shutdown=true</code>).
*
* @since 1.0-beta-1
*/
private boolean skipOnConnectionError;
// ////////////////////////////// Source info /////////////////////////////
// //////////////////////////////// Database info /////////////////////////
/**
* Database URL.
*
* @since 1.0-beta-1
*/
private String url;
/**
* Database driver classname. If not give, it will be discovered using provided url with jdbc4
*
* @since 1.0-beta-1
*/
private String driver;
// //////////////////////////// Operation Configuration ////////////////////
/**
* Set to <code>true</code> to execute none-transactional SQL.
*
* @since 1.0-beta-1
*/
private boolean autocommit;
/**
* Action to perform if an error is found. Possible values are <code>abort</code> and <code>continue</code>.
*
* @since 1.0-beta-1
*/
private String onError = ON_ERROR_ABORT;
// //////////////////////////// Parser Configuration ////////////////////
/**
* Set the delimiter that separates SQL statements.
*
* @since 1.0-beta-1
*/
private String delimiter = ";";
/**
* <p>
* The delimiter type takes two values - "normal" and "row". Normal means that any occurrence of the delimiter
* terminate the SQL command whereas with row, only a line containing just the delimiter is recognized as the end of
* the command.
* </p>
* <p>
* For example, set this to "go" and delimiterType to "row" for Sybase ASE or MS SQL Server.
* </p>
*
* @since 1.0-beta-1
*/
private DelimiterType delimiterType = DelimiterType.NORMAL;
/**
* Set the order in which the SQL files will be executed. Possible values are <code>ascending</code> and
* <code>descending</code>. Any other value means that no sorting will be performed.
*
* @since 1.0-beta-1
*/
private String orderFile = null;
/**
* Keep the format of an SQL block.
*
* @since 1.0-beta-1
*/
private boolean keepFormat = false;
// /////////////////////////////////////////////////////////////////////////////////////
/**
* Print SQL results.
*
* @since 1.0-beta-1
*/
private boolean printResultSet = false;
/**
* Print header columns.
*/
private boolean showheaders = true;
/**
* Encoding to use when reading SQL statements from a file.
*
* @since 1.0-beta-1
*/
private String encoding = "";
/**
* Append to an existing file or overwrite it?
*/
private boolean append = false;
/**
* Argument to Statement.setEscapeProcessing If you want the driver to use regular SQL syntax then set this to
* false.
*
* @since 1.0-beta-1
*/
private boolean escapeProcessing = true;
private boolean verbose = false;
/**
* Repeats the execution for stress test purpose
*
* @since 1.0-beta-1
*/
private int repeats = 1;
/**
* Pause between repeat for stress test purpose
*
* @since 1.0-beta-1
*/
private long sleepTimeBetweenRepeats = 0;
/**
* Transactions per connection execution for stress test purpose
*
* @since 1.0-beta-1
*/
private int transactionsPerConnection = 1;
/**
* Number of retries to open connection before giving up. Mainly to handle the case where application and database
* colocated and database is much slower to accept connection at system startup
*
* @since 1.0-beta-1
*/
private int connectionRetries = 1;
/**
* Number of delay in msec between each connection retry
*
* @since 1.0-beta-1
*/
private int connectionRetryDelay = 10000; // msec
// /////////////////////////////////////////////////////////////////////////////////////
// Accessor
// /////////////////////////////////////////////////////////////////////////////////////
public void setRepeatesPerConnection( int num )
{
this.transactionsPerConnection = num;
}
public void setRepeats( int repeats )
{
this.repeats = repeats;
}
public void setSleepTimeBetweenRepeats( long sleepTimeBetweenRepeats )
{
this.sleepTimeBetweenRepeats = sleepTimeBetweenRepeats;
}
public String getUsername()
{
return this.username;
}
public void setUsername( String username )
{
this.username = username;
}
public String getPassword()
{
return this.password;
}
public void setPassword( String password )
{
this.password = password;
}
public String getUrl()
{
return this.url;
}
public void setUrl( String url )
{
this.url = url;
}
public String getDriver()
{
return this.driver;
}
public void setDriver( String driver )
{
this.driver = driver;
}
void setAutocommit( boolean autocommit )
{
this.autocommit = autocommit;
}
public String getOrderFile()
{
return this.orderFile;
}
public void setOrderFile( String orderFile )
{
if ( FILE_SORTING_ASC.equalsIgnoreCase( orderFile ) )
{
this.orderFile = FILE_SORTING_ASC;
}
else if ( FILE_SORTING_DSC.equalsIgnoreCase( orderFile ) )
{
this.orderFile = FILE_SORTING_DSC;
}
else
{
throw new IllegalArgumentException( orderFile + " is not a valid value for orderFile, only '"
+ FILE_SORTING_ASC + "' or '" + FILE_SORTING_DSC + "'." );
}
}
public String getOnError()
{
return this.onError;
}
public void setOnError( String action )
{
if ( ON_ERROR_ABORT.equalsIgnoreCase( action ) )
{
this.onError = ON_ERROR_ABORT;
}
else if ( ON_ERROR_CONTINUE.equalsIgnoreCase( action ) )
{
this.onError = ON_ERROR_CONTINUE;
}
else if ( ON_ERROR_ABORT_AFTER.equalsIgnoreCase( action ) )
{
this.onError = ON_ERROR_ABORT_AFTER;
}
else
{
throw new IllegalArgumentException( action + " is not a valid value for onError, only '" + ON_ERROR_ABORT
+ "', '" + ON_ERROR_ABORT_AFTER + "', or '" + ON_ERROR_CONTINUE + "'." );
}
}
public void setDriverProperties( String driverProperties )
{
this.driverProperties = driverProperties;
}
/**
* Set the file encoding to use on the SQL files read in
*
* @param encoding the encoding to use on the files
*/
public void setEncoding( String encoding )
{
this.encoding = encoding;
}
/**
* Set the delimiter that separates SQL statements. Defaults to ";";
*/
public void setDelimiter( String delimiter )
{
this.delimiter = delimiter;
}
/**
* Set the delimiter type: "normal" or "row" (default "normal").
*/
public void setDelimiterType( DelimiterType delimiterType )
{
this.delimiterType = delimiterType;
}
/**
* Print result sets from the statements; optional, default false
*/
public void setPrintResutlSet( boolean print )
{
this.printResultSet = print;
}
/**
* Print headers for result sets from the statements; optional, default true.
*/
public void setShowheaders( boolean showheaders )
{
this.showheaders = showheaders;
}
/**
* whether output should be appended to or overwrite an existing file. Defaults to false.
*/
public void setAppend( boolean append )
{
this.append = append;
}
/**
* whether or not format should be preserved. Defaults to false.
*
* @param keepformat The keepformat to set
*/
public void setKeepFormat( boolean keepformat )
{
this.keepFormat = keepformat;
}
/**
* Set escape processing for statements.
*/
public void setEscapeProcessing( boolean enable )
{
escapeProcessing = enable;
}
public boolean isEnableAnonymousPassword()
{
return enableAnonymousPassword;
}
public void setEnableAnonymousPassword( boolean enableAnonymousPassword )
{
this.enableAnonymousPassword = enableAnonymousPassword;
}
public String getDriverProperties()
{
return driverProperties;
}
/**
* parse driverProperties into Properties set
*
* @return Proproties
*/
public Properties getDriverPropertyMap()
{
// set as protected scopy for unit test purpose
Properties properties = new Properties();
if ( !StringUtils.isEmpty( this.driverProperties ) )
{
String[] tokens = StringUtils.split( this.driverProperties, ",;" );
for ( int i = 0; i < tokens.length; ++i )
{
String[] keyValueTokens = StringUtils.split( tokens[i].trim(), "=" );
if ( keyValueTokens.length != 2 )
{
throw new RuntimeException( "Invalid JDBC Driver properties: " + this.driverProperties );
}
properties.setProperty( keyValueTokens[0], keyValueTokens[1] );
}
}
return properties;
}
public boolean isSkipOnConnectionError()
{
return skipOnConnectionError;
}
public void setSkipOnConnectionError( boolean skipOnConnectionError )
{
this.skipOnConnectionError = skipOnConnectionError;
}
public boolean isAutocommit()
{
return autocommit;
}
public boolean isPrintResultSet()
{
return printResultSet;
}
public void setPrintResultSet( boolean printResultSet )
{
this.printResultSet = printResultSet;
}
public int getTransactionsPerConnection()
{
return transactionsPerConnection;
}
public void setTransactionsPerConnection( int transactionsPerConnection )
{
this.transactionsPerConnection = transactionsPerConnection;
}
public String getDelimiter()
{
return delimiter;
}
public DelimiterType getDelimiterType()
{
return delimiterType;
}
public boolean isKeepFormat()
{
return keepFormat;
}
public boolean isShowheaders()
{
return showheaders;
}
public String getEncoding()
{
return encoding;
}
public boolean isAppend()
{
return append;
}
public boolean isEscapeProcessing()
{
return escapeProcessing;
}
public int getRepeats()
{
return repeats;
}
public long getSleepTimeBetweenRepeats()
{
return sleepTimeBetweenRepeats;
}
public int getConnectionRetries()
{
return connectionRetries;
}
public void setConnectionRetries( int connectionRetries )
{
this.connectionRetries = connectionRetries;
}
public int getConnectionRetryDelay()
{
return connectionRetryDelay;
}
public void setConnectionRetryDelay( int connectionRetryDelay )
{
this.connectionRetryDelay = connectionRetryDelay;
}
public boolean isVerbose()
{
return verbose;
}
public void setVerbose( boolean verbose )
{
this.verbose = verbose;
}
}
| UTF-8 | Java | 14,651 | java | SQLExecConfig.java | Java | [
{
"context": "e( String username )\n {\n this.username = username;\n }\n\n public String getPassword()\n {\n ",
"end": 7631,
"score": 0.9557886719703674,
"start": 7623,
"tag": "USERNAME",
"value": "username"
},
{
"context": "d( String password )\n {\n this.password = password;\n }\n\n public String getUrl()\n {\n ",
"end": 7800,
"score": 0.9728569388389587,
"start": 7792,
"tag": "PASSWORD",
"value": "password"
}
] | null | [] | package org.codehaus.mojo.dbupgrade.sqlexec;
import java.util.Properties;
import org.codehaus.mojo.dbupgrade.sqlexec.SQLExec.DelimiterType;
import org.codehaus.plexus.util.StringUtils;
/*
* Copyright 2000-2010 The Apache Software Foundation
*
* 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.
*/
public class SQLExecConfig
{
/**
* Call {@link #setOnError(String)} with this value to abort SQL command execution if an error is found.
*/
public static final String ON_ERROR_ABORT = "abort";
/**
* Call {@link #setOnError(String)} with this value to continue SQL command execution until all commands have been
* attempted, then abort the build if an SQL error occurred in any of the commands.
*/
public static final String ON_ERROR_ABORT_AFTER = "abortAfter";
/**
* Call {@link #setOnError(String)} with this value to continue SQL command execution if an error is found.
*/
public static final String ON_ERROR_CONTINUE = "continue";
/**
* Call {@link #setOrderFile(String)} with this value to sort in ascendant order the sql files.
*/
public static final String FILE_SORTING_ASC = "ascending";
/**
* Call {@link #setOrderFile(String)} with this value to sort in descendant order the sql files.
*/
public static final String FILE_SORTING_DSC = "descending";
// ////////////////////////// User Info ///////////////////////////////////
/**
* Database username. If not given, it will be looked up through <code>settings.xml</code>'s server with
* <code>${settingsKey}</code> as key.
*
* @since 1.0-beta-1
*/
private String username;
/**
* Database password. If not given, it will be looked up through <code>settings.xml</code>'s server with
* <code>${settingsKey}</code> as key.
*
* @since 1.0-beta-1
*/
private String password;
/**
* Ignore the password and use anonymous access. This may be useful for databases like MySQL which do not allow
* empty password parameters in the connection initialization.
*
* @since 1.0-beta-1
*/
private boolean enableAnonymousPassword;
/**
* Additional key=value pairs separated by comma(,) or semicolon(;) to be passed into JDBC driver.
*
* @since 1.0-beta-1
*/
private String driverProperties;
/**
* Skip execution when there is an error obtaining a connection. This is a special case to support databases, such
* as embedded Derby, that can shutdown the database via the URL (i.e. <code>shutdown=true</code>).
*
* @since 1.0-beta-1
*/
private boolean skipOnConnectionError;
// ////////////////////////////// Source info /////////////////////////////
// //////////////////////////////// Database info /////////////////////////
/**
* Database URL.
*
* @since 1.0-beta-1
*/
private String url;
/**
* Database driver classname. If not give, it will be discovered using provided url with jdbc4
*
* @since 1.0-beta-1
*/
private String driver;
// //////////////////////////// Operation Configuration ////////////////////
/**
* Set to <code>true</code> to execute none-transactional SQL.
*
* @since 1.0-beta-1
*/
private boolean autocommit;
/**
* Action to perform if an error is found. Possible values are <code>abort</code> and <code>continue</code>.
*
* @since 1.0-beta-1
*/
private String onError = ON_ERROR_ABORT;
// //////////////////////////// Parser Configuration ////////////////////
/**
* Set the delimiter that separates SQL statements.
*
* @since 1.0-beta-1
*/
private String delimiter = ";";
/**
* <p>
* The delimiter type takes two values - "normal" and "row". Normal means that any occurrence of the delimiter
* terminate the SQL command whereas with row, only a line containing just the delimiter is recognized as the end of
* the command.
* </p>
* <p>
* For example, set this to "go" and delimiterType to "row" for Sybase ASE or MS SQL Server.
* </p>
*
* @since 1.0-beta-1
*/
private DelimiterType delimiterType = DelimiterType.NORMAL;
/**
* Set the order in which the SQL files will be executed. Possible values are <code>ascending</code> and
* <code>descending</code>. Any other value means that no sorting will be performed.
*
* @since 1.0-beta-1
*/
private String orderFile = null;
/**
* Keep the format of an SQL block.
*
* @since 1.0-beta-1
*/
private boolean keepFormat = false;
// /////////////////////////////////////////////////////////////////////////////////////
/**
* Print SQL results.
*
* @since 1.0-beta-1
*/
private boolean printResultSet = false;
/**
* Print header columns.
*/
private boolean showheaders = true;
/**
* Encoding to use when reading SQL statements from a file.
*
* @since 1.0-beta-1
*/
private String encoding = "";
/**
* Append to an existing file or overwrite it?
*/
private boolean append = false;
/**
* Argument to Statement.setEscapeProcessing If you want the driver to use regular SQL syntax then set this to
* false.
*
* @since 1.0-beta-1
*/
private boolean escapeProcessing = true;
private boolean verbose = false;
/**
* Repeats the execution for stress test purpose
*
* @since 1.0-beta-1
*/
private int repeats = 1;
/**
* Pause between repeat for stress test purpose
*
* @since 1.0-beta-1
*/
private long sleepTimeBetweenRepeats = 0;
/**
* Transactions per connection execution for stress test purpose
*
* @since 1.0-beta-1
*/
private int transactionsPerConnection = 1;
/**
* Number of retries to open connection before giving up. Mainly to handle the case where application and database
* colocated and database is much slower to accept connection at system startup
*
* @since 1.0-beta-1
*/
private int connectionRetries = 1;
/**
* Number of delay in msec between each connection retry
*
* @since 1.0-beta-1
*/
private int connectionRetryDelay = 10000; // msec
// /////////////////////////////////////////////////////////////////////////////////////
// Accessor
// /////////////////////////////////////////////////////////////////////////////////////
public void setRepeatesPerConnection( int num )
{
this.transactionsPerConnection = num;
}
public void setRepeats( int repeats )
{
this.repeats = repeats;
}
public void setSleepTimeBetweenRepeats( long sleepTimeBetweenRepeats )
{
this.sleepTimeBetweenRepeats = sleepTimeBetweenRepeats;
}
public String getUsername()
{
return this.username;
}
public void setUsername( String username )
{
this.username = username;
}
public String getPassword()
{
return this.password;
}
public void setPassword( String password )
{
this.password = <PASSWORD>;
}
public String getUrl()
{
return this.url;
}
public void setUrl( String url )
{
this.url = url;
}
public String getDriver()
{
return this.driver;
}
public void setDriver( String driver )
{
this.driver = driver;
}
void setAutocommit( boolean autocommit )
{
this.autocommit = autocommit;
}
public String getOrderFile()
{
return this.orderFile;
}
public void setOrderFile( String orderFile )
{
if ( FILE_SORTING_ASC.equalsIgnoreCase( orderFile ) )
{
this.orderFile = FILE_SORTING_ASC;
}
else if ( FILE_SORTING_DSC.equalsIgnoreCase( orderFile ) )
{
this.orderFile = FILE_SORTING_DSC;
}
else
{
throw new IllegalArgumentException( orderFile + " is not a valid value for orderFile, only '"
+ FILE_SORTING_ASC + "' or '" + FILE_SORTING_DSC + "'." );
}
}
public String getOnError()
{
return this.onError;
}
public void setOnError( String action )
{
if ( ON_ERROR_ABORT.equalsIgnoreCase( action ) )
{
this.onError = ON_ERROR_ABORT;
}
else if ( ON_ERROR_CONTINUE.equalsIgnoreCase( action ) )
{
this.onError = ON_ERROR_CONTINUE;
}
else if ( ON_ERROR_ABORT_AFTER.equalsIgnoreCase( action ) )
{
this.onError = ON_ERROR_ABORT_AFTER;
}
else
{
throw new IllegalArgumentException( action + " is not a valid value for onError, only '" + ON_ERROR_ABORT
+ "', '" + ON_ERROR_ABORT_AFTER + "', or '" + ON_ERROR_CONTINUE + "'." );
}
}
public void setDriverProperties( String driverProperties )
{
this.driverProperties = driverProperties;
}
/**
* Set the file encoding to use on the SQL files read in
*
* @param encoding the encoding to use on the files
*/
public void setEncoding( String encoding )
{
this.encoding = encoding;
}
/**
* Set the delimiter that separates SQL statements. Defaults to ";";
*/
public void setDelimiter( String delimiter )
{
this.delimiter = delimiter;
}
/**
* Set the delimiter type: "normal" or "row" (default "normal").
*/
public void setDelimiterType( DelimiterType delimiterType )
{
this.delimiterType = delimiterType;
}
/**
* Print result sets from the statements; optional, default false
*/
public void setPrintResutlSet( boolean print )
{
this.printResultSet = print;
}
/**
* Print headers for result sets from the statements; optional, default true.
*/
public void setShowheaders( boolean showheaders )
{
this.showheaders = showheaders;
}
/**
* whether output should be appended to or overwrite an existing file. Defaults to false.
*/
public void setAppend( boolean append )
{
this.append = append;
}
/**
* whether or not format should be preserved. Defaults to false.
*
* @param keepformat The keepformat to set
*/
public void setKeepFormat( boolean keepformat )
{
this.keepFormat = keepformat;
}
/**
* Set escape processing for statements.
*/
public void setEscapeProcessing( boolean enable )
{
escapeProcessing = enable;
}
public boolean isEnableAnonymousPassword()
{
return enableAnonymousPassword;
}
public void setEnableAnonymousPassword( boolean enableAnonymousPassword )
{
this.enableAnonymousPassword = enableAnonymousPassword;
}
public String getDriverProperties()
{
return driverProperties;
}
/**
* parse driverProperties into Properties set
*
* @return Proproties
*/
public Properties getDriverPropertyMap()
{
// set as protected scopy for unit test purpose
Properties properties = new Properties();
if ( !StringUtils.isEmpty( this.driverProperties ) )
{
String[] tokens = StringUtils.split( this.driverProperties, ",;" );
for ( int i = 0; i < tokens.length; ++i )
{
String[] keyValueTokens = StringUtils.split( tokens[i].trim(), "=" );
if ( keyValueTokens.length != 2 )
{
throw new RuntimeException( "Invalid JDBC Driver properties: " + this.driverProperties );
}
properties.setProperty( keyValueTokens[0], keyValueTokens[1] );
}
}
return properties;
}
public boolean isSkipOnConnectionError()
{
return skipOnConnectionError;
}
public void setSkipOnConnectionError( boolean skipOnConnectionError )
{
this.skipOnConnectionError = skipOnConnectionError;
}
public boolean isAutocommit()
{
return autocommit;
}
public boolean isPrintResultSet()
{
return printResultSet;
}
public void setPrintResultSet( boolean printResultSet )
{
this.printResultSet = printResultSet;
}
public int getTransactionsPerConnection()
{
return transactionsPerConnection;
}
public void setTransactionsPerConnection( int transactionsPerConnection )
{
this.transactionsPerConnection = transactionsPerConnection;
}
public String getDelimiter()
{
return delimiter;
}
public DelimiterType getDelimiterType()
{
return delimiterType;
}
public boolean isKeepFormat()
{
return keepFormat;
}
public boolean isShowheaders()
{
return showheaders;
}
public String getEncoding()
{
return encoding;
}
public boolean isAppend()
{
return append;
}
public boolean isEscapeProcessing()
{
return escapeProcessing;
}
public int getRepeats()
{
return repeats;
}
public long getSleepTimeBetweenRepeats()
{
return sleepTimeBetweenRepeats;
}
public int getConnectionRetries()
{
return connectionRetries;
}
public void setConnectionRetries( int connectionRetries )
{
this.connectionRetries = connectionRetries;
}
public int getConnectionRetryDelay()
{
return connectionRetryDelay;
}
public void setConnectionRetryDelay( int connectionRetryDelay )
{
this.connectionRetryDelay = connectionRetryDelay;
}
public boolean isVerbose()
{
return verbose;
}
public void setVerbose( boolean verbose )
{
this.verbose = verbose;
}
}
| 14,653 | 0.587059 | 0.580984 | 571 | 24.658493 | 28.939772 | 120 | false | false | 0 | 0 | 0 | 0 | 87 | 0.017678 | 0.225919 | false | false | 4 |
c2f6d4729b45adff17c6fe2d3b7328084120c41c | 27,453,430,975,506 | 8b395076a55b7a5d38ca1f7216f1e2a54ebff983 | /src/test/java/br/com/vitormarcal/eltjob/helpers/MockPOJO.java | fda0847ec63728b5a45f9669381e5369217722be | [] | no_license | vitormarcal/etljob | https://github.com/vitormarcal/etljob | 460ea572611b8790d28414541e12d40514c69635 | 833536b080d4083d8bf5d17c3e0656b7aedeee0f | refs/heads/master | 2023-04-13T07:36:47.107000 | 2018-11-30T11:37:42 | 2018-11-30T11:37:42 | 159,663,184 | 1 | 0 | null | false | 2018-11-30T11:37:43 | 2018-11-29T12:31:06 | 2018-11-29T14:06:13 | 2018-11-30T11:37:43 | 85 | 1 | 0 | 4 | Java | false | null | package br.com.vitormarcal.eltjob.helpers;
import br.com.vitormarcal.eltjob.core.AbstractFileObject;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
@Data
@EqualsAndHashCode(callSuper = false)
@Builder
public class MockPOJO extends AbstractFileObject {
private String nome;
private String sobrenome;
private Integer idade;
private List<String> cores;
}
| UTF-8 | Java | 425 | java | MockPOJO.java | Java | [] | null | [] | package br.com.vitormarcal.eltjob.helpers;
import br.com.vitormarcal.eltjob.core.AbstractFileObject;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
@Data
@EqualsAndHashCode(callSuper = false)
@Builder
public class MockPOJO extends AbstractFileObject {
private String nome;
private String sobrenome;
private Integer idade;
private List<String> cores;
}
| 425 | 0.785882 | 0.785882 | 20 | 20.25 | 17.575195 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
248645a957c2ad5aec0d2b5b838ec55b5b5c67a8 | 188,978,595,048 | e737a537195a431fe255fa3839a1e337d806a372 | /java/src/concurrencies/frameworks/rxjava/com/rxjava3/reactivex/rxjava/SequenceEquals.java | 4562c8c6fc2f76c11ddbe957cdc8883098d5f647 | [] | no_license | iceleeyo/concurrency | https://github.com/iceleeyo/concurrency | 132e9444fe20e5c80efd5c13d477af7e5c3a5d13 | fa8a1d1ccad92330c17ae4b7e34d17c65076a7a4 | refs/heads/master | 2023-05-09T09:11:36.706000 | 2020-09-10T10:52:15 | 2020-09-10T10:52:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rxjava3.reactivex.rxjava;
import io.reactivex.rxjava3.core.Observable;
/**
*
*
* @author EMAIL:vuquangtin@gmail.com , tel:0377443333
* @version 1.0.0
* @see <a
* href="https://github.com/vuquangtin/concurrency">https://github.com/vuquangtin/concurrency</a>
*
*/
public class SequenceEquals {
public static void main(String[] args) {
Observable.
sequenceEqual(Observable.range(0, 5),
Observable.range(1, 5))
.doOnSuccess(i -> System.out.println("Are they the same sequence? " + i))
.subscribe();
}
}
| UTF-8 | Java | 617 | java | SequenceEquals.java | Java | [
{
"context": "a3.core.Observable;\n\n/**\n * \n * \n * @author EMAIL:vuquangtin@gmail.com , tel:0377443333\n * @version 1.0.0\n * @see <a\n * ",
"end": 134,
"score": 0.999923586845398,
"start": 114,
"tag": "EMAIL",
"value": "vuquangtin@gmail.com"
},
{
"context": "1.0.0\n * @see <a\n * href=\"https://github.com/vuquangtin/concurrency\">https://github.com/vuquangtin/concur",
"end": 224,
"score": 0.9992280006408691,
"start": 214,
"tag": "USERNAME",
"value": "vuquangtin"
},
{
"context": "ub.com/vuquangtin/concurrency\">https://github.com/vuquangtin/concurrency</a>\n *\n */\npublic class SequenceEqual",
"end": 267,
"score": 0.9994608163833618,
"start": 257,
"tag": "USERNAME",
"value": "vuquangtin"
}
] | null | [] | package com.rxjava3.reactivex.rxjava;
import io.reactivex.rxjava3.core.Observable;
/**
*
*
* @author EMAIL:<EMAIL> , tel:0377443333
* @version 1.0.0
* @see <a
* href="https://github.com/vuquangtin/concurrency">https://github.com/vuquangtin/concurrency</a>
*
*/
public class SequenceEquals {
public static void main(String[] args) {
Observable.
sequenceEqual(Observable.range(0, 5),
Observable.range(1, 5))
.doOnSuccess(i -> System.out.println("Are they the same sequence? " + i))
.subscribe();
}
}
| 604 | 0.604538 | 0.573744 | 23 | 25.826086 | 28.481348 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.304348 | false | false | 4 |
43c1bf6c803f164a791e0b9cadf5c8846fc4e6e4 | 1,211,180,789,430 | 139aec54e72fa566d28adf36870f43db613ca387 | /client-side/doppelganger-client-TEST/model/src/main/java/com/group17/model/helper/DoppelgangerApplication.java | 5163152877afc35e92688d476c4a870aa6f80f3f | [] | no_license | egeorgiev1/Doppelganger | https://github.com/egeorgiev1/Doppelganger | e048d5bbb3f02c906a830ff7f325114c3f44fbd1 | 1c9f809b4e74fcb0a32843b7ceabe91e5c225e1f | refs/heads/master | 2022-11-06T18:07:03.649000 | 2020-06-30T04:08:26 | 2020-06-30T04:08:26 | 275,927,426 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.group17.model.helper;
import android.app.Application;
import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.BuildConfig;
import android.arch.persistence.room.Room;
import android.content.Context;
import com.group17.model.db.migrations.DoppelgangerDatabase;
import com.group17.model.rest.IDoppelgangerAPI;
import com.group17.model.rest.SessionIdCapturer;
import com.group17.model.rest.SessionIdInjector;
import java.lang.reflect.Method;
import java.util.HashMap;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
public class DoppelgangerApplication extends Application {
private static DoppelgangerApplication app;
public IDoppelgangerAPI api = null;
public DoppelgangerDatabase db = null;
public static DoppelgangerApplication getApp(){
return app;
}
public DoppelgangerApplication() {
super.onCreate();
app = this;
}
// DEBUG
public static void setInMemoryRoomDatabases(SupportSQLiteDatabase... database) {
if (BuildConfig.DEBUG) {
try {
Class<?> debugDB = Class.forName("com.amitshekhar.DebugDB");
Class[] argTypes = new Class[]{HashMap.class};
HashMap<String, SupportSQLiteDatabase> inMemoryDatabases = new HashMap<>();
// set your inMemory databases
inMemoryDatabases.put("InMemoryOne.db", database[0]);
Method setRoomInMemoryDatabase = debugDB.getMethod("setInMemoryRoomDatabases", argTypes);
setRoomInMemoryDatabase.invoke(null, inMemoryDatabases);
} catch (Exception ignore) {
}
}
}
@Override
public void onCreate() {
super.onCreate();
// Create Retrofit client
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
clientBuilder.addInterceptor(new SessionIdCapturer(this));
clientBuilder.addInterceptor(new SessionIdInjector(this));
OkHttpClient client = clientBuilder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://206.189.125.23/auth/")
.addConverterFactory(ScalarsConverterFactory.create())
.client(client)
.build();
this.api = retrofit.create(IDoppelgangerAPI.class);
// Create the database
db = Room.databaseBuilder(
this,
DoppelgangerDatabase.class,
"doppelganger_db"
).allowMainThreadQueries().build(); // Not recommended to do it in the main thread for performance
// DEBUG
setInMemoryRoomDatabases(db.getOpenHelper().getReadableDatabase());
}
}
| UTF-8 | Java | 2,788 | java | DoppelgangerApplication.java | Java | [] | null | [] | package com.group17.model.helper;
import android.app.Application;
import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.BuildConfig;
import android.arch.persistence.room.Room;
import android.content.Context;
import com.group17.model.db.migrations.DoppelgangerDatabase;
import com.group17.model.rest.IDoppelgangerAPI;
import com.group17.model.rest.SessionIdCapturer;
import com.group17.model.rest.SessionIdInjector;
import java.lang.reflect.Method;
import java.util.HashMap;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
public class DoppelgangerApplication extends Application {
private static DoppelgangerApplication app;
public IDoppelgangerAPI api = null;
public DoppelgangerDatabase db = null;
public static DoppelgangerApplication getApp(){
return app;
}
public DoppelgangerApplication() {
super.onCreate();
app = this;
}
// DEBUG
public static void setInMemoryRoomDatabases(SupportSQLiteDatabase... database) {
if (BuildConfig.DEBUG) {
try {
Class<?> debugDB = Class.forName("com.amitshekhar.DebugDB");
Class[] argTypes = new Class[]{HashMap.class};
HashMap<String, SupportSQLiteDatabase> inMemoryDatabases = new HashMap<>();
// set your inMemory databases
inMemoryDatabases.put("InMemoryOne.db", database[0]);
Method setRoomInMemoryDatabase = debugDB.getMethod("setInMemoryRoomDatabases", argTypes);
setRoomInMemoryDatabase.invoke(null, inMemoryDatabases);
} catch (Exception ignore) {
}
}
}
@Override
public void onCreate() {
super.onCreate();
// Create Retrofit client
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
clientBuilder.addInterceptor(new SessionIdCapturer(this));
clientBuilder.addInterceptor(new SessionIdInjector(this));
OkHttpClient client = clientBuilder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://206.189.125.23/auth/")
.addConverterFactory(ScalarsConverterFactory.create())
.client(client)
.build();
this.api = retrofit.create(IDoppelgangerAPI.class);
// Create the database
db = Room.databaseBuilder(
this,
DoppelgangerDatabase.class,
"doppelganger_db"
).allowMainThreadQueries().build(); // Not recommended to do it in the main thread for performance
// DEBUG
setInMemoryRoomDatabases(db.getOpenHelper().getReadableDatabase());
}
}
| 2,788 | 0.672884 | 0.663917 | 82 | 33 | 27.307196 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.512195 | false | false | 4 |
c5d23ee3151369966e05927ed6cd1df082094e86 | 11,072,425,723,577 | b71ecb0c73acfe4c67a5efead7ca41b2cddbb30e | /cafe/src/main/java/com/cafe/admin/controller/AdminController.java | b57d1ffef904327e060ac20e95834a880b3f5415 | [] | no_license | ChoYeonJu/SpringProject | https://github.com/ChoYeonJu/SpringProject | 0de4872b73e2f70b0085324541bf7ec7382e8e90 | 4b541c5162fb2398227016654542893c0900eaec | refs/heads/master | 2020-05-23T23:39:13.989000 | 2019-05-16T23:17:53 | 2019-05-16T23:17:53 | 186,999,156 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cafe.admin.controller;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.cafe.member.model.MemberDto;
@Controller
@RequestMapping(value="/admin")
public class AdminController {
@RequestMapping(value="/index.cafe", method=RequestMethod.GET)
public String index(HttpSession session) {
MemberDto memberDto = (MemberDto) session.getAttribute("userInfo");
if(memberDto != null && memberDto.getRole() == 0) {
return "admin/index";
}
return "redirect:/commons/index.cafe";
}
}
| UTF-8 | Java | 676 | java | AdminController.java | Java | [] | null | [] | package com.cafe.admin.controller;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.cafe.member.model.MemberDto;
@Controller
@RequestMapping(value="/admin")
public class AdminController {
@RequestMapping(value="/index.cafe", method=RequestMethod.GET)
public String index(HttpSession session) {
MemberDto memberDto = (MemberDto) session.getAttribute("userInfo");
if(memberDto != null && memberDto.getRole() == 0) {
return "admin/index";
}
return "redirect:/commons/index.cafe";
}
}
| 676 | 0.776627 | 0.775148 | 23 | 28.391304 | 23.872377 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.043478 | false | false | 4 |
cd9c51be245f938642a6350e8db240358fee90a7 | 8,899,172,280,639 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/21/21_b523a40abce419f46e95efd47001ce8ae06d4ef8/MinecraftFrame/21_b523a40abce419f46e95efd47001ce8ae06d4ef8_MinecraftFrame_s.java | 39e97af7c9aafd7d032d0574745cdbcd03b87477 | [] | no_license | zhongxingyu/Seer | https://github.com/zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false | package org.smbarbour.mcu;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import javax.swing.ImageIcon;
import net.minecraft.Launcher;
import org.smbarbour.mcu.util.LoginData;
import org.smbarbour.mcu.util.MCUpdater;
import org.smbarbour.mcu.util.ServerList;
public class MinecraftFrame extends Frame implements WindowListener {
/**
*
*/
private static final long serialVersionUID = -2949740978305392280L;
private Launcher applet = null;
public static void main(String[] args) {
LoginData login = new LoginData();
login.setUserName(args[0]);
login.setSessionId(args[1]);
ServerList server = new ServerList(null, args[2], null, null, null, null, args[5], true, null);
Path instPath = new File(args[3]).toPath();
Path lwjglPath = new File(args[4]).toPath();
ImageIcon icon = null;
try {
icon = new ImageIcon(new URL(args[6]));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException indexException) {}
if (icon == null) { icon = MCUpdater.getInstance().defaultIcon; }
MinecraftFrame me = new MinecraftFrame("MCUpdater - " + server.getName(), icon);
me.launch(instPath, lwjglPath, login, server);
}
public MinecraftFrame(String title, ImageIcon icon) {
super(title);
Image source = icon.getImage();
int w = source.getWidth(null);
int h = source.getHeight(null);
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D)image.getGraphics();
g2d.drawImage(source, 0, 0, null);
setIconImage(image);
this.addWindowListener(this);
g2d.dispose();
}
public void launch(Path instance, Path lwjgl, LoginData login, ServerList server) {
try {
URI address;
String port;
address = new URI("my://" + server.getAddress());
if (address.getPort() != -1) {
port = Integer.toString(address.getPort());
} else {
port = Integer.toString(25565);
}
applet = new Launcher(instance, lwjgl, login, address.getHost(), port);
System.setProperty("minecraft.applet.TargetDirectory", instance.toString());
System.setProperty("org.lwjgl.librarypath", lwjgl.resolve("natives").toString());
System.setProperty("net.java.games.input.librarypath", lwjgl.resolve("natives").toString());
this.add(applet);
applet.setPreferredSize(new Dimension(1280, 720));
this.pack();
this.setLocationRelativeTo(null);
this.setResizable(true);
validate();
applet.init();
applet.start();
setVisible(true);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void windowClosing(WindowEvent e) {
new Thread() {
public void run() {
try {
Thread.sleep(30000L);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.println("~~~ Forcing exit! ~~~");
System.exit(0);
}
}.start();
if (applet != null)
{
applet.stop();
applet.destroy();
}
System.exit(0);
}
@Override
public void windowOpened(WindowEvent e) {}
@Override
public void windowActivated(WindowEvent e) {}
@Override
public void windowClosed(WindowEvent e) {}
@Override
public void windowIconified(WindowEvent e) {}
@Override
public void windowDeiconified(WindowEvent e) {}
@Override
public void windowDeactivated(WindowEvent e) {}
}
| UTF-8 | Java | 3,789 | java | 21_b523a40abce419f46e95efd47001ce8ae06d4ef8_MinecraftFrame_s.java | Java | [] | null | [] | package org.smbarbour.mcu;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import javax.swing.ImageIcon;
import net.minecraft.Launcher;
import org.smbarbour.mcu.util.LoginData;
import org.smbarbour.mcu.util.MCUpdater;
import org.smbarbour.mcu.util.ServerList;
public class MinecraftFrame extends Frame implements WindowListener {
/**
*
*/
private static final long serialVersionUID = -2949740978305392280L;
private Launcher applet = null;
public static void main(String[] args) {
LoginData login = new LoginData();
login.setUserName(args[0]);
login.setSessionId(args[1]);
ServerList server = new ServerList(null, args[2], null, null, null, null, args[5], true, null);
Path instPath = new File(args[3]).toPath();
Path lwjglPath = new File(args[4]).toPath();
ImageIcon icon = null;
try {
icon = new ImageIcon(new URL(args[6]));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException indexException) {}
if (icon == null) { icon = MCUpdater.getInstance().defaultIcon; }
MinecraftFrame me = new MinecraftFrame("MCUpdater - " + server.getName(), icon);
me.launch(instPath, lwjglPath, login, server);
}
public MinecraftFrame(String title, ImageIcon icon) {
super(title);
Image source = icon.getImage();
int w = source.getWidth(null);
int h = source.getHeight(null);
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D)image.getGraphics();
g2d.drawImage(source, 0, 0, null);
setIconImage(image);
this.addWindowListener(this);
g2d.dispose();
}
public void launch(Path instance, Path lwjgl, LoginData login, ServerList server) {
try {
URI address;
String port;
address = new URI("my://" + server.getAddress());
if (address.getPort() != -1) {
port = Integer.toString(address.getPort());
} else {
port = Integer.toString(25565);
}
applet = new Launcher(instance, lwjgl, login, address.getHost(), port);
System.setProperty("minecraft.applet.TargetDirectory", instance.toString());
System.setProperty("org.lwjgl.librarypath", lwjgl.resolve("natives").toString());
System.setProperty("net.java.games.input.librarypath", lwjgl.resolve("natives").toString());
this.add(applet);
applet.setPreferredSize(new Dimension(1280, 720));
this.pack();
this.setLocationRelativeTo(null);
this.setResizable(true);
validate();
applet.init();
applet.start();
setVisible(true);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void windowClosing(WindowEvent e) {
new Thread() {
public void run() {
try {
Thread.sleep(30000L);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.println("~~~ Forcing exit! ~~~");
System.exit(0);
}
}.start();
if (applet != null)
{
applet.stop();
applet.destroy();
}
System.exit(0);
}
@Override
public void windowOpened(WindowEvent e) {}
@Override
public void windowActivated(WindowEvent e) {}
@Override
public void windowClosed(WindowEvent e) {}
@Override
public void windowIconified(WindowEvent e) {}
@Override
public void windowDeiconified(WindowEvent e) {}
@Override
public void windowDeactivated(WindowEvent e) {}
}
| 3,789 | 0.681446 | 0.667194 | 132 | 27.69697 | 22.495096 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.431818 | false | false | 4 |
449cae61c294b9a8db4d9d8f2c466fa44873e498 | 16,569,983,896,292 | 2ea69c60fa25b88baf2628e11ac5ff745efefc20 | /EcellAdminDashboard/src/java/Utility/hibernateutility.java | 76bee770bae973c2169c6f5a4d9b13b82668ac35 | [] | no_license | jvalbhani/EcellstreetAdminDashBoard | https://github.com/jvalbhani/EcellstreetAdminDashBoard | 76b3ff79ea7edd765751109374bcfaff7dbca933 | 47ddb891edfbb004fc77d7acf139187b5554eb22 | refs/heads/master | 2021-06-20T03:58:57.898000 | 2017-03-22T12:06:20 | 2017-03-22T12:06:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 Utility;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
*
* @author jayesh
*/
public class HibernateUtility implements ServletContextListener{
private SessionFactory sessionfactory=null;
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc=sce.getServletContext();
try{
System.out.println("__________________________Going to check config files________________________________________");
Configuration cf=new Configuration();
Configuration cfg=cf.configure("/hbmfolder/hibernate.cfg.xml");
sessionfactory=cfg.buildSessionFactory();
System.out.println("______________________________done______________________________");
sc.setAttribute("sf",sessionfactory);
}
catch(HibernateException e)
{
System.out.println(e.getMessage());
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
try{
ServletContext sc=sce.getServletContext();
sessionfactory=(SessionFactory)sc.getAttribute("sf");
sessionfactory.close();
System.out.println("\n\ndone");
}
catch(HibernateException e)
{
System.out.println(e.getMessage());
}
}
}
| UTF-8 | Java | 1,813 | java | hibernateutility.java | Java | [
{
"context": "rg.hibernate.cfg.Configuration;\n\n/**\n *\n * @author jayesh\n */\npublic class HibernateUtility implements Serv",
"end": 470,
"score": 0.9933357834815979,
"start": 464,
"tag": "USERNAME",
"value": "jayesh"
}
] | null | [] | /*
* 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 Utility;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
*
* @author jayesh
*/
public class HibernateUtility implements ServletContextListener{
private SessionFactory sessionfactory=null;
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc=sce.getServletContext();
try{
System.out.println("__________________________Going to check config files________________________________________");
Configuration cf=new Configuration();
Configuration cfg=cf.configure("/hbmfolder/hibernate.cfg.xml");
sessionfactory=cfg.buildSessionFactory();
System.out.println("______________________________done______________________________");
sc.setAttribute("sf",sessionfactory);
}
catch(HibernateException e)
{
System.out.println(e.getMessage());
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
try{
ServletContext sc=sce.getServletContext();
sessionfactory=(SessionFactory)sc.getAttribute("sf");
sessionfactory.close();
System.out.println("\n\ndone");
}
catch(HibernateException e)
{
System.out.println(e.getMessage());
}
}
}
| 1,813 | 0.583563 | 0.583563 | 57 | 30.807018 | 27.998396 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.438596 | false | false | 4 |
017fc8d2fa0669814a6db8b9b8303aed9b2173fb | 15,702,400,456,356 | fefb9f9dd5962200d660805a64eb2d3af6596880 | /day1118/TestGridLayout.java | a1bbc0eb13a9744083e88f530a6b421e9bc56b58 | [] | no_license | kinowk/JAVA-SW- | https://github.com/kinowk/JAVA-SW- | b796aafd38a824a6a2212bd81f040bc613fe0649 | 28b56c3f85a808cbaf02e885cc77b5a49e402404 | refs/heads/master | 2023-01-30T19:17:19.191000 | 2020-12-06T11:03:40 | 2020-12-06T11:03:40 | 309,224,836 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day1118;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
* GridLayout - 격자레이아웃<br>
* rows, columns에 component size가 동일하게 설정되는 layout<br>
* rows, columns와 component의 개수가 다른 경우 rows에 맞혀 자동 배치
*
* @author owner
*/
@SuppressWarnings("serial")
// 1. Window Component 상속
public class TestGridLayout extends JFrame {
// 2. default constructor
public TestGridLayout() {
super("GridLayout");
// 3. Layout Manager
setLayout(new GridLayout(3, 3)); // GridLayout(int rows, int cols)
// 4.add - Component 배치
// add(new JButton("1"));
// add(new JButton("2"));
// add(new JButton("3"));
// add(new JButton("4"));
// add(new JButton("5"));
// add(new JButton("6"));
// add(new JButton("7"));
// add(new JButton("8"));
// add(new JButton("9"));
// add(new JButton("10"));
// JButton[] arrJButton = new JButton[9];
// for (int i = 0; i < arrJButton.length; i++) {
// arrJButton[i] = new JButton(String.valueOf(i + 1));
//// arrJButton[i] = new JButton(Integer.toString(i + 1));
// add(arrJButton[i]);
// }
List<JButton> list = new ArrayList<JButton>();
for(int i = 1; i<10; i++) {
list.add(new JButton(String.valueOf(i)));
}
for(int i = 0; i<list.size(); i++) {
add(list.get(i));
}
// int jButtonNum = 9;
// for (int i = 0; i < jButtonNum; i++) {
// add(new JButton(Integer.toString(i + 1)));
//
// }
// 5. setSize - Window Component 크기 설정
setSize(400, 400);
// 6. setVisible
setVisible(true);
// 7. setDefaultCloseOperation - Window Component 종료이벤트 처리
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestGridLayout();
}
}
| UHC | Java | 1,837 | java | TestGridLayout.java | Java | [
{
"context": "component의 개수가 다른 경우 rows에 맞혀 자동 배치\n * \n * @author owner\n */\n@SuppressWarnings(\"serial\")\n// 1. Window Comp",
"end": 314,
"score": 0.9987121820449829,
"start": 309,
"tag": "USERNAME",
"value": "owner"
}
] | null | [] | package day1118;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
* GridLayout - 격자레이아웃<br>
* rows, columns에 component size가 동일하게 설정되는 layout<br>
* rows, columns와 component의 개수가 다른 경우 rows에 맞혀 자동 배치
*
* @author owner
*/
@SuppressWarnings("serial")
// 1. Window Component 상속
public class TestGridLayout extends JFrame {
// 2. default constructor
public TestGridLayout() {
super("GridLayout");
// 3. Layout Manager
setLayout(new GridLayout(3, 3)); // GridLayout(int rows, int cols)
// 4.add - Component 배치
// add(new JButton("1"));
// add(new JButton("2"));
// add(new JButton("3"));
// add(new JButton("4"));
// add(new JButton("5"));
// add(new JButton("6"));
// add(new JButton("7"));
// add(new JButton("8"));
// add(new JButton("9"));
// add(new JButton("10"));
// JButton[] arrJButton = new JButton[9];
// for (int i = 0; i < arrJButton.length; i++) {
// arrJButton[i] = new JButton(String.valueOf(i + 1));
//// arrJButton[i] = new JButton(Integer.toString(i + 1));
// add(arrJButton[i]);
// }
List<JButton> list = new ArrayList<JButton>();
for(int i = 1; i<10; i++) {
list.add(new JButton(String.valueOf(i)));
}
for(int i = 0; i<list.size(); i++) {
add(list.get(i));
}
// int jButtonNum = 9;
// for (int i = 0; i < jButtonNum; i++) {
// add(new JButton(Integer.toString(i + 1)));
//
// }
// 5. setSize - Window Component 크기 설정
setSize(400, 400);
// 6. setVisible
setVisible(true);
// 7. setDefaultCloseOperation - Window Component 종료이벤트 처리
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestGridLayout();
}
}
| 1,837 | 0.628801 | 0.605278 | 75 | 22.24 | 18.166519 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.8 | false | false | 4 |
a729aecb0d166253250fa47bc71860783aea5ff6 | 30,992,484,021,965 | d63249c4e1b2baf1dd122394fad59f7407a4d8d4 | /src/main/java/com/heee/bean/usuario/UsuarioCrear.java | f4419747bd75546aa407149eede75bfe6a861cdb | [] | no_license | wvaldiviezo/Siap-HEEE | https://github.com/wvaldiviezo/Siap-HEEE | edadfbdbe635847decd2b911cfdeea6604135180 | f7fc2dfaf3b5e1ce424eb53dc7ba9980d25c27f5 | refs/heads/master | 2021-09-15T00:21:51.296000 | 2018-05-22T19:24:39 | 2018-05-22T19:24:39 | 118,697,975 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.heee.bean.usuario;
import com.heee.bean.menu.SessionBean;
import com.heee.bean.model.entity.Empleado;
import com.heee.bean.model.entity.Usuario;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
@ManagedBean(name = "usuarioController")
public class UsuarioCrear implements Serializable{
private static final long serialVersionUID = 1L;
private Empleado empleado;
private Usuario usuario;
SessionBean sesion = new SessionBean();
private List<Empleado> verificarExistenciaVector;
/*Método Constructor*/
public UsuarioCrear(){
this.empleado = new Empleado(); //Inicialización de la variable
}
/*Método para validar los duplicados*/
/*Getters & Setters*/
public Empleado getEmpleado() {
if(this.empleado == null) {
this.empleado = new Empleado();
}
return empleado;
}
public void setEmpleado(Empleado empleado) {
this.empleado = empleado;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public SessionBean getSesion() {
return sesion;
}
public void setSesion(SessionBean sesion) {
this.sesion = sesion;
}
public List<Empleado> getVerificarExistenciaVector() {
return verificarExistenciaVector;
}
public void setVerificarExistenciaVector(List<Empleado> verificarExistenciaVector) {
this.verificarExistenciaVector = verificarExistenciaVector;
}
}
| UTF-8 | Java | 1,650 | java | UsuarioCrear.java | Java | [] | null | [] | package com.heee.bean.usuario;
import com.heee.bean.menu.SessionBean;
import com.heee.bean.model.entity.Empleado;
import com.heee.bean.model.entity.Usuario;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
@ManagedBean(name = "usuarioController")
public class UsuarioCrear implements Serializable{
private static final long serialVersionUID = 1L;
private Empleado empleado;
private Usuario usuario;
SessionBean sesion = new SessionBean();
private List<Empleado> verificarExistenciaVector;
/*Método Constructor*/
public UsuarioCrear(){
this.empleado = new Empleado(); //Inicialización de la variable
}
/*Método para validar los duplicados*/
/*Getters & Setters*/
public Empleado getEmpleado() {
if(this.empleado == null) {
this.empleado = new Empleado();
}
return empleado;
}
public void setEmpleado(Empleado empleado) {
this.empleado = empleado;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public SessionBean getSesion() {
return sesion;
}
public void setSesion(SessionBean sesion) {
this.sesion = sesion;
}
public List<Empleado> getVerificarExistenciaVector() {
return verificarExistenciaVector;
}
public void setVerificarExistenciaVector(List<Empleado> verificarExistenciaVector) {
this.verificarExistenciaVector = verificarExistenciaVector;
}
}
| 1,650 | 0.659381 | 0.658774 | 72 | 21.875 | 21.252411 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.305556 | false | false | 4 |
6818354bf28a6d571052f728cc63fc97825bdef2 | 15,101,105,014,285 | b3d510fc07ecae2fc6a6b78951ee2e63077eb944 | /src/main/java/cn/com/dayang/suyou/vo/UsersModel.java | 9ff45cafcdd7c5e9b7ba9a812a8630bbd696dadf | [] | no_license | ortrue/DYSuYou | https://github.com/ortrue/DYSuYou | c7b4518430fea425c22085a8d9956c97f6a308c8 | 59e5ef3269cb63e9b0a9e31201f7744f52786507 | refs/heads/master | 2016-09-05T17:05:27.485000 | 2014-09-28T09:42:57 | 2014-10-16T08:46:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*******************************************************************************
* Copyright (c) 2005, 2014 springside.github.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package cn.com.dayang.suyou.vo;
import java.io.Serializable;
import java.util.Date;
public class UsersModel implements Serializable{
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String email;
private String passwd;
private String salt;
private Integer type;
private Integer status;
private Date createtime;
private String singupinfo;
private Double spacetotal;
private Double spaceused;
private Double downloadflowtotal;
private Double downloadflowused;
private Integer chargetypeid;
private String activetime;
private String roles;
private Integer mailsCount;
private Integer attaCount;
private Double mailsTotal;
private Double attaTotal;
private String spaceusedStr;
private String mailsTotalStr;
private String attaTotalStr;
/**
* @return the spaceusedStr
*/
public String getSpaceusedStr() {
return spaceusedStr;
}
/**
* @param spaceusedStr the spaceusedStr to set
*/
public void setSpaceusedStr(String spaceusedStr) {
this.spaceusedStr = spaceusedStr;
}
/**
* @return the mailsTotalStr
*/
public String getMailsTotalStr() {
return mailsTotalStr;
}
/**
* @param mailsTotalStr the mailsTotalStr to set
*/
public void setMailsTotalStr(String mailsTotalStr) {
this.mailsTotalStr = mailsTotalStr;
}
/**
* @return the attaTotalStr
*/
public String getAttaTotalStr() {
return attaTotalStr;
}
/**
* @param attaTotalStr the attaTotalStr to set
*/
public void setAttaTotalStr(String attaTotalStr) {
this.attaTotalStr = attaTotalStr;
}
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the passwd
*/
public String getPasswd() {
return passwd;
}
/**
* @param passwd the passwd to set
*/
public void setPasswd(String passwd) {
this.passwd = passwd;
}
/**
* @return the salt
*/
public String getSalt() {
return salt;
}
/**
* @param salt the salt to set
*/
public void setSalt(String salt) {
this.salt = salt;
}
/**
* @return the type
*/
public Integer getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(Integer type) {
this.type = type;
}
/**
* @return the status
*/
public Integer getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(Integer status) {
this.status = status;
}
/**
* @return the createtime
*/
public Date getCreatetime() {
return createtime;
}
/**
* @param createtime the createtime to set
*/
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
/**
* @return the singupinfo
*/
public String getSingupinfo() {
return singupinfo;
}
/**
* @param singupinfo the singupinfo to set
*/
public void setSingupinfo(String singupinfo) {
this.singupinfo = singupinfo;
}
/**
* @return the spacetotal
*/
public Double getSpacetotal() {
return spacetotal;
}
/**
* @param spacetotal the spacetotal to set
*/
public void setSpacetotal(Double spacetotal) {
this.spacetotal = spacetotal;
}
/**
* @return the spaceused
*/
public Double getSpaceused() {
return spaceused;
}
/**
* @param spaceused the spaceused to set
*/
public void setSpaceused(Double spaceused) {
this.spaceused = spaceused;
}
/**
* @return the downloadflowtotal
*/
public Double getDownloadflowtotal() {
return downloadflowtotal;
}
/**
* @param downloadflowtotal the downloadflowtotal to set
*/
public void setDownloadflowtotal(Double downloadflowtotal) {
this.downloadflowtotal = downloadflowtotal;
}
/**
* @return the downloadflowused
*/
public Double getDownloadflowused() {
return downloadflowused;
}
/**
* @param downloadflowused the downloadflowused to set
*/
public void setDownloadflowused(Double downloadflowused) {
this.downloadflowused = downloadflowused;
}
/**
* @return the chargetypeid
*/
public Integer getChargetypeid() {
return chargetypeid;
}
/**
* @param chargetypeid the chargetypeid to set
*/
public void setChargetypeid(Integer chargetypeid) {
this.chargetypeid = chargetypeid;
}
/**
* @return the activetime
*/
public String getActivetime() {
return activetime;
}
/**
* @param activetime the activetime to set
*/
public void setActivetime(String activetime) {
this.activetime = activetime;
}
/**
* @return the roles
*/
public String getRoles() {
return roles;
}
/**
* @param roles the roles to set
*/
public void setRoles(String roles) {
this.roles = roles;
}
/**
* @return the mailsCount
*/
public Integer getMailsCount() {
return mailsCount;
}
/**
* @param mailsCount the mailsCount to set
*/
public void setMailsCount(Integer mailsCount) {
this.mailsCount = mailsCount;
}
/**
* @return the attaCount
*/
public Integer getAttaCount() {
return attaCount;
}
/**
* @param attaCount the attaCount to set
*/
public void setAttaCount(Integer attaCount) {
this.attaCount = attaCount;
}
/**
* @return the mailsTotal
*/
public Double getMailsTotal() {
return mailsTotal;
}
/**
* @param mailsTotal the mailsTotal to set
*/
public void setMailsTotal(Double mailsTotal) {
this.mailsTotal = mailsTotal;
}
/**
* @return the attaTotal
*/
public Double getAttaTotal() {
return attaTotal;
}
/**
* @param attaTotal the attaTotal to set
*/
public void setAttaTotal(Double attaTotal) {
this.attaTotal = attaTotal;
}
} | UTF-8 | Java | 6,512 | java | UsersModel.java | Java | [
{
"context": "*********************\r\n * Copyright (c) 2005, 2014 springside.github.io\r\n *\r\n * Licensed under the Apache Licen",
"end": 120,
"score": 0.573345959186554,
"start": 110,
"tag": "USERNAME",
"value": "springside"
}
] | null | [] | /*******************************************************************************
* Copyright (c) 2005, 2014 springside.github.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
package cn.com.dayang.suyou.vo;
import java.io.Serializable;
import java.util.Date;
public class UsersModel implements Serializable{
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String email;
private String passwd;
private String salt;
private Integer type;
private Integer status;
private Date createtime;
private String singupinfo;
private Double spacetotal;
private Double spaceused;
private Double downloadflowtotal;
private Double downloadflowused;
private Integer chargetypeid;
private String activetime;
private String roles;
private Integer mailsCount;
private Integer attaCount;
private Double mailsTotal;
private Double attaTotal;
private String spaceusedStr;
private String mailsTotalStr;
private String attaTotalStr;
/**
* @return the spaceusedStr
*/
public String getSpaceusedStr() {
return spaceusedStr;
}
/**
* @param spaceusedStr the spaceusedStr to set
*/
public void setSpaceusedStr(String spaceusedStr) {
this.spaceusedStr = spaceusedStr;
}
/**
* @return the mailsTotalStr
*/
public String getMailsTotalStr() {
return mailsTotalStr;
}
/**
* @param mailsTotalStr the mailsTotalStr to set
*/
public void setMailsTotalStr(String mailsTotalStr) {
this.mailsTotalStr = mailsTotalStr;
}
/**
* @return the attaTotalStr
*/
public String getAttaTotalStr() {
return attaTotalStr;
}
/**
* @param attaTotalStr the attaTotalStr to set
*/
public void setAttaTotalStr(String attaTotalStr) {
this.attaTotalStr = attaTotalStr;
}
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the passwd
*/
public String getPasswd() {
return passwd;
}
/**
* @param passwd the passwd to set
*/
public void setPasswd(String passwd) {
this.passwd = passwd;
}
/**
* @return the salt
*/
public String getSalt() {
return salt;
}
/**
* @param salt the salt to set
*/
public void setSalt(String salt) {
this.salt = salt;
}
/**
* @return the type
*/
public Integer getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(Integer type) {
this.type = type;
}
/**
* @return the status
*/
public Integer getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(Integer status) {
this.status = status;
}
/**
* @return the createtime
*/
public Date getCreatetime() {
return createtime;
}
/**
* @param createtime the createtime to set
*/
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
/**
* @return the singupinfo
*/
public String getSingupinfo() {
return singupinfo;
}
/**
* @param singupinfo the singupinfo to set
*/
public void setSingupinfo(String singupinfo) {
this.singupinfo = singupinfo;
}
/**
* @return the spacetotal
*/
public Double getSpacetotal() {
return spacetotal;
}
/**
* @param spacetotal the spacetotal to set
*/
public void setSpacetotal(Double spacetotal) {
this.spacetotal = spacetotal;
}
/**
* @return the spaceused
*/
public Double getSpaceused() {
return spaceused;
}
/**
* @param spaceused the spaceused to set
*/
public void setSpaceused(Double spaceused) {
this.spaceused = spaceused;
}
/**
* @return the downloadflowtotal
*/
public Double getDownloadflowtotal() {
return downloadflowtotal;
}
/**
* @param downloadflowtotal the downloadflowtotal to set
*/
public void setDownloadflowtotal(Double downloadflowtotal) {
this.downloadflowtotal = downloadflowtotal;
}
/**
* @return the downloadflowused
*/
public Double getDownloadflowused() {
return downloadflowused;
}
/**
* @param downloadflowused the downloadflowused to set
*/
public void setDownloadflowused(Double downloadflowused) {
this.downloadflowused = downloadflowused;
}
/**
* @return the chargetypeid
*/
public Integer getChargetypeid() {
return chargetypeid;
}
/**
* @param chargetypeid the chargetypeid to set
*/
public void setChargetypeid(Integer chargetypeid) {
this.chargetypeid = chargetypeid;
}
/**
* @return the activetime
*/
public String getActivetime() {
return activetime;
}
/**
* @param activetime the activetime to set
*/
public void setActivetime(String activetime) {
this.activetime = activetime;
}
/**
* @return the roles
*/
public String getRoles() {
return roles;
}
/**
* @param roles the roles to set
*/
public void setRoles(String roles) {
this.roles = roles;
}
/**
* @return the mailsCount
*/
public Integer getMailsCount() {
return mailsCount;
}
/**
* @param mailsCount the mailsCount to set
*/
public void setMailsCount(Integer mailsCount) {
this.mailsCount = mailsCount;
}
/**
* @return the attaCount
*/
public Integer getAttaCount() {
return attaCount;
}
/**
* @param attaCount the attaCount to set
*/
public void setAttaCount(Integer attaCount) {
this.attaCount = attaCount;
}
/**
* @return the mailsTotal
*/
public Double getMailsTotal() {
return mailsTotal;
}
/**
* @param mailsTotal the mailsTotal to set
*/
public void setMailsTotal(Double mailsTotal) {
this.mailsTotal = mailsTotal;
}
/**
* @return the attaTotal
*/
public Double getAttaTotal() {
return attaTotal;
}
/**
* @param attaTotal the attaTotal to set
*/
public void setAttaTotal(Double attaTotal) {
this.attaTotal = attaTotal;
}
} | 6,512 | 0.631603 | 0.629914 | 317 | 18.548897 | 16.742294 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.343849 | false | false | 4 |
14fc3c5bdde434a0681280ae04dd1d2774763172 | 12,343,736,047,664 | 8ced32b21f1be9511c256cb8b589d7976b4b98d6 | /alanmall-service/order-service/order-provider/src/main/java/com/itcrazy/alanmall/order/context/AbsTransHandlerContext.java | fb3210d222c88e218adce6ef89b6cace1ab5f294 | [] | no_license | Yangliang266/Alanmall | https://github.com/Yangliang266/Alanmall | e5d1e57441790a481ae5aa75aa9d091909440281 | 38c2bde86dab6fd0277c87f99bc860bfc0fbdc0a | refs/heads/master | 2023-06-13T05:01:25.747000 | 2021-07-10T12:18:58 | 2021-07-10T12:18:58 | 293,702,057 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.itcrazy.alanmall.order.context;
import com.itcrazy.alanmall.order.conveter.CreateOrderConvert;
import com.itcrazy.alanmall.order.conveter.TransConverter;
public abstract class AbsTransHandlerContext implements TransHandlerContext{
private String orderId;
private TransConverter convert = new CreateOrderConvert();
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public TransConverter getConvert() {
return convert;
}
public void setConvert(TransConverter convert) {
this.convert = convert;
}
}
| UTF-8 | Java | 652 | java | AbsTransHandlerContext.java | Java | [] | null | [] | package com.itcrazy.alanmall.order.context;
import com.itcrazy.alanmall.order.conveter.CreateOrderConvert;
import com.itcrazy.alanmall.order.conveter.TransConverter;
public abstract class AbsTransHandlerContext implements TransHandlerContext{
private String orderId;
private TransConverter convert = new CreateOrderConvert();
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public TransConverter getConvert() {
return convert;
}
public void setConvert(TransConverter convert) {
this.convert = convert;
}
}
| 652 | 0.720859 | 0.720859 | 27 | 23.148148 | 23.791849 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 4 |
33993f57b4f3d47701e96a52474ffde73cbf8669 | 33,947,421,508,424 | b4d33bcdf781a8ba263cbeb6b24a1ef4d30ac938 | /src/main/java/com/mjl/controller/UserController.java | af618b0f067d9476fc7270f0f69bfb605fb2f778 | [] | no_license | alvin-mei/CloudNotes | https://github.com/alvin-mei/CloudNotes | 012a2e3c83289a3ad4745d208b3512c369f9597b | dafa0aa4f9cc817c805f10ca0d7fbaf0a6d0e88b | refs/heads/master | 2018-01-08T14:28:24.058000 | 2015-11-23T13:44:14 | 2015-11-23T13:44:14 | 45,039,471 | 6 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mjl.controller;
import com.mjl.Util.Constant;
import com.mjl.model.po.User;
import com.mjl.model.vo.ResultResponse;
import com.mjl.service.UserServiceI;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;
/**
* Created by Alvin on 15/10/29.
*/
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Resource
UserServiceI userServiceI;
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public ResultResponse userLogin(String userName,String userPassWord,HttpServletRequest request,HttpSession session){
Map<String,Object> result = userServiceI.login(userName,userPassWord);
if(result.get("status").equals(1)){
User dbuser = userServiceI.findUserByUserName(userName);
dbuser.setUserLastIp(request.getRemoteAddr());
dbuser.setUserLastLoginTime(new Timestamp(new Date().getTime()));
userServiceI.updateUserInfo(dbuser);
session.setAttribute("userName", dbuser.getUserName());
result.put("user", dbuser);
}
ResultResponse res = new ResultResponse((Integer) result.get("status"),(String)result.get("message"),result.get("user"));
System.out.println(res.toString());
return res;
}
@RequestMapping(value = "/register",method = RequestMethod.POST)
@ResponseBody
public ResultResponse register(User user) {
ResultResponse res = new ResultResponse();
String dbUserName = user.getUserName();
if(!userServiceI.checkUserName(dbUserName)){
res.setStatus(Constant.USER_REGISTER_ERROR);
res.setMessage("用户名已存在");
System.out.println("用户名存在");
return res;
}
userServiceI.createUser(user);
res.setStatus(Constant.USER_REGISTER_SUCCESS);
res.setMessage("恭喜你!注册成功");
return res;
}
@RequestMapping(value = "/logout" ,method = RequestMethod.POST)
@ResponseBody
public ResultResponse logout(HttpSession session){
session.invalidate();
return new ResultResponse(1,"退出成功",null);
}
@RequestMapping(value = "userInfo-{userName}",method = RequestMethod.GET)
@ResponseBody
public ResultResponse userInfo(@PathVariable String userName){
User dbuser = new User();
ResultResponse rs = new ResultResponse();
if(true == userServiceI.checkUserName(userName)){
dbuser = userServiceI.findUserByUserName(userName);
rs.setStatus(1);
rs.setMessage("查询成功");
rs.setData(dbuser);
return rs;
}
rs.setMessage("查询失败");
return rs;
}
}
| UTF-8 | Java | 3,183 | java | UserController.java | Java | [
{
"context": "til.Date;\nimport java.util.Map;\n\n/**\n * Created by Alvin on 15/10/29.\n */\n@Controller\n@RequestMapping(valu",
"end": 679,
"score": 0.984173595905304,
"start": 674,
"tag": "NAME",
"value": "Alvin"
}
] | null | [] | package com.mjl.controller;
import com.mjl.Util.Constant;
import com.mjl.model.po.User;
import com.mjl.model.vo.ResultResponse;
import com.mjl.service.UserServiceI;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;
/**
* Created by Alvin on 15/10/29.
*/
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Resource
UserServiceI userServiceI;
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public ResultResponse userLogin(String userName,String userPassWord,HttpServletRequest request,HttpSession session){
Map<String,Object> result = userServiceI.login(userName,userPassWord);
if(result.get("status").equals(1)){
User dbuser = userServiceI.findUserByUserName(userName);
dbuser.setUserLastIp(request.getRemoteAddr());
dbuser.setUserLastLoginTime(new Timestamp(new Date().getTime()));
userServiceI.updateUserInfo(dbuser);
session.setAttribute("userName", dbuser.getUserName());
result.put("user", dbuser);
}
ResultResponse res = new ResultResponse((Integer) result.get("status"),(String)result.get("message"),result.get("user"));
System.out.println(res.toString());
return res;
}
@RequestMapping(value = "/register",method = RequestMethod.POST)
@ResponseBody
public ResultResponse register(User user) {
ResultResponse res = new ResultResponse();
String dbUserName = user.getUserName();
if(!userServiceI.checkUserName(dbUserName)){
res.setStatus(Constant.USER_REGISTER_ERROR);
res.setMessage("用户名已存在");
System.out.println("用户名存在");
return res;
}
userServiceI.createUser(user);
res.setStatus(Constant.USER_REGISTER_SUCCESS);
res.setMessage("恭喜你!注册成功");
return res;
}
@RequestMapping(value = "/logout" ,method = RequestMethod.POST)
@ResponseBody
public ResultResponse logout(HttpSession session){
session.invalidate();
return new ResultResponse(1,"退出成功",null);
}
@RequestMapping(value = "userInfo-{userName}",method = RequestMethod.GET)
@ResponseBody
public ResultResponse userInfo(@PathVariable String userName){
User dbuser = new User();
ResultResponse rs = new ResultResponse();
if(true == userServiceI.checkUserName(userName)){
dbuser = userServiceI.findUserByUserName(userName);
rs.setStatus(1);
rs.setMessage("查询成功");
rs.setData(dbuser);
return rs;
}
rs.setMessage("查询失败");
return rs;
}
}
| 3,183 | 0.683317 | 0.680435 | 87 | 34.896553 | 26.13978 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.724138 | false | false | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.