blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 332 | content_id stringlengths 40 40 | detected_licenses listlengths 0 50 | license_type stringclasses 2
values | repo_name stringlengths 7 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 557
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 77.7k | fork_events_count int64 0 48k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 82
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 7 5.41M | extension stringclasses 11
values | content stringlengths 7 5.41M | authors listlengths 1 1 | author stringlengths 0 161 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ccfd4b64437c1665ca3b039759d86db1f8c91c31 | 885644d2cab48fa552330b9a9ae2dcf9ea5566e8 | /ApkTool/src/main/java/com/libs/brut/androlib/res/data/value/ResFractionValue.java | fdcbee85b1d6290fefa8d06e2c650ebeda5435a0 | [] | no_license | FynnHan/Support-Library | bdeeef08dfc41a360f05acb495b84e027ced3930 | 31d84cd67e51ac1fc078d93181a34c39823bd67a | refs/heads/master | 2021-01-11T00:12:26.226271 | 2016-10-24T09:51:59 | 2016-10-24T09:51:59 | 70,579,828 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 463 | java | package com.libs.brut.androlib.res.data.value;
import com.libs.android.util.TypedValue;
import com.libs.brut.androlib.AndrolibException;
public class ResFractionValue extends ResIntValue {
public ResFractionValue(int value, String rawValue) {
super(value, rawValue, "fraction");
}
@Override
protected String encodeAsResXml() throws AndrolibException {
return TypedValue.coerceToString(TypedValue.TYPE_FRACTION, mValue);
}
}
| [
"18330080926@163.com"
] | 18330080926@163.com |
444955bac3f5e6cf2b5534758cfd4ec419d7f7d8 | 9506a78860480e50c168daa6d5fa1b4fb04549ba | /APIStream/src/function/predicate/A_Predicate.java | 480c5477bd00a97f116ec3ba2c545f03306991c8 | [] | no_license | osimol/Java8 | f3bff1410d2af7102391f6f8ad3b62c4fcc6b142 | f260e0e9da9f4f5cc5b2dd590c5c442d7c6c05bb | refs/heads/master | 2020-03-28T12:27:45.620467 | 2018-09-21T11:42:09 | 2018-09-21T11:42:09 | 148,299,122 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,276 | java | package function.predicate;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.function.BiPredicate;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class A_Predicate {
public static void main(String[] args) {
Predicate<String> p1 = String::isEmpty;
Predicate<String> p2 = x -> x.isEmpty();
Predicate<Persona> predicadoVaron = Persona::getVaron;
System.out.println(p1.test(""));
System.out.println(p2.test(""));
Persona chico = new Persona("12345678A", "Pepe", "Perez", LocalDate.of(1990, 1, 2),"F");
System.out.printf("%s es varon? %b \n",chico.getNombre(),predicadoVaron.test(chico));
BiPredicate<String, String> b1 = String::startsWith;
BiPredicate<String, String> b2 = (string, prefix) -> string.startsWith(prefix);
System.out.println(b1.test("chicken", "a"));
System.out.println(b2.test("chicken", "chick"));
Predicate<String> nullCheck = arg -> arg != null;
Predicate<String> emptyCheck = arg -> arg.length() > 0;
Predicate<String> nullAndEmptyCheck = nullCheck.and(emptyCheck);
String helloStr = "hello";
System.out.println(helloStr + nullAndEmptyCheck.test(helloStr));
String nullStr = null;
System.out.println(nullStr + nullAndEmptyCheck.test(nullStr));
}
}
| [
"oiglesias@cic.es"
] | oiglesias@cic.es |
46fe351b2de67d136f6eb9364718bdf65e91e051 | 517d4258026e4d9e790481e301c76812c8e5b717 | /The-Open-Closed-Principle/java/src/main/java/com/theladders/solid/ocp/user/PhoneNumber.java | fb709a870577259881f3347a36b18989212a20ea | [] | no_license | pinakjain/solid-exercises | 78cce1ea97dc510353fa370d508b93316d37ad7a | 19fa12ebdb6214462bd5d7a51885ca2b8b988c85 | refs/heads/master | 2021-01-18T05:54:36.024301 | 2013-04-30T21:37:31 | 2013-04-30T21:37:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 285 | java | package com.theladders.solid.ocp.user;
import com.theladders.solid.ocp.resume.ConfidentialPhrase;
public class PhoneNumber extends ConfidentialPhrase {
private final String phoneNumber;
public PhoneNumber (String phoneNumber){
super();
this.phoneNumber = phoneNumber;
}
}
| [
"PJain@theladders.com"
] | PJain@theladders.com |
cd244b55de38b0a3a5bffd03bf319ccde53581ea | ffc9730979fc1b93577f3703da677d09f919dede | /src/p6/textbook/exercise/ex17/Printer.java | 7ff04d5f878c693cb24185a18f9e893f02ec8cdb | [] | no_license | cchm0024/java20210325 | d225d83112181206b9baf14dc3003c4442d40309 | f672a1fb6dd75d4db7bf32aafbe33fd446212b94 | refs/heads/master | 2023-06-16T15:01:26.963151 | 2021-07-13T00:44:34 | 2021-07-13T00:44:34 | 351,269,314 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 321 | java | package p6.textbook.exercise.ex17;
public class Printer {
static void println(int i) {
System.out.println(i);
}
static void println(boolean b) {
System.out.println(b);
}
static void println(double d) {
System.out.println(d);
}
static void println(String string) {
System.out.println(string);
}
}
| [
"cchm0024@naver.com"
] | cchm0024@naver.com |
32c7f1417eee49c0219e9a344e85ad245e2f2fd7 | 00ad96d67c03f0cb6d678fbdc6b561c451ea9b3c | /src/main/java/com/lcj/InParkingExample/MyInParkingDataEvent.java | 84f245c467e78e43d349fae009be932e53e284b6 | [] | no_license | gomton/disruptor-sample | ddd2f261f4d6bfadf184c7304ddd8e99c21059f5 | d149bb796130ad46be0f529e355194b4ea4e2b42 | refs/heads/master | 2020-05-07T21:44:34.508569 | 2019-04-21T06:08:20 | 2019-04-21T06:08:20 | 180,916,549 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 420 | java | package com.lcj.InParkingExample;
/**
代码包含以下内容:
1) 事件对象Event
2)三个消费者Handler
3)一个生产者Processer
4)执行Main方法
Event类:汽车信息
*/
public class MyInParkingDataEvent {
private String carLicense; // 车牌号
public String getCarLicense() {
return carLicense;
}
public void setCarLicense(String carLicense) {
this.carLicense = carLicense;
}
}
| [
"gomton@163.com"
] | gomton@163.com |
22a2f2efc4aeb298fb77a10574fd774609b2388f | bdd0fd4918d0e8dd70f25c7a3dca899570c91db3 | /mall-service/src/main/java/com/danlu/dmall/service/center/AreaHttpService.java | c5c6364aea1b198b67a6e10fbc9d9023e340e896 | [] | no_license | cz1986511/yfd | 0dba74745147f508d0db78d9c6dfaf158c4ea285 | 660de02653f06dd3334e658b1cbacb14c6314809 | refs/heads/master | 2021-08-31T16:24:18.607396 | 2017-12-22T02:22:58 | 2017-12-22T02:22:58 | 115,066,163 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,856 | java | package com.danlu.dmall.service.center;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import com.danlu.dlcommon.result.JsonResult;
import com.danlu.dlcommon.utils.CenterBase;
import com.danlu.dlhttpx.HttpService;
import com.danlu.dlpublic.dto.AreaDTO;
public class AreaHttpService extends HttpBaseService {
@Autowired
private HttpService httpService;
public List<AreaDTO> getAreaListByAmapCodeList(List<String> amapCodeList) {
List<AreaDTO> result = new ArrayList<AreaDTO>();
JsonResult<List<AreaDTO>> responseBody = null;
responseBody = this.postJson4Entity(this.getUrl("/public/V1/area_list/amap"),
this.getHttpHeaders(), amapCodeList,
new ParameterizedTypeReference<JsonResult<List<AreaDTO>>>() {
}, null);
if (null != responseBody) {
result = responseBody.getData();
}
return result;
}
public List<AreaDTO> getAreaListByParentCode(String areaParentCode) {
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("areaParentCode", areaParentCode);
JsonResult<List<AreaDTO>> result = this.getText4Entity(
this.getUrl("/public/V1/area_list/code"), this.getHttpHeaders(), paramMap,
new ParameterizedTypeReference<JsonResult<List<AreaDTO>>>() {
}, null);
if (null != result) {
return result.getData();
} else {
return null;
}
}
@Override
protected String getRootPath() {
return CenterBase.publicBase;
}
@Override
protected HttpService getHttpService() {
return this.httpService;
}
}
| [
"chenzhuo@danlu.com"
] | chenzhuo@danlu.com |
ee3503b81e0e18790204143fb66ac1f82b026333 | 9b5a364f534a319ba55c8757e2a6bf9271ddce6d | /src/main/java/kr/pku/leetcode/Lt2.java | 41754553fe3637f37edd49d633688dc9b9608b6b | [
"Apache-2.0"
] | permissive | kongrun/LeetCode | e001eb40560bd7fb01e783a304590d180eab4bef | ec95860ea57de4416e814ff573318e274ba22af4 | refs/heads/master | 2021-01-01T19:49:46.238257 | 2017-08-22T08:38:11 | 2017-08-22T08:38:11 | 98,702,020 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,740 | java | package kr.pku.leetcode;
/**
* Created by Administrator on 2017/7/31.
*/
public class Lt2 {
public static void main(String[] args)
{
ListNode l1 = new ListNode(5);
// l1.next = new ListNode(4);
ListNode tem = new ListNode(3);
// tem.next = null;
// l1.next.next = tem;
ListNode l2 = new ListNode(5);
// l2.next = new ListNode(6);
// tem = new ListNode(4);
// tem.next = null;
// l2.next.next = tem;
// l2.next.next.next = tem;
tem = addTwoNumbers(l1,l2);
while(tem != null)
{
System.out.print(tem.val);
tem = tem.next;
}
System.out.println("");
}
public static ListNode addTwoNumbers(ListNode l1,ListNode l2)
{
if(l1 == null || l2 == null)
throw new IllegalArgumentException("no two num solution");
ListNode l3 = null ,tem = null;
int flag = 0;int val1 = 0;int val2 = 0;
while(l1 != null || l2 != null)
{
val1 = val2 = 0;
if(l1 != null) {val1 = l1.val;l1 = l1.next;}
if(l2 != null) {val2 = l2.val;l2 = l2.next;}
int sum = flag + val1 + val2;
int val = sum % 10;
flag = sum / 10;
ListNode lt = new ListNode(val);
lt.next = null;
if(tem == null)
{
tem = lt;tem.next = null;
}
else tem.next = lt;
tem = lt;
if(l3 == null) l3 = tem;
}
if(flag > 0)
{
tem.next = new ListNode(flag);
}
return l3;
}
}
class ListNode{
int val;
ListNode next;
ListNode(int x){this.val = x;}
}
| [
"kongr15@pku.edu.cn"
] | kongr15@pku.edu.cn |
521688344b8b716d5459f6a7a047da5df1e9eb60 | db5e15c9bdf657799f67f024bb1b870f93400a58 | /bolt-extension/src/test/java/com/bolt/common/UrlTest.java | 07a5a5b003e6f21e18fa6953d35554908e2719bd | [] | no_license | maohua2013/hermes | ac00334cfa7c18569763552975f5c3b55bb7c218 | 5cd2fc32b6621ccf9d4f1e376afc876af7e8725c | refs/heads/master | 2023-03-17T06:27:10.294999 | 2020-05-15T10:37:14 | 2020-05-15T10:37:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,985 | java | package com.bolt.common;
import com.bolt.util.NetUtils;
import com.bolt.util.UrlUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: wangxw
* @DateTime: 2020/4/7
* @Description: TODO
*/
@RunWith(JUnit4.class)
public class UrlTest {
@Test
public void test_equals() {
InetSocketAddress socketAddress1 = new InetSocketAddress("127.0.0.1", 80);
InetSocketAddress socketAddress2 = new InetSocketAddress("127.0.0.1", 80);
Assert.assertEquals(socketAddress1, socketAddress2);
}
@Test
public void test_url_equals() {
Map<String, Object> option = new HashMap<String, Object>();
option.put(Url.SERIALIZATION, Constants.DEFAULT_REMOTING_SERIALIZATION);
Url urlA = Url.builder().port(80).host("123.0.0.1")
.setParameters(option).build();
Url urlB = Url.builder()
.port(80).host("123.0.0.1")
.setParameters(option).build();
option = new HashMap<String, Object>();
option.put(Url.MAX_CONNECTION, 10);
Url urlC = Url.builder()
.port(80).host("123.0.0.1")
.setParameters(option).build();
Assert.assertEquals(urlA, urlB);
Assert.assertNotEquals(urlA, urlC);
}
@Test
public void test_url_add() {
Map<String, Object> option = new HashMap<String, Object>();
option.put(Url.SERIALIZATION, "hessian2");
option.put(Url.MAX_CONNECTION, 10);
Url url = Url.builder()
.port(80).host("123.0.0.1")
.setParameters(option).build();
option = new HashMap<String, Object>();
option.put(Url.MAX_CONNECTION, 20);
url.addParameters(option);
System.out.println(url.toString());
}
@Test
public void test_url_parse() {
}
} | [
"os-wangxw@jsfund.cn"
] | os-wangxw@jsfund.cn |
8e0d500a8ebdc67665dac8726c5370bb74fd18f8 | 46dbc16ae018c094cf99f703f286330c3bb3e8b9 | /rest-gamma-app/src/main/java/com/rexen/rest/app/controller/tool/ToolGeneratorConsole.java | f5b39e7b6e4e738e7db9065398f89561c3c8bde4 | [] | no_license | liupengjie8/bdp-region | 28403699acdfc00f751a51e81ec477a49549b749 | e36ee1cbfb664443f9d41129b42b44709af6b19c | refs/heads/master | 2022-06-22T17:26:50.247220 | 2020-04-01T12:39:22 | 2020-04-01T12:39:22 | 248,727,822 | 0 | 0 | null | 2022-02-09T22:23:34 | 2020-03-20T10:26:58 | TSQL | UTF-8 | Java | false | false | 5,445 | java | package com.rexen.rest.app.controller.tool;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.rexen.rest.app.controller.AbstractController;
import com.rexen.rest.generator.InjectionConfig;
import com.rexen.rest.generator.RestGenerator;
import com.rexen.rest.generator.config.*;
import com.rexen.rest.generator.config.builder.ConfigBuilder;
import com.rexen.rest.generator.config.po.TableFill;
import com.rexen.rest.generator.config.rules.NamingStrategy;
import com.rexen.rest.generator.config.GlobalConfig;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* 代码生成工具类
*
* @author GavinHacker
*/
public class ToolGeneratorConsole {
public static void generateCode() {
String packageName = "com.rexen.rest";
boolean serviceNameStartWithI = false;
// 修改替换成你需要的表名,多个表名传数组
generateByTables(serviceNameStartWithI, packageName, "tool_generator_field_model", "tool_generator_table_model");
}
private static void generateByTables(boolean serviceNameStartWithI, String packageName, String... tableNames) {
GlobalConfig config = new GlobalConfig();
String dbUrl = "jdbc:mysql://172.17.2.194:3306/rest-gamma-bdp?useSSL=false&serverTimezone=GMT%2B8";
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig
//设置数据库类型
.setDbType(DbType.MYSQL)
//数据库链接地址
.setUrl(dbUrl)
//数据库链接用户名
.setUsername("root")
//数据库链接密码
.setPassword("Rexen123")
//数据库链接驱动
.setDriverName("com.mysql.cj.jdbc.Driver");
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig
//全局大写命名
.setCapitalMode(true)
//实体是否为lombok模型
.setEntityLombokModel(false)
//数据库列名下划线命名
//.setDbColumnUnderline(true)
//列名到属性名命名转换
.setNaming(NamingStrategy.underline_to_camel)
//包含表名
.setInclude(tableNames)
.setEntityLombokModel(true)
.setTableFillList(Arrays.asList(
new TableFill("create_time", FieldFill.INSERT),
new TableFill("update_time", FieldFill.INSERT_UPDATE),
new TableFill("create_by", FieldFill.INSERT),
new TableFill("update_by", FieldFill.INSERT_UPDATE)))
.setSuperControllerClass(AbstractController.class);
config.setActiveRecord(false)
//作者,修改为自己的名字
.setAuthor("GavinHacker")
//生成文件位置
.setOutputDir("/Users/gavin/data/code")
//XML 二级缓存
.setEnableCache(false)
//是否生成XML内的BaseResultMap
.setBaseResultMap(true)
//是否生成XML内的BaseColumnList
.setBaseColumnList(true)
//是否覆盖已有文件
.setFileOverride(true)
.setSwagger2(true);
if (!serviceNameStartWithI) {
config.setServiceName("%sService");
}
RestGenerator restGenerator = new RestGenerator().setGlobalConfig(config)
.setDataSource(dataSourceConfig)
.setStrategy(strategyConfig)
.setPackageInfo(
new PackageConfig()
//设置默认包名
.setParent(packageName)
.setController("app.controller")
.setEntity("model.entity")
.setService("service")
.setMapper("mapper")
.setServiceImpl("service.impl")
.setModuleName("tool")
)
.setTemplate(
new TemplateConfig().setEntity("/templates/restEntity.java")
.setController("/templates/restController.java")
)
.setCfg(new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<String,Object>(1);
map.put("FunctionName", "代码生成工具");
this.setMap(map);
}
});
restGenerator.setConfig(new ConfigBuilder(restGenerator.getPackageInfo(), restGenerator.getDataSource(), restGenerator.getStrategy(), restGenerator.getTemplate(), restGenerator.getGlobalConfig()));
if (null != restGenerator.getCfg()) {
restGenerator.getCfg().setConfig(restGenerator.getConfig());
}
restGenerator.execute();
}
private static void generateByTables(String packageName, String... tableNames) {
generateByTables(true, packageName, tableNames);
}
public static void main(String[] args) {
generateCode();
}
}
| [
"lpjmail@163.com"
] | lpjmail@163.com |
c35ec48c90bcfb131165f7aeb2083e241dc81883 | 716739e3a74b69f74fb1fec5e697dc094fb266c4 | /gtg-zuul-api-gateway-server/src/main/java/com/app/GtgZuulApiGatewayServerApplication.java | f4e9cd7d1d8d4b793594b30d88458cdde6d508e4 | [] | no_license | vishnuawasthi/gtg-micro-services | f12470c8d926345ff18976f94e1120d0cc040bbc | f56675d0029dcdefd9430aa7b62c742b806039cc | refs/heads/master | 2023-08-08T01:50:31.888763 | 2020-03-26T12:10:45 | 2020-03-26T12:10:45 | 241,016,839 | 0 | 0 | null | 2023-07-23T05:51:36 | 2020-02-17T04:09:55 | Java | UTF-8 | Java | false | false | 511 | java | package com.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy
public class GtgZuulApiGatewayServerApplication {
public static void main(String[] args) {
SpringApplication.run(GtgZuulApiGatewayServerApplication.class, args);
}
}
| [
"vishnuawasthi121@gmail.com"
] | vishnuawasthi121@gmail.com |
cddb4ca64379b50c873a9d7f4241686eb9a98b4a | 41c489a194120532959f8f21b98b5eceafd973e3 | /src/com/binarytree/CommonAncestorGivenNodes.java | f17d9b2aa1ba97b26e317ee5129070f6b9d82966 | [] | no_license | gobis/datastructure | 0639f438a61a774572b08eae65a799955a9dd8e7 | a1f719584040e6516c0034ecbabe0e8f022fb3b3 | refs/heads/master | 2021-03-26T10:27:17.328942 | 2017-12-12T14:43:33 | 2017-12-12T14:43:33 | 113,563,649 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,048 | java | package com.binarytree;
public class CommonAncestorGivenNodes {
// problem given binary search tree and find common ancestor
public static void main(String[] args) {
Node node1 = new Node(8,null,null);
Node node2 = new Node(12,null,null);
Node node3 = new Node(17,null,null);
Node node4 = new Node(19,null,null);
Node node5 = new Node(10,node2,node1);
Node node6 = new Node(18,node4,node3);
Node node7 = new Node(15,node6,node5);
Node node8 = new Node(22,null,null);
Node node9 = new Node(20,node8,node7);
Node head = node9;
Node lca = null;
lca = LowestCommonAncestorWORecur(head,8,17);
// lca = LowestCommonAncestor(head,8,17);
System.out.println(lca.val);
}
private static Node LowestCommonAncestor(Node head,int val1, int val2){
if(head == null) return head;
if(head.val > val1 && head.val > val2){
return LowestCommonAncestor(head.left,val1,val2);
}
if(head.val < val1 && head.val < val2){
return LowestCommonAncestor(head.right,val1,val2);
}
return head;
}
private static Node LowestCommonAncestorForBinaryTree(Node head,int val1, int val2){
if(head == null) return head;
if(head.val == val1 || head.val == val2) return head;
Node left = LowestCommonAncestorForBinaryTree(head.left,val1,val2);
Node right = LowestCommonAncestorForBinaryTree(head.right,val1,val2);
if(left != null && right != null) return head;
if(left == null && right == null) return null;
if(left != null) return left;
if(right != null) return right;
return head;
}
private static Node LowestCommonAncestorWORecur(Node head, int val1, int val2) {
boolean breakloop;
while (head != null) {
breakloop = true;
if (head.val > val1 && head.val > val2) {
if(head.left != null)
head = head.left;
breakloop = false;
}
if (head.val < val1 && head.val < val2) {
if(head.right != null)
head = head.right;
breakloop = false;
}
if(breakloop)break;
}
return head;
}
}
| [
"gobi.subramani@gmail.com"
] | gobi.subramani@gmail.com |
7ccc6ae94c25e7b785f3b49fd6b9f0cdd7ef4dc7 | 32f38cd53372ba374c6dab6cc27af78f0a1b0190 | /app/src/main/java/com/uc/webview/export/internal/setup/a.java | 6264be6511e7fe582c112e129ca8e0deaba719f7 | [] | no_license | shuixi2013/AmapCode | 9ea7aefb42e0413f348f238f0721c93245f4eac6 | 1a3a8d4dddfcc5439df8df570000cca12b15186a | refs/heads/master | 2023-06-06T23:08:57.391040 | 2019-08-29T04:36:02 | 2019-08-29T04:36:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 30,924 | java | package com.uc.webview.export.internal.setup;
import android.webkit.ValueCallback;
/* compiled from: ProGuard */
final class a implements ValueCallback<t> {
final /* synthetic */ BrowserSetupTask a;
a(BrowserSetupTask browserSetupTask) {
this.a = browserSetupTask;
}
/* JADX WARNING: Can't wrap try/catch for region: R(46:2|3|(3:5|(1:7)(1:8)|9)|10|11|12|(1:14)(1:15)|16|17|18|19|20|21|22|(1:24)(2:25|(1:27)(1:28))|31|32|(1:34)(1:35)|36|(1:38)(1:39)|40|(1:42)(1:43)|44|(1:46)(1:47)|48|49|51|52|53|54|55|56|(1:64)(1:63)|65|(3:67|(1:69)(1:70)|71)|(3:73|(1:75)(1:76)|77)|(1:79)|80|81|82|83|(1:85)|86|88|89|(3:91|92|93)) */
/* JADX WARNING: Failed to process nested try/catch */
/* JADX WARNING: Missing exception handler attribute for start block: B:17:0x00b5 */
/* JADX WARNING: Missing exception handler attribute for start block: B:19:0x00c4 */
/* JADX WARNING: Missing exception handler attribute for start block: B:53:0x01c0 */
/* JADX WARNING: Missing exception handler attribute for start block: B:55:0x01cd */
/* JADX WARNING: Missing exception handler attribute for start block: B:80:0x0256 */
/* JADX WARNING: Missing exception handler attribute for start block: B:82:0x028a */
/* JADX WARNING: Removed duplicated region for block: B:24:0x00da A[Catch:{ Throwable -> 0x00ef }] */
/* JADX WARNING: Removed duplicated region for block: B:25:0x00dd A[Catch:{ Throwable -> 0x00ef }] */
/* JADX WARNING: Removed duplicated region for block: B:34:0x011e A[Catch:{ Throwable -> 0x01b5 }] */
/* JADX WARNING: Removed duplicated region for block: B:35:0x0121 A[Catch:{ Throwable -> 0x01b5 }] */
/* JADX WARNING: Removed duplicated region for block: B:38:0x013f A[Catch:{ Throwable -> 0x01b5 }] */
/* JADX WARNING: Removed duplicated region for block: B:39:0x0142 A[Catch:{ Throwable -> 0x01b5 }] */
/* JADX WARNING: Removed duplicated region for block: B:42:0x0152 A[Catch:{ Throwable -> 0x01b5 }] */
/* JADX WARNING: Removed duplicated region for block: B:43:0x0155 A[Catch:{ Throwable -> 0x01b5 }] */
/* JADX WARNING: Removed duplicated region for block: B:46:0x019e A[Catch:{ Throwable -> 0x01b5 }] */
/* JADX WARNING: Removed duplicated region for block: B:47:0x01a1 A[Catch:{ Throwable -> 0x01b5 }] */
/* JADX WARNING: Removed duplicated region for block: B:58:0x01d9 A[Catch:{ Throwable -> 0x0256 }] */
/* JADX WARNING: Removed duplicated region for block: B:67:0x01f8 A[Catch:{ Throwable -> 0x0256 }] */
/* JADX WARNING: Removed duplicated region for block: B:73:0x0219 A[Catch:{ Throwable -> 0x0256 }] */
/* JADX WARNING: Removed duplicated region for block: B:79:0x0235 A[Catch:{ Throwable -> 0x0256 }] */
/* JADX WARNING: Removed duplicated region for block: B:85:0x0292 A[Catch:{ Throwable -> 0x02cd }] */
/* JADX WARNING: Removed duplicated region for block: B:91:0x02dd */
/* Code decompiled incorrectly, please refer to instructions dump. */
public final /* synthetic */ void onReceiveValue(java.lang.Object r19) {
/*
r18 = this;
r1 = r18
r2 = r19
com.uc.webview.export.internal.setup.t r2 = (com.uc.webview.export.internal.setup.t) r2
com.uc.webview.export.internal.setup.UCMRunningInfo r3 = r2.getLoadedUCM()
r4 = 1
r5 = 0
if (r3 == 0) goto L_0x031e
com.uc.webview.export.internal.setup.UCMRunningInfo r2 = r2.getLoadedUCM() // Catch:{ Throwable -> 0x030f }
com.uc.webview.export.internal.setup.BrowserSetupTask r3 = r1.a // Catch:{ Throwable -> 0x030f }
r3.setLoadedUCM(r2) // Catch:{ Throwable -> 0x030f }
com.uc.webview.export.internal.setup.BrowserSetupTask r3 = r1.a // Catch:{ Throwable -> 0x030f }
r3.setTotalLoadedUCM(r2) // Catch:{ Throwable -> 0x030f }
int r3 = r2.loadType // Catch:{ Throwable -> 0x030f }
com.uc.webview.export.internal.SDKFactory.o = r3 // Catch:{ Throwable -> 0x030f }
java.lang.String r3 = "d"
java.lang.String r6 = "BrowserSetupTask"
com.uc.webview.export.cyclone.UCLogger r3 = com.uc.webview.export.cyclone.UCLogger.create(r3, r6) // Catch:{ Throwable -> 0x030f }
r6 = 2
if (r3 == 0) goto L_0x0065
java.lang.String r7 = "mSuccessCB: dataDir is [%s] core type: [%d] isShareCore{%b}."
r8 = 3
java.lang.Object[] r8 = new java.lang.Object[r8] // Catch:{ Throwable -> 0x030f }
com.uc.webview.export.internal.setup.UCMRunningInfo r9 = com.uc.webview.export.internal.setup.UCSetupTask.getTotalLoadedUCM() // Catch:{ Throwable -> 0x030f }
com.uc.webview.export.internal.setup.UCMPackageInfo r9 = r9.ucmPackageInfo // Catch:{ Throwable -> 0x030f }
if (r9 == 0) goto L_0x0041
com.uc.webview.export.internal.setup.UCMRunningInfo r9 = com.uc.webview.export.internal.setup.UCSetupTask.getTotalLoadedUCM() // Catch:{ Throwable -> 0x030f }
com.uc.webview.export.internal.setup.UCMPackageInfo r9 = r9.ucmPackageInfo // Catch:{ Throwable -> 0x030f }
java.lang.String r9 = r9.dataDir // Catch:{ Throwable -> 0x030f }
goto L_0x0042
L_0x0041:
r9 = 0
L_0x0042:
r8[r5] = r9 // Catch:{ Throwable -> 0x030f }
com.uc.webview.export.internal.setup.UCMRunningInfo r9 = com.uc.webview.export.internal.setup.UCSetupTask.getTotalLoadedUCM() // Catch:{ Throwable -> 0x030f }
int r9 = r9.coreType // Catch:{ Throwable -> 0x030f }
java.lang.Integer r9 = java.lang.Integer.valueOf(r9) // Catch:{ Throwable -> 0x030f }
r8[r4] = r9 // Catch:{ Throwable -> 0x030f }
com.uc.webview.export.internal.setup.UCMRunningInfo r9 = com.uc.webview.export.internal.setup.UCSetupTask.getTotalLoadedUCM() // Catch:{ Throwable -> 0x030f }
boolean r9 = r9.isShareCore // Catch:{ Throwable -> 0x030f }
java.lang.Boolean r9 = java.lang.Boolean.valueOf(r9) // Catch:{ Throwable -> 0x030f }
r8[r6] = r9 // Catch:{ Throwable -> 0x030f }
java.lang.String r7 = java.lang.String.format(r7, r8) // Catch:{ Throwable -> 0x030f }
java.lang.Throwable[] r8 = new java.lang.Throwable[r5] // Catch:{ Throwable -> 0x030f }
r3.print(r7, r8) // Catch:{ Throwable -> 0x030f }
L_0x0065:
r7 = 10001(0x2711, float:1.4014E-41)
com.uc.webview.export.internal.setup.p r8 = new com.uc.webview.export.internal.setup.p // Catch:{ Throwable -> 0x00b5 }
r8.<init>() // Catch:{ Throwable -> 0x00b5 }
java.lang.Object[] r9 = new java.lang.Object[r4] // Catch:{ Throwable -> 0x00b5 }
com.uc.webview.export.internal.setup.UCAsyncTask r10 = com.uc.webview.export.utility.SetupTask.getRoot() // Catch:{ Throwable -> 0x00b5 }
r9[r5] = r10 // Catch:{ Throwable -> 0x00b5 }
com.uc.webview.export.internal.setup.UCAsyncTask r8 = r8.invoke(r7, r9) // Catch:{ Throwable -> 0x00b5 }
com.uc.webview.export.internal.setup.p r8 = (com.uc.webview.export.internal.setup.p) r8 // Catch:{ Throwable -> 0x00b5 }
com.uc.webview.export.internal.setup.BrowserSetupTask r9 = r1.a // Catch:{ Throwable -> 0x00b5 }
java.util.concurrent.ConcurrentHashMap r9 = r9.mOptions // Catch:{ Throwable -> 0x00b5 }
com.uc.webview.export.internal.setup.UCSubSetupTask r8 = r8.setOptions(r9) // Catch:{ Throwable -> 0x00b5 }
com.uc.webview.export.internal.setup.p r8 = (com.uc.webview.export.internal.setup.p) r8 // Catch:{ Throwable -> 0x00b5 }
java.lang.String r9 = "del_dec_fil"
com.uc.webview.export.internal.setup.BrowserSetupTask r10 = r1.a // Catch:{ Throwable -> 0x00b5 }
java.io.File r10 = r10.e // Catch:{ Throwable -> 0x00b5 }
if (r10 != 0) goto L_0x0090
r10 = 1
goto L_0x0091
L_0x0090:
r10 = 0
L_0x0091:
java.lang.Boolean r10 = java.lang.Boolean.valueOf(r10) // Catch:{ Throwable -> 0x00b5 }
com.uc.webview.export.internal.setup.UCSubSetupTask r8 = r8.setup(r9, r10) // Catch:{ Throwable -> 0x00b5 }
com.uc.webview.export.internal.setup.p r8 = (com.uc.webview.export.internal.setup.p) r8 // Catch:{ Throwable -> 0x00b5 }
java.lang.String r9 = "del_upd_fil"
java.lang.Boolean r10 = java.lang.Boolean.TRUE // Catch:{ Throwable -> 0x00b5 }
com.uc.webview.export.internal.setup.UCSubSetupTask r8 = r8.setup(r9, r10) // Catch:{ Throwable -> 0x00b5 }
com.uc.webview.export.internal.setup.p r8 = (com.uc.webview.export.internal.setup.p) r8 // Catch:{ Throwable -> 0x00b5 }
java.lang.String r9 = "die"
com.uc.webview.export.internal.setup.b r10 = new com.uc.webview.export.internal.setup.b // Catch:{ Throwable -> 0x00b5 }
r10.<init>(r1) // Catch:{ Throwable -> 0x00b5 }
com.uc.webview.export.internal.setup.UCAsyncTask r8 = r8.onEvent(r9, r10) // Catch:{ Throwable -> 0x00b5 }
com.uc.webview.export.internal.setup.p r8 = (com.uc.webview.export.internal.setup.p) r8 // Catch:{ Throwable -> 0x00b5 }
r8.start() // Catch:{ Throwable -> 0x00b5 }
L_0x00b5:
com.uc.webview.export.internal.setup.BrowserSetupTask r8 = r1.a // Catch:{ Throwable -> 0x00c4 }
com.uc.webview.export.internal.setup.UCMRunningInfo r9 = com.uc.webview.export.internal.setup.UCSetupTask.getTotalLoadedUCM() // Catch:{ Throwable -> 0x00c4 }
int r9 = r9.coreType // Catch:{ Throwable -> 0x00c4 }
java.lang.String r9 = java.lang.String.valueOf(r9) // Catch:{ Throwable -> 0x00c4 }
r8.callbackFinishStat(r9) // Catch:{ Throwable -> 0x00c4 }
L_0x00c4:
com.uc.webview.export.internal.setup.BrowserSetupTask r8 = r1.a // Catch:{ Throwable -> 0x01b5 }
java.lang.String r9 = "setup_priority"
java.lang.Object r8 = r8.getOption(r9) // Catch:{ Throwable -> 0x01b5 }
java.lang.Integer r8 = (java.lang.Integer) r8 // Catch:{ Throwable -> 0x01b5 }
com.uc.webview.export.internal.setup.BrowserSetupTask r9 = r1.a // Catch:{ Throwable -> 0x00ef }
java.lang.String r10 = "dlChecker"
java.lang.Object r9 = r9.getOption(r10) // Catch:{ Throwable -> 0x00ef }
java.util.concurrent.Callable r9 = (java.util.concurrent.Callable) r9 // Catch:{ Throwable -> 0x00ef }
if (r9 != 0) goto L_0x00dd
java.lang.String r9 = "N"
goto L_0x00f1
L_0x00dd:
java.lang.Object r9 = r9.call() // Catch:{ Throwable -> 0x00ef }
java.lang.Boolean r9 = (java.lang.Boolean) r9 // Catch:{ Throwable -> 0x00ef }
boolean r9 = r9.booleanValue() // Catch:{ Throwable -> 0x00ef }
if (r9 == 0) goto L_0x00ec
java.lang.String r9 = "T"
goto L_0x00f1
L_0x00ec:
java.lang.String r9 = "F"
goto L_0x00f1
L_0x00ef:
java.lang.String r9 = "E"
L_0x00f1:
com.uc.webview.export.internal.setup.BrowserSetupTask r10 = r1.a // Catch:{ Throwable -> 0x01b5 }
android.util.Pair r11 = new android.util.Pair // Catch:{ Throwable -> 0x01b5 }
java.lang.String r12 = "sdk_stp_suc"
com.uc.webview.export.cyclone.UCHashMap r13 = new com.uc.webview.export.cyclone.UCHashMap // Catch:{ Throwable -> 0x01b5 }
r13.<init>() // Catch:{ Throwable -> 0x01b5 }
java.lang.String r14 = "cnt"
java.lang.String r15 = "1"
com.uc.webview.export.cyclone.UCHashMap r13 = r13.set(r14, r15) // Catch:{ Throwable -> 0x01b5 }
java.lang.String r14 = "code"
com.uc.webview.export.internal.setup.UCMRunningInfo r15 = com.uc.webview.export.internal.setup.UCSetupTask.getTotalLoadedUCM() // Catch:{ Throwable -> 0x01b5 }
int r15 = r15.coreType // Catch:{ Throwable -> 0x01b5 }
java.lang.String r15 = java.lang.String.valueOf(r15) // Catch:{ Throwable -> 0x01b5 }
com.uc.webview.export.cyclone.UCHashMap r13 = r13.set(r14, r15) // Catch:{ Throwable -> 0x01b5 }
java.lang.String r14 = "dir"
com.uc.webview.export.internal.setup.UCMRunningInfo r15 = com.uc.webview.export.internal.setup.UCSetupTask.getTotalLoadedUCM() // Catch:{ Throwable -> 0x01b5 }
com.uc.webview.export.internal.setup.UCMPackageInfo r15 = r15.ucmPackageInfo // Catch:{ Throwable -> 0x01b5 }
if (r15 != 0) goto L_0x0121
java.lang.String r15 = "null"
goto L_0x0131
L_0x0121:
com.uc.webview.export.internal.setup.UCMRunningInfo r15 = com.uc.webview.export.internal.setup.UCSetupTask.getTotalLoadedUCM() // Catch:{ Throwable -> 0x01b5 }
com.uc.webview.export.internal.setup.UCMPackageInfo r15 = r15.ucmPackageInfo // Catch:{ Throwable -> 0x01b5 }
com.uc.webview.export.internal.setup.BrowserSetupTask r7 = r1.a // Catch:{ Throwable -> 0x01b5 }
android.content.Context r7 = r7.d // Catch:{ Throwable -> 0x01b5 }
java.lang.String r15 = r15.getDirAlias(r7) // Catch:{ Throwable -> 0x01b5 }
L_0x0131:
com.uc.webview.export.cyclone.UCHashMap r7 = r13.set(r14, r15) // Catch:{ Throwable -> 0x01b5 }
java.lang.String r13 = "old"
com.uc.webview.export.internal.setup.UCMRunningInfo r14 = com.uc.webview.export.internal.setup.UCSetupTask.getTotalLoadedUCM() // Catch:{ Throwable -> 0x01b5 }
boolean r14 = r14.isOldExtraKernel // Catch:{ Throwable -> 0x01b5 }
if (r14 == 0) goto L_0x0142
java.lang.String r14 = "T"
goto L_0x0144
L_0x0142:
java.lang.String r14 = "F"
L_0x0144:
com.uc.webview.export.cyclone.UCHashMap r7 = r7.set(r13, r14) // Catch:{ Throwable -> 0x01b5 }
java.lang.String r13 = "frun"
com.uc.webview.export.internal.setup.UCMRunningInfo r14 = com.uc.webview.export.internal.setup.UCSetupTask.getTotalLoadedUCM() // Catch:{ Throwable -> 0x01b5 }
boolean r14 = r14.isFirstTimeOdex // Catch:{ Throwable -> 0x01b5 }
if (r14 == 0) goto L_0x0155
java.lang.String r14 = "T"
goto L_0x0157
L_0x0155:
java.lang.String r14 = "F"
L_0x0157:
com.uc.webview.export.cyclone.UCHashMap r7 = r7.set(r13, r14) // Catch:{ Throwable -> 0x01b5 }
java.lang.String r13 = "cpu_cnt"
java.lang.String r14 = com.uc.webview.export.internal.utility.j.a() // Catch:{ Throwable -> 0x01b5 }
com.uc.webview.export.cyclone.UCHashMap r7 = r7.set(r13, r14) // Catch:{ Throwable -> 0x01b5 }
java.lang.String r13 = "cpu_freq"
java.lang.String r14 = com.uc.webview.export.internal.utility.j.b() // Catch:{ Throwable -> 0x01b5 }
com.uc.webview.export.cyclone.UCHashMap r7 = r7.set(r13, r14) // Catch:{ Throwable -> 0x01b5 }
java.lang.String r13 = "cost_cpu"
long r14 = android.os.SystemClock.currentThreadTimeMillis() // Catch:{ Throwable -> 0x01b5 }
com.uc.webview.export.internal.setup.BrowserSetupTask r6 = r1.a // Catch:{ Throwable -> 0x01b5 }
long r16 = r6.g // Catch:{ Throwable -> 0x01b5 }
r6 = 0
long r14 = r14 - r16
java.lang.String r6 = java.lang.String.valueOf(r14) // Catch:{ Throwable -> 0x01b5 }
com.uc.webview.export.cyclone.UCHashMap r6 = r7.set(r13, r6) // Catch:{ Throwable -> 0x01b5 }
java.lang.String r7 = "cost"
com.uc.webview.export.internal.setup.BrowserSetupTask r13 = r1.a // Catch:{ Throwable -> 0x01b5 }
com.uc.webview.export.cyclone.UCElapseTime r13 = r13.f // Catch:{ Throwable -> 0x01b5 }
long r13 = r13.getMilis() // Catch:{ Throwable -> 0x01b5 }
java.lang.String r13 = java.lang.String.valueOf(r13) // Catch:{ Throwable -> 0x01b5 }
com.uc.webview.export.cyclone.UCHashMap r6 = r6.set(r7, r13) // Catch:{ Throwable -> 0x01b5 }
java.lang.String r7 = "pri"
if (r8 != 0) goto L_0x01a1
java.lang.String r8 = "n"
goto L_0x01a5
L_0x01a1:
java.lang.String r8 = java.lang.String.valueOf(r8) // Catch:{ Throwable -> 0x01b5 }
L_0x01a5:
com.uc.webview.export.cyclone.UCHashMap r6 = r6.set(r7, r8) // Catch:{ Throwable -> 0x01b5 }
java.lang.String r7 = "wifi"
com.uc.webview.export.cyclone.UCHashMap r6 = r6.set(r7, r9) // Catch:{ Throwable -> 0x01b5 }
r11.<init>(r12, r6) // Catch:{ Throwable -> 0x01b5 }
r10.callbackStat(r11) // Catch:{ Throwable -> 0x01b5 }
L_0x01b5:
r6 = 10041(0x2739, float:1.407E-41)
java.lang.Object[] r7 = new java.lang.Object[r4] // Catch:{ Throwable -> 0x01c0 }
java.lang.ClassLoader r2 = r2.shellClassLoader // Catch:{ Throwable -> 0x01c0 }
r7[r5] = r2 // Catch:{ Throwable -> 0x01c0 }
com.uc.webview.export.internal.setup.UCMPackageInfo.invoke(r6, r7) // Catch:{ Throwable -> 0x01c0 }
L_0x01c0:
com.uc.webview.export.internal.setup.BrowserSetupTask r2 = r1.a // Catch:{ Throwable -> 0x01cd }
java.lang.String r6 = "load_share_core_host"
java.lang.Object r2 = r2.getOption(r6) // Catch:{ Throwable -> 0x01cd }
java.lang.String r2 = (java.lang.String) r2 // Catch:{ Throwable -> 0x01cd }
com.uc.webview.export.internal.utility.g.a(r2) // Catch:{ Throwable -> 0x01cd }
L_0x01cd:
com.uc.webview.export.internal.setup.BrowserSetupTask r2 = r1.a // Catch:{ Throwable -> 0x0256 }
java.lang.String r6 = "vmsize_saving"
java.lang.Object r2 = r2.getOption(r6) // Catch:{ Throwable -> 0x0256 }
java.lang.Boolean r2 = (java.lang.Boolean) r2 // Catch:{ Throwable -> 0x0256 }
if (r2 != 0) goto L_0x01e3
double r6 = java.lang.Math.random() // Catch:{ Throwable -> 0x0256 }
r8 = 4602678819172646912(0x3fe0000000000000, double:0.5)
int r6 = (r6 > r8 ? 1 : (r6 == r8 ? 0 : -1))
if (r6 > 0) goto L_0x01eb
L_0x01e3:
if (r2 == 0) goto L_0x01ed
boolean r2 = r2.booleanValue() // Catch:{ Throwable -> 0x0256 }
if (r2 == 0) goto L_0x01ed
L_0x01eb:
r2 = 1
goto L_0x01ee
L_0x01ed:
r2 = 0
L_0x01ee:
java.lang.String r6 = "com.uc.crashsdk.export.CrashApi"
java.lang.String r7 = "getInstance"
java.lang.Object r6 = com.uc.webview.export.internal.utility.ReflectionUtil.invokeNoThrow(r6, r7) // Catch:{ Throwable -> 0x0256 }
if (r6 == 0) goto L_0x0217
java.lang.String r7 = "addHeaderInfo"
r8 = 2
java.lang.Class[] r9 = new java.lang.Class[r8] // Catch:{ Throwable -> 0x0256 }
java.lang.Class<java.lang.String> r10 = java.lang.String.class
r9[r5] = r10 // Catch:{ Throwable -> 0x0256 }
java.lang.Class<java.lang.String> r10 = java.lang.String.class
r9[r4] = r10 // Catch:{ Throwable -> 0x0256 }
java.lang.Object[] r10 = new java.lang.Object[r8] // Catch:{ Throwable -> 0x0256 }
java.lang.String r8 = "vmsize_saving_enable"
r10[r5] = r8 // Catch:{ Throwable -> 0x0256 }
if (r2 == 0) goto L_0x0210
java.lang.String r8 = "true"
goto L_0x0212
L_0x0210:
java.lang.String r8 = "false"
L_0x0212:
r10[r4] = r8 // Catch:{ Throwable -> 0x0256 }
com.uc.webview.export.internal.utility.ReflectionUtil.invokeNoThrow(r6, r7, r9, r10) // Catch:{ Throwable -> 0x0256 }
L_0x0217:
if (r3 == 0) goto L_0x0233
java.lang.StringBuilder r6 = new java.lang.StringBuilder // Catch:{ Throwable -> 0x0256 }
java.lang.String r7 = "mSuccessCB: vmsize_saving_enable="
r6.<init>(r7) // Catch:{ Throwable -> 0x0256 }
if (r2 == 0) goto L_0x0225
java.lang.String r7 = "true"
goto L_0x0227
L_0x0225:
java.lang.String r7 = "false"
L_0x0227:
r6.append(r7) // Catch:{ Throwable -> 0x0256 }
java.lang.String r6 = r6.toString() // Catch:{ Throwable -> 0x0256 }
java.lang.Throwable[] r7 = new java.lang.Throwable[r5] // Catch:{ Throwable -> 0x0256 }
r3.print(r6, r7) // Catch:{ Throwable -> 0x0256 }
L_0x0233:
if (r2 == 0) goto L_0x0256
com.uc.webview.export.internal.setup.UCAsyncTask r2 = new com.uc.webview.export.internal.setup.UCAsyncTask // Catch:{ Throwable -> 0x0256 }
com.uc.webview.export.cyclone.UCVmsize r3 = new com.uc.webview.export.cyclone.UCVmsize // Catch:{ Throwable -> 0x0256 }
com.uc.webview.export.internal.setup.BrowserSetupTask r6 = r1.a // Catch:{ Throwable -> 0x0256 }
android.content.Context r6 = r6.d // Catch:{ Throwable -> 0x0256 }
r3.<init>(r6) // Catch:{ Throwable -> 0x0256 }
r2.<init>(r3) // Catch:{ Throwable -> 0x0256 }
java.lang.Object[] r3 = new java.lang.Object[r4] // Catch:{ Throwable -> 0x0256 }
com.uc.webview.export.internal.setup.UCAsyncTask r6 = com.uc.webview.export.utility.SetupTask.getRoot() // Catch:{ Throwable -> 0x0256 }
r3[r5] = r6 // Catch:{ Throwable -> 0x0256 }
r6 = 10001(0x2711, float:1.4014E-41)
com.uc.webview.export.internal.setup.UCAsyncTask r2 = r2.invoke(r6, r3) // Catch:{ Throwable -> 0x0256 }
r2.start() // Catch:{ Throwable -> 0x0256 }
L_0x0256:
com.uc.webview.export.internal.setup.ay r2 = new com.uc.webview.export.internal.setup.ay // Catch:{ Throwable -> 0x028a }
r2.<init>() // Catch:{ Throwable -> 0x028a }
java.lang.Object[] r3 = new java.lang.Object[r4] // Catch:{ Throwable -> 0x028a }
com.uc.webview.export.internal.setup.UCAsyncTask r6 = com.uc.webview.export.utility.SetupTask.getRoot() // Catch:{ Throwable -> 0x028a }
r3[r5] = r6 // Catch:{ Throwable -> 0x028a }
r6 = 10001(0x2711, float:1.4014E-41)
com.uc.webview.export.internal.setup.UCAsyncTask r2 = r2.invoke(r6, r3) // Catch:{ Throwable -> 0x028a }
com.uc.webview.export.internal.setup.ay r2 = (com.uc.webview.export.internal.setup.ay) r2 // Catch:{ Throwable -> 0x028a }
com.uc.webview.export.internal.setup.BrowserSetupTask r3 = r1.a // Catch:{ Throwable -> 0x028a }
java.util.concurrent.ConcurrentHashMap r3 = r3.mOptions // Catch:{ Throwable -> 0x028a }
com.uc.webview.export.internal.setup.UCSubSetupTask r2 = r2.setOptions(r3) // Catch:{ Throwable -> 0x028a }
com.uc.webview.export.internal.setup.ay r2 = (com.uc.webview.export.internal.setup.ay) r2 // Catch:{ Throwable -> 0x028a }
java.lang.String r3 = "stat"
com.uc.webview.export.internal.setup.UCSubSetupTask$a r6 = new com.uc.webview.export.internal.setup.UCSubSetupTask$a // Catch:{ Throwable -> 0x028a }
com.uc.webview.export.internal.setup.BrowserSetupTask r7 = r1.a // Catch:{ Throwable -> 0x028a }
r7.getClass() // Catch:{ Throwable -> 0x028a }
r6.<init>() // Catch:{ Throwable -> 0x028a }
com.uc.webview.export.internal.setup.UCAsyncTask r2 = r2.onEvent(r3, r6) // Catch:{ Throwable -> 0x028a }
com.uc.webview.export.internal.setup.ay r2 = (com.uc.webview.export.internal.setup.ay) r2 // Catch:{ Throwable -> 0x028a }
r2.start() // Catch:{ Throwable -> 0x028a }
L_0x028a:
com.uc.webview.export.internal.setup.BrowserSetupTask r2 = r1.a // Catch:{ Throwable -> 0x02cd }
com.uc.webview.export.internal.setup.t r2 = r2.c // Catch:{ Throwable -> 0x02cd }
if (r2 == 0) goto L_0x02cd
com.uc.webview.export.internal.setup.BrowserSetupTask r2 = r1.a // Catch:{ Throwable -> 0x02cd }
com.uc.webview.export.internal.setup.t r2 = r2.c // Catch:{ Throwable -> 0x02cd }
java.lang.Object[] r3 = new java.lang.Object[r4] // Catch:{ Throwable -> 0x02cd }
com.uc.webview.export.internal.setup.UCAsyncTask r6 = com.uc.webview.export.internal.setup.UCSetupTask.getRoot() // Catch:{ Throwable -> 0x02cd }
r3[r5] = r6 // Catch:{ Throwable -> 0x02cd }
r6 = 10001(0x2711, float:1.4014E-41)
com.uc.webview.export.internal.setup.UCAsyncTask r2 = r2.invoke(r6, r3) // Catch:{ Throwable -> 0x02cd }
com.uc.webview.export.internal.setup.t r2 = (com.uc.webview.export.internal.setup.t) r2 // Catch:{ Throwable -> 0x02cd }
r6 = 5000(0x1388, double:2.4703E-320)
r2.start(r6) // Catch:{ Throwable -> 0x02cd }
com.uc.webview.export.internal.setup.BrowserSetupTask r2 = r1.a // Catch:{ Throwable -> 0x02cd }
r2.c = null // Catch:{ Throwable -> 0x02cd }
com.uc.webview.export.internal.setup.UCAsyncTask r2 = new com.uc.webview.export.internal.setup.UCAsyncTask // Catch:{ Throwable -> 0x02cd }
com.uc.webview.export.cyclone.UCDex r3 = new com.uc.webview.export.cyclone.UCDex // Catch:{ Throwable -> 0x02cd }
r3.<init>() // Catch:{ Throwable -> 0x02cd }
r2.<init>(r3) // Catch:{ Throwable -> 0x02cd }
java.lang.Object[] r3 = new java.lang.Object[r4] // Catch:{ Throwable -> 0x02cd }
com.uc.webview.export.internal.setup.UCAsyncTask r6 = com.uc.webview.export.utility.SetupTask.getRoot() // Catch:{ Throwable -> 0x02cd }
r3[r5] = r6 // Catch:{ Throwable -> 0x02cd }
r6 = 10001(0x2711, float:1.4014E-41)
com.uc.webview.export.internal.setup.UCAsyncTask r2 = r2.invoke(r6, r3) // Catch:{ Throwable -> 0x02cd }
r2.start() // Catch:{ Throwable -> 0x02cd }
L_0x02cd:
r2 = 10064(0x2750, float:1.4103E-41)
java.lang.Object[] r3 = new java.lang.Object[r5] // Catch:{ Throwable -> 0x030f }
java.lang.Object r2 = com.uc.webview.export.internal.SDKFactory.invoke(r2, r3) // Catch:{ Throwable -> 0x030f }
java.lang.Boolean r2 = (java.lang.Boolean) r2 // Catch:{ Throwable -> 0x030f }
boolean r2 = r2.booleanValue() // Catch:{ Throwable -> 0x030f }
if (r2 == 0) goto L_0x033c
java.lang.String r2 = "BrowserSetupTask"
java.lang.String r3 = "CDInitTask new"
com.uc.webview.export.internal.utility.Log.d(r2, r3) // Catch:{ Throwable -> 0x033c }
java.lang.String r2 = "com.uc.webview.export.cd.Utils"
java.lang.String r3 = "createInitTaskForBrowserSetupTask"
r6 = 2
java.lang.Class[] r7 = new java.lang.Class[r6] // Catch:{ Throwable -> 0x033c }
java.lang.Class<java.lang.String> r8 = java.lang.String.class
r7[r5] = r8 // Catch:{ Throwable -> 0x033c }
java.lang.Class<com.uc.webview.export.internal.setup.BrowserSetupTask> r8 = com.uc.webview.export.internal.setup.BrowserSetupTask.class
r7[r4] = r8 // Catch:{ Throwable -> 0x033c }
java.lang.Object[] r6 = new java.lang.Object[r6] // Catch:{ Throwable -> 0x033c }
java.lang.String r8 = "stat"
r6[r5] = r8 // Catch:{ Throwable -> 0x033c }
com.uc.webview.export.internal.setup.BrowserSetupTask r5 = r1.a // Catch:{ Throwable -> 0x033c }
r6[r4] = r5 // Catch:{ Throwable -> 0x033c }
java.lang.Object r2 = com.uc.webview.export.internal.utility.ReflectionUtil.invoke(r2, r3, r7, r6) // Catch:{ Throwable -> 0x033c }
com.uc.webview.export.internal.setup.UCSubSetupTask r2 = (com.uc.webview.export.internal.setup.UCSubSetupTask) r2 // Catch:{ Throwable -> 0x033c }
com.uc.webview.export.internal.setup.BrowserSetupTask r3 = r1.a // Catch:{ Throwable -> 0x033c }
java.util.concurrent.ConcurrentHashMap r3 = r3.mOptions // Catch:{ Throwable -> 0x033c }
com.uc.webview.export.internal.setup.UCSubSetupTask r2 = r2.setOptions(r3) // Catch:{ Throwable -> 0x033c }
r2.start() // Catch:{ Throwable -> 0x033c }
goto L_0x033c
L_0x030f:
r0 = move-exception
r2 = r0
com.uc.webview.export.internal.setup.BrowserSetupTask r3 = r1.a
com.uc.webview.export.internal.setup.UCSetupException r4 = new com.uc.webview.export.internal.setup.UCSetupException
r5 = 4004(0xfa4, float:5.611E-42)
r4.<init>(r5, r2)
r3.setException(r4)
goto L_0x033c
L_0x031e:
com.uc.webview.export.internal.setup.BrowserSetupTask r3 = r1.a
com.uc.webview.export.internal.setup.UCSetupException r6 = new com.uc.webview.export.internal.setup.UCSetupException
r7 = 4001(0xfa1, float:5.607E-42)
java.lang.String r8 = "Task [%s] report success but no loaded UCM."
java.lang.Object[] r4 = new java.lang.Object[r4]
java.lang.Class r2 = r2.getClass()
java.lang.String r2 = r2.getName()
r4[r5] = r2
java.lang.String r2 = java.lang.String.format(r8, r4)
r6.<init>(r7, r2)
r3.setException(r6)
L_0x033c:
r2 = 42
com.uc.webview.export.internal.uc.startup.StartupStats.a(r2)
java.lang.String r2 = "BrowserCore.setup success"
com.uc.webview.export.internal.uc.startup.StartupTrace.traceEvent(r2)
return
*/
throw new UnsupportedOperationException("Method not decompiled: com.uc.webview.export.internal.setup.a.onReceiveValue(java.lang.Object):void");
}
}
| [
"hubert.yang@nf-3.com"
] | hubert.yang@nf-3.com |
b116d491ab68b6076c1bf0c9daa9de9aca807a5f | 1963063777fe495089a820130ac2d61d852c7839 | /problems/0034/Solution.java | 5389d825269d388373e0bbd74bb9ab8d55266d2d | [] | no_license | mark1701/leet-code | 6c48f69deb4e8a8aa7274ab7ab876cb0656baa45 | 6ad5b86221f4703ffc16aac5844e73df4e5e4db6 | refs/heads/master | 2022-01-23T00:06:45.369210 | 2022-01-10T22:23:53 | 2022-01-10T22:23:53 | 243,752,166 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,053 | java | class Solution {
public int[] searchRange(int[] nums, int target) {
if(nums == null || nums.length == 0) return new int[] {-1,-1};
int idxOfSmaller = binarySearchSmaller(nums, target); //index of biggest element smaller than target
int idxOfBigger = binarySearchBigger(nums, target); //index of smallest element bigger than target
int left = findLowerBound(nums, idxOfSmaller, target);
int right = findUpperBound(nums, idxOfBigger, target);
int[] res = new int[] {-1,-1};
if(left != -1 && right != -1){
res[0] = left;
res[1] = right;
}
return res;
}
private int binarySearchSmaller(int[] nums, int target){
int lo = 0, hi = nums.length -1;
//index of biggest element smaller than target
// 0 1 2 3 4 5
// 5 7 7 8 8 10
while(lo < hi){
int mid = lo + (hi-lo+1)/2;
if(nums[mid] >= target){
hi = mid - 1;
} else {
lo = mid;
}
}
return lo;
}
private int binarySearchBigger(int[] nums, int target){
int lo = 0, hi = nums.length -1;
// 0 1 2 3 4 5
// 5 7 7 8 8 10
while(lo < hi){
int mid = lo + (hi-lo)/2;
if(nums[mid] > target){
hi = mid;
} else {
lo = mid+1;
}
}
return lo;
}
private int findLowerBound(int[] nums, int idx, int target){
if(nums[idx] == target) return idx;
if(idx < nums.length - 1 && nums[idx+1] == target) return idx+1;
return -1;
}
private int findUpperBound(int[] nums, int idx, int target){
if(nums[idx] == target) return idx;
if(idx > 0 && nums[idx-1] == target) return idx-1;
return -1;
}
} | [
"noreply@github.com"
] | noreply@github.com |
4a0f8e52b008ba67e6d933f9af60ba554d261fa2 | e46830db8185ffc494f167b7113f90b8c5e4c07d | /vdb-release-2009/trunk/src/main/java/de/unibonn/inf/dbdependenciesui/ui/LogTableModel.java | 92ecefa44e674a5fc66a5f94f897c39cfb759392 | [] | no_license | knalli/visualdependencies | 6f10e7ad0ab3d71eb24eccfcd821ffe4bcc54258 | 97ca6503807fc07eb0e5ff3d10fffbd968a3968d | refs/heads/master | 2021-01-10T20:25:33.886748 | 2011-06-22T18:52:15 | 2011-06-22T18:52:15 | 32,104,838 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,872 | java | /**
* $Id: Main.java 41 2009-03-01 16:21:20Z philipp $
*/
package de.unibonn.inf.dbdependenciesui.ui;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.logging.LogRecord;
import javax.swing.table.AbstractTableModel;
import de.unibonn.inf.dbdependenciesui.Configuration;
import de.unibonn.inf.dbdependenciesui.misc.Internationalization;
/**
* The log table data model.
*
* @author Andre Kasper
* @author Jan Philipp
*/
public class LogTableModel extends AbstractTableModel {
private static final long serialVersionUID = -393838935151720190L;
private final List<String> columnNames;
private final DateFormat dateFormatter;
private final List<LogRecord> records = new ArrayList<LogRecord>();
public LogTableModel() {
this(Internationalization.getText("application.log.table.time"),
Internationalization.getText("application.log.table.level"),
Internationalization.getText("application.log.table.message"),
Internationalization.getText("application.log.table.source"));
}
public LogTableModel(final String... names) {
this.columnNames = Arrays.asList(names);
this.dateFormatter = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
DateFormat.MEDIUM, Configuration.LOCALE);
}
/**
* Add a new log record.
*
* @param record
*/
public void addLogRecord(final LogRecord record) {
this.records.add(record);
this.fireTableRowsInserted(this.getRowCount() - 1,
this.getRowCount() - 1);
}
/**
* Return the log record by the given index
*
* @param index
* @return
*/
public LogRecord getLogRecord(final int index) {
return this.records.get(index);
}
@Override
public String getColumnName(final int column) {
Object id = null;
// This test is to cover the case when
// getColumnCount has been subclassed by mistake ...
if (column < this.columnNames.size()) {
id = this.columnNames.get(column);
}
return (id == null) ? super.getColumnName(column) : id.toString();
}
@Override
public int getColumnCount() {
return this.columnNames.size();
}
@Override
public int getRowCount() {
return this.records.size();
}
@Override
public Object getValueAt(final int rowIndex, final int columnIndex) {
try {
final LogRecord record = this.records.get(rowIndex);
switch (columnIndex) {
case 0:
return this.dateFormatter.format(new Date(record.getMillis()));
case 1:
return record.getLevel().toString();
case 2:
return record.getMessage();
case 3:
return record.getSourceMethodName();
}
} catch (final Exception e) {
}
return null;
}
@Override
public void setValueAt(final Object value, final int rowIndex,
final int columnIndex) {
}
@Override
public boolean isCellEditable(final int rowIndex, final int columnIndex) {
return false;
}
}
| [
"knallisworld@googlemail.com"
] | knallisworld@googlemail.com |
2d8a03fb5a667eb6a57920d7aa70506afaa8b90c | e0f13cff9c7379a4a48abc9a5cc0377dafef85fc | /ficha5/FICHA_AIBM/poms/code/routines/src/main/java/routines/TalendDate.java | da549ccb058a14da11a39019d6fcf91e717913b8 | [] | no_license | GuilhermeViveiros/AIB | 09ec44669ab2ca1593d4f0fbcb31456a9eaf3508 | 301e1c665c0548740ff4c4be7849b413692ecfc8 | refs/heads/master | 2022-06-24T03:11:51.882422 | 2019-11-19T19:42:51 | 2019-11-19T19:42:51 | 222,772,867 | 0 | 0 | null | 2022-06-21T04:09:12 | 2019-11-19T19:26:59 | Java | UTF-8 | Java | false | false | 55,170 | java | // ============================================================================
//
// Copyright (c) 2006-2015, Talend Inc.
//
// This source code has been automatically generated by_Talend Open Studio for Big Data
// / 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 routines;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DateTimeException;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import routines.system.FastDateParser;
import routines.system.LocaleProvider;
import routines.system.TalendTimestampWithTZ;
public class TalendDate {
/**
* get part of date. like YEAR, MONTH, HOUR, or DAY_OF_WEEK, WEEK_OF_MONTH, WEEK_OF_YEAR, TIMEZONE and so on
*
* @param partName which part to get.
* @param date the date value.
* @return the specified part value.
*
* {talendTypes} Integer
*
* {Category} TalendDate
*
* {param} string("DAY_OF_WEEK") partName : which part to get
*
* {param} date(TalendDate.parseDate("yyyy-MM-dd", "2010-12-26")) date : the date value
*
* {example} getPartOfDate("DAY_OF_WEEK", TalendDate.parseDate("yyyy-MM-dd", "2010-12-26")) #
*/
public static int getPartOfDate(String partName, Date date) {
if (partName == null || date == null) {
return 0;
}
int ret = 0;
String[] fieldsName = { "YEAR", "MONTH", "HOUR", "MINUTE", "SECOND", "DAY_OF_WEEK", "DAY_OF_MONTH", "DAY_OF_YEAR",
"WEEK_OF_MONTH", "DAY_OF_WEEK_IN_MONTH", "WEEK_OF_YEAR", "TIMEZONE" };
java.util.List<String> filedsList = java.util.Arrays.asList(fieldsName);
Calendar c = Calendar.getInstance();
c.setTime(date);
switch (filedsList.indexOf(partName)) {
case 0:
ret = c.get(Calendar.YEAR);
break;
case 1:
ret = c.get(Calendar.MONTH);
break;
case 2:
ret = c.get(Calendar.HOUR);
break;
case 3:
ret = c.get(Calendar.MINUTE);
break;
case 4:
ret = c.get(Calendar.SECOND);
break;
case 5:
ret = c.get(Calendar.DAY_OF_WEEK);
break;
case 6:
ret = c.get(Calendar.DAY_OF_MONTH);
break;
case 7:
ret = c.get(Calendar.DAY_OF_YEAR);
break;
case 8:
// the ordinal number of current week in a month (it means a 'week' may be not contain 7 days)
ret = c.get(Calendar.WEEK_OF_MONTH);
break;
case 9:
// 1-7 correspond to 1, 8-14 correspond to 2,...
ret = c.get(Calendar.DAY_OF_WEEK_IN_MONTH);
break;
case 10:
ret = c.get(Calendar.WEEK_OF_YEAR);
break;
case 11:
ret = (c.get(Calendar.ZONE_OFFSET)) / (1000 * 60 * 60);
break;
default:
break;
}
return ret;
}
/**
* Formats a Date into a date/time string.
*
* @param pattern the pattern to format.
* @param date the time value to be formatted into a time string.
* @return the formatted time string.
*
* {talendTypes} String
*
* {Category} TalendDate
*
* {param} string("yyyy-MM-dd HH:mm:ss") pattern : the pattern to format
*
* {param} date(myDate) date : the time value to be formatted into a time string
*
* {example} formatDate("yyyy-MM-dd", new Date()) #
*/
public synchronized static String formatDate(String pattern, java.util.Date date) {
DateFormat format = FastDateParser.getInstance(pattern);
if (date instanceof TalendTimestampWithTZ) {
format.setTimeZone(((TalendTimestampWithTZ) date).getTimeZone());
} else {
format.setTimeZone(TimeZone.getDefault());
}
return format.format(date);
}
/**
* Formats a Date into a date/time string under the UTC timezone.
*
* @param pattern the pattern to format.
* @param date the time value to be formatted into a time string.
* @return the formatted time string.
*
* {talendTypes} String
*
* {Category} TalendDate
*
* {param} string("yyyy-MM-dd HH:mm:ss") pattern : the pattern to format
*
* {param} date(myDate) date : the time value to be formatted into a time string
*
* {example} formatDate("yyyy-MM-dd", new Date()) #
*/
public synchronized static String formatDateInUTC(String pattern, java.util.Date date) {
DateFormat format = FastDateParser.getInstance(pattern);
TimeZone originalTZ = format.getTimeZone();
format.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateStr = format.format(date);
format.setTimeZone(originalTZ);
return dateStr;
}
/**
* test string value as a date (with right pattern)
*
* @param stringDate (A <code>String</code> whose beginning should be parsed)
* @param pattern (the pattern to format, like: "yyyy-MM-dd HH:mm:ss")
* @return the result whether the stringDate is a date string that with a right pattern
*
* {talendTypes} Boolean
*
* {Category} TalendDate
*
* {param} String(mydate) stringDate : the date to judge
*
* {param} String("yyyy-MM-dd HH:mm:ss") pattern : the specified pattern
*
* {examples}
*
* ->> isDate("2008-11-24 12:15:25", "yyyy-MM-dd HH:mm:ss") return true
*
* ->> isDate("2008-11-24 12:15:25", "yyyy-MM-dd HH:mm") return false
*
* ->> isDate("2008-11-32 12:15:25", "yyyy-MM-dd HH:mm:ss") return false #
*/
public static boolean isDate(String stringDate, String pattern) {
if (stringDate == null) {
return false;
}
if (pattern == null) {
pattern = "yyyy-MM-dd HH:mm:ss";
}
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(pattern);
java.util.Date testDate = null;
try {
testDate = sdf.parse(stringDate);
} catch (ParseException e) {
return false;
}
if (!sdf.format(testDate).equalsIgnoreCase(stringDate)) {
return false;
}
return true;
}
/**
* test string value as a date with right pattern. </br>examples: </br>TimeZone:+0100 </br>2011/03/27 01:00:00 begin
* to carry out the daylight saving time. So parse dateString "20110327 021711" with TimeZone is wrong </br>
* <code>isDate("20110327 021711", "yyyyMMdd HHmmss",false)</code> return <code>false</code>
*
* </br> <code>isDate("20110327 021711", "yyyyMMdd HHmmss",true)</code> return <code>true</code>
*
* </br> <code>isDate("2008-11-32 12:15:25", "yyyy-MM-dd HH:mm:ss",true)</code> return <code>false</code>
*
* </br> <code>isDate("2008-11-32 12:15:25", "yyyy-MM-dd HH:mm:ss",false)</code> return <code>false</code>
*
* @param stringDate (A <code>String</code> whose beginning should be parsed)
* @param pattern (the pattern to format, like: "yyyy-MM-dd HH:mm:ss")
* @param ignoreTimeZone (if true ignore TimeZone when pare date with pattern)
* @return the result whether the stringDate is a date string that with a right pattern
*
* {talendTypes} Boolean
*
* {Category} TalendDate
*
* {param} String(mydate) stringDate : the date to judge
*
* {param} String("yyyy-MM-dd HH:mm:ss") pattern : the specified pattern
*
* {param} boolean(true) ignoreTimeZone : ignore the time zone
*/
public static boolean isDate(String stringDate, String pattern, boolean ignoreTimeZone) {
TimeZone tz = TimeZone.getDefault();
if (ignoreTimeZone) {
tz = TimeZone.getTimeZone("UTC");
}
if (stringDate == null) {
return false;
}
if (pattern == null) {
pattern = "yyyy-MM-dd HH:mm:ss";
}
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(pattern);
sdf.setTimeZone(tz);
sdf.setLenient(false);
java.util.Date testDate = null;
try {
testDate = sdf.parse(stringDate);
} catch (ParseException e) {
return false;
}
String formatDate = sdf.format(testDate);
if (formatDate.equalsIgnoreCase(stringDate) || formatDate.length() == stringDate.length()) {
return true;
}
return false;
}
/**
* Tests string value as a date with right pattern using strict rules.
* This validation uses Java 8 time tools such {@link DateTimeFormatter#parse }
* and {@link DateTimeFormatter#format }
* </br>
* </br>
* Examples:
* </br>
* <code>isDateStrict("20110327 121711", "yyyyMMdd HHmmss")</code> return <code>true</code></br>
* <code>isDateStrict("01100327 121711", "yyyyMMdd HHmmss")</code> return <code>false</code></br>
* <code>isDateStrict("20180229 221711", "yyyyMMdd HHmmss")</code> return <code>false</code></br>
* <code>isDateStrict("2016-02-29 22:17:11", "yyyy-MM-dd HH:mm:ss")</code> return <code>true</code></br>
* <code>isDateStrict("2011/03/27 22:17:11+0100", "yyyy/MM/dd HH:mm:ssZ")</code> return <code>true</code></br>
* <code>isDateStrict("20110327 021711+1900", "yyyyMMdd HHmmssZ")</code> return <code>false</code></br>
* </br>
* The range of time-zone offsets is restricted to -18:00 to 18:00 inclusive.
*
* @param stringDate the date to judge
* @param pattern the specified pattern, like: "yyyy-MM-dd HH:mm:ss")
* @return whether the stringDate is a date string with a right pattern.
* @throws IllegalArgumentException if pattern is not defined.
*
*/
public static boolean isDateStrict(String stringDate, String pattern) {
if (stringDate == null) {
return false;
}
DateTimeFormatter formatter = java.util.Optional
.ofNullable(pattern)
.filter((entry) -> !entry.isEmpty())
.map(DateTimeFormatter::ofPattern)
.orElseThrow(() -> new IllegalArgumentException("Date format is not defined"));
try {
TemporalAccessor testDate = formatter.parse(stringDate);
String formattedString = formatter.format(testDate);
return stringDate.equalsIgnoreCase(formattedString);
} catch (DateTimeException e) {
return false;
}
}
/**
* compare two date
*
* @param date1 (first date)
* @param date2 (second date)
* @param pattern (compare specified part, example: "yyyy-MM-dd")
* @return the result whether two date is the same, if first one less than second one return number -1, equlas
* return number 0, bigger than return number 1. (can compare partly)
*
* {talendTypes} Integer
*
* {Category} TalendDate
*
* {param} date(myDate) date1 : the first date to compare
*
* {param} date(myDate2) date2 : the second date to compare
*
* {param} String("yyyy-MM-dd") pattern : compare specified part
*
* {examples}
*
* ->> compareDate(2008/11/24 12:15:25, 2008/11/24 16:10:35) return -1
*
* ->> compareDate(2008/11/24 16:10:35, 2008/11/24 12:15:25) return 1
*
* ->> compareDate(2008/11/24 12:15:25, 2008/11/24 16:10:35,"yyyy/MM/dd") return 0 #
*/
public static int compareDate(Date date1, Date date2, String pattern) {
if (date1 == null && date2 == null) {
return 0;
} else if (date1 != null && date2 == null) {
return 1;
} else if (date1 == null && date2 != null) {
return -1;
}
if (pattern != null) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String part1 = sdf.format(date1), part2 = sdf.format(date2);
return (part1.compareTo(part2) >= 1 ? 1 : (part1.compareTo(part2) <= -1 ? -1 : 0));
} else {
long time1 = date1.getTime(), time2 = date2.getTime();
return (time1 < time2 ? -1 : (time1 == time2 ? 0 : 1));
}
}
/**
* compare two date
*
* @param date1 (first date)
* @param date2 (second date)
* @return the result whether two date is the same, if first one less than second one return number -1, equlas
* return number 0, bigger than return number 1. (can compare partly)
*
* {talendTypes} Integer
*
* {Category} TalendDate
*
* {param} date(myDate) date1 : the first date to compare
*
* {param} date(myDate2) date2 : the second date to compare
*
* {example} compareDate(2008/11/24 12:15:25, 2008/11/24 16:10:35) return -1 #
*
*/
public static int compareDate(Date date1, Date date2) {
return compareDate(date1, date2, null);
}
/**
* add number of day, month ... to a date (with Java date type !)
*
* @param date (a <code>Date</code> type value)
* @param nb (the value to add)
* @param dateType (date pattern = ("yyyy","MM","dd","HH","mm","ss","SSS" ))
* @return a new date
*
* {talendTypes} Date
*
* {Category} TalendDate
*
* {param} date(myDate) date : the date to update
*
* {param} int(addValue) nb : the added value
*
* {param} date("MM") dateType : the part to add
*
* {examples}
*
* ->> addDate(dateVariable), 5,"dd") return a date with 2008/11/29 12:15:25 (with dateVariable is a date with
* 2008/11/24 12:15:25) #
*
* ->> addDate(2008/11/24 12:15:25, 5,"ss") return 2008/11/24 12:15:30 #
*
*/
public static Date addDate(Date date, int nb, String dateType) {
if (date == null || dateType == null) {
return null;
}
Calendar c1 = Calendar.getInstance();
c1.setTime(date);
if (dateType.equalsIgnoreCase("yyyy")) { //$NON-NLS-1$
c1.add(Calendar.YEAR, nb);
} else if (dateType.equals("MM")) { //$NON-NLS-1$
c1.add(Calendar.MONTH, nb);
} else if (dateType.equalsIgnoreCase("dd")) { //$NON-NLS-1$
c1.add(Calendar.DAY_OF_MONTH, nb);
} else if (dateType.equals("HH")) { //$NON-NLS-1$
c1.add(Calendar.HOUR, nb);
} else if (dateType.equals("mm")) { //$NON-NLS-1$
c1.add(Calendar.MINUTE, nb);
} else if (dateType.equalsIgnoreCase("ss")) { //$NON-NLS-1$
c1.add(Calendar.SECOND, nb);
} else if (dateType.equalsIgnoreCase("SSS")) { //$NON-NLS-1$
c1.add(Calendar.MILLISECOND, nb);
} else {
throw new RuntimeException("Can't support the dateType: " + dateType);
}
return c1.getTime();
}
/**
* add number of day, month ... to a date (with Date given in String with a pattern)
*
* @param date (a Date given in string)
* @param pattern (the pattern for the related date)
* @param nb (the value to add)
* @param dateType (date pattern = ("yyyy","MM","dd","HH","mm","ss","SSS" ))
* @return a new date
*
* {talendTypes} String
*
* {Category} TalendDate
*
* {param} String("") string : date represent in string
*
* {param} String("yyyy-MM-dd") pattern : date pattern
*
* {param} int(addValue) nb : the added value
*
* {param} date("MM") dateType : the part to add
*
* {examples}
*
* ->> addDate("2008/11/24 12:15:25", "yyyy-MM-dd HH:mm:ss", 5,"dd") return "2008/11/29 12:15:25"
*
* ->> addDate("2008/11/24 12:15:25", "yyyy/MM/DD HH:MM:SS", 5,"ss") return "2008/11/24 12:15:30" #
*
*/
public static String addDate(String string, String pattern, int nb, String dateType) {
if (string == null || dateType == null) {
return null;
}
java.util.Date date = null;
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(pattern);
try {
date = sdf.parse(string);
} catch (ParseException e) {
throw new RuntimeException(pattern + " can't support the date!"); //$NON-NLS-1$
}
String dateString = sdf.format(addDate(date, nb, dateType));
return dateString;
}
/**
* return difference between two dates
*
* @param Date1 ( first date )
* @param Date1 ( second date )
* @param dateType value=("yyyy","MM","dd","HH","mm","ss","SSS") for type of return
* @return a number of years, months, days ... date1 - date2
*
* {talendTypes} Long
*
* {Category} TalendDate
*
* {param} date(myDate) date1 : the first date to compare
*
* {param} date(myDate2) date2 : the second date to compare
*
* {param} String("MM") dateType : the difference on the specified part
*
* {examples}
*
* ->> diffDate(2008/11/24 12:15:25, 2008/10/14 16:10:35, "yyyy") : return 0
*
* ->> diffDate(2008/11/24 12:15:25, 2008/10/14 16:10:35, "MM") : return 1
*
* ->> diffDate(2008/11/24 12:15:25, 2008/10/14 16:10:35, "dd") : return 41 #
*/
public static long diffDate(Date date1, Date date2, String dateType) {
return diffDate(date1, date2, dateType, false);
}
/**
* return difference between two dates
*
* @param Date1 ( first date )
* @param Date1 ( second date )
* @param dateType value=("yyyy","MM","dd","HH","mm","ss","SSS") for type of return
* @param ignoreDST
* @return a number of years, months, days ... date1 - date2
*
* {talendTypes} Long
*
* {Category} TalendDate
*
* {param} date(myDate) date1 : the first date to compare
*
* {param} date(myDate2) date2 : the second date to compare
*
* {param} String("MM") dateType : the difference on the specified part
*
* {param} boolean(true) ignoreDST : ignore daylight saving time or not.
*
* {examples}
*
* ->> diffDate(2012/03/26 00:00:00, 2012/03/24 00:00:00, "dd", true) : return 2 not 1 in GMT+1#
*
* ->> diffDate(2012/03/26 00:00:00, 2012/03/24 00:00:00, "dd", false) : return 1 not 2 in GMT+1#
*/
public static long diffDate(Date date1, Date date2, String dateType, boolean ignoreDST) {
if (date1 == null) {
date1 = new Date(0);
}
if (date2 == null) {
date2 = new Date(0);
}
if (dateType == null) {
dateType = "SSS";
}
// ignore DST
int addDSTSavings = 0;
if (ignoreDST) {
boolean d1In = TimeZone.getDefault().inDaylightTime(date1);
boolean d2In = TimeZone.getDefault().inDaylightTime(date2);
if (d1In != d2In) {
if (d1In) {
addDSTSavings = TimeZone.getDefault().getDSTSavings();
} else if (d2In) {
addDSTSavings = -TimeZone.getDefault().getDSTSavings();
}
}
}
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(date1);
c2.setTime(date2);
if (dateType.equalsIgnoreCase("yyyy")) { //$NON-NLS-1$
return c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
} else if (dateType.equals("MM")) { //$NON-NLS-1$
return (c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR)) * 12 + (c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH));
} else {
long diffTime = date1.getTime() - date2.getTime() + addDSTSavings;
if (dateType.equalsIgnoreCase("HH")) { //$NON-NLS-1$
return diffTime / (1000 * 60 * 60);
} else if (dateType.equals("mm")) { //$NON-NLS-1$
return diffTime / (1000 * 60);
} else if (dateType.equalsIgnoreCase("ss")) { //$NON-NLS-1$
return diffTime / 1000;
} else if (dateType.equalsIgnoreCase("SSS")) { //$NON-NLS-1$
return diffTime;
} else if (dateType.equalsIgnoreCase("dd")) {
return diffTime / (1000 * 60 * 60 * 24);
} else {
throw new RuntimeException("Can't support the dateType: " + dateType);
}
}
}
/**
* return difference between two dates ignore DST
*
* @param Date1 ( first date )
* @param Date1 ( second date )
* @param dateType value=("yyyy","MM","dd","HH","mm","ss","SSS") for type of return
* @return a number of years, months, days ... date1 - date2
*
* {talendTypes} Long
*
* {Category} TalendDate
*
* {param} date(myDate) date1 : the first date to compare
*
* {param} date(myDate2) date2 : the second date to compare
*
* {param} String("MM") dateType : the difference on the specified part
*
* {examples}
*
* ->> diffDate(2012/03/26 00:00:00, 2012/03/24 00:00:00, "dd") : return 2 not 1 in GMT+1#
*/
public static long diffDateIgnoreDST(Date date1, Date date2, String dateType) {
return diffDate(date1, date2, dateType, true);
}
/**
* return difference between two dates ignore DST
*
* @param Date1 ( first date )
* @param Date1 ( second date )
* @return a number of years, months, days ... date1 - date2
*
* {talendTypes} Long
*
* {Category} TalendDate
*
* {param} date(myDate) date1 : the first date to compare
*
* {param} date(myDate2) date2 : the second date to compare
*
* {examples}
*
* ->> diffDate(2012/03/26 00:00:00, 2012/03/24 00:00:00) : return 2 not 1 in GMT+1#
*/
public static long diffDateIgnoreDST(Date date1, Date date2) {
return diffDateIgnoreDST(date1, date2, "dd");
}
/**
* return difference between two dates by floor
*
* @param Date1 ( first date )
* @param Date1 ( second date )
* @param dateType value=("yyyy","MM") for type of return
* @return a number of years, months (date1 - date2)
*
* {talendTypes} Integer
*
* {Category} TalendDate
*
* {param} date(myDate) date1 : the first date to compare
*
* {param} date(myDate2) date2 : the second date to compare
*
* {param} String("MM") dateType : the difference on the specified part
*
* {examples}
*
* ->> diffDate(2009/05/10, 2008/10/15, "yyyy") : return 0
*
* ->> diffDate(2009/05/10, 2008/10/15, "MM") : return 6
*/
public static int diffDateFloor(Date date1, Date date2, String dateType) {
if (date1 == null) {
date1 = new Date(0);
}
if (date2 == null) {
date2 = new Date(0);
}
if (dateType == null) {
dateType = "yyyy";
}
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(date1);
c2.setTime(date2);
int result = 0;
Calendar tmp = null;
boolean flag = false;
if (c1.compareTo(c2) < 0) {
flag = true;
tmp = c1;
c1 = c2;
c2 = tmp;
}
result = (c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR)) * 12 + (c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH));
c2.add(Calendar.MONTH, result);
result += c2.after(c1) ? -1 : 0;
if (flag) {
result = -result;
}
if (dateType.equalsIgnoreCase("yyyy")) {
return result / 12;
} else if (dateType.equals("MM")) {
return result;
} else {
throw new RuntimeException("Can't support the dateType: " + dateType + " ,please try \"yyyy\" or \"MM\"");
}
}
/**
* return difference between two dates
*
* @param Date1 ( first date )
* @param Date1 ( second date )
* @return a number of years, months, days ... date1 - date2
*
* {talendTypes} Long
*
* {Category} TalendDate
*
* {param} date(myDate) date1 : the first date to compare
*
* {param} date(myDate) date2 : the second date to compare
*
* {examples} diffDate(2008/11/24 12:15:25, 2008/10/14 16:10:35) : return 41 #
*/
public static long diffDate(Date date1, Date date2) {
return diffDate(date1, date2, "dd");
}
/**
* get first day of the month
*
* @param date (a date value)
* @return a new date (the date has been changed to the first day)
*
* {talendTypes} Date
*
* {Category} TalendDate
*
* {param} date(mydate) date : the date to get first date of current month
*
* {example} getFirstDayMonth(2008/02/24 12:15:25) return 2008/02/01 12:15:25 #
*/
public static Date getFirstDayOfMonth(Date date) {
if (date == null) {
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DATE, 1);
return c.getTime();
}
/**
* get last day of the month
*
* @param date (a date value)
* @return a new date (the date has been changed to the last day)
*
* {talendTypes} Date
*
* {Category} TalendDate
*
* {param} date(mydate) date : the date to get last date of current month
*
* {example} getFirstDayMonth(2008/02/24 12:15:25) return 2008/02/28 12:15:25
*/
public static Date getLastDayOfMonth(Date date) {
if (date == null) {
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(date);
int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
c.set(Calendar.DATE, lastDay);
return c.getTime();
}
/**
*
* set a date new value partly
*
* @param date (a date value)
* @param nb (new number)
* @param dateType (the part)
* @return a new date
*
* {talendTypes} Date
*
* {Category} TalendDate
*
* {param} date(mydate) date : the date to set
*
* {param} Integer(newValue) nb : the new value
*
* {param} String("MM") dateType : the part to set
*
* {examples}
*
* ->> setDate(2008/11/24 12:15:25, 2010, "yyyy") return 2010/11/24 12:15:25
*
* ->> setDate(2008/11/24 12:15:25, 01, "MM") return 2008/01/24 12:15:25
*
* ->> setDate(2008/11/24 12:15:25, 15, "dd") return 2008/11/15 12:15:25 #
*/
public static Date setDate(Date date, int nb, String dateType) {
if (date == null || dateType == null) {
return null;
}
// if (nb < 0) {
// return date;
// }
Calendar c = Calendar.getInstance();
c.setTime(date);
if (dateType.equalsIgnoreCase("yyyy")) { //$NON-NLS-1$
c.set(Calendar.YEAR, nb);
} else if (dateType.equals("MM")) { //$NON-NLS-1$
c.set(Calendar.MONTH, nb - 1);
} else if (dateType.equalsIgnoreCase("dd")) { //$NON-NLS-1$
c.set(Calendar.DATE, nb);
} else if (dateType.equalsIgnoreCase("HH")) { //$NON-NLS-1$
c.set(Calendar.HOUR_OF_DAY, nb);
} else if (dateType.equals("mm")) { //$NON-NLS-1$
c.set(Calendar.MINUTE, nb);
} else {
throw new RuntimeException("Can't support the dateType: " + dateType);
}
return c.getTime();
}
/**
* Formats a Date into a date/time string using the given pattern and the default date format symbols for the given
* locale.
*
* @param pattern the pattern to format.
* @param date the time value to be formatted into a time string.
* @param locale the locale whose date format symbols should be used.
* @return the formatted time string.
*
* {talendTypes} String
*
* {Category} TalendDate
*
* {param} string("yyyy-MM-dd HH:mm:ss") pattern : the pattern to format
*
* {param} date(myDate) date : the time value to be formatted into a time string
*
* {param} string("EN") languageOrCountyCode : the language or country whose date format symbols should be used, in
* lower or upper case
*
* {example} formatDateLocale("yyyy-MM-dd", new Date(), "en") #
*/
public synchronized static String formatDateLocale(String pattern, java.util.Date date, String languageOrCountyCode) {
return FastDateParser.getInstance(pattern, LocaleProvider.getLocale(languageOrCountyCode)).format(date);
}
/**
* Parses text from the beginning of the given string to produce a date using the given pattern and the default date
* format symbols for the given locale. The method may not use the entire text of the given string.
* <p>
*
* @param pattern the pattern to parse.
* @param stringDate A <code>String</code> whose beginning should be parsed.
* @return A <code>Date</code> parsed from the string.
* @throws ParseException
* @exception ParseException if the beginning of the specified string cannot be parsed.
*
* {talendTypes} Date
*
* {Category} TalendDate
*
* {param} string("yyyy-MM-dd HH:mm:ss") pattern : the pattern to parse
*
* {param} string("") stringDate : A <code>String</code> whose beginning should be parsed
*
* {example} parseDate("yyyy-MMM-dd HH:mm:ss", "23-Mar-1979 23:59:59") #
*/
public synchronized static Date parseDate(String pattern, String stringDate) {
return parseDate(pattern, stringDate, true);
}
/**
* Parses text from the beginning of the given string to produce a date using the given pattern and the default date
* format symbols for the given locale. The method may not use the entire text of the given string.
* <p>
*
* @param pattern the pattern to parse.
* @param stringDate A <code>String</code> whose beginning should be parsed.
* @param isLenient A <code>boolean</code>judge DateFormat parse the date Lenient or not.
* @return A <code>Date</code> parsed from the string.
* @throws ParseException
* @exception ParseException if the beginning of the specified string cannot be parsed.
*
* {talendTypes} Date
*
* {Category} TalendDate
*
* {param} string("yyyy-MM-dd HH:mm:ss") pattern : the pattern to parse
*
* {param} string("") stringDate : A <code>String</code> whose beginning should be parsed
*
* {param} boolean(true) isLenient : Judge DateFormat parse the date Lenient or not.
*
* {example} parseDate("yyyy-MM-dd HH:mm:ss", "29-02-1979 23:59:59",false) #
*/
public synchronized static Date parseDate(String pattern, String stringDate, boolean isLenient) {
try {
boolean hasZone = false;
boolean inQuote = false;
char[] ps = pattern.toCharArray();
for (char p : ps) {
if (p == '\'') {
inQuote = !inQuote;
} else if (!inQuote && (p == 'Z' || p == 'z')) {
hasZone = true;
break;
}
}
DateFormat df = FastDateParser.getInstance(pattern);
df.setLenient(isLenient);
Date d = df.parse(stringDate);
if (hasZone) {
int offset = df.getCalendar().get(Calendar.ZONE_OFFSET);
char sign = offset >= 0 ? '+' : '-';
int hour = Math.abs(offset) / 1000 / 60 / 60;
int min = Math.abs(offset) / 1000 / 60 % 60;
String minStr = min < 10 ? "0" + min : min + "";
TalendTimestampWithTZ tstz = new TalendTimestampWithTZ(new java.sql.Timestamp(d.getTime()),
TimeZone.getTimeZone("GMT" + sign + hour + ":" + minStr));
return tstz;
} else {
return d;
}
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* Parses text from the beginning of the given string to produce a date using the given pattern and the default date
* format symbols for UTC. The method may not use the entire text of the given string.
* <p>
*
* @param pattern the pattern to parse.
* @param stringDate A <code>String</code> whose beginning should be parsed.
* @return A <code>Date</code> parsed from the string.
* @throws ParseException
* @exception ParseException if the beginning of the specified string cannot be parsed.
*
* {talendTypes} Date
*
* {Category} TalendDate
*
* {param} string("yyyy-MM-dd HH:mm:ss") pattern : the pattern to parse
*
* {param} string("") stringDate : A <code>String</code> whose beginning should be parsed
*
* {example} parseDate("yyyy-MMM-dd HH:mm:ss", "23-Mar-1979 23:59:59") #
*/
public synchronized static Date parseDateInUTC(String pattern, String stringDate) {
return parseDateInUTC(pattern, stringDate, true);
}
/**
* Parses text from the beginning of the given string to produce a date in UTC using the given pattern and the
* default date format symbols for the UTC. The method may not use the entire text of the given string.
* <p>
*
* @param pattern the pattern to parse.
* @param stringDate A <code>String</code> whose beginning should be parsed.
* @param isLenient A <code>boolean</code>judge DateFormat parse the date Lenient or not.
* @return A <code>Date</code> parsed from the string.
* @throws ParseException
* @exception ParseException if the beginning of the specified string cannot be parsed.
*
* {talendTypes} Date
*
* {Category} TalendDate
*
* {param} string("yyyy-MM-dd HH:mm:ss") pattern : the pattern to parse
*
* {param} string("") stringDate : A <code>String</code> whose beginning should be parsed
*
* {param} boolean(true) isLenient : Judge DateFormat parse the date Lenient or not.
*
* {example} parseDate("yyyy-MM-dd HH:mm:ss", "29-02-1979 23:59:59",false) #
*/
public synchronized static Date parseDateInUTC(String pattern, String stringDate, boolean isLenient) {
try {
boolean hasZone = false;
boolean inQuote = false;
char[] ps = pattern.toCharArray();
for (char p : ps) {
if (p == '\'') {
inQuote = !inQuote;
} else if (!inQuote && (p == 'Z' || p == 'z')) {
hasZone = true;
break;
}
}
DateFormat df = FastDateParser.getInstance(pattern);
TimeZone originalTZ = df.getTimeZone();
df.setTimeZone(TimeZone.getTimeZone("UTC"));
df.setLenient(isLenient);
Date d = df.parse(stringDate);
df.setTimeZone(originalTZ);
if (hasZone) {
int offset = df.getCalendar().get(Calendar.ZONE_OFFSET);
char sign = offset >= 0 ? '+' : '-';
int hour = Math.abs(offset) / 1000 / 60 / 60;
int min = Math.abs(offset) / 1000 / 60 % 60;
String minStr = min < 10 ? "0" + min : min + "";
TalendTimestampWithTZ tstz = new TalendTimestampWithTZ(new java.sql.Timestamp(d.getTime()),
TimeZone.getTimeZone("GMT" + sign + hour + ":" + minStr));
return tstz;
} else {
return d;
}
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* Parses text from the beginning of the given string to produce a date. The method may not use the entire text of
* the given string.
* <p>
*
* @param pattern the pattern to parse.
* @param stringDate A <code>String</code> whose beginning should be parsed.
* @param locale the locale whose date format symbols should be used.
* @return A <code>Date</code> parsed from the string.
* @throws ParseException
* @exception ParseException if the beginning of the specified string cannot be parsed.
*
* {talendTypes} Date
*
* {Category} TalendDate
*
* {param} string("yyyy-MM-dd HH:mm:ss") pattern : the pattern to parse
*
* {param} string("") stringDate : A <code>String</code> whose beginning should be parsed
*
* {param} string("EN") languageOrCountyCode : the language or country whose date format symbols should be used, in
* lower or upper case
*
* {example} parseDateLocale("yyyy-MMM-dd", "23-Mar-1979", "en") #
*/
public synchronized static Date parseDateLocale(String pattern, String stringDate, String languageOrCountyCode) {
try {
return FastDateParser.getInstance(pattern, LocaleProvider.getLocale(languageOrCountyCode)).parse(stringDate);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* getDate : return the current datetime with the given display format format : (optional) string representing the
* wished format of the date. This string contains fixed strings and variables related to the date. By default, the
* format string is DD/MM/CCYY. Here is the list of date variables:
*
*
* {talendTypes} String
*
* {Category} TalendDate
*
* {param} string("CCYY-MM-DD hh:mm:ss") pattern : date pattern + CC for century + YY for year + MM for month + DD
* for day + hh for hour + mm for minute + ss for second
*
* {example} getDate("CCYY-MM-DD hh:mm:ss") #
*/
public static String getDate(String pattern) {
if (pattern == null) {
pattern = "yyyy-MM-dd HH:mm:ss";
}
StringBuffer result = new StringBuffer();
pattern = pattern.replace("CC", "yy"); //$NON-NLS-1$ //$NON-NLS-2$
pattern = pattern.replace("YY", "yy"); //$NON-NLS-1$ //$NON-NLS-2$
pattern = pattern.replace("MM", "MM"); //$NON-NLS-1$ //$NON-NLS-2$
pattern = pattern.replace("DD", "dd"); //$NON-NLS-1$ //$NON-NLS-2$
pattern = pattern.replace("hh", "HH"); //$NON-NLS-1$ //$NON-NLS-2$
// not needed
// pattern.replace("mm", "mm");
// pattern.replace("ss", "ss");
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
sdf.format(Calendar.getInstance().getTime(), result, new FieldPosition(0));
return result.toString();
}
/**
* getDate : return the current date
*
*
*
* {talendTypes} Date
*
* {Category} TalendDate
*
* {example} getCurrentDate()
*/
public static Date getCurrentDate() {
return new Date();
}
/**
* return an ISO formatted random date
*
*
* {talendTypes} Date
*
* {Category} TalendDate
*
* {param} string("2007-01-01") min : minimum date
*
* {param} string("2008-12-31") max : maximum date (superior to min)
*
* {example} getRandomDate("1981-01-18", "2005-07-24") {example} getRandomDate("1980-12-08", "2007-02-26")
*/
public static Date getRandomDate(String minDate, String maxDate) {
if (minDate == null) {
minDate = "1970-01-01";
}
if (maxDate == null) {
maxDate = "2099-12-31";
}
if (!minDate.matches("\\d{4}-\\d{2}-\\d{2}") || !minDate.matches("\\d{4}-\\d{2}-\\d{2}")) {
throw new IllegalArgumentException("The parameter should be \"yyy-MM-dd\"");
}
int minYear = Integer.parseInt(minDate.substring(0, 4));
int minMonth = Integer.parseInt(minDate.substring(5, 7));
int minDay = Integer.parseInt(minDate.substring(8, 10));
int maxYear = Integer.parseInt(maxDate.substring(0, 4));
int maxMonth = Integer.parseInt(maxDate.substring(5, 7));
int maxDay = Integer.parseInt(maxDate.substring(8, 10));
Calendar minCal = Calendar.getInstance();
minCal.set(Calendar.YEAR, minYear);
minCal.set(Calendar.MONTH, minMonth - 1);
minCal.set(Calendar.DAY_OF_MONTH, minDay);
Calendar maxCal = Calendar.getInstance();
maxCal.set(Calendar.YEAR, maxYear);
maxCal.set(Calendar.MONTH, maxMonth - 1);
maxCal.set(Calendar.DAY_OF_MONTH, maxDay);
long random = minCal.getTimeInMillis()
+ (long) ((maxCal.getTimeInMillis() - minCal.getTimeInMillis() + 1) * Math.random());
return new Date(random);
}
/**
*
* Testcase:
* <p>
* getRandomDate(String minDate, String maxDate)
* </p>
*/
public static void test_getRandomDate() {
System.out
.println("getRandomDate: " + TalendDate.formatDate("yyyy-MM-dd HH:mm:ss", TalendDate.getRandomDate(null, null))); //$NON-NLS-1$
}
/**
*
* Testcase:
* <p>
* compareDate(Date date1, Date date2)
* </p>
*/
public static void test_compareDate() {
System.out
.println("compareDate: " + Boolean.toString(TalendDate.compareDate(new Date(), new Date(System.currentTimeMillis() - 10000)) == 1)); //$NON-NLS-1$
}
/**
*
* Testcase:
* <p>
* isDate(String stringDate, String pattern)
* </p>
*/
public static void test_isDate() {
System.out.println("isDate: " + Boolean.toString(TalendDate.isDate("2008-11-35 12:15:25", "yyyy-MM-dd HH:mm") == false)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
/**
* format date to mssql 2008 type datetimeoffset ISO 8601 string with local time zone format string : yyyy-MM-dd
* HH:mm:ss.SSSXXX(JDK7 support it)
*/
public static String formatDatetimeoffset(Date date) {
String dateString = formatDate("yyyy-MM-dd HH:mm:ss.SSSZ", date);// keep the max precision in java
StringBuilder sb = new StringBuilder(30);
sb.append(dateString);
sb.insert(dateString.length() - 2, ':');
return sb.toString();
}
/**
*
* Testcase:
* <p>
* formatDate(String pattern, java.util.Date date)
* </p>
* <p>
* formatDateLocale(String pattern, java.util.Date date, String languageOrCountyCode)
* </p>
*/
public static void test_formatDate() {
final int LOOPS = 100000;
final String dateTimeRef_Test1 = "1979-03-23 mars 12:30";
Thread test1 = new Thread() {
@Override
public void run() {
Calendar calendar = GregorianCalendar.getInstance();
calendar.set(1979, 2, 23, 12, 30, 40);
Date dateCalendar = calendar.getTime();
for (int i = 0; i < LOOPS; i++) {
String date = TalendDate.formatDate("yyyy-MM-dd MMM HH:mm", dateCalendar);
// System.out.println("Test1:" + date + " # " + dateTimeRef_Test1);
if (!dateTimeRef_Test1.equals(date)) {
throw new IllegalStateException("Test1: Date ref : '" + dateTimeRef_Test1 + "' is different of '" + date
+ "'");
}
}
System.out.println("test1 ok");
}
};
final String dateTimeRef_Test2 = "1980-03-23 mars 12:30";
Thread test2 = new Thread() {
@Override
public void run() {
Calendar calendar = GregorianCalendar.getInstance();
calendar.set(1980, 2, 23, 12, 30, 40);
Date dateCalendar = calendar.getTime();
for (int i = 0; i < LOOPS; i++) {
String date = TalendDate.formatDate("yyyy-MM-dd MMM HH:mm", dateCalendar);
// System.out.println("Test2:" + date + " # " + dateTimeRef_Test2);
if (!dateTimeRef_Test2.equals(date)) {
throw new IllegalStateException("Test2: Date ref : '" + dateTimeRef_Test2 + "' is different of '" + date
+ "'");
}
}
System.out.println("test2 ok");
}
};
final String dateTimeRef_Test3 = "1979-03-23 mars 12:30";
Thread test3 = new Thread() {
@Override
public void run() {
Calendar calendar = GregorianCalendar.getInstance();
calendar.set(1979, 2, 23, 12, 30, 40);
Date dateCalendar = calendar.getTime();
for (int i = 0; i < LOOPS; i++) {
String date = TalendDate.formatDateLocale("yyyy-MM-dd MMM HH:mm", dateCalendar, "FR");
// System.out.println("Test3:" + date + " # " + dateTimeRef_Test3);
if (!dateTimeRef_Test3.equals(date)) {
throw new IllegalStateException("Test3: Date ref : '" + dateTimeRef_Test3 + "' is different of '" + date
+ "'");
}
}
System.out.println("test3 ok");
}
};
final String dateTimeRef_Test4 = "1980-03-23 Mar 12:30";
Thread test4 = new Thread() {
@Override
public void run() {
Calendar calendar = GregorianCalendar.getInstance();
calendar.set(1980, 2, 23, 12, 30, 40);
Date dateCalendar = calendar.getTime();
for (int i = 0; i < LOOPS; i++) {
String date = TalendDate.formatDateLocale("yyyy-MM-dd MMM HH:mm", dateCalendar, "EN");
// System.out.println("Test4:" + date + " # " + dateTimeRef_Test4);
if (!dateTimeRef_Test4.equals(date)) {
throw new IllegalStateException("Test4: Date ref : '" + dateTimeRef_Test4 + "' is different of '" + date
+ "'");
}
}
System.out.println("test4 ok");
}
};
final String dateTimeRef_Test5 = "1979-03-23";
Thread test5 = new Thread() {
@Override
public void run() {
Calendar calendar = GregorianCalendar.getInstance();
calendar.set(1979, 2, 23, 12, 30, 40);
Date dateCalendar = calendar.getTime();
for (int i = 0; i < LOOPS; i++) {
String date = TalendDate.formatDate("yyyy-MM-dd", dateCalendar);
// System.out.println("Test5:" + date + " # " + dateTimeRef_Test5);
if (!dateTimeRef_Test5.equals(date)) {
throw new IllegalStateException("Test5: Date ref : '" + dateTimeRef_Test5 + "' is different of '" + date
+ "'");
}
}
System.out.println("test5 ok");
}
};
test1.start();
test2.start();
test3.start();
test4.start();
test5.start();
}
/**
*
* @param string Must be a string datatype. Passes the values that you want to convert.
* @param format Enter a valid TO_DATE format string. The format string must match the parts of the string argument
* default formate is "MM/DD/yyyy HH:mm:ss.sss" if not specified.
* @return Date
* @throws ParseException
* {example} TO_DATE("1464576463231", "J") #Mon May 30 10:47:43 CST 2016
* {example} TO_DATE("2015-11-21 13:23:45","yyyy-MM-dd HH:mm:ss") #Sat Nov 21 13:23:45 CST 2015
*
*/
public static Date TO_DATE(String string, String format) throws ParseException {
String defaultFormat = "MM/dd/yyyy HH:mm:ss.SSS";
if (StringHandling.isVacant(string)) {
return null;
}
if (!StringHandling.isVacant(format)) {
if (format.equals("J")) {
return new Date(Long.parseLong(string));
}
SimpleDateFormat sdf = new SimpleDateFormat(dateFormatConvert(format));
return sdf.parse(string);
} else {
SimpleDateFormat sdf = new SimpleDateFormat(defaultFormat);
return sdf.parse(string);
}
}
public static Date TO_DATE(String string) throws ParseException {
return TO_DATE(string, null);
}
private static String dateFormatConvert(String format) {
/**
* we do not support the type list below:
* D : Day of week (1-7), where Sunday equals 1.
* NS: Nanoseconds (0-999999999). SSSSS: Seconds since midnight (00000 - 86399).
* US: Microseconds (0-999999).
* Q: Quarter of year (1-4), where January to March equals 1.
*/
format = format.replaceAll("Y", "y");
format = format.replaceAll("RR", "yy");
format = format.replaceAll("MONTH", "MMMM");
format = format.replaceAll("MON", "MMM");
format = format.replaceAll("WW", "w");// Week of year (01-53)
format = format.replaceAll("W", "F");// Week of month (1-5)
format = format.replaceAll("(AM|A.M.|PM|P.M.)", "a");
format = format.replaceAll("DY", "E");// Abbreviated three-character
// name for a day (for example,
// Wed).
format = format.replaceAll("DDD", "D");// Day of year (001-366,
// including leap years).
format = format.replaceAll("DD", "d");// Day of month (01-31).
format = format.replaceAll("HH24", "zx@i#o%l!");//protect HH24 from HH
format = format.replaceAll("(HH|HH12)", "hh");
format = format.replaceAll("zx@i#o%l!", "HH");
format = format.replaceAll("MS", "sss");
format = format.replaceAll("MI", "mm");
format = format.replaceAll("SS", "ss");
return format;
}
/**
*
* @param date Passes the values you want to change
* @param format A format string specifying the portion of the date value you want to change.For example, 'mm'.
* @param amount An integer value specifying the amount of years, months, days, hours,
* and so on by which you want to change the date value.
* @return Date NULL if a null value is passed as an argument to the function.
* @throws ParseException
* {example} ADD_TO_DATE(new Date(1464576463231l), "HH",2) #Mon May 30 12:47:43 CST 2016
*/
public static Date ADD_TO_DATE(Date date, String format, int amount) throws ParseException{
if (date == null || StringHandling.isVacant(format)) {
return null;
}
if (format != null) {
format = dateFormatADD_TO_DATE(format);
}
Long time = date.getTime();
Calendar calender = Calendar.getInstance();
calender.setTime(date);
switch (format) {
case "Y":
calender.add(Calendar.YEAR, amount);
time = calender.getTimeInMillis();
break;
case "MONTH":
calender.add(Calendar.MONTH, amount);
time = calender.getTimeInMillis();
break;
case "DAY":
time += (long)amount * (long)86400000;
break;
case "HH":
time += (long)amount * (long)3600000;
break;
case "MI":
time += (long)amount * (long)60000;
break;
case "SS":
time += (long)amount * (long)1000;
break;
case "MS":
time += amount;
break;
case "US":
time += amount / 1000;
break;
case "NS":
time += amount / 1000000;
break;
default:
throw new ParseException("Please enter a vaild format.", 0);
}
return new Date(time);
}
private static String dateFormatADD_TO_DATE(String format) {
if (format.equals("Y") || format.equals("YY") || format.equals("YYY") || format.equals("YYYY")) {
return "Y";
}
if (format.equals("MONTH") || format.equals("MM") || format.equals("MON")) {
return "MONTH";
}
if (format.equals("D") || format.equals("DD") || format.equals("DDD") || format.equals("DAY")
|| format.equals("DY")) {
return "DAY";
}
if (format.equals("HH") || format.equals("HH12") || format.equals("HH24")) {
return "HH";
}
return format;
}
/**
*
* @param date Date/Time datatype. Passes the date values you want to convert to character strings.
* @param format Enter a valid TO_CHAR format string. The format string defines the format of the return value,
* @return String. NULL if a value passed to the function is NULL.
*/
public static String TO_CHAR(Date date, String format) {
if (date == null) {
return null;
}
if(format==null||format.equals("")){
format="MM/DD/YYYY HH24:MI:SS";
}
if("J".equals(format)){
return Long.toString(date.getTime());
}
SimpleDateFormat sdf = new SimpleDateFormat(dateFormatConvert(format));
return sdf.format(date);
}
}
| [
"a80524@alunos.uminho.pt"
] | a80524@alunos.uminho.pt |
3a13ebbe56a0b5b0f7e8ec46c7a3f2494eba9eac | a752561d2e4bbff664a736e0310dfd89ffaef603 | /src/com/phorse/monkey/leetcode/leetcode800_900/Test867_Solution.java | d1fbabdd39b621fc0960f0d912a36631699f8166 | [] | no_license | 7phorse/phorse-monkey | 9758485bdf2c812b6c2d1964de3179337333ebd6 | e25e5d6511352b2dd3c176e4b2cad5332e17f6dc | refs/heads/master | 2023-07-03T02:10:47.723142 | 2021-08-08T04:06:10 | 2021-08-08T04:06:10 | 122,641,460 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,047 | java | package com.phorse.monkey.leetcode.leetcode800_900;
import java.util.Arrays;
/**
* 给你一个二维整数数组 matrix, 返回 matrix 的 转置矩阵 。
* <p>
* 矩阵的 转置 是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。
* <p>
* 示例 1:
* <p>
* 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
* 输出:[[1,4,7],[2,5,8],[3,6,9]]
* 示例 2:
* <p>
* 输入:matrix = [[1,2,3],[4,5,6]]
* 输出:[[1,4],[2,5],[3,6]]
* @author luoxusheng 2021/2/25 22:07
* @version v1.0.0
*/
public class Test867_Solution {
public static int[][] transpose(int[][] matrix) {
int[][] res = new int[matrix[0].length][matrix.length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
res[j][i] = matrix[i][j];
}
}
return res;
}
public static void main(String[] args) {
System.out.println(Arrays.deepToString(transpose(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}})));
}
}
| [
"luoxusheng@xiaomi.com"
] | luoxusheng@xiaomi.com |
94cb66ab9b467afd27e7af41d71c492ab428e9c9 | 397da400f333f6fb85174688f0a09d3a1ada77f5 | /Math/src/com/wang/math/Main13.java | 6fa8d23d75e65ed3760f0e733bbb708d7d0e8c91 | [] | no_license | WANGYUNING88/javase | fa3c4f971b440ecabaf6190c7acf455b63e57353 | 54a16f4f3b54b34b477942af06e7f9d1536a5041 | refs/heads/master | 2020-03-23T09:49:52.102036 | 2018-09-07T01:15:04 | 2018-09-07T01:15:04 | 141,409,933 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 861 | java | package com.wang.math;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main13 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String ab = scan.nextLine();
String[] abc = ab.split(" ");
String a = abc[0];
String b = abc[1];
String c = abc[2];
System.out.println(getMath(a,b,c));
}
}
public static String getMath(String a,String b,String c){
String a1 = String.valueOf(a.charAt(a.length()-1));
String a2 = String.valueOf(b.charAt(0));
String b1 = String.valueOf(b.charAt(b.length()-1));
String b2 = String.valueOf(c.charAt(0));
if(a1.equals(a2)&&b1.equals(b2))
return "YES";
else
return "NO";
}
}
| [
"247197442@qq.com"
] | 247197442@qq.com |
07a1fa7e71d72ac86010f8a61468f4ce5fa40078 | 07ab2450b105a104d6d79289b68014e578f622fc | /src/main/java/com/test/calculator/core/infraestructure/shiplaod/ShipLoadConstants.java | 0590ade701ef427d14b82057b003fa0cd5d7339c | [] | no_license | yaselanaya/calculator | 27687b68b95cdde68b42401924b4c6ba3d1059d1 | eeb5e8da4ebb58f0c3f577115ac35a147ae04555 | refs/heads/master | 2020-05-21T13:23:54.777166 | 2019-05-14T13:25:52 | 2019-05-14T13:25:52 | 186,070,306 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 251 | java | package com.test.calculator.core.infraestructure.shiplaod;
public class ShipLoadConstants {
/* API DOC */
public static final String API_DOC = "Operations pertaining to ship load";
public static final String ENTITY_URI = "/shipLoad";
}
| [
"yasel@generalsoftwareinc.com"
] | yasel@generalsoftwareinc.com |
061a57fa057bf2e247c58d5038c3834228a0694b | 60e57a51b9188e5cd588fd844e0b5a3fd24450b7 | /src/main/java/com/miaoshaSystem/validator/ValidationResult.java | 5b0c18b853730119b9dabd43b81b7600ed97d46b | [] | no_license | wwyynnn/MiaoShaSystem | 04078180d2d14de5521ce4fd210a2a24ee5829d9 | f3dea2b9d4bf6f2d07717b20ceeb42fe08d79678 | refs/heads/master | 2022-12-01T06:32:19.668169 | 2020-08-12T16:51:42 | 2020-08-12T16:51:42 | 286,767,394 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 977 | java | package com.miaoshaSystem.validator;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* @author: Wang Yannan
* @date: 2020/6/11 10:33 上午
*/
public class ValidationResult {
//校验结果是否有错
private boolean hasError=false;
//存放错误信息的map
private Map<String, String> errorMsgMap = new HashMap<>();
public boolean isHasError() {
return hasError;
}
public void setHasError(boolean hasError) {
this.hasError = hasError;
}
public Map<String, String> getErrorMsgMap() {
return errorMsgMap;
}
public void setErrorMsgMap(Map<String, String> errorMsgMap) {
this.errorMsgMap = errorMsgMap;
}
//实现通用的通过格式化字符串信息获取错误结果的msg方法
public String getErrMsg(){
//获取所有msg的值并返回
return StringUtils.join(errorMsgMap.values().toArray(),",");
}
}
| [
"2435173W@student.gla.ac.uk"
] | 2435173W@student.gla.ac.uk |
a9db3c1f731d381037f202fed807eace215e79e0 | d730de2e4dab036b1a4bfa1ea2577c70657cd525 | /labs/7/test.java | e44f825ff1d11b4092cd9eafe4086f41ce45cabd | [] | no_license | willespo22/cmpt220Esposito | 24cadcf2234211cc8ca11f24af01c778fc917c14 | 71ce23990c8d285c1301ae0691f948b1e6000361 | refs/heads/master | 2021-01-11T16:51:14.197663 | 2017-05-16T00:35:06 | 2017-05-16T00:35:06 | 79,684,508 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 566 | java | /**
* file: test.java
* author: William Esposito
* course: CMPT 220
* assignment: Lab 5
* due date: April 20 2017
* version: 1.3
*
* This file contains a program with answer for designated problem
*/
import Chap10Problem10.Queue;
public class test {
public static void main(String[] args) {
Queue queue = new Queue();
// inserting 20 numbers into queue
for (int i = 0; i < 20; i++) {
queue.enqueue(i + 1);
}
while (!queue.empty()) {
System.out.println("The dequeued element is: " + queue.dequeue());
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
c36e7a9ee3ab8ce55a8abf6cc47836addaf42598 | 711d46544cb5f0066f862b7024bd76c6d3f0b98e | /src/main/java/br/com/neves/shorturl/service/impl/relational/ShorterUrlServiceImpl.java | ca365bf0c3b64acca9b4e7c7fc7a251157f5e512 | [] | no_license | nevesgustavo/shorterurl | fa332bcf615b7757c17baadef1cf66f39750b238 | f747a6dabee614d8cb453ad3ec2708d83e8299f0 | refs/heads/main | 2023-06-11T11:41:23.817230 | 2021-07-02T17:47:07 | 2021-07-02T17:47:07 | 375,526,023 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,630 | java | package br.com.neves.shorturl.service.impl.relational;
import br.com.neves.shorturl.exception.*;
import br.com.neves.shorturl.jpa.model.relational.ShortUrl;
import br.com.neves.shorturl.jpa.repository.relational.RelationalShortUrlRepository;
import br.com.neves.shorturl.service.ShorterUrlService;
import br.com.neves.shorturl.service.hashGenerator.HashGenerator;
import br.com.neves.shorturl.utils.DateUtil;
import br.com.neves.shorturl.utils.HashGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.time.LocalDateTime;
@Transactional
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
public class ShorterUrlServiceImpl implements ShorterUrlService {
// ------------------------------ FIELDS ------------------------------
@Value("${domain}")
private String domain;
@Value("${hash.expiration.days}")
private Integer expirationDays;
@Autowired
private HashGenerator hashGenerator;
@Autowired
private RelationalShortUrlRepository relationalShortUrlRepository;
@Autowired
private ShortUrlLogService shortUrlLogService;
// ------------------------ INTERFACE METHODS ------------------------
// --------------------- Interface ShorterUrlService ---------------------
public String createCustomShortUrl(String customHash, String originalUrl, Integer expirationDays) {
prepareExpirationDateRemoveExpiredShortUrlAndSaveShortUrl(new ShortUrl(customHash, originalUrl), expirationDays);
return String.format("%s%s", domain, customHash);
}
public String createShortUrl(String loginName, String originalUrl, Integer expirationDays) {
String hash = generateHash(loginName);
prepareExpirationDateRemoveExpiredShortUrlAndSaveShortUrl(new ShortUrl(hash, originalUrl), expirationDays);
return String.format("%s%s", domain, hash);
}
public String generateHash(String loginName) {
return HashGeneratorUtil.generateHash(hashGenerator, loginName);
}
public String getOriginalUrlByHashAndSaveLog(String hash) {
ShortUrl shortUrl = relationalShortUrlRepository.findByHashAndExpirationDateAfter(hash, LocalDateTime.now());
if (shortUrl == null && relationalShortUrlRepository.existsByHash(hash))
throw new UrlExpiredException("The url is expired");
if (shortUrl == null)
throw new UrlNotFoundException("The url was not found");
shortUrlLogService.save(shortUrl);
return shortUrl.getOriginalUrl();
}
// -------------------------- OTHER METHODS --------------------------
private void prepareExpirationDateRemoveExpiredShortUrlAndSaveShortUrl(ShortUrl shortUrl, Integer expirationDays) {
if (expirationDays == null)
expirationDays = this.expirationDays;
removeExpiredHashIfExists(shortUrl.getHash());
shortUrl.setExpirationDate(DateUtil.sumDaysInCurrentDate(expirationDays));
saveShortUrlOnRepository(shortUrl);
}
public void removeExpiredHashIfExists(String hash) {
relationalShortUrlRepository.deleteByHashAndExpirationDateBefore(hash, LocalDateTime.now());
}
private void saveShortUrlOnRepository(ShortUrl shortUrl) throws HashAlreadyExistsException {
if (relationalShortUrlRepository.existsByHash(shortUrl.getHash()))
throw new HashAlreadyExistsException("The hash already exists");
relationalShortUrlRepository.save(shortUrl);
}
}
| [
"gustavo.neves@me.com.br"
] | gustavo.neves@me.com.br |
50364c04f4cd86db7b74d81422705dfb400a576f | 4442e647ecf1ccacda6946fc43010f9e804ae0d8 | /app/controllers/Diagnostic.java | 6fd8ebbe58cf9ea17dc6d70597ba6ec2ee79f06b | [] | no_license | iambowen/scala-workshop-online-problems | 76066a8a9d663924bb773f2ede9d5f77ccd3295e | 7a30de77ae13089deaa07721c35cb47059a64dac | refs/heads/master | 2020-12-25T08:42:03.646649 | 2014-07-23T15:10:31 | 2014-07-23T15:10:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 473 | java | package controllers;
import play.mvc.Controller;
import play.Play;
public class Diagnostic extends Controller {
public static void version() {
String version = Play.configuration.get("app.version").toString();
renderText(version);
}
public static void appName() {
String appName = Play.configuration.get("application.name").toString();
renderText(appName);
}
public static void ping() {
renderText("OK");
}
}
| [
"iambowen.m@gmail.com"
] | iambowen.m@gmail.com |
20ed917e1fc3210296d973fc97844f90a6bcc3e5 | 2d9f3a652d9498888ec72d9b909ae985c94eb37b | /Minigames/src/main/java/au/com/mineauz/minigames/minigame/modules/CTFModule.java | 121726a7b6ad6ecdf14313bfea0efdf92b5d8ac9 | [
"MIT"
] | permissive | Mattlk13/Minigames | 31780f004b8c28dd69a7cdeea72ad189a7d00529 | 21f70b195b538b47df02a551f3c4447f4f24cfef | refs/heads/master | 2023-07-19T18:57:26.657987 | 2020-08-17T13:38:44 | 2020-08-17T13:38:44 | 85,856,039 | 0 | 0 | MIT | 2020-09-10T13:41:15 | 2017-03-22T17:18:31 | Java | UTF-8 | Java | false | false | 2,278 | java | package au.com.mineauz.minigames.minigame.modules;
import au.com.mineauz.minigames.MinigameUtils;
import au.com.mineauz.minigames.config.BooleanFlag;
import au.com.mineauz.minigames.config.Flag;
import au.com.mineauz.minigames.menu.Menu;
import au.com.mineauz.minigames.menu.MenuItemPage;
import au.com.mineauz.minigames.menu.MenuUtility;
import au.com.mineauz.minigames.minigame.Minigame;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import java.util.HashMap;
import java.util.Map;
/**
* Created for the Ark: Survival Evolved.
* Created by Narimm on 19/01/2017.
*/
public class CTFModule extends MinigameModule {
private BooleanFlag useFlagAsCapturePoint = new BooleanFlag(true, "useFlagAsCapturePoint");
public CTFModule(Minigame mgm) {
super(mgm);
}
public static CTFModule getMinigameModule(Minigame mgm) {
return (CTFModule) mgm.getModule("CTF");
}
public Boolean getUseFlagAsCapturePoint() {
return useFlagAsCapturePoint.getFlag();
}
public void setUseFlagAsCapturePoint(Boolean useFlagAsCapturePoint) {
this.useFlagAsCapturePoint.setFlag(useFlagAsCapturePoint);
}
@Override
public String getName() {
return "CTF";
}
@Override
public Map<String, Flag<?>> getFlags() {
Map<String, Flag<?>> flags = new HashMap<>();
flags.put("useFlagAsCapturePoint", useFlagAsCapturePoint);
return flags;
}
@Override
public boolean useSeparateConfig() {
return false;
}
@Override
public void save(FileConfiguration config) {
}
@Override
public void load(FileConfiguration config) {
}
@Override
public void addEditMenuOptions(Menu menu) {
}
@Override
public boolean displayMechanicSettings(Menu previous) {
Menu m = new Menu(6, "CTF Settings", previous.getViewer());
m.addItem(new MenuItemPage("Back", MenuUtility.getBackMaterial(), previous), m.getSize() - 9);
m.addItem(useFlagAsCapturePoint.getMenuItem("CTF Flag is Capture Point", Material.BLACK_BANNER,
MinigameUtils.stringToList("Use a teams Flag as a capture point")));
m.displayMenu(previous.getViewer());
return true;
}
}
| [
"benjicharlton@gmail.com"
] | benjicharlton@gmail.com |
ff69b0a8d50320e23633832c6b8f6b01bd780af6 | 4b8f3ac810d2117964f2475d73d890c3502b03c9 | /src/org/dougllas/classgenerator/classdefinition/SDFilteredLazyDataModelClassDefinition.java | a7efcb6a5d3877c4fa10fbee2d2ef5aaa28fb9a7 | [] | no_license | dougllasfps/eclipseplugin | dada636709a5fb0aef89f8ec9e0a851993345b61 | e1a6831c8dda9b3e9953b8e586c7b142fdb4f120 | refs/heads/master | 2020-06-26T02:29:51.754289 | 2016-11-23T18:48:16 | 2016-11-23T18:48:16 | 74,603,524 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 707 | java | package org.dougllas.classgenerator.classdefinition;
import org.dougllas.classgenerator.ClassInfo;
import org.dougllas.classgenerator.generator.RepositoryClassGenerator;
public class SDFilteredLazyDataModelClassDefinition implements ClassDefinition {
@Override
public String[] getAnnotations() {
return null;
}
@Override
public String getInheritanceStatement(ClassInfo info) {
return String.format( " extends SDFilteredLazyDataModel<%s, %s> ", info.getClassName(), info.getClassName().concat(RepositoryClassGenerator.REPOSITORY_SUFIX) );
}
@Override
public String[] getImports(ClassInfo info) {
return new String[]{
"br.gov.ce.seduc.crud.datamodel.SDFilteredLazyDataModel"
};
}
}
| [
"dougllas.sousa@seduc.ce.gov.br"
] | dougllas.sousa@seduc.ce.gov.br |
3fedfadb49fafab8a14fb5cd31de2ab9e10a5317 | 054b1ff58584fbe49de7f30fe46ac4ab0ac594d4 | /apps/rasp/optimized-decompiled/rasp-home/dava/src/android/support/v4/widget/ListPopupWindowCompatKitKat.java | 589f7b16b5dbc26192d00c1a94f280d1f7414cb9 | [] | no_license | fthomas-de/android_ipc | 55083eeb8c52ff76116ad95e5b0716ddeb77dda3 | 626dc6aee76ededfb2d15084dfad74a1e7040016 | refs/heads/master | 2021-05-29T19:02:42.862103 | 2015-10-15T06:52:31 | 2015-10-15T06:52:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 423 | java | package android.support.v4.widget;
import android.view.View;
import android.widget.ListPopupWindow;
import android.view.View$OnTouchListener;
class ListPopupWindowCompatKitKat
{
ListPopupWindowCompatKitKat()
{
this.<init>();
}
public static View$OnTouchListener createDragToOpenListener(Object r0, View r1)
{
return ((ListPopupWindow) r0).createDragToOpenListener(r1);
}
}
| [
"fthomas@tzi.de"
] | fthomas@tzi.de |
6cddf0dec71b4f64ff8f29ae3d2bbaa8f983b5e4 | b4e5f0befedc66440d50ac5c213dfafdd3779fad | /src/main/java/com/zhanghao/searchboot/util/http/HttpClientConfig.java | 74f08870949c2e013d5b6b173dc4b514f89c6581 | [] | no_license | ZhangHao0810/BMW-SearchBoot | 88f7b1505d3d3eb4d3dddf6964647d822f768e95 | 2f6ed8f0b8cfb372c2c3938368f3b5c1ceb3af44 | refs/heads/master | 2023-01-04T04:10:22.213779 | 2020-11-01T13:32:50 | 2020-11-01T13:32:50 | 307,890,570 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,842 | java | package com.zhanghao.searchboot.util.http;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class HttpClientConfig {
//最大连接数
@Value("${http.maxTotal}")
private Integer maxTotal;
//并发数
@Value("${http.defaultMaxPerRoute}")
private Integer defaultMaxPerRoute;
//设置连接超时时间
@Value("${http.connectTimeout}")
private Integer connectTimeout;
//设置连接请求最长时间
@Value("${http.connectionRequestTimeout}")
private Integer connectionRequestTimeout;
//数据传输的最长时间
@Value("${http.socketTimeout}")
private Integer socketTimeout;
//提交请求前测试连接是否可用
@Value("${http.staleConnectionCheckEnabled}")
private boolean staleConnectionCheckEnabled;
/**
* 首先实例化一个连接池管理器,设置最大连接数、并发连接数
*
* @return
*/
@Bean(name = "httpClientConnectionManager")
public PoolingHttpClientConnectionManager getHttpClientConnectionManager() {
PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager();
// 最大连接数
httpClientConnectionManager.setMaxTotal(maxTotal);
// 并发数
httpClientConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
return httpClientConnectionManager;
}
/**
* 实例化连接池,设置连接池管理器。 这里需要以参数形式注入上面实例化的连接池管理器
*
* @param httpClientConnectionManager
* @return
*/
@Bean(name = "httpClientBuilder")
public HttpClientBuilder getHttpClientBuilder(@Qualifier("httpClientConnectionManager") PoolingHttpClientConnectionManager httpClientConnectionManager) {
// HttpClientBuilder中的构造方法被protected修饰,所以这里不能直接使用new来实例化一个HttpClientBuilder,可以使用HttpClientBuilder提供的静态方法create()来获取HttpClientBuilder对象
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setConnectionManager(httpClientConnectionManager);
return httpClientBuilder;
}
/**
* 注入连接池,用于获取httpClient
*
* @param httpClientBuilder
* @return
*/
@Bean
public CloseableHttpClient getCloseableHttpClient(@Qualifier("httpClientBuilder") HttpClientBuilder httpClientBuilder) {
return httpClientBuilder.build();
}
/**
* Builder是RequestConfig的一个内部类 通过RequestConfig的custom方法来获取到一个Builder对象
* 设置builder的连接信息 这里还可以设置proxy,cookieSpec等属性。有需要的话可以在此设置
*
* @return
*/
@Bean(name = "builder")
public RequestConfig.Builder getBuilder() {
RequestConfig.Builder builder = RequestConfig.custom();
return builder.setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(staleConnectionCheckEnabled);
}
/**
* 使用builder构建一个RequestConfig对象
*
* @param builder
* @return
*/
@Bean
public RequestConfig getRequestConfig(@Qualifier("builder") RequestConfig.Builder builder) {
return builder.build();
}
} | [
"874993952@qq.com"
] | 874993952@qq.com |
0ba4045ee932a3c7b2ce28e99a39a1e20d7ee433 | bdb35cfe85b5b79915e8d68f24b8b2febcff4021 | /graph/src/LeetCode/IslandNum.java | fd53a45e63b397fedaad0ec3ac3cdbdc40e0779d | [] | no_license | cuichangrui/dsa | e12ff17591bceaa9c55d10c722b38e41f42399bd | 3cda587f66781196e06adbee877a929b0c9d2561 | refs/heads/master | 2022-11-10T07:33:58.888604 | 2020-06-28T14:54:38 | 2020-06-28T14:54:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,454 | java | package LeetCode;
/**
* 给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
* 岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
* 此外,你可以假设该网格的四条边均被水包围。
* <p>
* 示例 1:
* 输入:
* 11110
* 11010
* 11000
* 00000
* 输出: 1
* 示例 2:
* 输入:
* 11000
* 11000
* 00100
* 00011
* 输出: 3
* 解释: 每座岛屿只能由水平和/或竖直方向上相邻的陆地连接而成。
*/
public class IslandNum {
/**
* 思路:利用dfs将相连的岛屿改为海洋
*/
public int numIslands(char[][] grid) {
if (grid.length == 0)
return 0;
int m = grid.length, n = grid[0].length, count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
count++;
inject(grid, i, j, m, n);
}
}
}
return count;
}
public void inject(char[][] grid, int i, int j, int m, int n) {
if (i >= 0 && j >= 0 && i < m && j < n && grid[i][j] == '1') {
grid[i][j] = '0';
inject(grid, i + 1, j, m, n);
inject(grid, i - 1, j, m, n);
inject(grid, i, j + 1, m, n);
inject(grid, i, j - 1, m, n);
}
}
}
| [
"lfgewj21345@163.com"
] | lfgewj21345@163.com |
c3e3fb1973cce8e34c72eeebda4b93cc38a1572d | ce755f690207d4ed68331c382d7d3b16ba915cc9 | /TelegramBot/src/main/java/ru/home/telegrambot/cache/UserDataCache.java | cb834659b279b249d638d8ce352c848255fa9822 | [] | no_license | extense1337/Java-Telegram-Bot | f65a5074234424754d75b3d91554a999c57b3f22 | ea4cb76eb1126fbe1e77023d2a21f156cefcd054 | refs/heads/main | 2023-06-02T15:19:21.505352 | 2021-06-24T13:32:17 | 2021-06-24T13:32:17 | 379,702,349 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,283 | java | package ru.home.telegrambot.cache;
import org.springframework.stereotype.Component;
import ru.home.telegrambot.botapi.BotState;
import ru.home.telegrambot.model.UserProfileData;
import java.util.HashMap;
import java.util.Map;
@Component
public class UserDataCache implements DataCache {
private Map<Integer, BotState> usersBotStates = new HashMap<>();
private Map<Integer, UserProfileData> usersProfileData = new HashMap<>();
@Override
public void setUsersCurrentBotState(int userId, BotState botState) {
usersBotStates.put(userId, botState);
}
@Override
public BotState getUsersCurrentBotState(int userId) {
BotState botState = usersBotStates.get(userId);
if (botState == null) {
botState = BotState.ASK_INTERESTING_FACT;
}
return botState;
}
@Override
public UserProfileData getUserProfileData(int userId) {
UserProfileData userProfileData = usersProfileData.get(userId);
if (userProfileData == null) {
userProfileData = new UserProfileData();
}
return userProfileData;
}
@Override
public void saveUserProfileData(int userId, UserProfileData userProfileData) {
usersProfileData.put(userId, userProfileData);
}
}
| [
"mxm1337@rambler.ru"
] | mxm1337@rambler.ru |
77dbf452081bb5257cfe1924760ee48e6041cf16 | a6bebf82dc3cbb15efb4740ee9dbc45c8279bb7d | /Inheritance4/CommissionEmployee.java | 017f55b7792e95e6c8c893d7f0ca781033c0fdb7 | [
"Unlicense"
] | permissive | github21yandex/Calismalarim-Java | 1fdc513615e17defd5adb86072a9e7d4cfe2b09c | 09239377a2b24739d74c0fdc1875b4e75cd754cc | refs/heads/main | 2023-09-01T01:47:22.211945 | 2021-10-20T00:06:48 | 2021-10-20T00:06:48 | 419,121,113 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,299 | java | package Inheritance4;
public class CommissionEmployee extends Employee {
private double grossSales;
private double commissionRate;
public CommissionEmployee(String firstName, String lastName, String socialSecurityNumber, double grossSales, double commissionRate){
super(firstName, lastName, socialSecurityNumber);
if (grossSales < 0){
throw new IllegalArgumentException(
"Gros sales must be >= 0"
);
}
this.grossSales = grossSales;
this.commissionRate = commissionRate;
}
public double getGrossSales() {
return grossSales;
}
public void setGrossSales(double grossSales) {
this.grossSales = grossSales;
}
public double getCommissionRate() {
return commissionRate;
}
public void setCommissionRate(double commissionRate) {
this.commissionRate = commissionRate;
}
public double earnings(){
return commissionRate*grossSales;
}
@Override
public double getPaymentAmount() {
return earnings();
}
@Override
public String toString() {
return String.format("%s: %s%n%s: $%,.2f; %s: %.2f",
"commissionEmployee", super.toString(), "gross sales", getGrossSales(), "commission rate", getCommissionRate());
}
} | [
"github21@yandex.com"
] | github21@yandex.com |
4443d211b42f6fd5c26a2aafe6ff03402eaf7156 | 19d9e87ae9295a9497a14927ae15cce109058667 | /JavaTicTacToe.java | fd1748b17fa3f732a934a83eadd1eff26a2bd33a | [] | no_license | keogh-rory/rory.github.io | 865f4cb307dbe49e7e4f812fb93cc28d9b9926f2 | 14b8c15e356b687119934fd0d5d802065e04d30a | refs/heads/master | 2021-01-05T14:40:14.194833 | 2020-02-20T19:37:53 | 2020-02-20T19:37:53 | 241,053,315 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,160 | java | import java.util.*;
class JavaTicTacToe{
public static Scanner UserInputS = new Scanner(System.in);
public static Scanner UserInputI = new Scanner(System.in);
public static int[] move = new int[2];
public static void main(String [] args){//main method declaration
char[][] board = {{'|', '-','-','-','-','-', '+' ,'-','-','-','-','-', '+', '-','-','-','-','-', '+', '-','-','-','-','-', '|'},
{'|', ' ',' ',' ',' ',' ', '|' ,' ',' ',' ',' ',' ', '|', ' ',' ',' ',' ', ' ', '|', ' ',' ',' ',' ',' ', '|'},
{'|', ' ',' ','_',' ',' ', '|' ,' ',' ','1',' ',' ', '|', ' ',' ','2',' ', ' ', '|', ' ',' ','3',' ',' ', '|'},
{'|', ' ',' ',' ',' ',' ', '|' ,' ',' ',' ',' ',' ', '|', ' ',' ',' ',' ', ' ', '|', ' ',' ',' ',' ',' ', '|'},
{'|', '-','-','-','-','-', '+' ,'-','-','-','-','-', '+', '-','-','-','-','-', '+', '-','-','-','-','-', '|'},
{'|', ' ',' ',' ',' ',' ', '|' ,' ',' ',' ',' ',' ', '|', ' ',' ',' ',' ', ' ', '|', ' ',' ',' ',' ',' ', '|'},
{'|', ' ',' ','a',' ',' ', '|' ,' ',' ',' ',' ',' ', '|', ' ',' ',' ',' ', ' ', '|', ' ',' ',' ',' ',' ', '|'},
{'|', ' ',' ',' ',' ',' ', '|' ,' ',' ',' ',' ',' ', '|', ' ',' ',' ',' ', ' ', '|', ' ',' ',' ',' ',' ', '|'},
{'|', '-','-','-','-','-', '+' ,'-','-','-','-','-', '+', '-','-','-','-','-', '+', '-','-','-','-','-', '|'},
{'|', ' ',' ',' ',' ',' ', '|' ,' ',' ',' ',' ',' ', '|', ' ',' ',' ',' ', ' ', '|', ' ',' ',' ',' ',' ', '|'},
{'|', ' ',' ','b',' ',' ', '|' ,' ',' ',' ',' ',' ', '|', ' ',' ',' ',' ', ' ', '|', ' ',' ',' ',' ',' ', '|'},
{'|', ' ',' ',' ',' ',' ', '|' ,' ',' ',' ',' ',' ', '|', ' ',' ',' ',' ', ' ', '|', ' ',' ',' ',' ',' ', '|'},
{'|', '-','-','-','-','-', '+' ,'-','-','-','-','-', '+', '-','-','-','-','-', '+', '-','-','-','-','-', '|'},
{'|', ' ',' ',' ',' ',' ', '|' ,' ',' ',' ',' ',' ', '|', ' ',' ',' ',' ', ' ', '|', ' ',' ',' ',' ',' ', '|'},
{'|', ' ',' ','c',' ',' ', '|' ,' ',' ',' ',' ',' ', '|', ' ',' ',' ',' ', ' ', '|', ' ',' ',' ',' ',' ', '|'},
{'|', ' ',' ',' ',' ',' ', '|' ,' ',' ',' ',' ',' ', '|', ' ',' ',' ',' ', ' ', '|', ' ',' ',' ',' ',' ', '|'},
{'|', '-','-','-','-','-', '+' ,'-','-','-','-','-', '+', '-','-','-','-','-', '+', '-','-','-','-','-', '|'}};
board[2][9] = '1';
board[2][15] = '2';
board[2][21] = '3';
board[6][3] = 'a';
board[10][3] = 'b';
board[14][3] = 'c';
boolean [][] playerPos = new boolean [4][4];
boolean [][] comPos = new boolean [4][4];
boolean [][] pos = new boolean [4][4];
setFalse(playerPos); //filling 2D array with false values
setFalse(comPos);
setFalse(pos);
gameLoop(playerPos, comPos, pos, board);
System.out.println("game over");
}
public static void gameLoop(boolean playerPos[][], boolean comPos[][], boolean pos[][], char[][] board) {
int count = 0;
boolean won = false;
while (won == false) {
comLoop(comPos, pos, board, playerPos);
count++;
printBoard(board);
if (count == 9) {
System.out.println("draw!");
won = true;
break;
}
if (isWon(comPos)) {
System.out.println("computer wins!");
won = true;
break;
}
userLoop(pos, playerPos, board);
count++;
printBoard(board);
if (isWon(playerPos)) {
System.out.println("player wins!");
won = true;
break;
}
}
}
public static void userLoop(boolean pos [][], boolean playerPos [][], char board [][]){
System.out.println("What row would you like to place your piece? (a-c)");
int row = getRow();
System.out.println("What collum would you like to place your piece? (1-3)");
int col = getCol();
if (!(isOccupied(pos, row, col))) {
pos[row][col] = true;
playerPos[row][col] = true;
placePeg(row, col, board, "player"); //for player
} else if ((isOccupied(pos, row, col))) {
System.out.println("Error this position is already occupied, please try again.");
userLoop(pos, playerPos, board);
}
}
public static void comLoop(boolean comPos[][], boolean pos [][], char board [][], boolean playerPos [][]){
int comRow = getOpValue(); //if optimal value cant be found an 'optimal value' will be randomly generated
int comCol = getOpValue();
if (winningMove(playerPos, pos)){ //checking if the player can win on the next turn (defense is priority)
comRow = move[0];
comCol = move[1];
}
if (winningMove(comPos, pos)){ //checking if the computer can win on the next turn
comRow = move[0];
comCol = move[1];
}
if (!(isOccupied(pos, comRow, comCol))) {
pos[comRow][comCol] = true;
comPos[comRow][comCol] = true;
placePeg(comRow, comCol, board, "com"); //for computer
}
else{
comLoop(comPos, pos, board, playerPos);
}
}
public static void printBoard(char board[][]) {
for (char[] row: board) {
for (char collum: row) {
System.out.print(collum); //not println
}
System.out.println();
}
}
public static void placePeg(int r, int c, char board[][], String user) {
r = convRow(r);
c = convCol(c);
if (user == "player")
board[r][c] = 'x';
if (user == "com")
board[r][c] = 'o';
}
public static int getOpValue() {
int random = (int)(Math.random() * 3) + 1;
return random;
}
public static int convRow(int r) {
switch (r) {
case 1:
r = 6;
break;
case 2:
r = 10;
break;
case 3:
r = 14;
break;
}
return r;
}
public static int convCol(int c) {
switch (c) {
case 1:
c = 9;
break;
case 2:
c = 15;
break;
case 3:
c = 21;
break;
}
return c;
}
public static boolean isOccupied(boolean arr[][], int r, int c) {
if (arr[r][c] == true)
return true;
else
return false;
}
public static void setFalse(boolean array[][]) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
array[i][j] = false;
}
}
}
public static int getRow() {
String input;
int convNum = -1;
input = UserInputS.next();
if (!(input.equalsIgnoreCase("a") || input.equalsIgnoreCase("b") || input.equalsIgnoreCase("c"))) {
System.out.println("Error, invalid input!\nPlease input a valid row");
return getRow();
}
switch (input) {
case "a":
convNum = 1;
break;
case "b":
convNum = 2;
break;
case "c":
convNum = 3;
}
return convNum;
}
public static int getCol() {
int input;
input = UserInputI.nextInt();
if (input > 3) {
System.out.println("Error, invalid input!\nPlease input a valid collumn");
//UserInputI.nextInt();
return getCol();
}
return input;
}
public static boolean isWon(boolean curr[][]) {
if (curr[1][1] && curr[1][2] && curr[1][3]) //checking horizontal wins
return true;
if (curr[2][1] && curr[2][2] && curr[2][3])
return true;
if (curr[3][1] && curr[3][2] && curr[3][3])
return true;
if (curr[1][1] && curr[2][1] && curr[3][1]) //checking vertical wins
return true;
if (curr[1][2] && curr[2][2] && curr[3][2])
return true;
if (curr[1][3] && curr[2][3] && curr[3][3])
return true;
if (curr[1][1] && curr[2][2] && curr[3][3])
return true;
if (curr[1][3] && curr[2][2] && curr[3][1])
return true;
else
return false;
}
public static boolean winningMove(boolean curr[][], boolean pos[][]){
boolean win = false;
for (int i = 1; i < 4; i++){
if (curr[i][1] && curr[i][2] && (!(isOccupied(pos, i, 3)))){ //checking for horizontal wins
move[0] = i;
move[1] = 3;
win = true;
break;
}
if (curr[i][2] && curr[i][3]&& (!(isOccupied(pos, i, 1)))){ //checking for horizontal wins
move[0] = i;
move[1] = 1;
win = true;
break;
}
if (curr[i][1] && curr[i][3]&& (!(isOccupied(pos, i, 2)))){ //checking for horizontal wins
move[0] = i;
move[1] = 2;
win = true;
break;
}
if (curr[1][i] && curr[2][i] && (!(isOccupied(pos, 3, i)))){ //checking for vertical wins
move[0] = 3;
move[1] = i;
win = true;
break;
}
if (curr[2][i] && curr[3][i]&& (!(isOccupied(pos, 1, i)))){ //checking for vertical wins
move[0] = 1;
move[1] = i;
win = true;
break;
}
if (curr[1][i] && curr[3][i]&& (!(isOccupied(pos, 2, i)))){ //checking for vertical wins
move[0] = 2;
move[1] = i;
win = true;
break;
}
}
if (curr[1][1] && curr[2][2]&& (!(isOccupied(pos, 3, 3)))){ //checking for diagnoal wins
move[0] = 3;
move[1] = 3;
win = true;
}
if (curr[3][3] && curr[2][2]&& (!(isOccupied(pos, 1, 1)))){ //checking for diagnoal wins
move[0] = 1;
move[1] = 1;
win = true;
}
if (curr[3][1] && curr[2][2]&& (!(isOccupied(pos, 1, 3)))){ //checking for diagnoal wins
move[0] = 1;
move[1] = 3;
win = true;
}
if (curr[1][3] && curr[2][2]&& (!(isOccupied(pos, 3, 1)))){ //checking for diagnoal wins
move[0] = 3;
move[1] = 1;
win = true;
}
if ( (curr[1][1] && curr[3][3] || curr[1][3] && curr[3][1]) && (!(isOccupied(pos, 2, 2)))){ //checking the center piece
move[0] = 2;
move[1] = 2;
win = true;
}
return win;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
361699c673d51cff52a840e68ea9be62db091260 | 66c92136877faf92dcaae78295b37eb012a524e6 | /src/component/login/LoginTelaComponent.java | f8059a25c418dfdfbfa1b52664a899ec5f751d9d | [] | no_license | Nidrag/SELearning | caee14cdf27702248634b6532c48e90c83ce285f | ed27ba62ba5d976e62cdaccb8e3dbfdf22aa2c20 | refs/heads/master | 2022-12-25T10:01:03.716385 | 2019-11-07T01:57:25 | 2019-11-07T01:57:25 | 220,120,459 | 0 | 0 | null | 2022-12-15T23:40:46 | 2019-11-07T00:56:03 | Java | UTF-8 | Java | false | false | 513 | java | package component.login;
import javafx.scene.layout.BorderPane;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
public class LoginTelaComponent extends BorderPane {
public LoginTelaComponent (Stage stage, MediaPlayer mediaPlayer) {
ConteudoEsquerdaComponent conteudoEsquerda = new ConteudoEsquerdaComponent(stage);
ConteudoDireitaComponent conteudoDireita = new ConteudoDireitaComponent(stage, this, mediaPlayer);
this.setLeft(conteudoEsquerda);
this.setRight(conteudoDireita);
}
}
| [
"higorgardin@hotmail.com"
] | higorgardin@hotmail.com |
dad3b87026ea97647b2bec60999210fde0cfd93a | eef1ae852bce0fbd00d8e5c16f4c562689968b42 | /src/test/java/com/ghailene/recipeappjpadatamodelingspringhibernate/controllers/IndexControllerTest.java | 655aec4fd64083b00b1e3a39f3b162d1da4af55c | [] | no_license | ghailen/recipe-app-jpa-modeling-spring-hibernate | 4fb67ab17ca562378b8a8614fac1c277c64cbc68 | 8f7f1d387046bc7c34c841356b3ab7697866e008 | refs/heads/main | 2023-08-16T13:31:37.998111 | 2021-09-13T13:25:40 | 2021-09-13T13:25:40 | 403,777,882 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,282 | java | package com.ghailene.recipeappjpadatamodelingspringhibernate.controllers;
import com.ghailene.recipeappjpadatamodelingspringhibernate.domain.Recipe;
import com.ghailene.recipeappjpadatamodelingspringhibernate.services.RecipeService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.ui.Model;
import java.util.HashSet;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
class IndexControllerTest {
@Mock
RecipeService recipeService;
@Mock
Model model;
IndexController controller;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
controller = new IndexController(recipeService);
}
@Test
public void testMockMvc() throws Exception {
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
mockMvc.perform(MockMvcRequestBuilders.get("/"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.view().name("index"));
}
@Test
void getIndexPage() {
// given
Set<Recipe> recipes = new HashSet<>();
recipes.add(new Recipe());
Recipe recipe = new Recipe();
recipe.setId(1L);
recipes.add(recipe);
Mockito.when(recipeService.getRecipes()).thenReturn(recipes);
ArgumentCaptor<Set<Recipe>> argumentCaptor = ArgumentCaptor.forClass(Set.class);
// when
String viewName = controller.getIndexPage(model);
//then
assertEquals("index", viewName);
Mockito.verify(recipeService, Mockito.times(1)).getRecipes();
Mockito.verify(model, Mockito.times(1)).addAttribute(Mockito.eq("recipes"), argumentCaptor.capture());
Set<Recipe> setInController = argumentCaptor.getValue();
assertEquals(2, setInController.size());
}
} | [
"ghailenemark@gmail.com"
] | ghailenemark@gmail.com |
906ae7638ea71dd97d75078c717c8f9d425658a1 | 3c7761a04995b6ffaee5bc2c56ce6a5e766d1d68 | /src/main/java/com/loneliness/entity/domain/Chapter.java | 9bc1654a89b28ab6593d3ec22c9f846a316baef7 | [] | no_license | EgorKrs/tzeentch-shop | 4df2a954e3fc50d9fe82a7ea91827a66aacbef8f | fa726473cb0ca6da2dcf454bd7f045fa8d44e08f | refs/heads/master | 2023-02-03T10:34:23.837901 | 2020-12-19T11:28:54 | 2020-12-19T11:28:54 | 302,887,153 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,092 | java | package com.loneliness.entity.domain;
import com.loneliness.validate_data.Exist;
import com.loneliness.validate_data.New;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Null;
import java.util.Set;
@Entity
@Table
@Data
@EqualsAndHashCode(of = { "id" })
public class Chapter implements Domain{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@NotBlank(groups = {Exist.class})
@Null(groups = {New.class})
private Integer id;
private Integer numberOfChapter;
@ManyToMany( cascade = CascadeType.REFRESH, mappedBy = "translatedChapter")
private Set<Translater> translaters;
private String chapterText;
@ManyToOne(fetch = FetchType.EAGER)
@OnDelete(action = OnDeleteAction.CASCADE)
private Chapter prevChapter;
@ManyToOne(fetch = FetchType.EAGER)
@OnDelete(action = OnDeleteAction.CASCADE)
private Chapter nextChapter;
}
| [
"ekrasouski@icloud.com"
] | ekrasouski@icloud.com |
fa1850f38af78041b41f4b727dc9c904148073c8 | b7c90816db5837294f8a0e7ff0c99d835f5375eb | /app/src/main/java/com/example/taili/androidubercaranimation/Common.java | 4914f4f531b79be410c45563a6283dea5b52d273 | [] | no_license | KidTrainee/AndroidUberCarAnimation | d7c08e3f2a11843d3cd1a9fb000c64d01f2043d0 | 20edc0b334470014bdf9c840a62ab82566943683 | refs/heads/master | 2020-03-07T20:18:06.954456 | 2018-04-02T03:45:50 | 2018-04-02T03:45:50 | 127,693,937 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 453 | java | package com.example.taili.androidubercaranimation;
import com.example.taili.androidubercaranimation.Remote.IGoogleApi;
import com.example.taili.androidubercaranimation.Remote.RetrofitClient;
/**
* Created by taili on 2/8/2018.
*/
public class Common {
public static final String baseUrl = "https://googleapis.com";
public static IGoogleApi getGoogleApi() {
return RetrofitClient.getClient(baseUrl).create(IGoogleApi.class);
}
}
| [
"tailieu.binh.01@gmail.com"
] | tailieu.binh.01@gmail.com |
bc86edccbccef98c25d602386c0bc5caadcf2ba4 | e935beef27535953f5a73fc5148f5194cab6a979 | /KeywordsAndExpressions/src/com/frankwylie/Main.java | 36d67b87cbefaaf82ee47ac6219ab9e7b3dcbfae | [] | no_license | frankwylie/JavaPrograms | d7ab8cd045eced0a6a60c80d148f5cd365a3b5bd | d3cba5ac8edd5de63a2da3492997dfdb31ad9811 | refs/heads/master | 2021-01-09T06:13:27.710700 | 2017-02-04T18:21:07 | 2017-02-04T18:21:07 | 80,938,663 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,240 | java | package com.frankwylie;
public class Main {
public static void main(String[] args) {
// Java programming language has 50 reserved words.
// programmers can not use them as names.
// you can not do this:
// int int = 5; BUT you can use int int2 = 5;
// Expressions = the building blocks of all programs.
// a mile is equal to 1.609344 kilometers.
double kilometers = (100 * 1.609344); // the expression if the (100 * 1.609344)
int highScore = 50;
if (highScore == 50){ // this is a valid expression in the brackets.
System.out.println("This is an expression"); // this is also an expression.
}
//Lecture Challenge:
// ------------------------------
// In the following code that I will type below, write down what parts of the code are expressions.
int score = 100; // score = 100 is the expression
if (score > 99){ // The part inside the expression, the if, brackets are not part of the expression.
System.out.println("You go the high score!"); // The information inside the brackets is a valid expression.
score = 0; // This is a valid expression
}
}
}
| [
"frankwylie@gmail.com"
] | frankwylie@gmail.com |
a562144e0af3fc62d1257d148a85c877b10db296 | c7128917baeaa24e946911baec002a86077f99b0 | /BasicSyntaxConditionalStatementsAndLoops/src/lab/RefactorSumOfOddNumbers.java | ca5291836289b259e8734856d3edf67417d9cb26 | [
"MIT"
] | permissive | DeianH94/JavaFundamentals2 | d5c8806a253f74fce5e9b35aba8aa126fd9a697a | bb845ba6ca0493f0438c96af1f93d64d11d23f25 | refs/heads/master | 2022-11-29T05:53:25.647553 | 2020-08-09T20:08:23 | 2020-08-09T20:08:23 | 286,308,055 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 427 | java | package lab;
import java.util.Scanner;
public class RefactorSumOfOddNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int sum = 0;
for (int i = 1; i <= n; i++) {
System.out.println(2 * i - 1);
sum += 2 * i - 1;
}
System.out.printf("Sum: %d%n", sum);
}
}
| [
"deianh94@gmail.com"
] | deianh94@gmail.com |
0a316db2fc04227723dcaa097c5c5303c10217e4 | 16683a4871f8c2bc74386cbd3dd8cf7b74a3f687 | /src/main/java/jpabook/jpashop/service/ItemService.java | 2dcbd573c0d746c562871a67d3b8b49f053eb743 | [] | no_license | rlatmd0829/jpashop | 6f556094b895b98e61722feddf5f558457c6ae3a | 4fcdf0135613168e132d922f28ac18708e2feb1d | refs/heads/master | 2023-05-05T05:55:33.886285 | 2021-05-14T07:05:57 | 2021-05-14T07:05:57 | 359,868,706 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,046 | java | package jpabook.jpashop.service;
import jpabook.jpashop.domain.item.Book;
import jpabook.jpashop.domain.item.Item;
import jpabook.jpashop.repository.ItemRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class ItemService {
private final ItemRepository itemRepository;
@Transactional
public void saveItem(Item item){
itemRepository.save(item);
}
public List<Item> findItems(){
return itemRepository.findAll();
}
@Transactional
public void updateItem(Long itemId, Book param){
Item findItem = itemRepository.findOne(itemId);
findItem.setPrice(param.getPrice());
findItem.setName(param.getName());
findItem.setStockQuantity(param.getStockQuantity());
}
public Item findOne(Long itemId){
return itemRepository.findOne(itemId);
}
}
| [
"rlatmd0829@naver.com"
] | rlatmd0829@naver.com |
583d1ca22282e3b1d5366dc454de0fd3dc738583 | 83db7b94bffce1425f85cd5310ebf5493001bdab | /main/java/com/vali/controller/ProductController.java | 8024e3547c06972e538b8e6990d7ea193446a674 | [] | no_license | qhuypham/webBanValiSpringBoot | f10d24ee480ed6a2ce7aa1aa4bfea80a0d7c11b9 | 687852459f28fb80df042bd6d554fb436a210d93 | refs/heads/master | 2022-12-20T16:28:59.175291 | 2020-10-10T17:37:50 | 2020-10-10T17:37:50 | 302,956,025 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,677 | java | package com.vali.controller;
import java.util.List;
import javax.mail.MessagingException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.vali.DAO.ProductDAO;
import com.vali.bean.MailInfo;
import com.vali.entity.Product;
import com.vali.service.CookieService;
import com.vali.service.MailService;
@Controller
public class ProductController {
@Autowired
ProductDAO pdao;
@Autowired
CookieService cookie;
@Autowired
MailService mail;
@RequestMapping("/product/list-by-category/{cid}")
public String listByCategory(Model model,
@PathVariable("cid") Integer categoryId) {
List<Product> list = pdao.findByCategoryId(categoryId);
model.addAttribute("list",list);
return "product/list";
}
@RequestMapping("/product/list-by-keyword")
public String listByKeywords(Model model,
@RequestParam("keywords") String keywords) {
List<Product> list = pdao.findByKeywords(keywords);
model.addAttribute("list",list);
return "product/list";
}
@RequestMapping("/product/detail/{id}")
public String detail(Model model,
@PathVariable("id") Integer id) {
//Chi tiet san pham
Product p = pdao.findById(id);
model.addAttribute("prod",p);
//Tang viewCount +1
p.setViewCount(p.getViewCount()+1);
pdao.update(p);
//Hang Cung Loai
List<Product> list = pdao.findByCategoryId(p.getCategory().getId());
model.addAttribute("list",list);
//Hang favorite
Cookie favo = cookie.read("favo");
if(favo!=null) {
String ids = favo.getValue();
if(ids!=null) {
List<Product> list_favo = pdao.findByIds(ids);
model.addAttribute("favo",list_favo);
}
}
// Hang da xem
Cookie viewed = cookie.read("viewed");
String value = id.toString();
if(viewed!=null) {
value = viewed.getValue();
value += "," + id.toString();
}
cookie.create("viewed", value, 10);
List<Product> list_viewed = pdao.findByIds(value);
model.addAttribute("viewed", list_viewed);
return "product/detail";
}
@ResponseBody
@RequestMapping("/product/add-to-favo/{id}")
public boolean addToFavorite(Model model, @PathVariable("id") Integer id) {
Cookie favo = cookie.read("favo");
String value = id.toString();
if(favo!=null) {
value =favo.getValue();
if(!value.contains(id.toString())) {
value += "," + id.toString();
}
else {
return false;
}
}
favo = cookie.create("favo", value , 30);
return true;
}
@RequestMapping("/product/list-by-special/{id}")
public String listBySpecial(Model model,
@PathVariable("id") Integer id) {
List<Product> list = pdao.findBySpecial(id);
model.addAttribute("list",list);
return "product/list";
}
@ResponseBody
@RequestMapping("/product/send-email")
public boolean sendEmail(Model model, MailInfo info, HttpServletRequest req, HttpServletResponse res) {
//gui mail
info.setSubject("Thong tin hang hoa");
info.setFrom("validep99@gmail.com");
try {
String id = req.getParameter("id");
String link = req.getRequestURL().toString().replace("send-email", "detail/"+id);
info.setBody("Hang hoa dep.Xem chi tiet tai:"+link);
mail.send(info);
return true;
} catch (MessagingException e) {
return false;
}
}
}
| [
"pqhuy192@gmail.com"
] | pqhuy192@gmail.com |
6e64f0174e09f52471b60707c437ede38339d46f | 0937e390198da08fa4240e1de0a9afd80dd06dca | /src/main/java/homework/MathTest.java | 438187b5c411579053ca6431efe60b668e2bc477 | [] | no_license | sakop/advanced | 5ef969eed69f5346cdbae20cfdc07089cf6a94f0 | 7d76f1ee1854ceba9c624978938a4069f39d5cfe | refs/heads/master | 2020-06-05T10:55:29.004489 | 2014-11-14T10:27:14 | 2014-11-14T10:27:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 521 | java | package homework;
public class MathTest {
public static void main(String[] args) {
/**
* 1.double a = -1.577,打印他的Math.floor,Math.ceil,Math.round,Math.abs
*
* 2.勾股 定理,斜边=(直角边a平方+直角边b平方)的开根
* 现在假设直角边1为3,直角边2为4,求斜边,请利用Math类的sqrt和pow函数计算
*
* 3.使用String.valueOf和Integer.parseInt,Double.parseDouble自己写几个小李子
*/
}
}
| [
"sakopqiu@gmail.com"
] | sakopqiu@gmail.com |
dd966f7c4343e564335c40c469a7f9ae72ec4b89 | 6d6514b36393cb31bd60a8022cee72aa085f54fa | /src/packjuego/audio.java | 7782d8cab8da011c3f30e6fcfacb82bd851be0b2 | [] | no_license | alvaroquispe094/Game-space-java-files | 6d7e8ec8543d1c68d403ebcc41c40b3989d5bda1 | 619deaebb27f3f2f811a38b7a87de49808e9dde1 | refs/heads/master | 2022-01-26T01:48:16.854476 | 2019-07-20T01:01:01 | 2019-07-20T01:01:19 | 197,861,211 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,468 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package packjuego;
import java.applet.AudioClip;
import java.io.*;
import sun.audio.*;
/**
*
* @author Master
*/
public class audio {
public AudioClip sonido;
public AudioClip sonido_pear;
public AudioClip efecto;
public AudioClip efecto_error;
public AudioClip efecto_item;
public AudioClip efecto_boom;
public AudioClip efecto_laser;
public audio(){
/*String sonido = "C:/users/master/desktop/audio.Wav";
ImputStream in = new FileImputStream(sonido);
AudioStream audio = new AudioStream(in);
AudioPlayer.player.start(audio);
**/
//AudioClip sonido;
sonido = java.applet.Applet.newAudioClip(getClass().getResource("sonido/audio.wav"));
sonido_pear = java.applet.Applet.newAudioClip(getClass().getResource("sonido/papapear.wav"));
efecto = java.applet.Applet.newAudioClip(getClass().getResource("sonido/bien.wav"));
efecto_error = java.applet.Applet.newAudioClip(getClass().getResource("sonido/error.wav"));
efecto_laser = java.applet.Applet.newAudioClip(getClass().getResource("sonido/laser.wav"));
efecto_item = java.applet.Applet.newAudioClip(getClass().getResource("sonido/item.wav"));
efecto_boom = java.applet.Applet.newAudioClip(getClass().getResource("sonido/explosion.wav"));
}
}
| [
"alvarodanielq17@gmail.com"
] | alvarodanielq17@gmail.com |
d5f69bad4e4cd9571b0c360c80b990b4221882ab | 818e1c7e00933bf435f6fb24a8daca0b5e9aa786 | /openapi/rest/src/main/java/in/clouthink/nextoa/bl/openapi/controller/RoleRestControler.java | 15720b3dcf85ea9db2476cef3b66dc528a1f0e6c | [] | no_license | next-teable/next-oa-service | d8ad7e9ff78ae0c2ad4b0de6bf4a33ac736b069a | 21a3e1b89db16d12c6033b7727f4fd01ce3d0184 | refs/heads/master | 2021-06-12T21:13:20.132069 | 2020-06-07T09:39:14 | 2020-06-07T09:39:14 | 254,399,204 | 0 | 0 | null | 2020-06-07T09:39:16 | 2020-04-09T14:48:21 | Java | UTF-8 | Java | false | false | 4,455 | java | package in.clouthink.nextoa.bl.openapi.controller;
import in.clouthink.nextoa.bl.openapi.dto.*;
import in.clouthink.nextoa.bl.openapi.support.RoleRestSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Api("角色管理")
@RestController
@RequestMapping("/api/roles")
public class RoleRestControler {
@Autowired
private RoleRestSupport roleRestSupport;
@ApiOperation(value = "获取内置角色(角色管理)")
@RequestMapping(value = "/sysroles", method = RequestMethod.GET)
public List<RoleSummary> getSysRoles() {
return roleRestSupport.getSysRoles();
}
@ApiOperation(value = "获取内置角色(权限管理)")
@RequestMapping(value = "/sysroles/privilege", method = RequestMethod.GET)
public List<RoleSummary> getSysRoles4Privilege() {
return roleRestSupport.getSysRoles4Privilege();
}
@ApiOperation(value = "获取新增角色")
@RequestMapping(value = "/approles", method = RequestMethod.GET)
public Page<RoleSummary> getAppRoles(RoleQueryParameter request) {
return roleRestSupport.getAppRoles(request);
}
@ApiOperation(value = "获取新增角色(不分页)")
@RequestMapping(value = "/approles/list", method = RequestMethod.GET)
public List<RoleSummary> getAppRolesList() {
return roleRestSupport.getAppRolesList();
}
@ApiOperation(value = "获取内置角色对应用户")
@RequestMapping(value = "/sysroles/{id}/users", method = RequestMethod.GET)
public Page<UserSummary> getUsersBySysRoleId(@PathVariable String id,
UserQueryParameter request) {
return roleRestSupport.getUsersBySysRoleId(id, request);
}
@ApiOperation(value = "获取新增角色对应用户")
@RequestMapping(value = "/approles/{id}/users", method = RequestMethod.GET)
public Page<UserSummary> getUsersByAppRoleId(@PathVariable String id,
UserQueryParameter request) {
return roleRestSupport.getUsersByAppRoleId(id, request);
}
@ApiOperation(value = "新增角色")
@RequestMapping(value = "/approles", method = RequestMethod.POST)
public String createAppRole(@RequestBody SaveRoleParameter request) {
return roleRestSupport.createAppRole(request).getId();
}
@ApiOperation(value = "更新角色")
@RequestMapping(value = "/approles/{id}", method = RequestMethod.POST)
public void updateAppRole(@PathVariable String id,
@RequestBody SaveRoleParameter request) {
roleRestSupport.updateAppRole(id, request);
}
@ApiOperation(value = "删除角色")
@RequestMapping(value = "/approles/{id}", method = RequestMethod.DELETE)
public void deleteAppRole(@PathVariable String id) {
roleRestSupport.deleteAppRole(id);
}
@ApiOperation(value = "为角色绑定用户")
@RequestMapping(value = "/approles/{id}/bindUsers", method = RequestMethod.POST)
public void bindUsers4AppRole(@PathVariable String id,
@RequestBody UsersForRoleParameter request) {
roleRestSupport.bindUsers4AppRole(id, request);
}
@ApiOperation(value = "为角色解绑用户")
@RequestMapping(value = "/approles/{id}/unBindUsers", method = RequestMethod.POST)
public void unBindUsers4AppRole(@PathVariable String id,
@RequestBody UsersForRoleParameter request) {
roleRestSupport.unBindUsers4AppRole(id, request);
}
@ApiOperation(value = "为角色绑定用户")
@RequestMapping(value = "/sysroles/{id}/bindUsers", method = RequestMethod.POST)
public void bindUsers4SysRole(@PathVariable String id,
@RequestBody UsersForRoleParameter request) {
roleRestSupport.bindUsers4SysRole(id, request);
}
@ApiOperation(value = "为角色解绑用户")
@RequestMapping(value = "/sysroles/{id}/unBindUsers", method = RequestMethod.POST)
public void unBindUsers4SysRole(@PathVariable String id,
@RequestBody UsersForRoleParameter request) {
roleRestSupport.unBindUsers4SysRole(id, request);
}
}
| [
"melthaw@gmail.com"
] | melthaw@gmail.com |
58204201860ba535a78f4e0a815dc699a21c2ee8 | 4b11fb9c63e5673c47a6cc54c70c45bf8089c913 | /src/test/java/loginPageTests.java | ecbcea8b6ff8b54f4ce5f421426216d98acf853a | [] | no_license | HimanshuSingh09/PushApmplifyTestSuite | 230955b1186c827e793f48ac010feecc3a89fdf2 | 2be3d8f4513990237fafb96d7a1bb9409a852567 | refs/heads/master | 2020-03-31T06:03:57.179520 | 2018-10-07T18:18:30 | 2018-10-07T18:18:30 | 151,966,956 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,624 | java | import PageFactory.LoginPage;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import utils.ConfigFileReader;
import utils.ExcelUtils;
import utils.HelperDriverClass;
public class loginPageTests {
public WebDriver driver;
ConfigFileReader configFileReader=new ConfigFileReader();
@BeforeClass
public void startBrowser() throws Exception {
ExcelUtils.setExcelFile(configFileReader.getInputSheetPath(),"AUTOMATED TEST CASES");
HelperDriverClass helperDriverClass=new HelperDriverClass();
driver=helperDriverClass.SelectBrowser();
}
@Test(priority = 13)
public void VerifyLoginPageLink() throws Exception {
driver.get(configFileReader.getLoginPageUrl());
Thread.sleep(2000);
if (driver.getTitle().equalsIgnoreCase(configFileReader.getWindowTiltleOfLoginOrRegistrationPage())) {
ExcelUtils.setCellData("Login Page link is up and running", 1, 4);
ExcelUtils.setCellData("PASS", 1, 5);
}
else {
ExcelUtils.setCellData("Link not working", 1, 4);
ExcelUtils.setCellData("FAIL", 1, 5);
}
}
@Test(priority = 14)
public void VerifyRegisterLink() throws Exception {
driver.get(configFileReader.getLoginPageUrl());
LoginPage loginPage=new LoginPage(driver);
loginPage.clickOnRegisterButton();
Thread.sleep(3000);
String currentUrl=driver.getCurrentUrl();
if(configFileReader.getRegisterPageUrl().equalsIgnoreCase(currentUrl))
{
ExcelUtils.setCellData("Redirected to Registration page",4,4);
ExcelUtils.setCellData("PASS",4,5);
}
else
{
ExcelUtils.setCellData("Link not working",4,4);
ExcelUtils.setCellData("FAIL",4,5);
}
}
@Test(priority = 15)
public void VerifyLoginPageNegative() throws Exception {
driver.get(configFileReader.getLoginPageUrl());
LoginPage loginPage=new LoginPage(driver);
loginPage.LoginIntoAmplify("123com","1234");
Thread.sleep(3000);
String currentUrl=driver.getCurrentUrl();
if(currentUrl.equalsIgnoreCase(configFileReader.getLoginPageUrl()))
{
ExcelUtils.setCellData("login is unsuccessful and an error message is displayed",3,4);
ExcelUtils.setCellData("PASS",3,5);
}
else
{
ExcelUtils.setCellData("login is succesfull and redirected to dashbaord",3,4);
ExcelUtils.setCellData("FAIL",3,5);
}
}
@Test(priority = 16)
public void VerifyLoginPagePositive() throws Exception {
driver.get(configFileReader.getLoginPageUrl());
LoginPage loginPage = new LoginPage(driver);
loginPage.LoginIntoAmplify("tester@test.com", "1234");
Thread.sleep(3000);
String currentUrl = driver.getCurrentUrl();
if (currentUrl.equalsIgnoreCase(configFileReader.getLoginPageUrl())) {
ExcelUtils.setCellData("login is unsuccessful and an error message is displayed", 2, 4);
ExcelUtils.setCellData("FAIL", 2, 5);
}
else{
ExcelUtils.setCellData("login is successful and redirected to dashboard", 2, 4);
ExcelUtils.setCellData("PASS", 2, 5);
}
}
@AfterClass
public void closeup()
{
driver.close();
driver.quit();
}
}
| [
"himanshu93official@gmail.com"
] | himanshu93official@gmail.com |
de11bd20727d742bc074323ec5a4bbfbde688573 | 17583eee898dc6462a54cac9b79a64562086e77e | /src/paintballrun/BanderaEnemiga.java | 19a562764b33ea78cf36c9aa54f770fa1ce1e467 | [] | no_license | juandigv/PaintballRun | e9c4d73f12c0cfff91be6294c1764ff66504af7f | 68e5b575338b9ffb2aa9d01010a7886118f45d6d | refs/heads/master | 2021-09-10T13:11:00.656829 | 2018-03-26T20:39:51 | 2018-03-26T20:39:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 389 | java | package paintballrun;
import java.util.Random;
import javafx.scene.shape.Circle;
public class BanderaEnemiga extends Circle {
private Random r;
public BanderaEnemiga() {
super();
r = new Random();
this.setCenterX(r.nextInt(330) + 50);
this.setCenterY(45);
this.setRadius(40);
}
public void respawn() {
this.setCenterX(r.nextInt(330) + 50);
this.setCenterY(45);
}
}
| [
"juandigv69@gmail.com"
] | juandigv69@gmail.com |
b35eff62e5159d7b5f691993a059f5d955880336 | 74ddc3372848eb0fda0eb8f324f349d88f5c3fbd | /src/net/frebib/sscmailclient/Email.java | 055321151db063cca68ffeb4c65ad2ac39fab992 | [] | no_license | frebib/ssc-mailclient | e42bbab7c2d805031dd110d7e42a3836b61d3fea | bbf26e1cd0579018f060834d232a559b8e0ba99b | refs/heads/master | 2021-01-10T11:46:19.754394 | 2015-11-19T11:17:59 | 2015-11-19T11:22:49 | 45,434,106 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,135 | java | package net.frebib.sscmailclient;
import net.frebib.util.task.Worker;
import javax.mail.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Observable;
public class Email extends Observable {
private Address from;
private Address[] to;
private String subject;
private Date receivedDate;
private boolean read, recent, answered;
private Content content;
private List<CustomFlag> flags;
private Message msg;
public Email(Message msg) {
this.msg = msg;
flags = new ArrayList<>();
try {
from = msg.getFrom()[0];
to = msg.getAllRecipients();
subject = msg.getSubject();
receivedDate = msg.getReceivedDate();
read = msg.isSet(Flags.Flag.SEEN);
recent = msg.isSet(Flags.Flag.RECENT);
answered = msg.isSet(Flags.Flag.ANSWERED);
content = getContent(msg);
} catch (MessagingException e) {
MailClient.LOG.exception(e);
}
}
public Address[] getTo() {
return to;
}
public Address getFrom() {
return from;
}
public Content getContent() {
return content;
}
public Date getReceivedDate() {
return receivedDate;
}
public String getSubject() {
return subject;
}
public String getBody() {
return content.getBody();
}
public boolean isAnswered() {
return answered;
}
public boolean isRead() {
return read;
}
public boolean isRecent() {
return recent;
}
public void setAnswered(boolean answered) {
this.answered = answered;
setFlag(Flags.Flag.ANSWERED, answered);
}
public void setRead(boolean read) {
this.read = read;
setFlag(Flags.Flag.SEEN, read);
}
public void setRecent(boolean recent) {
this.recent = recent;
setFlag(Flags.Flag.RECENT, recent);
}
public void delete() {
setFlag(Flags.Flag.DELETED, true);
}
public void setCustomFlag(CustomFlag flag, boolean value) {
if (value && !flags.contains(flag))
flags.add(flag);
if (!value && flags.contains(flag))
flags.remove(flag);
setChanged();
notifyObservers();
}
public boolean hasCustomFlag(CustomFlag flag) {
return flags.contains(flag);
}
public void toggleCustomFlag(CustomFlag flag) {
setCustomFlag(flag, !hasCustomFlag(flag));
}
public String getFlags() {
return String.join(", ", flags.stream().map(s -> s.flag).toArray(String[]::new));
}
private void setFlag(Flags.Flag flag, boolean value) {
new Worker<>()
.todo((c, p) -> {
msg.setFlag(flag, value);
msg.getFolder().expunge();
}).done(e -> {
setChanged();
notifyObservers();
}).error(MailClient.LOG::exception);
}
private Content getContent(Part part) {
try {
// Is a text/html message
if (part.isMimeType("text/*")) {
return new TextContent(part);
} else {
return new MultipartContent(part);
}
} catch (MessagingException e) {
e.printStackTrace();
}
return null;
}
public interface Content {
String getBody();
}
public class TextContent implements Content {
protected Part part;
protected boolean downloaded = false;
protected String body;
public TextContent(Part part) {
this.part = part;
}
public String getType() {
try {
if (part.isMimeType("text/html"))
return "text/html";
else if (part.isMimeType("text/plain"))
return "text/plain";
else return null;
} catch (MessagingException e) {
MailClient.LOG.exception(e);
}
return null;
}
@Override
public String getBody() {
try {
if (!downloaded) {
downloaded = true;
body = (String) Email.this.msg.getContent();
}
return body;
} catch (Exception e) {
MailClient.LOG.exception(e);
}
return null;
}
}
public class MultipartContent extends TextContent {
private List<Content> contents;
public MultipartContent(Part part) {
super(part);
contents = new ArrayList<Content>();
}
@Override
public String getBody() {
try {
if (!downloaded) {
downloaded = true;
Multipart mp = (Multipart) part.getContent();
for (int i = 0; i < mp.getCount(); i++) {
Part part = mp.getBodyPart(i);
if (part.isMimeType("multipart/*")) {
// Yay recursion :D
Content subch = getContent(part);
String txt = subch.getBody();
if (txt != null)
body += txt;
contents.add(subch);
}
if (part.isMimeType("text/*")) {
body = (String) part.getContent();
break;
}
}
}
return body;
} catch (Exception e) {
MailClient.LOG.exception(e);
}
return null;
}
public Object[] getAttachments() {
return new Object[0];
}
}
public enum CustomFlag {
SPAM("!SPAM!"),
FLAG2("ABC"),
FLAG3("123");
public String flag;
CustomFlag(String flag) {
this.flag = flag;
}
}
}
| [
"frebib@gmail.com"
] | frebib@gmail.com |
7608229cb656b0876de2d1c0be7cd5e37f7f58fa | cb08a5a20c7fbede4e8ce0bc3f49e6fd52ba3541 | /dart-impl/src/main/java/com/jetbrains/lang/dart/psi/impl/DartInitializersImpl.java | 0ed6855d36c4cf2f47858ced9366bfe78079d584 | [] | no_license | yongwangy91/consulo-google-dart | 18d6de9abaa5b8914db31a830fd2ddbfaff73eeb | b0d3d506a0bf92147e617473f3b8091ec83c251a | refs/heads/master | 2023-01-18T17:01:52.010959 | 2020-10-20T18:24:38 | 2020-10-20T18:24:38 | 311,940,552 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | true | 884 | java | // This is a generated file. Not intended for manual editing.
package com.jetbrains.lang.dart.psi.impl;
import java.util.List;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import javax.annotation.Nonnull;
import com.jetbrains.lang.dart.psi.*;
public class DartInitializersImpl extends DartPsiCompositeElementImpl implements DartInitializers {
public DartInitializersImpl(ASTNode node) {
super(node);
}
public void accept(@Nonnull PsiElementVisitor visitor) {
if (visitor instanceof DartVisitor) ((DartVisitor)visitor).visitInitializers(this);
else super.accept(visitor);
}
@Override
@Nonnull
public List<DartSuperCallOrFieldInitializer> getSuperCallOrFieldInitializerList() {
return PsiTreeUtil.getChildrenOfTypeAsList(this, DartSuperCallOrFieldInitializer.class);
}
}
| [
"vistall.valeriy@gmail.com"
] | vistall.valeriy@gmail.com |
970b848eed553d1ce240db0e90e3e6f179b78e05 | 1af45aaa1a96a88aa0a49b69afab31e8447ac2bb | /composite/src/main/java/com/iluwatar/composite/own/Coder.java | 28496b4f6dc8142b64d616e08e308eec6bb88de2 | [
"MIT"
] | permissive | altuga/java-design-patterns | 94de63c6c458d4bbc6b9da99dcca7f76da70b08f | ee43d9aa04f863021d3f709532a8d7a465c0f4a4 | refs/heads/master | 2021-09-01T04:41:20.606992 | 2017-12-24T21:37:34 | 2017-12-24T21:37:34 | 112,590,752 | 7 | 1 | null | 2017-11-30T09:15:47 | 2017-11-30T09:15:47 | null | UTF-8 | Java | false | false | 661 | java | package com.iluwatar.composite.own;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Coder extends Employee {
private static final Logger LOGGER = LoggerFactory.getLogger(Coder.class);
public Coder(String name, double salary) {
this.setName( name );
this.setSalary(salary );
}
public void add(Employee employee) {
// leaf
}
public Employee getChild(int i) {
return null;
}
public void print() {
LOGGER.info("-------------");
LOGGER.info("Name ="+getName());
LOGGER.info("Salary ="+getSalary());
LOGGER.info("-------------");
}
}
| [
"upux1234"
] | upux1234 |
b3ba89dba4583832dbc71956b00d5573ec6ffacf | 9453c48ce7ffea86a5a46c952b04b2532e950a28 | /src/test/java/com/meli/mutants/data/repository/StatsRepositoryTest.java | e806b74369e3ec1a0dae13dd8277b56959d7a6c4 | [
"Apache-2.0"
] | permissive | calojamatt/mutant-project-mongo | d53c782649381ddb4116e37e0fce91605180bbd9 | 06b9dd3adce5b35889b6f37447d3a5b9d9f58dd9 | refs/heads/main | 2023-03-15T04:32:29.549827 | 2021-03-10T19:44:09 | 2021-03-10T19:44:09 | 349,893,215 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,396 | java | /*
* Carlos Alberto Maturana Mulett
*
* Copyright © 2021
* All right reserved.
*
* mutants-project
* StatsRepositoryTest.java
*/
package com.meli.mutants.data.repository;
import com.meli.mutants.MutantsApplicationTests;
import com.meli.mutants.data.entities.Stats;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests class for Stats Repository
*
* @author <a href:"carlos.maturana@dytssol.com">Carlos Maturana</a>
* @version 1.0.1
* @created 7/03/21 10:05 a. m.
* @since 1.0.0
*/
@ExtendWith(SpringExtension.class)
@SpringBootTest
class StatsRepositoryTest extends MutantsApplicationTests {
/** the stats repository to test*/
@Autowired
private StatsRepository statsRepository;
/**
*
* */
@Test
void generateStatistics_test() {
final Stats stats = statsRepository.generateStatistics();
assertNotNull(stats);
assertTrue(stats.getCountMutantDna() >= 0);
assertTrue(stats.getCountMutantDna() >= 0);
assertTrue(stats.getRatio() >= 0.0);
}
} | [
"carlosmaturanamulett@gmail.com"
] | carlosmaturanamulett@gmail.com |
6b0ebcacd053d30075eabf1aeaf81e6b51e6e820 | b49e4bd859345ba6685be62e9092f0869cee1d58 | /Code-It/Algorithms/src/slidingWindow/SumOfSubArrayK.java | d97be3edc7a3fb9645e1905191f207fc7b33f4f4 | [] | no_license | code-it/code-it | 077b5f71ae2e201067a4283292f15522c8c51b3d | 38a0803d2c6c30c795e3d1e697caa466cf5e1e94 | refs/heads/master | 2020-07-30T03:46:59.466957 | 2019-10-13T22:40:48 | 2019-10-13T22:40:48 | 210,075,691 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 865 | java | package slidingWindow;
import java.util.Arrays;
public class SumOfSubArrayK {
public static void main(String[] args) {
int[] a = {1,4,39,2,3,5,11,22,6};
int k=3;
SumOfSubArrayK sumOfSubArrayK = new SumOfSubArrayK();
int[] result = sumOfSubArrayK.sumOfSubArrayK(a,k);
System.out.println(Arrays.toString(result));
}
public int[] sumOfSubArrayK(int[] a, int k){
if(a==null || a.length==0 || k<=1)
return null;
int[] result = new int[a.length-k+1];
int start_index=0;
int winSum=0;
for(int winEnd=0;winEnd<a.length;winEnd++){
winSum += a[winEnd];
if(winEnd>=k-1){
result[start_index]=winSum;
winSum -= a[start_index];
start_index++;
}
}
return result;
}
}
| [
"codeitgranger@gmail.com"
] | codeitgranger@gmail.com |
72621b408faebbb958ab1f20cfc6508fbe963030 | c5adfb2cd553f582eb9135290c7a14eb8c063556 | /scm-event-log/src/main/java/org/ametiste/scm/log/boot/config/EventLogConfiguration.java | 3b5d313377aeac40753e89bad1c23e15da716eac | [] | no_license | LittleRain1984/ametiste-scm-event-log | 997acf22988b31f3f3f1d93ed4b9922eb501cd80 | 2f3ec5583917538e7f6763cf4543cd520d2f6bc5 | refs/heads/master | 2021-05-30T19:20:06.504219 | 2015-12-24T13:41:13 | 2015-12-24T13:41:13 | 109,091,389 | 1 | 0 | null | 2017-11-01T05:38:13 | 2017-11-01T05:38:13 | null | UTF-8 | Java | false | false | 888 | java | package org.ametiste.scm.log.boot.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* Main configuration of Event Log Application include configurations of necessary feature:
* <ul>
* <li><b>LoggingFeatureConfiguration</b> - components to provide logging incoming events to persistent storage.</li>
* <li><b>InformerFeatureConfiguration</b> - components to provide access to stored data.</li>
* <li><b>ReplayFeatureConfiguration</b> - components of event replay mechanism.</li>
* </ul><p>
* Any of this configurations is fully independent from other and can be used as standalone configuration.
*/
@Configuration
@Import({ LoggingFeatureConfiguration.class,
InformerFeatureConfiguration.class,
ReplayFeatureConfiguration.class })
public class EventLogConfiguration {
}
| [
"bliznyuk.andrey@gmail.com"
] | bliznyuk.andrey@gmail.com |
58ea1edf9063d93040121aae27d84baa0aa793f5 | 48660cb0f51f466768b3329b5a43a5af777cb35c | /09IntentsBroadcasts/app/src/main/java/com/example/a9intentsbroadcasts/ExplicitActivity.java | 0e27eeaa03a698a4906ee0b2cab300db0a9b9feb | [] | no_license | jermerf/androidclass | 36b49e5e6aa9d3dbaca69ad76d5898a0a4064a9f | d9a30564f609f5602f1b2d83fd1a7b41c7c7fe1f | refs/heads/master | 2022-12-25T19:24:38.130649 | 2020-10-07T11:22:21 | 2020-10-07T11:22:21 | 295,699,063 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 598 | java | package com.example.a9intentsbroadcasts;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class ExplicitActivity extends AppCompatActivity {
public static final String EXTRA_CONTENT = "EXTRAEXTRA";
private TextView txtStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_explicit);
txtStatus = findViewById(R.id.txtStatus);
txtStatus.setText(getIntent().getStringExtra(EXTRA_CONTENT));
}
} | [
"jermerf@gmail.com"
] | jermerf@gmail.com |
25152649ccd2a06a97cd08fbd93d11cd64ed8d51 | 52edb19bd200b8e289d3b8286fbafdc66f0d5ee0 | /Comparable.java | 9b92f348c74ead86f427469e3b14ab5cecd2d6cd | [] | no_license | mhuangg/SuperRepo | 1eae0b9f186905d55f8d18546e0e4a25bf91ff55 | 20d5e35f1f695286db2e5d4defa24c2744ba0004 | refs/heads/master | 2021-01-10T06:33:10.790171 | 2015-12-10T10:45:11 | 2015-12-10T10:45:11 | 47,703,723 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 64 | java | public interface Comparable {
Object compareTo(Object o);
}
| [
"mhuang5@stuy.edu"
] | mhuang5@stuy.edu |
6c38aabdef5231222a3a4467cedcb849c3bd90d7 | a6cacba283ac2547ab53196c001ccbfacf12d053 | /src/main/java/xiuqin/ml/knn/KNN.java | 648181f41e73df8b3d000c013bd55495c0806f8b | [] | no_license | pxiuqin/Statistical-Learning-Method_Code_Java | 67082608b3fbf3c8826a1bce227876a15dbff130 | 112cc93c5d997f5e09242eca33349653bf614a61 | refs/heads/master | 2023-01-15T22:23:54.531869 | 2020-11-13T07:05:58 | 2020-11-13T07:05:58 | 286,403,036 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,320 | java | package xiuqin.ml.knn;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.indexing.BooleanIndexing;
import org.nd4j.linalg.indexing.conditions.EqualsCondition;
import xiuqin.ml.ModelBase;
public class KNN extends ModelBase {
public static void main(String[] args) {
int topK = 25;
int labels = 10;
KNN knn = new KNN();
long currentTime = System.currentTimeMillis();
//1、读取训练数据
String filePath = "data/Mnist/mnist_train.csv";
System.out.println("read file:" + filePath);
knn.loadTrainData(filePath, ",");
//2、读取测试数据
filePath = "data/Mnist/mnist_test.csv";
System.out.println("read file:" + filePath);
knn.loadTestData(filePath, ",");
//3、进行测试并获得准确率
System.out.println("training data");
double accuracy = knn.modelTest(topK, labels);
System.out.println("accuracy rate is " + accuracy);
//4、计算所用时间
System.out.println((System.currentTimeMillis() - currentTime) / 1000);
}
private double calcDistance(INDArray x1, INDArray x2) {
return x1.distance2(x2); //EuclideanDistance
}
/**
* get closest sample label
*
* @param sample test sample
* @param topK topK
* @param labels count of label
* @return label
*/
private long getClosest(INDArray sample, int topK, int labels) {
//distance of one sample to training sample
INDArray distArray = Nd4j.zeros(this.trainDataArr.rows());
for (int i = 0; i < this.trainDataArr.rows(); i++) {
INDArray each = this.trainDataArr.getRow(i);
//calc distance
double dist = calcDistance(sample, each);
//add distList
distArray.putScalar(i, dist);
}
//sort the distList
INDArray topKArray = distArray.dup();
Nd4j.sort(topKArray, true);
//create a labelList to store the number of votes
INDArray labelArray = Nd4j.zeros(labels);
//voting
for (int i = 0; i < topK; i++) {
double dist = topKArray.getDouble(i); //get dist value
int index = BooleanIndexing.firstIndex(distArray, new EqualsCondition(dist)).getInt(0); //get topK index
int label = this.trainLabelArr.getInt(index); //trans index to label
labelArray.putScalar(label, labelArray.getInt(label) + 1); //votes accumulate
}
//return max vote label
return BooleanIndexing
.firstIndex(labelArray, new EqualsCondition(Nd4j.max(labelArray).getInt(0)))
.getInt(0);
}
private double modelTest(int topK, int labels) {
int errorCount = 0;
int testCount = 200; //this.testDataArr.rows();
for (int i = 0; i < testCount; i++) {
INDArray each = this.testDataArr.getRow(i);
long label = getClosest(each, topK, labels);
if (label != this.testLabelArr.getLong(i)) {
errorCount += 1;
}
if (i % 10 == 0) {
System.out.println("testing:" + i);
}
}
return 1 - 1.0 * errorCount / testCount;
}
}
| [
"liangxiuqin@mininglamp.com"
] | liangxiuqin@mininglamp.com |
b902a1612e30c035c367601406883c1276494497 | fe1722cf5eb65792fae37d9c414796dbb7459eaa | /Heap/Java/src/com/ssanusi/Main.java | 408b6d391472f6cae3d50c5963f8ab6a6816c2ad | [] | no_license | ssanusi/Data-Structure | 1421e3b6ec9ccc03e3014385737c1934d4c2358d | edbd4725596767a8c6edcc6b745bbf0d5b500d41 | refs/heads/master | 2021-01-02T21:51:01.799003 | 2020-02-26T02:51:42 | 2020-02-26T02:51:42 | 239,814,879 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 752 | java | package com.ssanusi;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
var heap = new Heap(10);
heap.insert(10);
heap.insert(5);
heap.insert(17);
heap.insert(4);
heap.insert(22);
heap.remove();
System.out.println("Done");
int[] numbers = { 5, 3, 10, 1, 4, 2 };
var heap2 = new Heap(10);
for(var number: numbers)
heap2.insert(number);
for (var i = numbers.length - 1; i >= 0; i--){
numbers[i] = heap2.remove();
}
System.out.println(Arrays.toString(numbers));
//Max Heap
MaxHeap.heapify(numbers);
System.out.println(Arrays.toString(numbers));
System.out.println(MaxHeap.getKthLargest(numbers, 7));
}
}
| [
"sulaiman.sanusi@icloud.com"
] | sulaiman.sanusi@icloud.com |
06ae4b58d99f1f90aa9b7c969e3c80df434a9a99 | 544202bfbd4d7e7669a9096f50e3823125bffef0 | /app/src/main/java/com/krsolutions/upstack/adapter/SelectedTagItemAdapter.java | 5701b1866a9f3e02f95a2bc7350f8de71df76d84 | [] | no_license | KunalRaghav/upStack | 108ca2aef312c8aebc54d953988ea9b4ee206d05 | deebc8e3b7c7b54de0200ebbaa1de886fa5b9b9b | refs/heads/master | 2020-05-09T22:46:52.124750 | 2019-05-03T12:12:33 | 2019-05-03T12:12:33 | 181,482,142 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,655 | java | package com.krsolutions.upstack.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.material.button.MaterialButton;
import com.krsolutions.upstack.R;
import com.krsolutions.upstack.viewmodel.TagItem;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class SelectedTagItemAdapter extends RecyclerView.Adapter<SelectedTagItemAdapter.ViewHolder> {
List<TagItem> selectedTags;
public SelectedTagItemAdapter(List<TagItem> selectedTags) {
this.selectedTags = selectedTags;
}
public void setSelectedTags(List<TagItem> selectedTags) {
this.selectedTags = selectedTags;
}
@NonNull
@Override
public SelectedTagItemAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_item_tag_selected,parent,false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull SelectedTagItemAdapter.ViewHolder holder, int position) {
holder.button.setText(selectedTags.get(position).getName());
}
@Override
public int getItemCount() {
return selectedTags.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
MaterialButton button;
public ViewHolder(@NonNull View itemView) {
super(itemView);
button=itemView.findViewById(R.id.selectedTag);
}
}
}
| [
"kraghav123@gmail.com"
] | kraghav123@gmail.com |
ee77214f254491d802331f8d88be3504e76aad61 | 925bc93135c98d9d9a2040d6407e7a54003f9d5f | /backend/java/src/atm/Cards.java | c72a4aa8b49b7e8cc1488f8f0ab2178cdc4f5b9f | [] | no_license | AparnnaKallarackal/TY_CG_HTD_BangaloreNovember_JFS_AparnnaKs | a526c47a650a9b5e0abb3d163fc789e3afcfa55d | 71b067d0754192663d00d03cd26fa5b57058ff32 | refs/heads/master | 2020-09-24T21:22:19.364642 | 2019-12-22T06:10:25 | 2019-12-22T06:10:25 | 225,846,231 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 97 | java | package atm;
public class Cards {
void swipe()
{
System.out.println("card accepted");
}
}
| [
"apkallarackal12@gmail.com"
] | apkallarackal12@gmail.com |
dd54727d443eb32743df0bd12b49e91b900f3630 | beb2f74b1e5e4c02d981461df7b71e7fe4872a76 | /models/EarthMovingMiningAndConstruction.java | 3f13359ad6ac7baaa79393e58df39d1264e063ad | [] | no_license | sakshi512/lixi | 7e2cc9baebbb9750c8bd18c177ee52c60f217d2c | 17d875a0c1afcdc97b3046442ef35246976652e0 | refs/heads/master | 2023-01-22T14:20:21.002967 | 2020-11-19T12:10:13 | 2020-11-19T12:10:13 | 314,234,071 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 699 | java | package io.model;
import com.fasterxml.jackson.annotation.*;
@lombok.Data
public class EarthMovingMiningAndConstruction {
private String additionalIDType;
private String additionalIDValue;
private Long age;
private ConditionList condition;
private String conditionDescription;
private String description;
private Double effectiveLife;
private GoodToBeUsedLocationList goodToBeUsedLocation;
private String make;
private String model;
private String otherInformation;
private Long quantity;
private String serialNumber;
private EarthMovingMiningAndConstructionTypeList type;
private String xGoodToBeUsedAddress;
private String year;
}
| [
"sakshi.aggarwal@thoughtworks.com"
] | sakshi.aggarwal@thoughtworks.com |
f4c1144f8d63fe8392734a3235d1abce6e4e4b6f | 1cf1c4e00c4b7b2972d8c0b32b02a17e363d31b9 | /sources/com/google/android/gms/internal/ads/C1261eb.java | 5034b088c070a68b14fb8123b639b532ada12949 | [] | no_license | rootmelo92118/analysis | 4a66353c77397ea4c0800527afac85e06165fd48 | a9cd8bb268f54c03630de8c6bdff86b0e068f216 | refs/heads/main | 2023-03-16T10:59:50.933761 | 2021-03-05T05:36:43 | 2021-03-05T05:36:43 | 344,705,815 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,616 | java | package com.google.android.gms.internal.ads;
/* renamed from: com.google.android.gms.internal.ads.eb */
public abstract class C1261eb extends azd implements C1260ea {
public C1261eb() {
super("com.google.android.gms.ads.internal.formats.client.IUnifiedNativeAd");
}
/* JADX WARNING: type inference failed for: r2v2, types: [android.os.IInterface] */
/* access modifiers changed from: protected */
/* JADX WARNING: Multi-variable type inference failed */
/* JADX WARNING: Unknown variable types count: 1 */
/* Code decompiled incorrectly, please refer to instructions dump. */
public final boolean dispatchTransaction(int r1, android.os.Parcel r2, android.os.Parcel r3, int r4) {
/*
r0 = this;
switch(r1) {
case 2: goto L_0x0154;
case 3: goto L_0x0149;
case 4: goto L_0x013e;
case 5: goto L_0x0133;
case 6: goto L_0x0128;
case 7: goto L_0x011d;
case 8: goto L_0x0112;
case 9: goto L_0x0107;
case 10: goto L_0x00fc;
case 11: goto L_0x00f1;
case 12: goto L_0x00e5;
case 13: goto L_0x00dd;
case 14: goto L_0x00d1;
case 15: goto L_0x00c1;
case 16: goto L_0x00ad;
case 17: goto L_0x009d;
case 18: goto L_0x0091;
case 19: goto L_0x0085;
case 20: goto L_0x0079;
case 21: goto L_0x0055;
case 22: goto L_0x004d;
case 23: goto L_0x0041;
case 24: goto L_0x0035;
case 25: goto L_0x0025;
case 26: goto L_0x0015;
case 27: goto L_0x000d;
case 28: goto L_0x0005;
default: goto L_0x0003;
}
L_0x0003:
r1 = 0
return r1
L_0x0005:
r0.mo11608x()
r3.writeNoException()
goto L_0x015e
L_0x000d:
r0.mo11607w()
r3.writeNoException()
goto L_0x015e
L_0x0015:
android.os.IBinder r1 = r2.readStrongBinder()
com.google.android.gms.internal.ads.bst r1 = com.google.android.gms.internal.ads.bsu.m6362a(r1)
r0.mo11585a((com.google.android.gms.internal.ads.bst) r1)
r3.writeNoException()
goto L_0x015e
L_0x0025:
android.os.IBinder r1 = r2.readStrongBinder()
com.google.android.gms.internal.ads.bsx r1 = com.google.android.gms.internal.ads.bsy.m6366a(r1)
r0.mo11586a((com.google.android.gms.internal.ads.bsx) r1)
r3.writeNoException()
goto L_0x015e
L_0x0035:
boolean r1 = r0.mo11592h()
r3.writeNoException()
com.google.android.gms.internal.ads.aze.m4504a((android.os.Parcel) r3, (boolean) r1)
goto L_0x015e
L_0x0041:
java.util.List r1 = r0.mo11591g()
r3.writeNoException()
r3.writeList(r1)
goto L_0x015e
L_0x004d:
r0.mo11609y()
r3.writeNoException()
goto L_0x015e
L_0x0055:
android.os.IBinder r1 = r2.readStrongBinder()
if (r1 != 0) goto L_0x005d
r1 = 0
goto L_0x0071
L_0x005d:
java.lang.String r2 = "com.google.android.gms.ads.internal.formats.client.IUnconfirmedClickListener"
android.os.IInterface r2 = r1.queryLocalInterface(r2)
boolean r4 = r2 instanceof com.google.android.gms.internal.ads.C1256dx
if (r4 == 0) goto L_0x006b
r1 = r2
com.google.android.gms.internal.ads.dx r1 = (com.google.android.gms.internal.ads.C1256dx) r1
goto L_0x0071
L_0x006b:
com.google.android.gms.internal.ads.dz r2 = new com.google.android.gms.internal.ads.dz
r2.<init>(r1)
r1 = r2
L_0x0071:
r0.mo11587a((com.google.android.gms.internal.ads.C1256dx) r1)
r3.writeNoException()
goto L_0x015e
L_0x0079:
android.os.Bundle r1 = r0.mo11604t()
r3.writeNoException()
com.google.android.gms.internal.ads.aze.m4507b(r3, r1)
goto L_0x015e
L_0x0085:
com.google.android.gms.a.a r1 = r0.mo11602r()
r3.writeNoException()
com.google.android.gms.internal.ads.aze.m4502a((android.os.Parcel) r3, (android.os.IInterface) r1)
goto L_0x015e
L_0x0091:
com.google.android.gms.a.a r1 = r0.mo11601q()
r3.writeNoException()
com.google.android.gms.internal.ads.aze.m4502a((android.os.Parcel) r3, (android.os.IInterface) r1)
goto L_0x015e
L_0x009d:
android.os.Parcelable$Creator r1 = android.os.Bundle.CREATOR
android.os.Parcelable r1 = com.google.android.gms.internal.ads.aze.m4501a((android.os.Parcel) r2, r1)
android.os.Bundle r1 = (android.os.Bundle) r1
r0.mo11589c(r1)
r3.writeNoException()
goto L_0x015e
L_0x00ad:
android.os.Parcelable$Creator r1 = android.os.Bundle.CREATOR
android.os.Parcelable r1 = com.google.android.gms.internal.ads.aze.m4501a((android.os.Parcel) r2, r1)
android.os.Bundle r1 = (android.os.Bundle) r1
boolean r1 = r0.mo11588b(r1)
r3.writeNoException()
com.google.android.gms.internal.ads.aze.m4504a((android.os.Parcel) r3, (boolean) r1)
goto L_0x015e
L_0x00c1:
android.os.Parcelable$Creator r1 = android.os.Bundle.CREATOR
android.os.Parcelable r1 = com.google.android.gms.internal.ads.aze.m4501a((android.os.Parcel) r2, r1)
android.os.Bundle r1 = (android.os.Bundle) r1
r0.mo11584a((android.os.Bundle) r1)
r3.writeNoException()
goto L_0x015e
L_0x00d1:
com.google.android.gms.internal.ads.bz r1 = r0.mo11605u()
r3.writeNoException()
com.google.android.gms.internal.ads.aze.m4502a((android.os.Parcel) r3, (android.os.IInterface) r1)
goto L_0x015e
L_0x00dd:
r0.mo11606v()
r3.writeNoException()
goto L_0x015e
L_0x00e5:
java.lang.String r1 = r0.mo11603s()
r3.writeNoException()
r3.writeString(r1)
goto L_0x015e
L_0x00f1:
com.google.android.gms.internal.ads.btb r1 = r0.mo11600p()
r3.writeNoException()
com.google.android.gms.internal.ads.aze.m4502a((android.os.Parcel) r3, (android.os.IInterface) r1)
goto L_0x015e
L_0x00fc:
java.lang.String r1 = r0.mo11599o()
r3.writeNoException()
r3.writeString(r1)
goto L_0x015e
L_0x0107:
java.lang.String r1 = r0.mo11598n()
r3.writeNoException()
r3.writeString(r1)
goto L_0x015e
L_0x0112:
double r1 = r0.mo11597m()
r3.writeNoException()
r3.writeDouble(r1)
goto L_0x015e
L_0x011d:
java.lang.String r1 = r0.mo11596l()
r3.writeNoException()
r3.writeString(r1)
goto L_0x015e
L_0x0128:
java.lang.String r1 = r0.mo11595k()
r3.writeNoException()
r3.writeString(r1)
goto L_0x015e
L_0x0133:
com.google.android.gms.internal.ads.ce r1 = r0.mo11594j()
r3.writeNoException()
com.google.android.gms.internal.ads.aze.m4502a((android.os.Parcel) r3, (android.os.IInterface) r1)
goto L_0x015e
L_0x013e:
java.lang.String r1 = r0.mo11593i()
r3.writeNoException()
r3.writeString(r1)
goto L_0x015e
L_0x0149:
java.util.List r1 = r0.mo11236f()
r3.writeNoException()
r3.writeList(r1)
goto L_0x015e
L_0x0154:
java.lang.String r1 = r0.mo11590e()
r3.writeNoException()
r3.writeString(r1)
L_0x015e:
r1 = 1
return r1
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.android.gms.internal.ads.C1261eb.dispatchTransaction(int, android.os.Parcel, android.os.Parcel, int):boolean");
}
}
| [
"rootmelo92118@gmail.com"
] | rootmelo92118@gmail.com |
ee476ae54673d70edd0334063d25805731a59577 | f8f22a09f879cc3f6350037607a88d09b237eb4a | /Laicode/BinarySearch/SmallestElementLargerThanTarget_M.java | 3d458714a12d1b8a20403d67e26b637f3c424159 | [] | no_license | HarryWei666lol/Algorithm-Self-Training | 446eafc0fae13bfb3c5f6b2efd53601b013348de | edf52e2c53efec0288e971da4105d30a27e6013f | refs/heads/master | 2022-04-09T02:05:42.736459 | 2020-03-17T21:20:19 | 2020-03-17T21:20:19 | 230,165,081 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 559 | java | package BinarySearch;
public class SmallestElementLargerThanTarget_M {
public int smallestElementLargerThanTarget(int[] array, int target) {
// Write your solution here
if(array == null || array.length == 0){
return -1;
}
int left = 0;
int right = array.length - 1;
while(left < right -1){
int mid = left + (right - left) / 2;
if(array[mid] <= target){
left = mid + 1;
} else {
right = mid;
}
}
if(array[left] > target){
return left;
} else if (array[right] > target){
return right;
}
return -1;
}
}
| [
"wei.xianda@wustl.edu"
] | wei.xianda@wustl.edu |
73d518cf691253e33481d98066d2be92edee8043 | 3954cc187b338ca7c751c75b6aae3ae5dec9eb07 | /src/main/java/com/bxwl/admin/sys/utils/SessionUtils.java | 6768e28cf1fe55ca8a41a737bb64d6446ab5f6d5 | [] | no_license | michunxulove2/dev | 7c7be61d2cec54324894d6c9d24363b0b54d678f | d518e0a5adaf0a5551341ae21c40f87b24f179c5 | refs/heads/master | 2023-02-22T00:58:28.752090 | 2021-02-01T13:01:19 | 2021-02-01T13:01:19 | 334,901,315 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,257 | java | package com.bxwl.admin.sys.utils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.bxwl.admin.sys.model.SysUser;
public class SessionUtils {
private static final String LOGIN_SESSION_KEY = "loginUser";
/**
* 用户登录
* @param request
* @param sysUser
*/
public static void login(HttpServletRequest request,SysUser sysUser) {
HttpSession session=request.getSession(true);
session.setAttribute(LOGIN_SESSION_KEY, sysUser);
}
/**
* 获取登录用户信息
* @param request
* @return
*/
public static SysUser getUser(HttpServletRequest request) {
return (SysUser)request.getSession().getAttribute(LOGIN_SESSION_KEY);
}
/**
* 获取登录IP
* @param request
* @return
*/
public static String getIpAdrress(HttpServletRequest request) {
String ip = null;
//X-Forwarded-For:Squid 服务代理
String ipAddresses = request.getHeader("X-Forwarded-For");
String unknown = "unknown";
if (ipAddresses == null || ipAddresses.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
//Proxy-Client-IP:apache 服务代理
ipAddresses = request.getHeader("Proxy-Client-IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
//WL-Proxy-Client-IP:weblogic 服务代理
ipAddresses = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
//HTTP_CLIENT_IP:有些代理服务器
ipAddresses = request.getHeader("HTTP_CLIENT_IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
//X-Real-IP:nginx服务代理
ipAddresses = request.getHeader("X-Real-IP");
}
//有些网络通过多层代理,那么获取到的ip就会有多个,一般都是通过逗号(,)分割开来,并且第一个ip为客户端的真实IP
if (ipAddresses != null && ipAddresses.length() != 0) {
ip = ipAddresses.split(",")[0];
}
//还是不能获取到,最后再通过request.getRemoteAddr();获取
if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ipAddresses)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
| [
"364379229@qq.com"
] | 364379229@qq.com |
993395678052b9189fda07e17d3ad39097e3e073 | bd37f9f6413b40abf8b80337efb3c613e2e866dc | /jfact/src/uk/ac/manchester/cs/jfact/kernel/dl/ConceptDataMinCardinality.java | fa3c84eea2054e6dd59b5d93fb0bed37a1e8eb16 | [] | no_license | w00tzenheimer/jfact | 981af29bf61216b89760f100d875ef1313ea4abd | 4ef321f52e700119ac6538d4747b7d4d19ea0ac0 | refs/heads/master | 2021-05-27T08:57:48.978076 | 2012-11-05T23:28:26 | 2012-11-05T23:28:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,222 | java | package uk.ac.manchester.cs.jfact.kernel.dl;
/* This file is part of the JFact DL reasoner
Copyright 2011 by Ignazio Palmisano, Dmitry Tsarkov, University of Manchester
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA*/
import uk.ac.manchester.cs.jfact.kernel.dl.interfaces.ConceptDataCardinalityExpression;
import uk.ac.manchester.cs.jfact.kernel.dl.interfaces.DataExpression;
import uk.ac.manchester.cs.jfact.kernel.dl.interfaces.DataRoleArg;
import uk.ac.manchester.cs.jfact.kernel.dl.interfaces.DataRoleExpression;
import uk.ac.manchester.cs.jfact.visitors.DLExpressionVisitor;
import uk.ac.manchester.cs.jfact.visitors.DLExpressionVisitorEx;
public class ConceptDataMinCardinality implements ConceptDataCardinalityExpression,
DataRoleArg {
/** data role argument */
private DataRoleExpression dataRoleExpression;
private int delegate;
private DataExpression delegateExpression;
public ConceptDataMinCardinality(int n, DataRoleExpression R, DataExpression E) {
dataRoleExpression = R;
delegateExpression = E;
delegate = n;
}
public void accept(DLExpressionVisitor visitor) {
visitor.visit(this);
}
public <O> O accept(DLExpressionVisitorEx<O> visitor) {
return visitor.visit(this);
}
public int getCardinality() {
return delegate;
}
/** get access to the argument */
public DataRoleExpression getDataRoleExpression() {
return dataRoleExpression;
}
public DataExpression getExpr() {
return delegateExpression;
}
}
| [
"ignazio.palmisano@gmail.com"
] | ignazio.palmisano@gmail.com |
6e01ce7495b71bdaab83a09a51e5b13b08622017 | e30b5dd58a4c42356897c890eb09709ecae4b634 | /common/src/main/java/com/serenegiant/glutils/RenderHolderCallback.java | 943d8ee91c3497950fa7629511ac7d5def4efc20 | [
"Apache-2.0"
] | permissive | xiaopao2014/ScreenRecordingSample | 23e4662a76ad777bc56db2bd0ebabc5c26fed3e1 | 82fb4d0332982ded2c1bcd16b0667f68f65ba2ef | refs/heads/master | 2020-06-20T11:28:51.830973 | 2019-07-18T06:55:41 | 2019-07-18T06:55:41 | 197,108,583 | 0 | 0 | null | 2019-07-16T02:49:11 | 2019-07-16T02:49:11 | null | UTF-8 | Java | false | false | 940 | java | package com.serenegiant.glutils;
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2016 saki t_saki@serenegiant.com
*
* 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.
*/
import android.view.Surface;
/**
* RenderHolderのコールバックリスナー
*/
public interface RenderHolderCallback {
public void onCreate(Surface surface);
public void onFrameAvailable();
public void onDestroy();
}
| [
"linliangbin@ruijie.com.cn"
] | linliangbin@ruijie.com.cn |
2ae6f819d803785bcf92d636a1a78eabd5a27abc | 98a8fc7596ff0706e7132a055f84cfaca92f5f7e | /Factory/FoodFactory.java | df700b1314649fe489b94f4b41726e5eaa8410e6 | [] | no_license | Maaz-hussain/Food-Ordering-System-with-Software-Design-Pattern | f4d5258d1ac50e486baef1bd232c82b37f233551 | 236a81a05fa052eae1a7323c5f2ac03653eceab4 | refs/heads/master | 2022-10-20T09:37:20.610114 | 2020-06-09T22:41:42 | 2020-06-09T22:41:42 | 271,124,378 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 508 | java |
package Factory;
public class FoodFactory {
public Factory.Food getFood(String foodType) {
if (foodType == null) {
return null;
}
if (foodType.equalsIgnoreCase("itemCategory")) {
return new ItemCategoryClass();
} else if (foodType.equalsIgnoreCase("item")) {
return new ItemClass();
} else if (foodType.equalsIgnoreCase("staff")) {
return new StaffClass();
}
return null;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
50abaad673c0f2e9f45c1b55ebc7fc4a99818286 | 46a4048ebd8a9c47e9d33ce26ef326908eb8c401 | /control_panel/console/src/main/java/ge/edu/tsu/handwriting_recognition/control_panel/console/ui/ControlPanel.java | a2d03720dd86670ecc2d44e9207990e00cad962a | [] | no_license | igobronidze/handwriting-recognition | 4f8f470a08a4a436611efb1ffe2f467a42f1dfff | 93c3fd5266e8f9a23f07ce416d5e7869edc8a891 | refs/heads/master | 2020-06-14T00:01:55.269546 | 2017-06-18T08:02:05 | 2017-06-18T08:02:05 | 75,542,273 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,398 | java | package ge.edu.tsu.handwriting_recognition.control_panel.console.ui;
import ge.edu.tsu.handwriting_recognition.control_panel.console.resources.Messages;
import ge.edu.tsu.handwriting_recognition.control_panel.console.utils.StageUtils;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ControlPanel extends Application {
private VBox root;
private Label titleLabel;
private FlowPane flowPane;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle(Messages.get("controlPanel"));
initUI();
primaryStage.setScene(new Scene(root));
StageUtils.setMaxSize(primaryStage);
primaryStage.show();
}
private void initUI() {
root = new VBox();
root.setAlignment(Pos.TOP_CENTER);
root.setSpacing(30);
root.setPadding(new Insets(20, 20, 20, 20));
titleLabel = new Label(Messages.get("projectControlPanel"));
titleLabel.setStyle("-fx-font-family: sylfaen; -fx-font-size: 25; -fx-text-fill: blue");
root.getChildren().add(titleLabel);
flowPane = new FlowPane();
flowPane.setHgap(10);
flowPane.setVgap(10);
addButton(new DataCreatorWithGrid(), Messages.get("dataCreatorWithGrid"));
addButton(new SystemParameterWindow(), Messages.get("systemParameter"));
addButton(new DataCreatorWithDraw(), Messages.get("dataCreatorWithDraw"));
addButton(new NeuralNetworkControlWindow(), Messages.get("neuralNetworkControl"));
root.getChildren().addAll(flowPane);
}
private void addButton(Stage stage, String text) {
Button button = new Button(text);
button.setStyle("-fx-font-family: sylfaen; -fx-font-size: 20; -fx-text-fill: brown");
button.setPrefWidth(350);
button.setPrefHeight(60);
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
stage.show();
}
});
flowPane.getChildren().addAll(button);
}
}
| [
"gobronidze.ioseb@gmail.com"
] | gobronidze.ioseb@gmail.com |
60829d5c9bef0493538c1ff7d46913bf7cfcb0f7 | 2387c7cb4698b1203fe5d225a751961b704653dd | /messages/src/main/java/org/fixtrading/orchestra/repository/messages/Serializer.java | 031c369f6f0257a35fba0c856b7e95af3d891f99 | [
"Apache-2.0"
] | permissive | jacobnorthey-itiviti/fix-orchestra | d46a53dc50614ccdfb34276ae79626769d0df2d0 | 8629ce663b9b17a983d7b936d02abf9cd30996f9 | refs/heads/master | 2021-01-21T07:35:07.801028 | 2016-07-19T19:06:23 | 2016-07-19T19:06:23 | 63,724,582 | 0 | 0 | null | 2016-07-19T20:08:23 | 2016-07-19T20:08:23 | null | UTF-8 | Java | false | false | 2,106 | java | /**
* Copyright 2016 FIX Protocol Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package org.fixtrading.orchestra.repository.messages;
import java.io.InputStream;
import java.io.OutputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.fixtrading.orchestra.repository.jaxb.FixRepository;
/**
* Serializes or deserializes a FIX Repository
*
* @author Don Mendelson
*
*/
public final class Serializer {
private Serializer() {
}
/**
* Serializes a repository to an output stream
* @param jaxbElement root element of tree to marshal
* @param outputStream stream to write to
* @throws JAXBException if a marshalling error occurs
*/
public static void marshal(FixRepository jaxbElement, OutputStream outputStream)
throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(FixRepository.class);
javax.xml.bind.Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.marshal(jaxbElement, outputStream);
}
/**
* Deserializes a repository from an input stream
* @param inputStream stream to read
* @return the root element of the repository tree
* @throws JAXBException if an unmarshalling error occurs
*/
public static FixRepository unmarshal(InputStream inputStream) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(FixRepository.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return (FixRepository) jaxbUnmarshaller.unmarshal(inputStream);
}
}
| [
"donmendelson@gmail.com"
] | donmendelson@gmail.com |
cbb332c46d4c937efaa048ef142b22ac06ff021c | cec305848b64a063c09597d988c670052976c45e | /src/com/example/videoplayer/InfoActivity.java | 7739cb41ef88c64806dae157eb8cad8cdc8686c9 | [] | no_license | Town1201/VideoPlayer | 49f57fe00625adc6c0c14730140d098a81c32b4b | bea5460e5e8598154a46697e1f217c67dcc8dc07 | refs/heads/master | 2021-01-20T08:16:11.295511 | 2017-05-03T08:29:16 | 2017-05-03T08:29:16 | 90,125,226 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 481 | java | package com.example.videoplayer;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
public class InfoActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setTitle("关于软件");
}
}
| [
"town1201@163.com"
] | town1201@163.com |
f7759902296cb1d948de8126861e8a24788bdc2d | c75e6df08eb4065ab80fcc1dcc1cb38ac1256f72 | /web/plugins/com.seekon.nextbi.palo.api/src/org/palo/api/subsets/filter/settings/AbstractParameter.java | f4cab75ca25e14c664e94c9a9e6fc16de06962f7 | [] | no_license | jerome-nexedi/nextbi | 7b219c1ec64b21bebf4ccf77c730e15a8ad1c6de | 0179b30bf6a86ae6a070434a3161d7935f166b42 | refs/heads/master | 2021-01-10T09:06:15.838199 | 2012-11-14T11:59:53 | 2012-11-14T11:59:53 | 36,644,370 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,953 | java | /*
*
* @file AbstractParameter.java
*
* Copyright (C) 2006-2009 Tensegrity Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as published
* by the Free Software Foundation at http://www.gnu.org/copyleft/gpl.html.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*
* If you are developing and distributing open source applications under the
* GPL License, then you are free to use JPalo Modules under the GPL License. For OEMs,
* ISVs, and VARs who distribute JPalo Modules with their products, and do not license
* and distribute their source code under the GPL, Tensegrity provides a flexible
* OEM Commercial License.
*
* @author ArndHouben
*
* @version $Id: AbstractParameter.java,v 1.2 2009/04/29 10:21:57 PhilippBouillon Exp $
*
*/
/*
* (c) Tensegrity Software 2008
* All rights reserved
*/
package org.palo.api.subsets.filter.settings;
import org.palo.api.subsets.Subset2;
/**
* <code>AbstractParameter</code>
* TODO DOCUMENT ME
*
* @author ArndHouben
* @version $Id: AbstractParameter.java,v 1.2 2009/04/29 10:21:57 PhilippBouillon Exp $
**/
abstract class AbstractParameter implements Parameter {
private Subset2 subset;
public final void bind(Subset2 subset) {
this.subset = subset;
markDirty();
}
public final void unbind() {
subset = null;
}
protected final void markDirty() {
if (subset != null)
subset.modified();
}
}
| [
"undyliu@126.com"
] | undyliu@126.com |
d02fd9ff14e54d6416aa299cc99d2813b9b92b58 | 51cb67eabcfcea0e57ad723e66ff418cd7c13275 | /src/Main.java | 66f2673efdc30301a108ead9d83b95d449b05c29 | [] | no_license | svitorio/ClientActiveMQ | a1995411884176a44798ef79e54247596887a13b | be7a0b5b9660f335c73dfa55d93ed8ae294a890f | refs/heads/master | 2021-01-23T08:33:53.597343 | 2017-09-19T21:10:21 | 2017-09-19T21:10:21 | 102,534,644 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 472 | java | import javax.swing.*;
public class Main {
public static Window janela;
private static void initialize() {
janela = new Window(380, 620);
MainPanel painel = new MainPanel(janela.getWidth() - 10, janela.getHeight() - 60);
janela.add(painel);
janela.setTitle("Calculadora");
janela.setResizable(false);
janela.setVisible(true);
}
public static void main(String[] args) {
initialize();
}
}
| [
"s.vitorio.alves@gmail.com"
] | s.vitorio.alves@gmail.com |
b860e1a6a789d6312c6f3e19460863fd1c707886 | e262954f86d020b3be5e612641c0aa28af357685 | /wualasync/src/com/laksrecordings/wualasync/SyncFilesUIUpdaterListener.java | 1ee60a74492b902d9ca1e74ad91ac14e7947e3e3 | [] | no_license | nagyistoce/wualasync | 4a0f1279bb6c14215e09965348d905ec0a991c49 | a0293e54d14d882dde0f4f3382dc4f2843853307 | refs/heads/master | 2021-01-01T19:24:27.625332 | 2012-07-09T13:02:05 | 2012-07-09T13:02:05 | 40,163,897 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 128 | java | package com.laksrecordings.wualasync;
public interface SyncFilesUIUpdaterListener {
public void updateProgress();
}
| [
"ilmar.kerm@gmail.com"
] | ilmar.kerm@gmail.com |
f4156d438dc4c3487fda7b9a3b237d948a9e1fb2 | f02d1ffbbfa132a483f6d1b62afebde2caeee162 | /coding/neikanhoutai/src/main/java/com/sqxinxibu/neikanhoutai/util/CorsConfig.java | 7008d42f1fa5d0a88577cd26704ebc79936c66e9 | [] | no_license | shWang4685/Coding | ed04f783419885f345a8c97775755901a48f8d0b | 5762522bffd83fd35ed8683c64fd0fba67b6cd9e | refs/heads/master | 2022-09-10T11:07:07.228656 | 2019-06-11T03:16:25 | 2019-06-11T03:16:25 | 174,049,693 | 0 | 0 | null | 2022-09-01T23:04:52 | 2019-03-06T01:41:19 | Roff | UTF-8 | Java | false | false | 1,228 | java | package com.sqxinxibu.neikanhoutai.util;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
//解决跨域问题
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}
| [
"244313089@qq.com"
] | 244313089@qq.com |
bfd84a20b4ba18ce056b894d5071279d6d207a6d | 857bd49bf02eb495c9abf1ca3da1a49efbca52e0 | /TeaTime_Demo/library_teaTime/src/main/java/com/teatime/library_teatime/View/SwitchButton.java | bbfcffd37f48aba028881c98d8eb7cb66ebff2e1 | [] | no_license | ancfdy/teaTime | b2e2a76e1f243e43ac354a2c709d23ef603beb94 | 2b1237c4e6dd3bbe68d141a67e96f491e39cb564 | refs/heads/master | 2020-12-30T18:02:42.066290 | 2018-05-21T05:54:59 | 2018-05-21T05:54:59 | 90,945,127 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 32,560 | java | package com.teatime.library_teatime.View;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Checkable;
import com.teatime.library_teatime.R;
/**
* SwitchButton.
*/
public class SwitchButton extends View implements Checkable {
private static final int DEFAULT_WIDTH = dp2pxInt(58);
private static final int DEFAULT_HEIGHT = dp2pxInt(36);
/**
* 动画状态:
* 1.静止
* 2.进入拖动
* 3.处于拖动
* 4.拖动-复位
* 5.拖动-切换
* 6.点击切换
* **/
private final int ANIMATE_STATE_NONE = 0;
private final int ANIMATE_STATE_PENDING_DRAG = 1;
private final int ANIMATE_STATE_DRAGING = 2;
private final int ANIMATE_STATE_PENDING_RESET = 3;
private final int ANIMATE_STATE_PENDING_SETTLE = 4;
private final int ANIMATE_STATE_SWITCH = 5;
public SwitchButton(Context context) {
super(context);
init(context, null);
}
public SwitchButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public SwitchButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SwitchButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs);
}
@Override
public final void setPadding(int left, int top, int right, int bottom) {
super.setPadding(0, 0, 0, 0);
}
/**
* 初始化参数
*/
private void init(Context context, AttributeSet attrs) {
TypedArray typedArray = null;
if(attrs != null){
typedArray = context.obtainStyledAttributes(attrs, R.styleable.SwitchButton);
}
shadowEffect = optBoolean(typedArray,
R.styleable.SwitchButton_sb_shadow_effect,
true);
uncheckCircleColor = optColor(typedArray,
R.styleable.SwitchButton_sb_uncheckcircle_color,
0XffAAAAAA);//0XffAAAAAA;
uncheckCircleWidth = optPixelSize(typedArray,
R.styleable.SwitchButton_sb_uncheckcircle_width,
dp2pxInt(1.5f));//dp2pxInt(1.5f);
uncheckCircleOffsetX = dp2px(10);
uncheckCircleRadius = optPixelSize(typedArray,
R.styleable.SwitchButton_sb_uncheckcircle_radius,
dp2px(4));//dp2px(4);
checkedLineOffsetX = dp2px(4);
checkedLineOffsetY = dp2px(4);
shadowRadius = optPixelSize(typedArray,
R.styleable.SwitchButton_sb_shadow_radius,
dp2pxInt(2.5f));//dp2pxInt(2.5f);
shadowOffset = optPixelSize(typedArray,
R.styleable.SwitchButton_sb_shadow_offset,
dp2pxInt(1.5f));//dp2pxInt(1.5f);
shadowColor = optColor(typedArray,
R.styleable.SwitchButton_sb_shadow_color,
0X33000000);//0X33000000;
uncheckColor = optColor(typedArray,
R.styleable.SwitchButton_sb_uncheck_color,
0XffDDDDDD);//0XffDDDDDD;
checkedColor = optColor(typedArray,
R.styleable.SwitchButton_sb_checked_color,
0Xff51d367);//0Xff51d367;
borderWidth = optPixelSize(typedArray,
R.styleable.SwitchButton_sb_border_width,
dp2pxInt(1));//dp2pxInt(1);
checkLineColor = optColor(typedArray,
R.styleable.SwitchButton_sb_checkline_color,
Color.WHITE);//Color.WHITE;
checkLineWidth = optPixelSize(typedArray,
R.styleable.SwitchButton_sb_checkline_width,
dp2pxInt(1f));//dp2pxInt(1.0f);
checkLineLength = dp2px(6);
int buttonColor = optColor(typedArray,
R.styleable.SwitchButton_sb_button_color,
Color.WHITE);//Color.WHITE;
int effectDuration = optInt(typedArray,
R.styleable.SwitchButton_sb_effect_duration,
300);//300;
isChecked = optBoolean(typedArray,
R.styleable.SwitchButton_sb_checked,
false);
showIndicator = optBoolean(typedArray,
R.styleable.SwitchButton_sb_show_indicator,
true);
background = optColor(typedArray,
R.styleable.SwitchButton_sb_background,
Color.WHITE);//Color.WHITE;
enableEffect = optBoolean(typedArray,
R.styleable.SwitchButton_sb_enable_effect,
true);
if(typedArray != null){
typedArray.recycle();
}
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
buttonPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
buttonPaint.setColor(buttonColor);
if(shadowEffect){
buttonPaint.setShadowLayer(
shadowRadius,
0, shadowOffset,
shadowColor);
}
viewState = new ViewState();
beforeState = new ViewState();
afterState = new ViewState();
valueAnimator = ValueAnimator.ofFloat(0f, 1f);
valueAnimator.setDuration(effectDuration);
valueAnimator.setRepeatCount(0);
valueAnimator.addUpdateListener(animatorUpdateListener);
valueAnimator.addListener(animatorListener);
super.setClickable(true);
this.setPadding(0, 0, 0, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setLayerType(LAYER_TYPE_SOFTWARE, null);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if(widthMode == MeasureSpec.UNSPECIFIED
|| widthMode == MeasureSpec.AT_MOST){
widthMeasureSpec = MeasureSpec.makeMeasureSpec(DEFAULT_WIDTH, MeasureSpec.EXACTLY);
}
if(heightMode == MeasureSpec.UNSPECIFIED
|| heightMode == MeasureSpec.AT_MOST){
heightMeasureSpec = MeasureSpec.makeMeasureSpec(DEFAULT_HEIGHT, MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
float viewPadding = Math.max(shadowRadius + shadowOffset, borderWidth);
height = h - viewPadding - viewPadding;
width = w - viewPadding - viewPadding;
viewRadius = height * .5f;
buttonRadius = viewRadius - borderWidth;
left = viewPadding;
top = viewPadding;
right = w - viewPadding;
bottom = h - viewPadding;
centerX = (left + right) * .5f;
centerY = (top + bottom) * .5f;
buttonMinX = left + viewRadius;
buttonMaxX = right - viewRadius;
if(isChecked()){
setCheckedViewState(viewState);
}else{
setUncheckViewState(viewState);
}
isUiInited = true;
postInvalidate();
}
/**
* @param viewState
*/
private void setUncheckViewState(ViewState viewState){
viewState.radius = 0;
viewState.checkStateColor = uncheckColor;
viewState.checkedLineColor = Color.TRANSPARENT;
viewState.buttonX = buttonMinX;
}
/**
* @param viewState
*/
private void setCheckedViewState(ViewState viewState){
viewState.radius = viewRadius;
viewState.checkStateColor = checkedColor;
viewState.checkedLineColor = checkLineColor;
viewState.buttonX = buttonMaxX;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setStrokeWidth(borderWidth);
paint.setStyle(Paint.Style.FILL);
//绘制白色背景
paint.setColor(background);
drawRoundRect(canvas,
left, top, right, bottom,
viewRadius, paint);
//绘制关闭状态的边框
paint.setStyle(Paint.Style.STROKE);
paint.setColor(uncheckColor);
drawRoundRect(canvas,
left, top, right, bottom,
viewRadius, paint);
//绘制小圆圈
if(showIndicator){
drawUncheckIndicator(canvas);
}
//绘制开启背景色
float des = viewState.radius * .5f;//[0-backgroundRadius*0.5f]
paint.setStyle(Paint.Style.STROKE);
paint.setColor(viewState.checkStateColor);
paint.setStrokeWidth(borderWidth + des * 2f);
drawRoundRect(canvas,
left + des, top + des, right - des, bottom - des,
viewRadius, paint);
//绘制按钮左边绿色长条遮挡
paint.setStyle(Paint.Style.FILL);
paint.setStrokeWidth(1);
drawArc(canvas,
left, top,
left + 2 * viewRadius, top + 2 * viewRadius,
90, 180, paint);
canvas.drawRect(
left + viewRadius, top,
viewState.buttonX, top + 2 * viewRadius,
paint);
//绘制小线条
if(showIndicator){
drawCheckedIndicator(canvas);
}
//绘制按钮
drawButton(canvas, viewState.buttonX, centerY);
}
/**
* 绘制选中状态指示器
* @param canvas
*/
protected void drawCheckedIndicator(Canvas canvas) {
drawCheckedIndicator(canvas,
viewState.checkedLineColor,
checkLineWidth,
left + viewRadius - checkedLineOffsetX, centerY - checkLineLength,
left + viewRadius - checkedLineOffsetY, centerY + checkLineLength,
paint);
}
/**
* 绘制选中状态指示器
* @param canvas
* @param color
* @param lineWidth
* @param sx
* @param sy
* @param ex
* @param ey
* @param paint
*/
protected void drawCheckedIndicator(Canvas canvas,
int color,
float lineWidth,
float sx, float sy, float ex, float ey,
Paint paint) {
paint.setStyle(Paint.Style.STROKE);
paint.setColor(color);
paint.setStrokeWidth(lineWidth);
canvas.drawLine(
sx, sy, ex, ey,
paint);
}
/**
* 绘制关闭状态指示器
* @param canvas
*/
private void drawUncheckIndicator(Canvas canvas) {
drawUncheckIndicator(canvas,
uncheckCircleColor,
uncheckCircleWidth,
right - uncheckCircleOffsetX, centerY,
uncheckCircleRadius,
paint);
}
/**
* 绘制关闭状态指示器
* @param canvas
* @param color
* @param lineWidth
* @param centerX
* @param centerY
* @param radius
* @param paint
*/
protected void drawUncheckIndicator(Canvas canvas,
int color,
float lineWidth,
float centerX, float centerY,
float radius,
Paint paint) {
paint.setStyle(Paint.Style.STROKE);
paint.setColor(color);
paint.setStrokeWidth(lineWidth);
canvas.drawCircle(centerX, centerY, radius, paint);
}
/**
* @param canvas
* @param left
* @param top
* @param right
* @param bottom
* @param startAngle
* @param sweepAngle
* @param paint
*/
private void drawArc(Canvas canvas,
float left, float top,
float right, float bottom,
float startAngle, float sweepAngle,
Paint paint){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
canvas.drawArc(left, top, right, bottom,
startAngle, sweepAngle, true, paint);
}else{
rect.set(left, top, right, bottom);
canvas.drawArc(rect,
startAngle, sweepAngle, true, paint);
}
}
/**
* @param canvas
* @param left
* @param top
* @param right
* @param bottom
* @param backgroundRadius
* @param paint
*/
private void drawRoundRect(Canvas canvas,
float left, float top,
float right, float bottom,
float backgroundRadius,
Paint paint){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
canvas.drawRoundRect(left, top, right, bottom,
backgroundRadius, backgroundRadius, paint);
}else{
rect.set(left, top, right, bottom);
canvas.drawRoundRect(rect,
backgroundRadius, backgroundRadius, paint);
}
}
/**
* @param canvas
* @param x px
* @param y px
*/
private void drawButton(Canvas canvas, float x, float y) {
canvas.drawCircle(x, y, buttonRadius, buttonPaint);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1);
paint.setColor(0XffDDDDDD);
canvas.drawCircle(x, y, buttonRadius, paint);
}
@Override
public void setChecked(boolean checked) {
if(checked == isChecked()){
postInvalidate();
return;
}
toggle(enableEffect, false);
}
@Override
public boolean isChecked() {
return isChecked;
}
@Override
public void toggle() {
toggle(true);
}
/**
* 切换状态
* @param animate
*/
public void toggle(boolean animate) {
toggle(animate, true);
}
private void toggle(boolean animate, boolean broadcast) {
if(!isEnabled()){return;}
if(isEventBroadcast){
throw new RuntimeException("should NOT switch the state in method: [onCheckedChanged]!");
}
if(!isUiInited){
isChecked = !isChecked;
if(broadcast){
broadcastEvent();
}
return;
}
if(valueAnimator.isRunning()){
valueAnimator.cancel();
}
if(!enableEffect || !animate){
isChecked = !isChecked;
if(isChecked()){
setCheckedViewState(viewState);
}else{
setUncheckViewState(viewState);
}
postInvalidate();
if(broadcast){
broadcastEvent();
}
return;
}
animateState = ANIMATE_STATE_SWITCH;
beforeState.copy(viewState);
if(isChecked()){
//切换到unchecked
setUncheckViewState(afterState);
}else{
setCheckedViewState(afterState);
}
valueAnimator.start();
}
/**
*
*/
private void broadcastEvent() {
if(onCheckedChangeListener != null){
isEventBroadcast = true;
onCheckedChangeListener.onCheckedChanged(this, isChecked());
}
isEventBroadcast = false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(!isEnabled()){return false;}
int actionMasked = event.getActionMasked();
switch (actionMasked){
case MotionEvent.ACTION_DOWN:{
isTouchingDown = true;
touchDownTime = System.currentTimeMillis();
//取消准备进入拖动状态
removeCallbacks(postPendingDrag);
//预设100ms进入拖动状态
postDelayed(postPendingDrag, 100);
break;
}
case MotionEvent.ACTION_MOVE:{
float eventX = event.getX();
if(isPendingDragState()){
//在准备进入拖动状态过程中,可以拖动按钮位置
float fraction = eventX / getWidth();
fraction = Math.max(0f, Math.min(1f, fraction));
viewState.buttonX = buttonMinX
+ (buttonMaxX - buttonMinX)
* fraction;
}else if(isDragState()){
//拖动按钮位置,同时改变对应的背景颜色
float fraction = eventX / getWidth();
fraction = Math.max(0f, Math.min(1f, fraction));
viewState.buttonX = buttonMinX
+ (buttonMaxX - buttonMinX)
* fraction;
viewState.checkStateColor = (int) argbEvaluator.evaluate(
fraction,
uncheckColor,
checkedColor
);
postInvalidate();
}
break;
}
case MotionEvent.ACTION_UP:{
isTouchingDown = false;
//取消准备进入拖动状态
removeCallbacks(postPendingDrag);
if(System.currentTimeMillis() - touchDownTime <= 300){
//点击时间小于300ms,认为是点击操作
toggle();
}else if(isDragState()){
//在拖动状态,计算按钮位置,设置是否切换状态
float eventX = event.getX();
float fraction = eventX / getWidth();
fraction = Math.max(0f, Math.min(1f, fraction));
boolean newCheck = fraction > .5f;
if(newCheck == isChecked()){
pendingCancelDragState();
}else{
isChecked = newCheck;
pendingSettleState();
}
}else if(isPendingDragState()){
//在准备进入拖动状态过程中,取消之,复位
pendingCancelDragState();
}
break;
}
case MotionEvent.ACTION_CANCEL:{
isTouchingDown = false;
removeCallbacks(postPendingDrag);
if(isPendingDragState()
|| isDragState()){
//复位
pendingCancelDragState();
}
break;
}
}
return true;
}
/**
* 是否在动画状态
* @return
*/
private boolean isInAnimating(){
return animateState != ANIMATE_STATE_NONE;
}
/**
* 是否在进入拖动或离开拖动状态
* @return
*/
private boolean isPendingDragState(){
return animateState == ANIMATE_STATE_PENDING_DRAG
|| animateState == ANIMATE_STATE_PENDING_RESET;
}
/**
* 是否在手指拖动状态
* @return
*/
private boolean isDragState(){
return animateState == ANIMATE_STATE_DRAGING;
}
/**
* 设置是否启用阴影效果
* @param shadowEffect true.启用
*/
public void setShadowEffect(boolean shadowEffect) {
if(this.shadowEffect == shadowEffect){return;}
this.shadowEffect = shadowEffect;
if(this.shadowEffect){
buttonPaint.setShadowLayer(
shadowRadius,
0, shadowOffset,
shadowColor);
}else{
buttonPaint.setShadowLayer(
0,
0, 0,
0);
}
}
public void setEnableEffect(boolean enable){
this.enableEffect = enable;
}
/**
* 开始进入拖动状态
*/
private void pendingDragState() {
if(isInAnimating()){return;}
if(!isTouchingDown){return;}
if(valueAnimator.isRunning()){
valueAnimator.cancel();
}
animateState = ANIMATE_STATE_PENDING_DRAG;
beforeState.copy(viewState);
afterState.copy(viewState);
if(isChecked()){
afterState.checkStateColor = checkedColor;
afterState.buttonX = buttonMaxX;
afterState.checkedLineColor = checkedColor;
}else{
afterState.checkStateColor = uncheckColor;
afterState.buttonX = buttonMinX;
afterState.radius = viewRadius;
}
valueAnimator.start();
}
/**
* 取消拖动状态
*/
private void pendingCancelDragState() {
if(isDragState() || isPendingDragState()){
if(valueAnimator.isRunning()){
valueAnimator.cancel();
}
animateState = ANIMATE_STATE_PENDING_RESET;
beforeState.copy(viewState);
if(isChecked()){
setCheckedViewState(afterState);
}else{
setUncheckViewState(afterState);
}
valueAnimator.start();
}
}
/**
* 动画-设置新的状态
*/
private void pendingSettleState() {
if(valueAnimator.isRunning()){
valueAnimator.cancel();
}
animateState = ANIMATE_STATE_PENDING_SETTLE;
beforeState.copy(viewState);
if(isChecked()){
setCheckedViewState(afterState);
}else{
setUncheckViewState(afterState);
}
valueAnimator.start();
}
@Override
public final void setOnClickListener(OnClickListener l) {}
@Override
public final void setOnLongClickListener(OnLongClickListener l) {}
public void setOnCheckedChangeListener(OnCheckedChangeListener l){
onCheckedChangeListener = l;
}
public interface OnCheckedChangeListener{
void onCheckedChanged(SwitchButton view, boolean isChecked);
}
/*******************************************************/
private static float dp2px(float dp){
Resources r = Resources.getSystem();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
}
private static int dp2pxInt(float dp){
return (int) dp2px(dp);
}
private static int optInt(TypedArray typedArray,
int index,
int def) {
if(typedArray == null){return def;}
return typedArray.getInt(index, def);
}
private static float optPixelSize(TypedArray typedArray,
int index,
float def) {
if(typedArray == null){return def;}
return typedArray.getDimension(index, def);
}
private static int optPixelSize(TypedArray typedArray,
int index,
int def) {
if(typedArray == null){return def;}
return typedArray.getDimensionPixelOffset(index, def);
}
private static int optColor(TypedArray typedArray,
int index,
int def) {
if(typedArray == null){return def;}
return typedArray.getColor(index, def);
}
private static boolean optBoolean(TypedArray typedArray,
int index,
boolean def) {
if(typedArray == null){return def;}
return typedArray.getBoolean(index, def);
}
/*******************************************************/
/**
* 阴影半径
*/
private int shadowRadius;
/**
* 阴影Y偏移px
*/
private int shadowOffset;
/**
* 阴影颜色
*/
private int shadowColor ;
/**
* 背景半径
*/
private float viewRadius;
/**
* 按钮半径
*/
private float buttonRadius;
/**
* 背景高
*/
private float height ;
/**
* 背景宽
*/
private float width;
/**
* 背景位置
*/
private float left ;
private float top ;
private float right ;
private float bottom ;
private float centerX;
private float centerY;
/**
* 背景底色
*/
private int background;
/**
* 背景关闭颜色
*/
private int uncheckColor;
/**
* 背景打开颜色
*/
private int checkedColor;
/**
* 边框宽度px
*/
private int borderWidth;
/**
* 打开指示线颜色
*/
private int checkLineColor;
/**
* 打开指示线宽
*/
private int checkLineWidth;
/**
* 打开指示线长
*/
private float checkLineLength;
/**
* 关闭圆圈颜色
*/
private int uncheckCircleColor;
/**
*关闭圆圈线宽
*/
private int uncheckCircleWidth;
/**
*关闭圆圈位移X
*/
private float uncheckCircleOffsetX;
/**
*关闭圆圈半径
*/
private float uncheckCircleRadius;
/**
*打开指示线位移X
*/
private float checkedLineOffsetX;
/**
*打开指示线位移Y
*/
private float checkedLineOffsetY;
/**
* 按钮最左边
*/
private float buttonMinX;
/**
* 按钮最右边
*/
private float buttonMaxX;
/**
* 按钮画笔
*/
private Paint buttonPaint;
/**
* 背景画笔
*/
private Paint paint;
/**
* 当前状态
*/
private ViewState viewState;
private ViewState beforeState;
private ViewState afterState;
private RectF rect = new RectF();
/**
* 动画状态
*/
private int animateState = ANIMATE_STATE_NONE;
/**
*
*/
private ValueAnimator valueAnimator;
private final android.animation.ArgbEvaluator argbEvaluator
= new android.animation.ArgbEvaluator();
/**
*是否选中
*/
private boolean isChecked;
/**
* 是否启用动画
*/
private boolean enableEffect;
/**
* 是否启用阴影效果
*/
private boolean shadowEffect;
/**
* 是否显示指示器
*/
private boolean showIndicator;
/**
* 收拾是否按下
*/
private boolean isTouchingDown = false;
/**
*
*/
private boolean isUiInited = false;
/**
*
*/
private boolean isEventBroadcast = false;
private OnCheckedChangeListener onCheckedChangeListener;
/**
* 手势按下的时刻
*/
private long touchDownTime;
private Runnable postPendingDrag = new Runnable() {
@Override
public void run() {
if(!isInAnimating()){
pendingDragState();
}
}
};
private ValueAnimator.AnimatorUpdateListener animatorUpdateListener
= new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = (Float) animation.getAnimatedValue();
switch (animateState) {
case ANIMATE_STATE_PENDING_SETTLE: {
}
case ANIMATE_STATE_PENDING_RESET: {
}
case ANIMATE_STATE_PENDING_DRAG: {
viewState.checkedLineColor = (int) argbEvaluator.evaluate(
value,
beforeState.checkedLineColor,
afterState.checkedLineColor
);
viewState.radius = beforeState.radius
+ (afterState.radius - beforeState.radius) * value;
if(animateState != ANIMATE_STATE_PENDING_DRAG){
viewState.buttonX = beforeState.buttonX
+ (afterState.buttonX - beforeState.buttonX) * value;
}
viewState.checkStateColor = (int) argbEvaluator.evaluate(
value,
beforeState.checkStateColor,
afterState.checkStateColor
);
break;
}
case ANIMATE_STATE_SWITCH: {
viewState.buttonX = beforeState.buttonX
+ (afterState.buttonX - beforeState.buttonX) * value;
float fraction = (viewState.buttonX - buttonMinX) / (buttonMaxX - buttonMinX);
viewState.checkStateColor = (int) argbEvaluator.evaluate(
fraction,
uncheckColor,
checkedColor
);
viewState.radius = fraction * viewRadius;
viewState.checkedLineColor = (int) argbEvaluator.evaluate(
fraction,
Color.TRANSPARENT,
checkLineColor
);
break;
}
default:
case ANIMATE_STATE_DRAGING: {
}
case ANIMATE_STATE_NONE: {
break;
}
}
postInvalidate();
}
};
private Animator.AnimatorListener animatorListener
= new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
switch (animateState) {
case ANIMATE_STATE_DRAGING: {
break;
}
case ANIMATE_STATE_PENDING_DRAG: {
animateState = ANIMATE_STATE_DRAGING;
viewState.checkedLineColor = Color.TRANSPARENT;
viewState.radius = viewRadius;
postInvalidate();
break;
}
case ANIMATE_STATE_PENDING_RESET: {
animateState = ANIMATE_STATE_NONE;
postInvalidate();
break;
}
case ANIMATE_STATE_PENDING_SETTLE: {
animateState = ANIMATE_STATE_NONE;
postInvalidate();
broadcastEvent();
break;
}
case ANIMATE_STATE_SWITCH: {
isChecked = !isChecked;
animateState = ANIMATE_STATE_NONE;
postInvalidate();
broadcastEvent();
break;
}
default:
case ANIMATE_STATE_NONE: {
break;
}
}
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
};
/*******************************************************/
/**
* 保存动画状态
* */
private static class ViewState {
/**
* 按钮x位置[buttonMinX-buttonMaxX]
*/
float buttonX;
/**
* 状态背景颜色
*/
int checkStateColor;
/**
* 选中线的颜色
*/
int checkedLineColor;
/**
* 状态背景的半径
*/
float radius;
ViewState(){}
private void copy(ViewState source){
this.buttonX = source.buttonX;
this.checkStateColor = source.checkStateColor;
this.checkedLineColor = source.checkedLineColor;
this.radius = source.radius;
}
}
}
| [
"1286679328@qq.com"
] | 1286679328@qq.com |
ebaed6dfbfe4821e89d800017b6e45bf5e97f090 | 3ebaee3a565d5e514e5d56b44ebcee249ec1c243 | /assetBank 3.77 decomplied fixed/src/java/com/bright/assetbank/opengis/servlet/OpenGisCswRestServlet.java | e1437bd2fd33a4bf3a2de497c948ca1872ec5ed3 | [] | no_license | webchannel-dev/Java-Digital-Bank | 89032eec70a1ef61eccbef6f775b683087bccd63 | 65d4de8f2c0ce48cb1d53130e295616772829679 | refs/heads/master | 2021-10-08T19:10:48.971587 | 2017-11-07T09:51:17 | 2017-11-07T09:51:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 19,623 | java | /* */ package com.bright.assetbank.opengis.servlet;
/* */
/* */ import com.bn2web.common.service.GlobalApplication;
/* */ import com.bright.assetbank.opengis.exception.OpenGisServiceException;
/* */ import com.bright.assetbank.opengis.exception.OpenGisServiceException.ExceptionType;
/* */ import com.bright.assetbank.opengis.service.OpenGisCswManager;
/* */ import com.bright.framework.util.XMLUtil;
/* */ import java.io.BufferedInputStream;
/* */ import java.io.BufferedOutputStream;
/* */ import java.io.IOException;
/* */ import java.io.InputStream;
/* */ import java.io.OutputStream;
/* */ import java.io.OutputStreamWriter;
/* */ import java.io.PrintWriter;
/* */ import java.io.StringReader;
/* */ import java.io.StringWriter;
/* */ import java.text.ParseException;
/* */ import java.util.Arrays;
/* */ import javax.servlet.ServletException;
/* */ import javax.servlet.http.HttpServlet;
/* */ import javax.servlet.http.HttpServletRequest;
/* */ import javax.servlet.http.HttpServletResponse;
/* */ import javax.xml.bind.JAXBElement;
/* */ import javax.xml.namespace.QName;
/* */ import javax.xml.parsers.DocumentBuilder;
/* */ import javax.xml.parsers.DocumentBuilderFactory;
/* */ import javax.xml.parsers.ParserConfigurationException;
/* */ import net.opengis.cat.csw._2_0.DescribeRecordType;
/* */ import net.opengis.cat.csw._2_0.GetRecordByIdType;
/* */ import net.opengis.cat.csw._2_0.GetRecordsType;
/* */ import net.opengis.ows.GetCapabilitiesType;
/* */ import org.apache.avalon.framework.component.ComponentException;
/* */ import org.apache.avalon.framework.component.ComponentManager;
/* */ import org.apache.axis.utils.XMLUtils;
/* */ import org.apache.commons.io.IOUtils;
/* */ import org.apache.commons.lang.StringUtils;
/* */ import org.apache.commons.logging.Log;
/* */ import org.jdom.Namespace;
/* */ import org.w3c.dom.Document;
/* */ import org.w3c.dom.Element;
/* */ import org.w3c.dom.Node;
/* */ import org.xml.sax.InputSource;
/* */ import org.xml.sax.SAXException;
/* */
/* */ public class OpenGisCswRestServlet extends HttpServlet
/* */ {
/* */ private static final String k_sNamespacePrefix_CSW = "csw";
/* */ private static final String k_sParamName_AcceptVersions = "AcceptVersions";
/* */ private static final String k_sParamName_Service = "SERVICE";
/* */ private static final String k_sParamName_Request = "REQUEST";
/* 75 */ private Log m_logger = GlobalApplication.getInstance().getLogger();
/* */
/* 77 */ private OpenGisCswManager m_cswManager = null;
/* */
/* */ protected void doGet(HttpServletRequest a_req, HttpServletResponse a_resp)
/* */ throws ServletException, IOException
/* */ {
/* 86 */ this.m_logger.trace(getClass().getSimpleName() + " get called");
/* */
/* 88 */ String sRequestName = a_req.getParameter("REQUEST");
/* 89 */ String sServiceName = a_req.getParameter("SERVICE");
/* 90 */ String sVersions = a_req.getParameter("AcceptVersions");
/* */
/* 92 */ PrintWriter out = null;
/* */ try
/* */ {
/* 98 */ if (StringUtils.isEmpty(sRequestName))
/* */ {
/* 100 */ throw new OpenGisServiceException(OpenGisServiceException.ExceptionType.MISSING_PARAMETER_VALUE, "Parameter REQUEST is missing or empty.");
/* */ }
/* 102 */ if (StringUtils.isEmpty(sServiceName))
/* */ {
/* 104 */ throw new OpenGisServiceException(OpenGisServiceException.ExceptionType.MISSING_PARAMETER_VALUE, "Parameter SERVICE is missing or empty.");
/* */ }
/* 106 */ if (!"CSW".equalsIgnoreCase(sServiceName))
/* */ {
/* 108 */ throw new OpenGisServiceException(OpenGisServiceException.ExceptionType.MISSING_PARAMETER_VALUE, "Parameter SERVICE must be CSW as this is the only service implementation available.");
/* */ }
/* */
/* 113 */ if (StringUtils.isNotEmpty(sVersions))
/* */ {
/* 115 */ String[] asVersions = sVersions.split(" *, *");
/* 116 */ Arrays.sort(asVersions);
/* 117 */ if (Arrays.binarySearch(asVersions, "2.0.2") < 0)
/* */ {
/* 119 */ throw new OpenGisServiceException(OpenGisServiceException.ExceptionType.VERSION_NEGOTIATION_FAILED, "Must accept version 2.0.2 of the OpenGIS CSW spec as this is the only version implemented.");
/* */ }
/* */
/* */ }
/* */
/* 125 */ String sResponse = dispatchServiceRequest(sRequestName, a_req);
/* */
/* 127 */ a_resp.setContentType("text/xml");
/* 128 */ a_resp.setCharacterEncoding("UTF-8");
/* 129 */ a_resp.setStatus(200);
/* */
/* 131 */ out = a_resp.getWriter();
/* 132 */ out.print(sResponse);
/* */ }
/* */ catch (OpenGisServiceException e)
/* */ {
/* 136 */ this.m_logger.error(getClass().getSimpleName() + "Handled exception whilst processing GET (KVP) request: " + e.getMessage(), e);
/* 137 */ handleServiceException(a_resp, e);
/* */ }
/* */ catch (Throwable t)
/* */ {
/* 141 */ this.m_logger.error(getClass().getSimpleName() + "Unhandled throwable whilst processing GET (KVP) request: " + t.getMessage(), t);
/* 142 */ handleServiceException(a_resp, t);
/* */ }
/* */ finally
/* */ {
/* 146 */ IOUtils.closeQuietly(out);
/* */ }
/* */ }
/* */
/* */ private String dispatchServiceRequest(String a_sServiceName, HttpServletRequest a_req)
/* */ throws OpenGisServiceException
/* */ {
/* 160 */ String sResponse = null;
/* 161 */ Document doc = createDocument();
/* 162 */ Element response = null;
/* */
/* 164 */ if ("GetCapabilities".equalsIgnoreCase(a_sServiceName))
/* */ {
/* 167 */ Element element = doc.createElementNS("http://www.opengis.net/cat/csw/2.0.2", "GetCapabilities");
/* 168 */ element.setPrefix("csw");
/* 169 */ element.setAttributeNS("http://www.opengis.net/ows", "service", "CSW");
/* 170 */ doc.appendChild(element);
/* */
/* 173 */ element = recreateElementForApparentlyNoReason(element);
/* */
/* 175 */ response = getOpenGisCswManager().getCapabilities(element, true);
/* */ }
/* 177 */ else if ("DescribeRecord".equalsIgnoreCase(a_sServiceName))
/* */ {
/* 179 */ Element element = doc.createElementNS("http://www.opengis.net/cat/csw/2.0.2", "DescribeRecord");
/* 180 */ element.setPrefix("csw");
/* 181 */ element.setAttributeNS("http://www.opengis.net/ows", "service", "CSW");
/* 182 */ doc.appendChild(element);
/* */
/* 184 */ Namespace[] namespaces = null;
/* */
/* 187 */ if (StringUtils.isNotEmpty(a_req.getParameter("NAMESPACE")))
/* */ {
/* 189 */ String[] asNamespaces = a_req.getParameter("NAMESPACE").split(" *, *");
/* 190 */ namespaces = new Namespace[asNamespaces.length];
/* 191 */ for (int i = 0; i < asNamespaces.length; i++)
/* */ {
/* 193 */ if (!StringUtils.isNotEmpty(asNamespaces[i]))
/* */ continue;
/* */ try
/* */ {
/* 197 */ namespaces[i] = XMLUtil.parseNamespace(asNamespaces[i]);
/* */ }
/* */ catch (ParseException e)
/* */ {
/* 201 */ throw new OpenGisServiceException("Could not parse value of NAMESPACE parameter", e);
/* */ }
/* */
/* */ }
/* */
/* */ }
/* */
/* 208 */ if (StringUtils.isNotEmpty(a_req.getParameter("TypeName")))
/* */ {
/* 210 */ String[] asTypeNames = a_req.getParameter("TypeName").split(" *, *");
/* */
/* 212 */ for (int i = 0; i < asTypeNames.length; i++)
/* */ {
/* 214 */ String sTypeName = asTypeNames[i];
/* */
/* 216 */ Element typeNameElement = doc.createElementNS("http://www.opengis.net/cat/csw/2.0.2", "TypeName");
/* 217 */ typeNameElement.setPrefix("csw");
/* */
/* 220 */ if ((namespaces != null) && (namespaces.length > i))
/* */ {
/* 223 */ if (!"http://www.opengis.net/cat/csw/2.0.2".equals(namespaces[i].getURI()))
/* */ {
/* 225 */ typeNameElement.setAttribute("xmlns:" + namespaces[i].getPrefix(), namespaces[i].getURI());
/* 226 */ sTypeName = namespaces[i].getPrefix() + ":" + sTypeName;
/* */ }
/* */ else
/* */ {
/* 230 */ sTypeName = "csw:" + sTypeName;
/* */ }
/* */ }
/* */
/* 234 */ typeNameElement.setTextContent(sTypeName);
/* 235 */ element.appendChild(typeNameElement);
/* */ }
/* */
/* */ }
/* */
/* 240 */ element = recreateElementForApparentlyNoReason(element);
/* */
/* 242 */ response = getOpenGisCswManager().describeRecord(element, true);
/* */ }
/* */ else
/* */ {
/* 247 */ throw new OpenGisServiceException(OpenGisServiceException.ExceptionType.OPERATION_NOT_SUPPORTED, "Service: " + a_sServiceName + " is not supported via the GET method by this implementation.");
/* */ }
/* */
/* 250 */ if (response != null)
/* */ {
/* 252 */ sResponse = XMLUtils.DocumentToString(response.getOwnerDocument());
/* */
/* 255 */ if (this.m_logger.isTraceEnabled())
/* */ {
/* 257 */ sResponse = XMLUtil.prettyFormatXmlString(sResponse, 3);
/* */ }
/* */ }
/* */
/* 261 */ return sResponse;
/* */ }
/* */
/* */ private Element recreateElementForApparentlyNoReason(Element element)
/* */ throws OpenGisServiceException
/* */ {
/* */ try
/* */ {
/* 279 */ DocumentBuilder builder = createDocumentBuilder();
/* 280 */ Document doc = builder.parse(new InputSource(new StringReader(XMLUtils.ElementToString(element))));
/* 281 */ return (Element)doc.getFirstChild();
/* */ }
/* */ catch (Throwable t) {
/* */
/* 285 */ throw new OpenGisServiceException("Exception whilst preparing GetCapabilities request.", t);
/* */ } }
/* */
/* */ private Document createDocument()
/* */ throws OpenGisServiceException
/* */ {
/* 291 */ DocumentBuilder docBuilder = createDocumentBuilder();
/* 292 */ Document doc = docBuilder.newDocument();
/* 293 */ return doc;
/* */ }
/* */
/* */ private DocumentBuilder createDocumentBuilder() throws OpenGisServiceException
/* */ {
/* */ try
/* */ {
/* 300 */ DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
/* 301 */ dbfac.setNamespaceAware(true);
/* */
/* 303 */ DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
/* 304 */ return docBuilder;
/* */ }
/* */ catch (ParserConfigurationException e) {
/* */
/* 308 */ throw new OpenGisServiceException("Exception whilst creating service request.", e);
/* */ }}
/* */
/* */ protected void doPost(HttpServletRequest a_req, HttpServletResponse a_resp)
/* */ throws ServletException, IOException
/* */ {
/* 319 */ InputStream in = new BufferedInputStream(a_req.getInputStream());
/* 320 */ OutputStream out = null;
/* */ try
/* */ {
/* 326 */ String sPostData = IOUtils.toString(in);
/* */
/* 328 */ this.m_logger.trace(getClass().getSimpleName() + " received post data:\n" + sPostData);
/* */
/* 330 */ if (StringUtils.isEmpty(sPostData))
/* */ {
/* 332 */ throw new OpenGisServiceException("The request was empty!");
/* */ }
/* */
/* */ Node node;
/* */ try
/* */ {
/* 340 */ DocumentBuilder docBuilder = createDocumentBuilder();
/* 341 */ InputSource is = new InputSource(new StringReader(sPostData));
/* 342 */ Document doc = docBuilder.parse(is);
/* 343 */ node = doc.getFirstChild();
/* */ }
/* */ catch (SAXException e)
/* */ {
/* 347 */ throw new OpenGisServiceException("Error while parsing POST data as xml.", e);
/* */ }
/* */
/* 350 */ if (!(node instanceof Element))
/* */ {
/* 352 */ throw new OpenGisServiceException("Error while parsing POST data as xml: top level node is not an element!");
/* */ }
/* */
/* 355 */ Element response = dispatchServiceRequest((Element)node);
/* */
/* 357 */ a_resp.setContentType("text/xml");
/* 358 */ a_resp.setCharacterEncoding("UTF-8");
/* 359 */ a_resp.setStatus(200);
/* */
/* 361 */ out = new BufferedOutputStream(a_resp.getOutputStream());
/* 362 */ Document doc = response.getOwnerDocument();
/* */
/* 365 */ if (this.m_logger.isTraceEnabled())
/* */ {
/* 367 */ String sResponse = XMLUtils.DocumentToString(doc);
/* 368 */ sResponse = XMLUtil.prettyFormatXmlString(sResponse, 3);
/* 369 */ OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
/* 370 */ osw.write(sResponse);
/* 371 */ osw.close();
/* */ }
/* */ else
/* */ {
/* 375 */ XMLUtils.DocumentToStream(doc, out);
/* */ }
/* */ }
/* */ catch (OpenGisServiceException e)
/* */ {
/* 380 */ this.m_logger.error(getClass().getSimpleName() + "Handled exception whilst processing POST (XML) request: " + e.getMessage(), e);
/* 381 */ handleServiceException(a_resp, e);
/* */ }
/* */ catch (Throwable t)
/* */ {
/* 385 */ this.m_logger.error(getClass().getSimpleName() + "Unhandled throwable whilst processing POST (XML) request: " + t.getMessage(), t);
/* 386 */ handleServiceException(a_resp, t);
/* */ }
/* */ finally
/* */ {
/* 390 */ IOUtils.closeQuietly(in);
/* 391 */ IOUtils.closeQuietly(out);
/* */ }
/* */ }
/* */
/* */ private Element dispatchServiceRequest(Element a_request)
/* */ throws OpenGisServiceException
/* */ {
/* 404 */ Element response = null;
/* 405 */ net.opengis.cat.csw._2_0.ObjectFactory cswFactory = new net.opengis.cat.csw._2_0.ObjectFactory();
/* 406 */ net.opengis.ows.ObjectFactory ogcFactory = new net.opengis.ows.ObjectFactory();
/* 407 */ String sServiceName = a_request.getLocalName();
/* */
/* 410 */ if (ogcFactory.createGetCapabilities(new GetCapabilitiesType()).getName().getLocalPart().equalsIgnoreCase(sServiceName))
/* */ {
/* 412 */ response = getOpenGisCswManager().getCapabilities(a_request, true);
/* */ }
/* 415 */ else if (cswFactory.createDescribeRecord(new DescribeRecordType()).getName().getLocalPart().equalsIgnoreCase(sServiceName))
/* */ {
/* 417 */ response = getOpenGisCswManager().describeRecord(a_request, true);
/* */ }
/* 420 */ else if (cswFactory.createGetRecords(new GetRecordsType()).getName().getLocalPart().equalsIgnoreCase(sServiceName))
/* */ {
/* 422 */ response = getOpenGisCswManager().getRecords(a_request, true);
/* */ }
/* 425 */ else if (cswFactory.createGetRecordById(new GetRecordByIdType()).getName().getLocalPart().equalsIgnoreCase(sServiceName))
/* */ {
/* 427 */ response = getOpenGisCswManager().getRecordById(a_request, true);
/* */ }
/* */ else
/* */ {
/* 431 */ throw new OpenGisServiceException(OpenGisServiceException.ExceptionType.OPERATION_NOT_SUPPORTED, sServiceName + " was not recognised as a valid service request element.");
/* */ }
/* */
/* 434 */ return response;
/* */ }
/* */
/* */ private void handleServiceException(HttpServletResponse a_resp, OpenGisServiceException a_exception)
/* */ {
/* 444 */ String sResponse = null;
/* 445 */ String sContentType = "plain/text";
/* 446 */ int iResponseCode = 500;
/* */ try
/* */ {
/* 450 */ DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
/* 451 */ DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
/* 452 */ Document doc = docBuilder.newDocument();
/* */
/* 455 */ a_exception.addExceptionReportElement(doc, true);
/* */
/* 458 */ sResponse = XMLUtils.DocumentToString(doc);
/* */
/* 461 */ if (this.m_logger.isTraceEnabled())
/* */ {
/* 463 */ sResponse = XMLUtil.prettyFormatXmlString(sResponse, 3);
/* */ }
/* */
/* 467 */ iResponseCode = a_exception.getHttpStatusCode();
/* */ }
/* */ catch (Throwable t)
/* */ {
/* 471 */ String sMsg = "An exception was encountered whilst creating the ExceptionReport! " + t.getClass().getSimpleName() + " : " + t.getLocalizedMessage();
/* */
/* 473 */ this.m_logger.error(sMsg, t);
/* */
/* 475 */ StringWriter sw = new StringWriter();
/* 476 */ PrintWriter pw = new PrintWriter(sw);
/* 477 */ t.printStackTrace(pw);
/* 478 */ sResponse = sMsg + "\n" + sw.toString();
/* */ }
/* */
/* 481 */ a_resp.setContentType(sContentType);
/* 482 */ a_resp.setStatus(iResponseCode);
/* */
/* 484 */ this.m_logger.trace(getClass().getSimpleName() + " set response status code: " + iResponseCode);
/* */ try
/* */ {
/* 488 */ OutputStream out = new BufferedOutputStream(a_resp.getOutputStream());
/* 489 */ IOUtils.write(sResponse, out, "UTF-8");
/* 490 */ out.close();
/* */
/* 492 */ this.m_logger.trace(getClass().getSimpleName() + " sent response data:\n" + sResponse);
/* */ }
/* */ catch (IOException e)
/* */ {
/* */ }
/* */ }
/* */
/* */ private void handleServiceException(HttpServletResponse a_resp, Throwable a_throwable)
/* */ {
/* 509 */ OpenGisServiceException wrapper = new OpenGisServiceException(a_throwable.getClass().getName() + " : " + a_throwable.getMessage(), a_throwable);
/* 510 */ wrapper.setStackTrace(a_throwable.getStackTrace());
/* 511 */ handleServiceException(a_resp, wrapper);
/* */ }
/* */
/* */ private OpenGisCswManager getOpenGisCswManager()
/* */ throws OpenGisServiceException
/* */ {
/* 517 */ if (this.m_cswManager == null)
/* */ {
/* */ try
/* */ {
/* 521 */ this.m_cswManager = ((OpenGisCswManager)GlobalApplication.getInstance().getComponentManager().lookup("OpenGisCswManager"));
/* */ }
/* */ catch (ComponentException e)
/* */ {
/* 525 */ this.m_logger.error("ComponentException caught whilst getting OpenGisCswManager : " + e.getMessage());
/* 526 */ throw new OpenGisServiceException("ComponentException caught whilst getting OpenGisCswManager", e);
/* */ }
/* */ }
/* 529 */ return this.m_cswManager;
/* */ }
/* */ }
/* Location: C:\Users\mamatha\Desktop\com.zip
* Qualified Name: com.bright.assetbank.opengis.servlet.OpenGisCswRestServlet
* JD-Core Version: 0.6.0
*/ | [
"42003122+code7885@users.noreply.github.com"
] | 42003122+code7885@users.noreply.github.com |
9f641498be5ce7bc72f0b3f8b3f4ff050d2e8c58 | 51d10402485830ef1e7f4657a128b48cdf793622 | /src/main/java/br/com/diogomurano/clans/services/clan/ClanService.java | b0c2651defdd0178805855692ced263c4a51b45e | [] | no_license | DiogoMurano/DMClans | e349138a8088f44c27b0e656d054279a29fa0118 | 3da07ea0a97d9d629f20a94b9c18d1a444070108 | refs/heads/master | 2021-04-14T10:36:12.930020 | 2020-03-22T16:43:11 | 2020-03-22T16:43:11 | 249,227,103 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 400 | java | package br.com.diogomurano.clans.services.clan;
import br.com.diogomurano.clans.model.Clan;
import com.google.common.collect.ImmutableList;
import java.util.UUID;
public interface ClanService {
ImmutableList<Clan> getAll();
void save(Clan clan);
void remove(Clan clan);
Clan findByName(String name);
Clan findByTag(String tag);
Clan findByUniqueId(UUID uniqueId);
}
| [
"braspvp@gmail.com"
] | braspvp@gmail.com |
ed30ff26bd1a5b416512383396bcd67bf69845a6 | 3d693e6b6a6c46499d48646f6fbe3d938b5e7cb2 | /drools-compiler-dr/src/org/drools/compiler/DescrBuildError.java | ff043e204f4f88eefc5a2f0f515e9e14850461e1 | [] | no_license | jorgemfk/dr-drools | 1101fd5c8c849731b1088c6a95ed1778952c79a3 | 8b3fc1db5919a88b3e07aeebb3ba2178ea700a07 | refs/heads/master | 2020-06-02T15:26:08.465658 | 2015-01-27T06:15:47 | 2015-01-27T06:15:47 | 29,899,027 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,210 | java | /*
* Copyright 2005 JBoss 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 org.drools.compiler;
import org.drools.commons.jci.problems.CompilationProblem;
import org.drools.lang.descr.BaseDescr;
public class DescrBuildError extends DroolsError {
private BaseDescr parentDescr;
private BaseDescr descr;
private Object object;
private String message;
private int[] errorLines = new int[0];
public DescrBuildError(final BaseDescr parentDescr,
final BaseDescr descr,
final Object object,
final String message) {
super();
this.parentDescr = parentDescr;
this.descr = descr;
this.object = object;
this.message = message;
}
public BaseDescr getParentDescr() {
return this.parentDescr;
}
public BaseDescr getDescr() {
return this.descr;
}
public Object getObject() {
return this.object;
}
public int[] getErrorLines() {
return this.errorLines;
}
/**
* This will return the line number of the error, if possible
* Otherwise it will be -1
*/
public int getLine() {
return this.descr != null ? this.descr.getLine() : -1;
}
public String getMessage() {
String summary = this.message;
if ( this.object instanceof CompilationProblem[] ) {
final CompilationProblem[] problem = (CompilationProblem[]) this.object;
for ( int i = 0; i < problem.length; i++ ) {
if ( i != 0 ) {
summary = summary + "\n" + problem[i].getMessage();
} else {
summary = summary + " " + problem[i].getMessage();
}
}
}
return summary;
}
public String toString() {
final StringBuilder buf = new StringBuilder();
buf.append( this.message );
buf.append( " : " );
buf.append( this.parentDescr );
buf.append( "\n" );
if ( this.object instanceof CompilationProblem[] ) {
final CompilationProblem[] problem = (CompilationProblem[]) this.object;
for ( int i = 0; i < problem.length; i++ ) {
buf.append( "\t" );
buf.append( problem[i] );
buf.append( "\n" );
}
} else if ( this.object != null ) {
buf.append( this.object );
}
return buf.toString();
}
// private String createMessage( String message ) {
// StringBuilder detail = new StringBuilder();
// detail.append( this.message );
// detail.append( " : " );
// detail.append( this.rule );
// detail.append( "\n" );
// if( object instanceof CompilationProblem[] ) {
// CompilationProblem[] cp = (CompilationProblem[]) object;
// this.errorLines = new int[cp.length];
// for( int i = 0; i < cp.length ; i ++ ) {
// this.errorLines[i] = cp[i].getStartLine() - this.descr.getOffset() + this.descr.getLine() - 1;
// detail.append( this.rule.getName() );
// detail.append( " (line:" );
// detail.append( this.errorLines[i] );
// detail.append( "): " );
// detail.append( cp[i].getMessage() );
// detail.append( "\n" );
// }
// } else {
// this.errorLines = new int[0];
// }
// return "[ "+this.rule.getName()+" : "+message + "\n"+detail.toString()+" ]";
// }
}
| [
"jorgemfk1@gmail.com"
] | jorgemfk1@gmail.com |
a1a451c377ddc938fe6e2c55800e013f74e29c4c | b48282caa22f85fa29f1415b98282c6d471feb34 | /src/main/java/gps/globalobjects/StreamingRootPickerGObj.java | 97febd915dbe09849a902de49e5fab08aba56b5b | [] | no_license | MBtech/gps | 7f50f49e4262a798d9d54bd2fae91860637fd474 | f916e1e04c940e577713c219b6a5ed8224838417 | refs/heads/master | 2020-04-26T06:55:44.014185 | 2019-03-01T23:13:23 | 2019-03-01T23:13:23 | 173,380,085 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 575 | java | package gps.globalobjects;
import gps.writable.MinaWritable;
import gps.writable.StreamingRootPickerWritable;
public class StreamingRootPickerGObj extends GlobalObject<StreamingRootPickerWritable>{
public StreamingRootPickerGObj() {
setValue(new StreamingRootPickerWritable());
}
public StreamingRootPickerGObj(StreamingRootPickerWritable rootPickerWritable) {
setValue(rootPickerWritable);
}
@Override
public void update(MinaWritable otherWritable) {
getValue().rootPicker.insertNewIntValues(((StreamingRootPickerWritable) otherWritable).rootPicker);
}
}
| [
"mbilal_ce@live.com"
] | mbilal_ce@live.com |
d7f1a3a47d7012b9a28f60a1ca1bcdafaf35b550 | 0b7689623ca2cffec9bba37b8974297254adfae3 | /PEAWarinchamrap/app/src/main/java/com/example/boony/peawarinchamrap/page_1.java | 567b978d12e320d1a1c8274b311f28b5299860e6 | [] | no_license | eye-bs/Android-project | 0d9d7cc9c03bea6c80295600dca1b2b2cbdc1daf | 7a0b1e32fbb1c7508a42ccbd210a40f873db05ff | refs/heads/master | 2021-10-09T05:02:42.517145 | 2018-12-21T18:24:22 | 2018-12-21T18:24:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,098 | java | package com.example.boony.peawarinchamrap;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class page_1 extends AppCompatActivity {
protected TextView txtContact;
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_page_1);
// ReplaceFont.replaceDefultFont(this,"MONOSPACE","THSarabun.ttf");
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final AlertDialog.Builder ad = new AlertDialog.Builder(this);
// txtUsername & txtPassword
final EditText txtUser = (EditText) findViewById(R.id.txtuser);
final EditText txtPass = (EditText) findViewById(R.id.txtpass);
txtContact = (TextView) findViewById(R.id.textView9);
txtContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent activity = new Intent(page_1.this,Contact.class);
startActivity(activity);
}
});
// btnLogin
final Button btnLogin = (Button) findViewById(R.id.btn_login);
// Perform action on click
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String url = "https://peawarinubon.000webhostapp.com/select.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("strUser", txtUser.getText().toString()));
params.add(new BasicNameValuePair("strPass", txtPass.getText().toString()));
String resultServer = getHttpPost(url,params);
/*** Default Value ***/
String strStatusID = "0";
String strMemberID = "0";
String strFName = null;
String strLName = null;
String strError = "Unknow Status!";
JSONObject c;
try {
c = new JSONObject(resultServer);
strStatusID = c.getString("StatusID");
strMemberID = c.getString("user_id");
strError = c.getString("Error");
strFName = c.getString("user_fname");
strLName = c.getString("user_lname");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Prepare Login
if(strStatusID.equals("0"))
{
// Dialog
ad.setTitle("Error! ");
ad.setIcon(android.R.drawable.btn_star_big_on);
ad.setPositiveButton("Close", null);
ad.setMessage(strError);
ad.show();
txtUser.setText("");
txtPass.setText("");
}
else
{
Toast.makeText(page_1.this, "Login OK", Toast.LENGTH_SHORT).show();
Intent newActivity = new Intent(page_1.this,stp_1.class);
newActivity.putExtra("MemberID", strMemberID);
newActivity.putExtra("MemberFName", strFName);
newActivity.putExtra("MemberLName", strLName);
startActivity(newActivity);
}
}
});
}
public String getHttpPost(String url,List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
}
| [
"boonyaporn.sudjunham@kkumail.com"
] | boonyaporn.sudjunham@kkumail.com |
1805890c3cade3239846ace3bea5b077a4375faa | 87529857b58c975515255a034ba52db7da9b54d9 | /src/main/java/designPattern/visitor/MainClass.java | 44d12ef6281863a658b7f8f80de42e6350ade32c | [] | no_license | flyingOrange/JavaTech | 03c6ad4834870e79c305f622190b406415dddea8 | a9fdd385b9cb33c8338578ec5274ef0b302cac95 | refs/heads/master | 2023-06-23T13:14:29.738685 | 2023-06-13T19:52:25 | 2023-06-13T19:52:25 | 114,010,496 | 0 | 0 | null | 2022-12-16T07:22:14 | 2017-12-12T16:02:28 | Java | UTF-8 | Java | false | false | 60 | java | package designPattern.visitor;
public class MainClass {
}
| [
"370686124@qq.com"
] | 370686124@qq.com |
acadd311f20c02c5bf50a10c54a45d29d7fe0bae | 8105917f3dd6b34e13383261b2585f2f84a70ef5 | /webapp/src/main/java/com/google/gwt/site/demo/gsss/animation/examples/Examples.java | 9cd3b0953393665bbd64d771ed0faa1712cf0c58 | [
"Apache-2.0"
] | permissive | abdulbasitkay/dev-site | cbb5454da43f3b0b6259e9de173357735a193153 | 4a298c4cabf5e713f994672339492608bf1c073a | refs/heads/master | 2021-01-14T13:47:28.564135 | 2015-07-23T18:44:30 | 2015-07-23T18:44:30 | 39,701,521 | 1 | 0 | null | 2015-07-25T20:16:40 | 2015-07-25T20:16:39 | null | UTF-8 | Java | false | false | 1,492 | java | /*
* Copyright 2014 ArcBees 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.google.gwt.site.demo.gsss.animation.examples;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
public class Examples implements IsWidget {
interface Binder extends UiBinder<Widget, Examples> {
}
private static Binder BINDER = GWT.create(Binder.class);
private final Widget widget;
@UiField
DivElement className;
protected Examples(String className) {
widget = BINDER.createAndBindUi(this);
this.className.addClassName(className);
}
@Override
public Widget asWidget() {
return widget;
}
public static IsWidget create(String className) {
return new Examples(className);
}
}
| [
"jason.lemay@arcbees.com"
] | jason.lemay@arcbees.com |
6d4d1c2114ace22624ec716841b5ce6eb6e0cdf0 | cca4d4244ff87265e294f56e49a1863a7c34bfbe | /app/src/test/java/br/com/nery/touchfeedback/ColorTest.java | 6f7e6b91062a4ecf42bfec072a7316dca6feb404 | [] | no_license | renannery/TouchFeedback | 30cb4bcc6d4f00b584468d347db262c704547330 | 323775d34cedf326bd91d35366399e686e361847 | refs/heads/master | 2021-01-10T05:05:41.761304 | 2016-01-12T17:49:09 | 2016-01-12T17:49:09 | 49,462,962 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 331 | java | package br.com.nery.touchfeedback;
import android.graphics.Color;
import org.junit.Test;
import static org.junit.Assert.*;
public class ColorTest {
@Test
public void colorAlpha_isCorrect() throws Exception {
//TODO implement MOCKITO
assertEquals(Bindings.getColorWithAlpha(Color.RED, 0.75f), 3);
}
} | [
"renannery@gmail.com"
] | renannery@gmail.com |
5092352462b1f2647e056d1e9ac7d2027d6fd91c | 664ac4cafa93344aa0c48fa4d8886be330c11493 | /back/fast-admin/src/main/java/com/yunjian/modules/automat/controller/DistributorController.java | e09c04a8098ceaf25b34cad8294570a66b6d972b | [] | no_license | xiapengyu/shjdev | b4b56ac94360d8a556b984f6e8742d37bb242af2 | cbf0e3e66570abe36697d46f2bff86fe718ce083 | refs/heads/master | 2022-12-12T02:14:16.858975 | 2019-12-17T12:29:03 | 2019-12-17T12:29:03 | 228,611,392 | 0 | 0 | null | 2022-12-06T00:45:21 | 2019-12-17T12:26:01 | JavaScript | UTF-8 | Java | false | false | 3,013 | java | package com.yunjian.modules.automat.controller;
import java.util.Date;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunjian.common.annotation.SysLog;
import com.yunjian.common.utils.PageUtils;
import com.yunjian.common.utils.R;
import com.yunjian.modules.automat.entity.DistributorEntity;
import com.yunjian.modules.automat.service.DistributorService;
import com.yunjian.modules.sys.controller.AbstractController;
import io.swagger.annotations.ApiOperation;
/**
* <p>
* 经销商信息 前端控制器
* </p>
*
* @author laizhiwen
* @since 2019-08-16
*/
@RestController
@RequestMapping("/automat/distributor")
public class DistributorController extends AbstractController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private DistributorService distributorService;
@GetMapping("/list")
public R list(@RequestParam Map<String, Object> params) {
PageUtils page = distributorService.queryPage(params);
return R.ok().put("page", page);
}
@GetMapping("/info/{id}")
public R distributorInfo(@PathVariable("id") Long id) {
QueryWrapper<DistributorEntity> queryWrapper = new QueryWrapper<DistributorEntity>();
queryWrapper.eq("id", id);
DistributorEntity result = distributorService.getOne(queryWrapper);
logger.info("查询经销商信息>>>[{}]", result);
return R.ok().put("distributor", result);
}
/**
* 保存配置
*/
@ApiOperation(value = "保存经销商信息")
@PostMapping("/save")
public R save(@RequestBody DistributorEntity data){
logger.info("保存经销商信息>>>[{}]", data);
data.setCreateTime(new Date());
distributorService.save(data);
return R.ok();
}
/**
* 修改配置
*/
@SysLog("修改经销商信息")
@PostMapping("/update")
public R update(@RequestBody DistributorEntity adData){
QueryWrapper<DistributorEntity> query = new QueryWrapper<DistributorEntity>();
query.eq("id", adData.getId());
distributorService.update(adData, query);
return R.ok();
}
/**
* 删除经销商信息
*/
@SysLog("删除经销商信息")
@PostMapping("/delete")
public R delete(@RequestBody DistributorEntity adData){
QueryWrapper<DistributorEntity> query = new QueryWrapper<DistributorEntity>();
query.eq("id", adData.getId());
distributorService.remove(query);
return R.ok();
}
}
| [
"xiapengyu@hdsc.com"
] | xiapengyu@hdsc.com |
574778e02a556bbaf6ee276c689368d28f60761a | d08b7b8ecbfcdb181093aeed4d2c95d118bc8c51 | /ia-clientlibrary/src/main/java/org/odpi/egeria/connectors/ibm/ia/clientlibrary/model/CardinalityType.java | d68ab8a63574857f6370d803ef6842e8e2f4f76e | [
"CC-BY-4.0",
"Apache-2.0"
] | permissive | odpi/egeria-connector-ibm-information-server | fd2c7e8dfb26f0daeec4b18b2355092c444cce8a | ad84432f4488392ee2813fa69488b7a0a71a3fe5 | refs/heads/main | 2023-08-31T23:21:28.510833 | 2023-06-05T08:34:47 | 2023-06-05T08:34:47 | 181,748,801 | 23 | 20 | Apache-2.0 | 2023-09-04T18:21:55 | 2019-04-16T18:55:17 | Java | UTF-8 | Java | false | false | 565 | java | /* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.egeria.connectors.ibm.ia.clientlibrary.model;
import com.fasterxml.jackson.annotation.JsonValue;
public enum CardinalityType implements IAEnum {
UNIQUE_AND_CONSTANT("unique_and_constant"),
NOT_CONSTRAINED("not_constrained"),
UNIQUE("unique"),
CONSTANT("constant");
@JsonValue
private String value;
CardinalityType(String value) { this.value = value; }
@Override
public String getValue() { return value; }
}
| [
"chris@thegrotes.net"
] | chris@thegrotes.net |
b4219c8d6a6d187f654c3d020962acdd598aef23 | b61feb206bc6c90c4cc66c4dbc96eb1b80ddb7a5 | /src/test/java/org/fest/assertions/internal/Dates_assertIsInSameMinuteAs_Test.java | 7b6343a8faf55e72aa114a38e4db65c68c6f9d5c | [
"Apache-2.0"
] | permissive | P4uline/fest-assert-2.x | 7dd67a4f120297af39c734ef6690560f5333cfc9 | f0d1e872616fca5d9cabfa8e866f6d9dd8714db9 | refs/heads/master | 2021-01-15T23:06:45.796802 | 2012-08-06T17:59:59 | 2012-08-06T17:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,763 | java | /*
* Created on Dec 24, 2010
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* Copyright @2010-2011 the original author or authors.
*/
package org.fest.assertions.internal;
import static org.fest.assertions.error.ShouldBeInSameMinute.shouldBeInSameMinute;
import static org.fest.assertions.test.ErrorMessages.dateToCompareActualWithIsNull;
import static org.fest.assertions.test.FailureMessages.actualIsNull;
import static org.fest.assertions.test.TestData.someInfo;
import static org.fest.assertions.test.TestFailures.failBecauseExpectedAssertionErrorWasNotThrown;
import static org.mockito.Mockito.verify;
import java.util.Date;
import org.junit.Test;
import org.fest.assertions.core.AssertionInfo;
/**
* Tests for <code>{@link Dates#assertIsInSameMinuteAs(AssertionInfo, Date, Date)}</code>.
*
* @author Joel Costigliola
*/
public class Dates_assertIsInSameMinuteAs_Test extends AbstractDatesTest {
@Override
protected void initActualDate() {
actual = parseDatetime("2011-01-01T03:15:00");
}
@Test
public void should_fail_if_actual_is_not_in_same_minute_as_given_date() {
AssertionInfo info = someInfo();
Date other = parseDatetime("2011-01-01T03:14:02");
try {
dates.assertIsInSameMinuteAs(info, actual, other);
} catch (AssertionError e) {
verify(failures).failure(info, shouldBeInSameMinute(actual, other));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
@Test
public void should_fail_if_actual_is_null() {
thrown.expectAssertionError(actualIsNull());
dates.assertIsInSameMinuteAs(someInfo(), null, new Date());
}
@Test
public void should_throw_error_if_given_date_is_null() {
thrown.expectNullPointerException(dateToCompareActualWithIsNull());
dates.assertIsInSameMinuteAs(someInfo(), actual, null);
}
@Test
public void should_pass_if_actual_is_in_same_minute_as_given_date() {
dates.assertIsInSameMinuteAs(someInfo(), actual, parseDatetime("2011-01-01T03:15:59"));
}
@Test
public void should_fail_if_actual_is_not_in_same_minute_as_given_date_whatever_custom_comparison_strategy_is() {
AssertionInfo info = someInfo();
Date other = parseDatetime("2011-01-01T03:14:02");
try {
datesWithCustomComparisonStrategy.assertIsInSameMinuteAs(info, actual, other);
} catch (AssertionError e) {
verify(failures).failure(info, shouldBeInSameMinute(actual, other));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
@Test
public void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() {
thrown.expectAssertionError(actualIsNull());
datesWithCustomComparisonStrategy.assertIsInSameMinuteAs(someInfo(), null, new Date());
}
@Test
public void should_throw_error_if_given_date_is_null_whatever_custom_comparison_strategy_is() {
thrown.expectNullPointerException(dateToCompareActualWithIsNull());
datesWithCustomComparisonStrategy.assertIsInSameMinuteAs(someInfo(), actual, null);
}
@Test
public void should_pass_if_actual_is_in_same_minute_as_given_date_whatever_custom_comparison_strategy_is() {
datesWithCustomComparisonStrategy.assertIsInSameMinuteAs(someInfo(), actual, parseDatetime("2011-01-01T03:15:59"));
}
}
| [
"joel.costigliola@gmail.com"
] | joel.costigliola@gmail.com |
52496a480b5f932eb17777464f093999b4b521c4 | 5034e5ec0fc5b27e84f9ed77a0a7661ef107a894 | /reversebit.java | efb3cdf9500c72e07bafc0c18baf760116050931 | [] | no_license | Tarunsahu2001/java | ac8b6558e1cc5ea92e5a73772293a705667b01c4 | 822b485e9aa593789d9bb7f6abc2498fd99d136c | refs/heads/main | 2023-07-02T02:25:05.416661 | 2021-08-10T13:22:48 | 2021-08-10T13:22:48 | 389,639,624 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 900 | java | class reversebit
{
public static int reverseBits(int n)
{
int pos = Integer.SIZE - 1;
int reverse = 0;
while (pos >= 0 && n != 0)
{
if ((n & 1) != 0)
{
reverse = reverse | (1 << pos);
}
n >>= 1;
pos--;
}
return reverse;
}
public static String toBinaryString(int n)
{
return String.format("%32s", Integer.toBinaryString(n)).replaceAll(" ", "0");
}
public static void main(String[] args)
{
int n = -100;
System.out.println(n + " in binary is " + toBinaryString(n));
System.out.println("On reversing bits " + toBinaryString(reverseBits(n)));
}
}
Output:
-100 in binary is 11111111111111111111111110011100
On reversing bits 00111001111111111111111111111111 | [
"noreply@github.com"
] | noreply@github.com |
cf53a9107be13edeb9ff6fb28184ce8e995a0f22 | 679ba52e53b331a4053b1c3bb695453ce9ded920 | /Desktop/Core_Java/Java_8/src/java8_2/ClassTreeSet.java | 0f60dcb15f8a5e6c7f270bbf1a6d03aee3e57cb3 | [] | no_license | sajidashaikh/testing | 471138ba7a59c3326e285dce417bc44eff77a40b | c6995da15fc62c27feb75e73017ff4a5f8850ed4 | refs/heads/master | 2023-02-12T01:01:59.427209 | 2021-01-09T14:59:30 | 2021-01-09T14:59:30 | 327,194,331 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,319 | java | package java8_2;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class ClassTreeSet {
public static void main(String[] args) {
TreeSet<String> ints = new TreeSet<String>();
ints.add("apple");
ints.add("mango");
ints.add("Apple");
ints.add("carrot");
ints.add("mango");
ints.add("chickoo");
ints.add("banana");
ints.add("strawbery");
System.out.println("first set :"+ints.descendingSet());
System.out.println("reverse set:"+ints.subSet("Apple", "mango"));
System.out.println(ints.contains("mango"));
System.out.println(ints.size());
System.out.println(ints.remove("apple"));
System.out.println(ints.headSet("banana")); //headset for before b
System.out.println(ints.tailSet("carrot")); //tailset for after c
Iterator<String> it = ints.iterator();
System.out.println("iterator");
while(it.hasNext()) {
System.out.println(it.next());
System.out.println("\t");}
ints.forEach(f-> System.out.println(f)); //java 1.8
//ints.forEach(System.out::println);
class ClassCompare implements Comparator<String>{
public int compare(String ints1 ,String ints2) {
int s = ints1.compareTo(ints2);
if(s>0) {
return -1;
}
else if(s<0) {
return 1;
}
else
{
return 0;
}
}
}
}
}
| [
"sajidashaikh@12.com"
] | sajidashaikh@12.com |
c313d2070332d9700ea724f20bd38add4bbd3453 | f378ddd47c8b7de6e9cf1d4228c84f73e9dc59f1 | /projetos/cheque-recognizer/client/android/src/ru/spbau/cheque/recognition/RegexTableExtractor.java | 884fa66b2efbd429ef5e41f7078b246f7613f40d | [] | no_license | charles-marques/dataset-375 | 29e2f99ac1ba323f8cb78bf80107963fc180487c | 51583daaf58d5669c69d8208b8c4ed4e009001a5 | refs/heads/master | 2023-01-20T07:23:09.445693 | 2020-11-27T22:35:49 | 2020-11-27T22:35:49 | 283,315,149 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,801 | java | package ru.spbau.cheque.recognition;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTableExtractor implements TableExtractor {
public List<BlueObject> extract(ChequeFormat format, List<String> text) {
List<BlueObject> entries = typeOneRegex(format, text);
if (entries.size() == 0) {
//try another regex set
entries = typeTwoRegex(format, text);
}
return entries;
}
private List<BlueObject> typeOneRegex(ChequeFormat format, List<String> text) {
List<BlueObject> entries = new ArrayList<BlueObject>();
String nameAccum = "";
for (String line : text) {
Matcher matcher = Pattern.compile("^([\\p{Digit}\\p{Punct}]+)\\p{Blank}+(.*)", Pattern.UNICODE_CASE).matcher(line);
if (matcher.matches()) {
String f1 = matcher.group(1);
String f2 = matcher.group(2);
Matcher matcher2 = Pattern.compile("(.*)\\p{Blank}(.*)?+$", Pattern.UNICODE_CASE).matcher(f2);
if (matcher2.matches()) {
String price = matcher2.group(2);
String price2 = price.replaceAll("^\\p{Punct}|\\p{Punct}$", "");
if (price2.matches("(\\p{Digit}+\\p{Punct}{1}\\p{Digit}+)")) {
entries.add(new BlueObject(nameAccum + matcher2.group(1),
Float.parseFloat(price2)));
} else {
entries.add(new BlueObject(nameAccum + matcher2.group(1), 0));
}
}
}
}
return entries;
}
private List<BlueObject> typeTwoRegex(ChequeFormat format, List<String> text) {
List<BlueObject> entries = new ArrayList<BlueObject>();
String nameAccum = "";
for (String line : text) {
//Matcher matcher = Pattern.compile("^\\p{Digit}+\\.([\\p{Alnum}\\p{Punct}]+)\\p{Blank}+
// ([\\p{Alnum}\\p{Punct}]+)\\p{Blank}+(([\\p{Alnum}\\p{Punct}]+))").matcher(line);
//"^\\p{Digit}+\\.(.*)\\p{Blank}+([\\p{Alnum}\\p{Punct}]+)$"
Matcher matcher = Pattern.compile("^\\p{Digit}+\\.((.*)(\\p{Blank}+([\\p{Alnum}\\p{Punct}]+)))" +
"\\p{Blank}+([\\p{Alnum}\\p{Punct}]+)$",
Pattern.UNICODE_CASE).matcher(line);
if (matcher.matches()) {
String f1 = matcher.group(1);
String f2 = matcher.group(2); //name,count
String f3 = matcher.group(5); //price
float countf = 0;
float pricef = 0;
String name = "";
f3 = f3.replaceAll("^\\p{Punct}|\\p{Punct}$", "")
.replaceAll("^\\p{Alpha}|\\p{Alpha}$", "");
Matcher matcher2 = Pattern.compile("(.*)\\p{Blank}(.*)?+$", Pattern.UNICODE_CASE).matcher(f2);
if (matcher2.matches()) {
String count = matcher2.group(2).replaceAll("^\\p{Punct}|\\p{Punct}$", "")
.replaceAll("^\\p{Alpha}|\\p{Alpha}$", "");
name = matcher2.group(1);
if (count.matches("([\\p{Digit}\\p{Punct}]?\\p{Digit}+)")) {
countf = Float.parseFloat(count);
}
if (f3.matches("(\\p{Digit}+\\p{Punct}{1}\\p{Digit}+)")) {
pricef = Float.parseFloat(f3.replaceAll("\\p{Punct}", "."));
}
entries.add(new BlueObject(name, countf, pricef));
}
}
}
return entries;
}
}
| [
"suporte@localhost.localdomain"
] | suporte@localhost.localdomain |
9b741dfb826ba4f0abfb10506337a1a8f7fa7848 | 78b9376777a8cd1ccee56bbe675bf5369cb98202 | /src/main/java/com/gimslab/algorithms/Palindrome.java | f2a0491c188a556075cdce88b60a4cb3a29e61da | [] | no_license | gimslab/algorithms | 5cf335400bbf802e03c89d069d86d869caed1d82 | eade7e245e0b9fd108db160288dcb6f87fb0c45f | refs/heads/master | 2022-06-24T08:16:24.433452 | 2022-06-18T01:26:26 | 2022-06-18T01:26:26 | 133,016,217 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,673 | java | package com.gimslab.algorithms;
/*
Given a string s, you are allowed to convert it to a palindrome by adding
characters in front of it. Find and return the shortest palindrome
you can find by performing this transformation.
"aabaa"
Example 1:
Input: "aacecaaa"
Output: "aaacecaaa"
Example 2:
Input: "abcd"
Output: "dcbabcd"
*/
public class Palindrome {
private static int l = 0;
public static void main(String[] args) {
testSolution("a", "a");
testSolution("ab", "bab");
testSolution("abc", "cbabc");
testSolution("abbade", "edabbade");
testSolution("racecarABC", "CBAracecarABC");
testSolution("computer is my friend", "dneirf ym si retupmocomputer is my friend");
}
private static void testSolution(String question, String expected) {
String result = new Palindrome().solution(question);
System.out.printf("%s : %s : %s\n", result, result.equals(expected), l);
}
private String solution(String origin) { // abbade
String rev = reverse(origin); // edabba
int dupLen = findLongestDuplicationLengthFromOrigin(origin, rev); // abba => 4
String remain = origin.substring(dupLen); // de
String revRemain = reverse(remain); // ed
return revRemain + origin;
}
private String reverse(String str) {
char[] arr = str.toCharArray();
char[] rev = new char[arr.length];
for (int i = 0; i < arr.length; i++) {
l++;
rev[arr.length - i - 1] = arr[i];
}
return new String(rev);
}
private int findLongestDuplicationLengthFromOrigin(String a, String b) {
// abbade
// edabba
for (int i = a.length(); i >= 1; i--) {
l++;
String token = a.substring(0, i);
if (b.endsWith(token))
return i;
}
return 0;
}
}
| [
"gimslab.com@gmail.com"
] | gimslab.com@gmail.com |
dfbf6727c1b9d0a96fa0b0c8d7b9f61aa24fd283 | c3445da9eff3501684f1e22dd8709d01ff414a15 | /LIS/sinosoft-parents/lis-business/src/main/java/com/sinosoft/lis/reinsure/calculate/calitem/RIItemCalClass.java | 2eb55363bfd928fc7aa844608634834cf381b381 | [] | no_license | zhanght86/HSBC20171018 | 954403d25d24854dd426fa9224dfb578567ac212 | c1095c58c0bdfa9d79668db9be4a250dd3f418c5 | refs/heads/master | 2021-05-07T03:30:31.905582 | 2017-11-08T08:54:46 | 2017-11-08T08:54:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,282 | java |
package com.sinosoft.lis.reinsure.calculate.calitem;
import com.sinosoft.utility.CErrors;
import com.sinosoft.lis.schema.RIItemCalSchema;
import com.sinosoft.lis.schema.RIRecordTraceSchema;
import com.sinosoft.lis.schema.RICalParamSchema;
import com.sinosoft.utility.CError;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2008</p>
* <p>Company: </p>
* @zhangbin
* @version 1.0
*/
public class RIItemCalClass {
public CErrors mErrors = new CErrors();
private double mReslut = 0;
public RIItemCalClass() {
}
public boolean calItem(RIRecordTraceSchema riRecordTraceSchema,RICalParamSchema riCalParamSchema,RIItemCalSchema riItemCalSchema){
try{
if(riItemCalSchema.getArithmeticID().equals("i001000001")){
if(riItemCalSchema.getCalItemOrder()==1){//新单分保保费
mReslut=riRecordTraceSchema.getCessionAmount()/1000*riCalParamSchema.getParamDouble1();
return true;
}
if(riItemCalSchema.getCalItemOrder()==2){//新单分保佣金
mReslut=riRecordTraceSchema.getPremChang()*riCalParamSchema.getParamDouble2();
return true;
}
if(riItemCalSchema.getCalItemOrder()==3){//续期分保保费
mReslut=riRecordTraceSchema.getCurentAmnt()*riCalParamSchema.getParamDouble1()/1000*riCalParamSchema.getParamDouble2();
return true;
}
if(riItemCalSchema.getCalItemOrder()==4){//续期分保佣金
mReslut=riRecordTraceSchema.getPremChang()/1000*riCalParamSchema.getParamDouble3();
return true;
}
if(riItemCalSchema.getCalItemOrder()==5){//保全分保保费
if(riRecordTraceSchema.getAddSubFlag().equals("1")){
mReslut=riCalParamSchema.getParamDouble4()/1000*riCalParamSchema.getParamDouble2();
return true;
}else{
mReslut=riRecordTraceSchema.getCurentAmnt()*riCalParamSchema.getParamDouble1()/1000*riCalParamSchema.getParamDouble2();
return true;
}
}
if(riItemCalSchema.getCalItemOrder()==6){//保全分保佣金
mReslut=riRecordTraceSchema.getPremChang()/1000*riCalParamSchema.getParamDouble3();
return true;
}
if(riItemCalSchema.getCalItemOrder()==7){//理赔摊回
mReslut=riCalParamSchema.getParamDouble2()*riCalParamSchema.getParamDouble1();
return true;
}
}
}catch(Exception ex){
buildError("RIItemCalClass",ex.getMessage());
return false;
}
return true;
}
public double getValue(){
return mReslut;
}
private void buildError(String szFunc, String szErrMsg) {
CError cError = new CError();
cError.moduleName = "RIItemCalClass";
cError.functionName = szFunc;
cError.errorMessage = szErrMsg;
this.mErrors.addOneError(cError);
System.out.print(szErrMsg);
}
}
| [
"dingzansh@sinosoft.com.cn"
] | dingzansh@sinosoft.com.cn |
57662ed2ccead801d8b4a451a988c94dcf0a82f8 | f662526b79170f8eeee8a78840dd454b1ea8048c | /org/apache/commons/io/output/ThresholdingOutputStream.java | 1b9613f4c25ffc6701dee12566e3fae3bf3613d4 | [] | no_license | jason920612/Minecraft | 5d3cd1eb90726efda60a61e8ff9e057059f9a484 | 5bd5fb4dac36e23a2c16576118da15c4890a2dff | refs/heads/master | 2023-01-12T17:04:25.208957 | 2020-11-26T08:51:21 | 2020-11-26T08:51:21 | 316,170,984 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,916 | java | /* */ package org.apache.commons.io.output;
/* */
/* */ import java.io.IOException;
/* */ import java.io.OutputStream;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public abstract class ThresholdingOutputStream
/* */ extends OutputStream
/* */ {
/* */ private final int threshold;
/* */ private long written;
/* */ private boolean thresholdExceeded;
/* */
/* */ public ThresholdingOutputStream(int threshold) {
/* 75 */ this.threshold = threshold;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public void write(int b) throws IOException {
/* 92 */ checkThreshold(1);
/* 93 */ getStream().write(b);
/* 94 */ this.written++;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public void write(byte[] b) throws IOException {
/* 109 */ checkThreshold(b.length);
/* 110 */ getStream().write(b);
/* 111 */ this.written += b.length;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public void write(byte[] b, int off, int len) throws IOException {
/* 128 */ checkThreshold(len);
/* 129 */ getStream().write(b, off, len);
/* 130 */ this.written += len;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public void flush() throws IOException {
/* 143 */ getStream().flush();
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public void close() throws IOException {
/* */ try {
/* 158 */ flush();
/* */ }
/* 160 */ catch (IOException iOException) {}
/* */
/* */
/* */
/* 164 */ getStream().close();
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public int getThreshold() {
/* 178 */ return this.threshold;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public long getByteCount() {
/* 189 */ return this.written;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public boolean isThresholdExceeded() {
/* 202 */ return (this.written > this.threshold);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ protected void checkThreshold(int count) throws IOException {
/* 221 */ if (!this.thresholdExceeded && this.written + count > this.threshold) {
/* */
/* 223 */ this.thresholdExceeded = true;
/* 224 */ thresholdReached();
/* */ }
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ protected void resetByteCount() {
/* 234 */ this.thresholdExceeded = false;
/* 235 */ this.written = 0L;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ protected void setByteCount(long count) {
/* 248 */ this.written = count;
/* */ }
/* */
/* */ protected abstract OutputStream getStream() throws IOException;
/* */
/* */ protected abstract void thresholdReached() throws IOException;
/* */ }
/* Location: F:\dw\server.jar!\org\apache\commons\io\output\ThresholdingOutputStream.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ | [
"jasonya2206@gmail.com"
] | jasonya2206@gmail.com |
88d7641fad3d7b92c18b6c76701be4b74eaca0dd | c3c0a3116e2a0dee2610a057063d9638a66f3b70 | /src/main/java/com/guchaolong/algorithm/zuoshensuanfa/train002/class05/AbstractSelfBalancingBinarySearchTree.java | 3a8b7152415e408ff1ef8d67188d7e869c165387 | [] | no_license | guchaolong/java-learn | 8523ecad5bb1ed4b61e563e0507cafb12b3ea95d | ac3b744551a185c7fc1601aa5633c9192c2b8aca | refs/heads/master | 2023-08-19T07:49:15.351765 | 2023-08-17T14:25:47 | 2023-08-17T14:25:47 | 159,709,168 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,009 | java | package com.guchaolong.algorithm.zuoshensuanfa.train002.class05;
/**
* Not implemented by zuochengyun
*
* Abstract class for self balancing binary search trees. Contains some methods
* that is used for self balancing trees.
*
* @author Ignas Lelys
* @created Jul 24, 2011
*
*/
public abstract class AbstractSelfBalancingBinarySearchTree
extends AbstractBinarySearchTree {
/**
* Rotate to the left.
*
* @param node Node on which to rotate.
* @return Node that is in place of provided node after rotation.
*/
protected Node rotateLeft(Node node) {
Node temp = node.right;
temp.parent = node.parent;
node.right = temp.left;
if (node.right != null) {
node.right.parent = node;
}
temp.left = node;
node.parent = temp;
// temp took over node's place so now its parent should point to temp
if (temp.parent != null) {
if (node == temp.parent.left) {
temp.parent.left = temp;
} else {
temp.parent.right = temp;
}
} else {
root = temp;
}
return temp;
}
/**
* Rotate to the right.
*
* @param node Node on which to rotate.
* @return Node that is in place of provided node after rotation.
*/
protected Node rotateRight(Node node) {
Node temp = node.left;
temp.parent = node.parent;
node.left = temp.right;
if (node.left != null) {
node.left.parent = node;
}
temp.right = node;
node.parent = temp;
// temp took over node's place so now its parent should point to temp
if (temp.parent != null) {
if (node == temp.parent.left) {
temp.parent.left = temp;
} else {
temp.parent.right = temp;
}
} else {
root = temp;
}
return temp;
}
}
| [
"guclno1@qq.com"
] | guclno1@qq.com |
9cd12cc0c0ab312df0d75c2e185366926c6b2764 | 2a0b5df31c675070761dca0d3d719733fc2ea187 | /java/oreilly/MyMediaInventory/app/src/main/java/com/ost/android2/MediaInventory/MediaBrowserActivity.java | 3b5bfb6e47ac7d898c2bd46cb1a235c1a3ce05e9 | [] | no_license | oussamad-blip/bookcode-compile-lang | 55ff480d50f6101fd727bbfedb60587cb9930b60 | 87a959cf821624765df34eff506faf28ae429b4c | refs/heads/master | 2023-05-05T00:05:49.387277 | 2019-02-17T10:08:17 | 2019-02-17T10:08:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 438 | java | package com.ost.android2.MediaInventory;
import android.support.v4.app.Fragment;
import android.util.Log;
public class MediaBrowserActivity extends FragmentContainerActivity {
private static final String TAG = "MediaBrowserActivity";
@Override
protected Fragment createFragment() {
Log.d(TAG, "createFragment() called ");
return MediaBrowserFragment.newInstance();
} // end of createFragment
} //end of Class | [
"jimagile@gmail.com"
] | jimagile@gmail.com |
fdb19010815fb3ab6d59573939ce093ad81d8f44 | 4f5c6562667203651e1e6680e3f214d41958f011 | /AOPSample1/src/main/java/com/aopexample1/Function.java | 5cdefc0af75682384d9d6947a3379ecd0c851028 | [] | no_license | hedara/laptop-scripts | f416dfff783a15036de75a840255be6d43763a0c | 1f2a717a807b6c8ffcd3640947addc47db734536 | refs/heads/master | 2021-01-13T04:26:19.081465 | 2017-01-24T03:40:42 | 2017-01-24T03:40:42 | 79,874,871 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 120 | java | package com.aopexample1;
/**
* Created by edara on 9/29/16.
*/
interface Function {
void perform(String host);
}
| [
"edara@Hareens-MBP.home"
] | edara@Hareens-MBP.home |
c1ab533e17f58738830bf7836506fe803364b76c | 99c03face59ec13af5da080568d793e8aad8af81 | /hom_classifier/2om_classifier/scratch/AOIU19ROR21/Pawn.java | ca61a2ee31eac4569c24aeb843f07d8d91c2f741 | [] | no_license | fouticus/HOMClassifier | 62e5628e4179e83e5df6ef350a907dbf69f85d4b | 13b9b432e98acd32ae962cbc45d2f28be9711a68 | refs/heads/master | 2021-01-23T11:33:48.114621 | 2020-05-13T18:46:44 | 2020-05-13T18:46:44 | 93,126,040 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,758 | java | // This is a mutant program.
// Author : ysma
import java.util.ArrayList;
public class Pawn extends ChessPiece
{
public Pawn( ChessBoard board, ChessPiece.Color color )
{
super( board, color );
}
public java.lang.String toString()
{
if (color == ChessPiece.Color.WHITE) {
return "♙";
} else {
return "♟";
}
}
public java.util.ArrayList<String> legalMoves()
{
java.util.ArrayList<String> returnList = new java.util.ArrayList<String>();
if (this.getColor().equals( ChessPiece.Color.WHITE )) {
int currentCol = this.getColumn();
int nextRow = this.getRow() + 1;
if (nextRow <= 7) {
if (board.getPiece( onePossibleMove( nextRow, currentCol ) ) == null) {
returnList.add( onePossibleMove( nextRow, currentCol ) );
}
}
if (this.getRow() == 1) {
int nextNextRow = this.getRow() + 2;
if (board.getPiece( onePossibleMove( nextRow, currentCol ) ) == null && board.getPiece( onePossibleMove( nextNextRow, currentCol ) ) == null) {
returnList.add( onePossibleMove( nextNextRow, currentCol ) );
}
}
int leftColumn = currentCol - 1;
int rightColumn = currentCol + 1;
if (leftColumn <= 0) {
if (board.getPiece( onePossibleMove( nextRow, leftColumn ) ) != null) {
if (!board.getPiece( onePossibleMove( nextRow, leftColumn ) ).getColor().equals( this.getColor() )) {
returnList.add( onePossibleMove( nextRow, leftColumn ) );
}
}
}
if (rightColumn <= 7) {
if (board.getPiece( onePossibleMove( nextRow, rightColumn ) ) != null) {
if (!board.getPiece( onePossibleMove( nextRow, rightColumn ) ).getColor().equals( this.getColor() )) {
returnList.add( onePossibleMove( nextRow, rightColumn ) );
}
}
}
} else {
int currentCol = this.getColumn();
int nextRow = this.getRow() - 1;
if (nextRow >= 0) {
if (board.getPiece( onePossibleMove( nextRow, currentCol ) ) == null) {
returnList.add( onePossibleMove( nextRow, currentCol ) );
}
}
if (this.getRow() == 6) {
int nextNextRow = this.getRow() - 2;
if (board.getPiece( onePossibleMove( nextRow, currentCol ) ) == null && board.getPiece( onePossibleMove( nextNextRow, currentCol ) ) == null) {
returnList.add( onePossibleMove( nextNextRow, currentCol ) );
}
}
int leftColumn = currentCol - 1;
int rightColumn = currentCol + 1;
if (leftColumn >= 0) {
if (board.getPiece( onePossibleMove( nextRow, leftColumn ) ) != null) {
if (!board.getPiece( onePossibleMove( nextRow, leftColumn ) ).getColor().equals( this.getColor() )) {
returnList.add( onePossibleMove( nextRow, leftColumn ) );
}
}
}
if (rightColumn <= 7) {
if (board.getPiece( onePossibleMove( nextRow, rightColumn ) ) != null) {
if (!board.getPiece( onePossibleMove( nextRow, rightColumn ) ).getColor().equals( this.getColor() )) {
returnList.add( onePossibleMove( -nextRow, rightColumn ) );
}
}
}
}
return returnList;
}
} | [
"fout.alex@gmail.com"
] | fout.alex@gmail.com |
6bb1ee8e0e127463eae6af429d2687548d4afc58 | 1df6f0c12187c32352a9be2a0ebfed621ba4557a | /app/src/main/java/com/example/trippi/HotelFragment.java | 05f900db0843f740f3aea778bf05e6a16d324523 | [] | no_license | lmp95/trippi | 3517aca5730091c3c47a28324040acaa6d69ffbc | f8c27f40e9cf855e5511845b05a633ba9fe0f6ab | refs/heads/master | 2023-04-24T10:52:20.059844 | 2021-02-16T12:05:53 | 2021-02-16T12:05:53 | 323,827,444 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,113 | java | package com.example.trippi;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collections;
/**
* A simple {@link Fragment} subclass.
* Use the {@link HotelFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class HotelFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
ArrayList<Hotel> hotelArrayList = new ArrayList<>();
UserAccount userAccount;
public HotelFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment HotelFragment.
*/
// TODO: Rename and change types and number of parameters
public static HotelFragment newInstance(String param1, String param2) {
HotelFragment fragment = new HotelFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
Bundle bundle = this.getArguments();
userAccount = (UserAccount) bundle.getSerializable("User");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_hotel, container, false);
ListView listView = view.findViewById(R.id.hotelListView);
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Hotels");
databaseReference.orderByChild("rating").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
hotelArrayList.clear();
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
Hotel hotel = snapshot.getValue(Hotel.class);
hotel.id = snapshot.getKey();
hotelArrayList.add(hotel);
}
Collections.reverse(hotelArrayList);
HotelListAdapter customAdapter = new HotelListAdapter(getActivity(), R.layout.hotel_list_item, hotelArrayList);
listView.setAdapter(customAdapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
listView.setOnItemClickListener((parent, view1, position, id) -> {
Intent intent = new Intent(HotelFragment.this.getActivity(), HotelDetail.class);
intent.putExtra("Hotel", hotelArrayList.get(position));
intent.putExtra("Account", userAccount);
startActivity(intent);
});
return view;
}
} | [
"lwinmgphyo95@gmail.com"
] | lwinmgphyo95@gmail.com |
dbd2330330bf2a8b47cdf7144e4c37f7fbf7fbe3 | 720d882710f6fb2801ed44e42ed38f280a5faaf3 | /bird-framework2/smart-framework/src/main/java/com/learning/framework/annotation/Service.java | cd6769e2f9a18ebafa89162f90b484163005ecf8 | [] | no_license | stillcoolme/bird | c1263df4b40e149311cf4fa95d2ada0b7c03668d | 0a5e8dfd95619528f36e2f66e6a85e847e4e6baf | refs/heads/master | 2023-05-04T16:33:13.609239 | 2022-09-02T11:18:13 | 2022-09-02T11:18:13 | 166,504,001 | 0 | 0 | null | 2023-04-21T20:43:03 | 2019-01-19T03:58:28 | Java | UTF-8 | Java | false | false | 328 | java | package com.learning.framework.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 服务类的注解
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Service {
}
| [
"stillcoolman@sina.com"
] | stillcoolman@sina.com |
6fec982dd5744f2da2f986639c880bf085a81738 | 1b0a9fb8fb6285822c7907b62a5840c66f43f90f | /dicer-core/src/tosca/impl/ImportImpl.java | 914842de3f35e1ada4b1b5d7cae86224b2663fc2 | [
"BSD-2-Clause-Views",
"BSD-3-Clause"
] | permissive | MicheleGuerriero/DICER | 99ffb6b29860b157fe2c498ce67d9bd028a80c68 | 3a2eb2bf5e31d66958839f8e647017300bac2417 | refs/heads/master | 2021-01-19T04:33:59.689146 | 2018-07-13T17:41:52 | 2018-07-13T18:15:40 | 63,014,681 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,132 | java | /**
*/
package tosca.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import tosca.Import;
import tosca.ToscaPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Import</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link tosca.impl.ImportImpl#getImport_name <em>Import name</em>}</li>
* <li>{@link tosca.impl.ImportImpl#getFile <em>File</em>}</li>
* <li>{@link tosca.impl.ImportImpl#getRepository <em>Repository</em>}</li>
* <li>{@link tosca.impl.ImportImpl#getNamespace_uri <em>Namespace uri</em>}</li>
* <li>{@link tosca.impl.ImportImpl#getNamespace_prefix <em>Namespace prefix</em>}</li>
* </ul>
*
* @generated
*/
public class ImportImpl extends MinimalEObjectImpl.Container implements Import {
/**
* The default value of the '{@link #getImport_name() <em>Import name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getImport_name()
* @generated
* @ordered
*/
protected static final String IMPORT_NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getImport_name() <em>Import name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getImport_name()
* @generated
* @ordered
*/
protected String import_name = IMPORT_NAME_EDEFAULT;
/**
* The default value of the '{@link #getFile() <em>File</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFile()
* @generated
* @ordered
*/
protected static final String FILE_EDEFAULT = null;
/**
* The cached value of the '{@link #getFile() <em>File</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFile()
* @generated
* @ordered
*/
protected String file = FILE_EDEFAULT;
/**
* The default value of the '{@link #getRepository() <em>Repository</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRepository()
* @generated
* @ordered
*/
protected static final String REPOSITORY_EDEFAULT = null;
/**
* The cached value of the '{@link #getRepository() <em>Repository</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRepository()
* @generated
* @ordered
*/
protected String repository = REPOSITORY_EDEFAULT;
/**
* The default value of the '{@link #getNamespace_uri() <em>Namespace uri</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getNamespace_uri()
* @generated
* @ordered
*/
protected static final String NAMESPACE_URI_EDEFAULT = null;
/**
* The cached value of the '{@link #getNamespace_uri() <em>Namespace uri</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getNamespace_uri()
* @generated
* @ordered
*/
protected String namespace_uri = NAMESPACE_URI_EDEFAULT;
/**
* The default value of the '{@link #getNamespace_prefix() <em>Namespace prefix</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getNamespace_prefix()
* @generated
* @ordered
*/
protected static final String NAMESPACE_PREFIX_EDEFAULT = null;
/**
* The cached value of the '{@link #getNamespace_prefix() <em>Namespace prefix</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getNamespace_prefix()
* @generated
* @ordered
*/
protected String namespace_prefix = NAMESPACE_PREFIX_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ImportImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return ToscaPackage.Literals.IMPORT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getImport_name() {
return import_name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setImport_name(String newImport_name) {
String oldImport_name = import_name;
import_name = newImport_name;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ToscaPackage.IMPORT__IMPORT_NAME, oldImport_name, import_name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getFile() {
return file;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setFile(String newFile) {
String oldFile = file;
file = newFile;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ToscaPackage.IMPORT__FILE, oldFile, file));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getRepository() {
return repository;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setRepository(String newRepository) {
String oldRepository = repository;
repository = newRepository;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ToscaPackage.IMPORT__REPOSITORY, oldRepository, repository));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getNamespace_uri() {
return namespace_uri;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setNamespace_uri(String newNamespace_uri) {
String oldNamespace_uri = namespace_uri;
namespace_uri = newNamespace_uri;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ToscaPackage.IMPORT__NAMESPACE_URI, oldNamespace_uri, namespace_uri));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getNamespace_prefix() {
return namespace_prefix;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setNamespace_prefix(String newNamespace_prefix) {
String oldNamespace_prefix = namespace_prefix;
namespace_prefix = newNamespace_prefix;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ToscaPackage.IMPORT__NAMESPACE_PREFIX, oldNamespace_prefix, namespace_prefix));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ToscaPackage.IMPORT__IMPORT_NAME:
return getImport_name();
case ToscaPackage.IMPORT__FILE:
return getFile();
case ToscaPackage.IMPORT__REPOSITORY:
return getRepository();
case ToscaPackage.IMPORT__NAMESPACE_URI:
return getNamespace_uri();
case ToscaPackage.IMPORT__NAMESPACE_PREFIX:
return getNamespace_prefix();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ToscaPackage.IMPORT__IMPORT_NAME:
setImport_name((String)newValue);
return;
case ToscaPackage.IMPORT__FILE:
setFile((String)newValue);
return;
case ToscaPackage.IMPORT__REPOSITORY:
setRepository((String)newValue);
return;
case ToscaPackage.IMPORT__NAMESPACE_URI:
setNamespace_uri((String)newValue);
return;
case ToscaPackage.IMPORT__NAMESPACE_PREFIX:
setNamespace_prefix((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ToscaPackage.IMPORT__IMPORT_NAME:
setImport_name(IMPORT_NAME_EDEFAULT);
return;
case ToscaPackage.IMPORT__FILE:
setFile(FILE_EDEFAULT);
return;
case ToscaPackage.IMPORT__REPOSITORY:
setRepository(REPOSITORY_EDEFAULT);
return;
case ToscaPackage.IMPORT__NAMESPACE_URI:
setNamespace_uri(NAMESPACE_URI_EDEFAULT);
return;
case ToscaPackage.IMPORT__NAMESPACE_PREFIX:
setNamespace_prefix(NAMESPACE_PREFIX_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ToscaPackage.IMPORT__IMPORT_NAME:
return IMPORT_NAME_EDEFAULT == null ? import_name != null : !IMPORT_NAME_EDEFAULT.equals(import_name);
case ToscaPackage.IMPORT__FILE:
return FILE_EDEFAULT == null ? file != null : !FILE_EDEFAULT.equals(file);
case ToscaPackage.IMPORT__REPOSITORY:
return REPOSITORY_EDEFAULT == null ? repository != null : !REPOSITORY_EDEFAULT.equals(repository);
case ToscaPackage.IMPORT__NAMESPACE_URI:
return NAMESPACE_URI_EDEFAULT == null ? namespace_uri != null : !NAMESPACE_URI_EDEFAULT.equals(namespace_uri);
case ToscaPackage.IMPORT__NAMESPACE_PREFIX:
return NAMESPACE_PREFIX_EDEFAULT == null ? namespace_prefix != null : !NAMESPACE_PREFIX_EDEFAULT.equals(namespace_prefix);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (import_name: ");
result.append(import_name);
result.append(", file: ");
result.append(file);
result.append(", repository: ");
result.append(repository);
result.append(", namespace_uri: ");
result.append(namespace_uri);
result.append(", namespace_prefix: ");
result.append(namespace_prefix);
result.append(')');
return result.toString();
}
} //ImportImpl
| [
"michele.guerriero2391@gmail.com"
] | michele.guerriero2391@gmail.com |
a87ac84646ae3e40bc6a4af6b03d5c7dcfc40e98 | 389ac98c88fb62e891ca2a73c08e37409aba7ddf | /src/java/entidades/AbstractFacade.java | 931cd28978c23ba547dccbe102eea0ba0b2b517e | [] | no_license | EOlazaba88/JSF_Nomina | 8603065a1b3690db077621c88a7ed8a74406485c | 9ef6b0859e0cacb91075cf233e926a9368fe617c | refs/heads/master | 2023-04-14T05:13:43.565816 | 2023-04-01T00:26:01 | 2023-04-01T00:26:01 | 135,326,703 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,967 | java | /*
* 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 entidades;
import java.util.List;
import javax.persistence.EntityManager;
/**
*
* @author edgar
*/
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
| [
"olazabaedgar@gmail.com"
] | olazabaedgar@gmail.com |
a44c39874fddabaaaa4a01f4de6875464c829e87 | 2b2fcb1902206ad0f207305b9268838504c3749b | /WakfuClientSources/srcx/class_9466_djO.java | 6129093450468ee318df05e090a96cd9e8c24853 | [] | no_license | shelsonjava/Synx | 4fbcee964631f747efc9296477dee5a22826791a | 0cb26d5473ba1f36a3ea1d7163a5b9e6ebcb0b1d | refs/heads/master | 2021-01-15T13:51:41.816571 | 2013-11-17T10:46:22 | 2013-11-17T10:46:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,501 | java | import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class djO
implements bXj
{
private List lgT = new ArrayList();
private List lgU = new ArrayList();
static Class cvG;
static Class cvH;
static Class cvJ;
static Class cvI;
static Class cvK;
static Class cvL;
static Class cvM;
static Class cvN;
private Class am(Class paramClass)
{
if (paramClass == (cvG == null ? (djO.cvG = cd("java.lang.Boolean")) : cvG)) {
return Boolean.TYPE;
}
if (paramClass == Boolean.TYPE) {
return cvG == null ? (djO.cvG = cd("java.lang.Boolean")) : cvG;
}
if (paramClass == (cvH == null ? (djO.cvH = cd("java.lang.Byte")) : cvH)) {
return Byte.TYPE;
}
if (paramClass == Byte.TYPE) {
return cvH == null ? (djO.cvH = cd("java.lang.Byte")) : cvH;
}
if (paramClass == (cvJ == null ? (djO.cvJ = cd("java.lang.Character")) : cvJ)) {
return Character.TYPE;
}
if (paramClass == Character.TYPE) {
return cvJ == null ? (djO.cvJ = cd("java.lang.Character")) : cvJ;
}
if (paramClass == (cvI == null ? (djO.cvI = cd("java.lang.Short")) : cvI)) {
return Short.TYPE;
}
if (paramClass == Short.TYPE) {
return cvI == null ? (djO.cvI = cd("java.lang.Short")) : cvI;
}
if (paramClass == (cvK == null ? (djO.cvK = cd("java.lang.Integer")) : cvK)) {
return Integer.TYPE;
}
if (paramClass == Integer.TYPE) {
return cvK == null ? (djO.cvK = cd("java.lang.Integer")) : cvK;
}
if (paramClass == (cvL == null ? (djO.cvL = cd("java.lang.Long")) : cvL)) {
return Long.TYPE;
}
if (paramClass == Long.TYPE) {
return cvL == null ? (djO.cvL = cd("java.lang.Long")) : cvL;
}
if (paramClass == (cvM == null ? (djO.cvM = cd("java.lang.Float")) : cvM)) {
return Float.TYPE;
}
if (paramClass == Float.TYPE) {
return cvM == null ? (djO.cvM = cd("java.lang.Float")) : cvM;
}
if (paramClass == (cvN == null ? (djO.cvN = cd("java.lang.Double")) : cvN)) {
return Double.TYPE;
}
if (paramClass == Double.TYPE) {
return cvN == null ? (djO.cvN = cd("java.lang.Double")) : cvN;
}
return null;
}
public void a(Class paramClass, aEQ paramaEQ)
{
this.lgT.add(new cxP(paramClass, paramaEQ));
Class localClass = am(paramClass);
if (localClass != null)
this.lgT.add(new cxP(localClass, paramaEQ));
}
public void a(Class paramClass, bYH parambYH)
{
this.lgU.add(new cxP(paramClass, parambYH));
Class localClass = am(paramClass);
if (localClass != null)
this.lgU.add(new cxP(localClass, parambYH));
}
protected void a(Class paramClass, dsn paramdsn)
{
a(paramClass, paramdsn);
a(paramClass, paramdsn);
}
private Object b(Class paramClass, List paramList) {
for (Iterator localIterator = paramList.iterator(); localIterator.hasNext(); ) {
cxP localcxP = (cxP)localIterator.next();
if (localcxP.type.isAssignableFrom(paramClass)) {
return localcxP.ilQ;
}
}
return null;
}
public bYH W(Class paramClass)
{
return (bYH)b(paramClass, this.lgU);
}
public aEQ X(Class paramClass)
{
return (aEQ)b(paramClass, this.lgT);
}
static Class cd(String paramString)
{
try
{
return Class.forName(paramString); } catch (ClassNotFoundException localClassNotFoundException) { throw new NoClassDefFoundError().initCause(localClassNotFoundException); }
}
} | [
"music_inme@hotmail.fr"
] | music_inme@hotmail.fr |
c74ca6634b6253c691452d28e1b7067e6acb33c0 | 20602944b7f6e93ce67de6b7f5644838ca2060eb | /src/test/java/concurrency/multithreading/synchronization/lock/intrinsic/wait/notify/reentrant/lock/ReentrantLockDemoTest.java | 16ca95ea09d113950f671cf52f7c9d4b4e1da687 | [
"Apache-2.0"
] | permissive | axal25/JavaCourse | acecf4fbd78df21f1306c1f4dcb4bf857b826bca | 881306212a888ce5490474f5b703a7399a436051 | refs/heads/master | 2023-08-17T13:05:35.003847 | 2023-08-16T13:28:15 | 2023-08-16T13:28:15 | 229,087,936 | 0 | 0 | Apache-2.0 | 2022-11-19T16:38:50 | 2019-12-19T15:49:24 | Java | UTF-8 | Java | false | false | 14,536 | java | package concurrency.multithreading.synchronization.lock.intrinsic.wait.notify.reentrant.lock;
import com.google.common.truth.Correspondence;
import concurrency.multithreading.synchronization.lock.intrinsic.wait.notify.demo5.LogsCopyOnAdd;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.IntStream;
import static com.google.common.truth.Truth.assertThat;
public class ReentrantLockDemoTest {
private static final Correspondence<Throwable, Throwable> CORRESPONDENCE_THROWABLE_IGNORE_STACK_TRACE = Correspondence.from(
ReentrantLockDemoTest::equalsIgnoreStackTrace,
String.format(
"actual %s equals expected %s",
Throwable.class.getSimpleName(),
Throwable.class.getSimpleName()));
private static boolean equalsIgnoreStackTrace(Throwable throwable1, Throwable throwable2) {
return throwable1 == throwable2
? true
: throwable1 == null || throwable2 == null
? false
: Objects.equals(throwable1.getClass(), throwable2.getClass())
&& Objects.equals(throwable1.toString(), throwable2.toString())
&& Objects.equals(throwable1.getMessage(), throwable2.getMessage())
&& Objects.equals(throwable1.getLocalizedMessage(), throwable2.getLocalizedMessage())
&& Arrays.equals(throwable1.getSuppressed(), throwable2.getSuppressed())
&& equalsIgnoreStackTrace(throwable1.getCause(), throwable2.getCause());
}
static final long SLEEP_DURATION_MILLIS = 250;
@TestTemplate
@ExtendWith(TestContextProviderWaitInterruptBeforeLocking.class)
void interruptBeforeLockingWait(ReentrantLockDemoTestCaseData testCaseData) throws InterruptedException {
testCaseData.getInputs().getReentrantLockAccessor().start();
Thread.sleep(SLEEP_DURATION_MILLIS);
testCaseData.getInputs().getReentrantLockAccessor().interrupt();
Thread.sleep(SLEEP_DURATION_MILLIS);
testCaseData.getInputs().getReentrantLockNotifier().notifyAccessor();
Thread.sleep(SLEEP_DURATION_MILLIS);
testCaseData.getInputs().getReentrantLockNotifier().notifyAccessor();
Thread.sleep(SLEEP_DURATION_MILLIS);
testCaseData.getInputs().getReentrantLockAccessor().join();
Thread.sleep(SLEEP_DURATION_MILLIS);
assertThat(testCaseData.getInputs().getLogs())
.isEqualTo(testCaseData.getExpecteds().getLogs());
ReentrantLockAccessor reentrantLockAccessor = testCaseData.getInputs().getReentrantLockAccessor();
List<Throwable> actualUncaughtExceptions = reentrantLockAccessor.getReentrantLockThreadGroup().getUncaughtExceptions().get(reentrantLockAccessor);
assertThat(reentrantLockAccessor.getUncaughtExceptions()).isEqualTo(actualUncaughtExceptions);
List<Throwable> expectedUncaughtExceptions = testCaseData.getExpecteds().getUncaughtExceptions();
assertThat(actualUncaughtExceptions).hasSize(expectedUncaughtExceptions.size());
IntStream.range(0, actualUncaughtExceptions.size()).forEach(index -> {
Throwable actualUncaughtException = actualUncaughtExceptions.get(index);
Throwable expectedUncaughtException = expectedUncaughtExceptions.get(index);
assertThat(actualUncaughtException.getClass()).isEqualTo(expectedUncaughtException.getClass());
assertThat(actualUncaughtException).hasMessageThat().isEqualTo(expectedUncaughtException.getMessage());
assertThat(actualUncaughtException.getCause().getClass()).isEqualTo(expectedUncaughtException.getCause().getClass());
assertThat(actualUncaughtException).hasCauseThat().hasMessageThat().isNull();
assertThat(expectedUncaughtException).hasCauseThat().hasMessageThat().isNull();
assertThat(actualUncaughtException.getCause().getCause()).isNull();
assertThat(expectedUncaughtException.getCause().getCause()).isNull();
});
assertThat(actualUncaughtExceptions)
.comparingElementsUsing(CORRESPONDENCE_THROWABLE_IGNORE_STACK_TRACE)
.containsExactlyElementsIn(expectedUncaughtExceptions);
}
@TestTemplate
@ExtendWith(TestContextProviderWaitInterruptAfterLocking.class)
void interruptAfterLockingWait(ReentrantLockDemoTestCaseData testCaseData) throws InterruptedException {
testCaseData.getInputs().getReentrantLockAccessor().start();
Thread.sleep(SLEEP_DURATION_MILLIS);
testCaseData.getInputs().getReentrantLockNotifier().notifyAccessor();
Thread.sleep(SLEEP_DURATION_MILLIS);
testCaseData.getInputs().getReentrantLockAccessor().interrupt();
Thread.sleep(SLEEP_DURATION_MILLIS);
testCaseData.getInputs().getReentrantLockNotifier().notifyAccessor();
Thread.sleep(SLEEP_DURATION_MILLIS);
testCaseData.getInputs().getReentrantLockAccessor().join();
Thread.sleep(SLEEP_DURATION_MILLIS);
assertThat(testCaseData.getInputs().getLogs()).isEqualTo(testCaseData.getExpecteds().getLogs());
ReentrantLockAccessor reentrantLockAccessor = testCaseData.getInputs().getReentrantLockAccessor();
List<Throwable> actualUncaughtExceptions = reentrantLockAccessor.getReentrantLockThreadGroup().getUncaughtExceptions().get(reentrantLockAccessor);
assertThat(reentrantLockAccessor.getUncaughtExceptions()).isEqualTo(actualUncaughtExceptions);
List<Throwable> expectedUncaughtExceptions = testCaseData.getExpecteds().getUncaughtExceptions();
assertThat(actualUncaughtExceptions).hasSize(expectedUncaughtExceptions.size());
IntStream.range(0, actualUncaughtExceptions.size()).forEach(index -> {
Throwable actualUncaughtException = actualUncaughtExceptions.get(index);
Throwable expectedUncaughtException = expectedUncaughtExceptions.get(index);
assertThat(actualUncaughtException.getClass()).isEqualTo(expectedUncaughtException.getClass());
assertThat(actualUncaughtException).hasMessageThat().isEqualTo(expectedUncaughtException.getMessage());
assertThat(actualUncaughtException.getCause().getClass()).isEqualTo(expectedUncaughtException.getCause().getClass());
assertThat(actualUncaughtException).hasCauseThat().hasMessageThat().isNull();
assertThat(expectedUncaughtException).hasCauseThat().hasMessageThat().isNull();
assertThat(actualUncaughtException.getCause().getCause()).isNull();
assertThat(expectedUncaughtException.getCause().getCause()).isNull();
});
assertThat(actualUncaughtExceptions)
.comparingElementsUsing(CORRESPONDENCE_THROWABLE_IGNORE_STACK_TRACE)
.containsExactlyElementsIn(expectedUncaughtExceptions);
}
@TestTemplate
@ExtendWith(TestContextProviderSleepInterruptBeforeLocking.class)
void interruptBeforeLockingSleep(ReentrantLockDemoTestCaseData testCaseData) throws InterruptedException {
testCaseData.getInputs().getReentrantLockAccessor().start();
Thread.sleep(SLEEP_DURATION_MILLIS);
testCaseData.getInputs().getReentrantLockAccessor().interrupt();
Thread.sleep(SLEEP_DURATION_MILLIS * 3);
testCaseData.getInputs().getReentrantLockAccessor().join();
Thread.sleep(SLEEP_DURATION_MILLIS);
assertThat(testCaseData.getInputs().getLogs())
.isEqualTo(testCaseData.getExpecteds().getLogs());
ReentrantLockAccessor reentrantLockAccessor = testCaseData.getInputs().getReentrantLockAccessor();
List<Throwable> actualUncaughtExceptions = reentrantLockAccessor.getReentrantLockThreadGroup().getUncaughtExceptions().get(reentrantLockAccessor);
assertThat(reentrantLockAccessor.getUncaughtExceptions()).isEqualTo(actualUncaughtExceptions);
List<Throwable> expectedUncaughtExceptions = testCaseData.getExpecteds().getUncaughtExceptions();
assertThat(actualUncaughtExceptions).hasSize(expectedUncaughtExceptions.size());
IntStream.range(0, actualUncaughtExceptions.size()).forEach(index -> {
Throwable actualUncaughtException = actualUncaughtExceptions.get(index);
Throwable expectedUncaughtException = expectedUncaughtExceptions.get(index);
assertThat(actualUncaughtException.getClass()).isEqualTo(expectedUncaughtException.getClass());
assertThat(actualUncaughtException).hasMessageThat().isEqualTo(expectedUncaughtException.getMessage());
assertThat(actualUncaughtException.getCause().getClass()).isEqualTo(expectedUncaughtException.getCause().getClass());
assertThat(actualUncaughtException).hasCauseThat().hasMessageThat().isNull();
assertThat(expectedUncaughtException).hasCauseThat().hasMessageThat().isNull();
assertThat(actualUncaughtException.getCause().getCause()).isNull();
assertThat(expectedUncaughtException.getCause().getCause()).isNull();
});
assertThat(actualUncaughtExceptions)
.comparingElementsUsing(CORRESPONDENCE_THROWABLE_IGNORE_STACK_TRACE)
.containsExactlyElementsIn(expectedUncaughtExceptions);
}
@TestTemplate
@ExtendWith(TestContextProviderSleepInterruptAfterLocking.class)
void interruptAfterLockingSleep(ReentrantLockDemoTestCaseData testCaseData) throws InterruptedException {
testCaseData.getInputs().getReentrantLockAccessor().start();
Thread.sleep(SLEEP_DURATION_MILLIS * 2);
testCaseData.getInputs().getReentrantLockAccessor().interrupt();
Thread.sleep(SLEEP_DURATION_MILLIS * 2);
testCaseData.getInputs().getReentrantLockAccessor().join();
Thread.sleep(SLEEP_DURATION_MILLIS * 2);
assertThat(testCaseData.getInputs().getLogs()).isEqualTo(testCaseData.getExpecteds().getLogs());
ReentrantLockAccessor reentrantLockAccessor = testCaseData.getInputs().getReentrantLockAccessor();
List<Throwable> actualUncaughtExceptions = reentrantLockAccessor.getReentrantLockThreadGroup().getUncaughtExceptions().get(reentrantLockAccessor);
assertThat(reentrantLockAccessor.getUncaughtExceptions()).isEqualTo(actualUncaughtExceptions);
List<Throwable> expectedUncaughtExceptions = testCaseData.getExpecteds().getUncaughtExceptions();
assertThat(actualUncaughtExceptions).hasSize(expectedUncaughtExceptions.size());
IntStream.range(0, actualUncaughtExceptions.size()).forEach(index -> {
Throwable actualUncaughtException = actualUncaughtExceptions.get(index);
Throwable expectedUncaughtException = expectedUncaughtExceptions.get(index);
assertThat(actualUncaughtException.getClass()).isEqualTo(expectedUncaughtException.getClass());
assertThat(actualUncaughtException).hasMessageThat().isEqualTo(expectedUncaughtException.getMessage());
assertThat(actualUncaughtException.getCause().getClass()).isEqualTo(expectedUncaughtException.getCause().getClass());
assertThat(actualUncaughtException).hasCauseThat().hasMessageThat().isNull();
assertThat(expectedUncaughtException).hasCauseThat().hasMessageThat().isNull();
assertThat(actualUncaughtException.getCause().getCause()).isNull();
assertThat(expectedUncaughtException.getCause().getCause()).isNull();
});
assertThat(actualUncaughtExceptions)
.comparingElementsUsing(CORRESPONDENCE_THROWABLE_IGNORE_STACK_TRACE)
.containsExactlyElementsIn(expectedUncaughtExceptions);
}
@Test
void reentrantLockAccessor_propertiesOverLifeCycle() throws InterruptedException {
boolean isInterruptibly = true;
LogsCopyOnAdd logs = new LogsCopyOnAdd();
ReentrantLockContainer reentrantLockContainer = new ReentrantLockWaitContainer(logs);
ReentrantLockAccessor reentrantLockAccessor = new ReentrantLockWaitAccessor(logs, reentrantLockContainer, isInterruptibly);
assertThat(reentrantLockAccessor.getThreadGroup()).isNotNull();
assertThat(reentrantLockAccessor.getUncaughtExceptionHandler()).isNotNull();
assertThat(reentrantLockAccessor.getReentrantLockThreadGroup()).isNotNull();
assertThat(reentrantLockAccessor.isInterrupted()).isFalse();
assertThat(reentrantLockAccessor.getState()).isEqualTo(Thread.State.NEW);
reentrantLockAccessor.start();
Thread.sleep(SLEEP_DURATION_MILLIS);
assertThat(reentrantLockAccessor.getThreadGroup()).isNotNull();
assertThat(reentrantLockAccessor.getUncaughtExceptionHandler()).isNotNull();
assertThat(reentrantLockAccessor.getReentrantLockThreadGroup()).isNotNull();
assertThat(reentrantLockAccessor.isInterrupted()).isFalse();
assertThat(reentrantLockAccessor.getState()).isEqualTo(Thread.State.WAITING);
reentrantLockAccessor.interrupt();
assertThat(reentrantLockAccessor.isInterrupted()).isTrue();
assertThat(reentrantLockAccessor.getState()).isEqualTo(Thread.State.WAITING);
assertThat(reentrantLockAccessor.getThreadGroup()).isNotNull();
assertThat(reentrantLockAccessor.getUncaughtExceptionHandler()).isNotNull();
assertThat(reentrantLockAccessor.getReentrantLockThreadGroup()).isNotNull();
Thread.sleep(SLEEP_DURATION_MILLIS);
assertThat(reentrantLockAccessor.getThreadGroup()).isNull();
assertThat(reentrantLockAccessor.getUncaughtExceptionHandler()).isNull();
assertThat(reentrantLockAccessor.getReentrantLockThreadGroup()).isNotNull();
assertThat(reentrantLockAccessor.isInterrupted()).isFalse();
assertThat(reentrantLockAccessor.getState()).isEqualTo(Thread.State.TERMINATED);
reentrantLockAccessor.join();
Thread.sleep(SLEEP_DURATION_MILLIS);
assertThat(reentrantLockAccessor.getThreadGroup()).isNull();
assertThat(reentrantLockAccessor.getUncaughtExceptionHandler()).isNull();
assertThat(reentrantLockAccessor.getReentrantLockThreadGroup()).isNotNull();
assertThat(reentrantLockAccessor.isInterrupted()).isFalse();
assertThat(reentrantLockAccessor.getState()).isEqualTo(Thread.State.TERMINATED);
}
}
| [
"emevig@gmail.com"
] | emevig@gmail.com |
333577c35734b8f22c632295e2b6c06f42f40ea1 | ed8ee1d81e78fd803096279a8bfaab2cb81986a5 | /src/abilities/knight_abilities/Execute.java | 9d761f05622ca362af3ac50dba02f150667cd1bc | [] | no_license | MariaGavenea/LeagueOfOOP | 60f99be254650a8b95d3784df369379b166c0285 | 4e8a22cde3a03af6b70bc4609901b2ae0aa0646d | refs/heads/master | 2023-03-17T10:17:52.518075 | 2021-03-08T08:43:44 | 2021-03-08T08:43:44 | 224,904,848 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,477 | java | package abilities.knight_abilities;
import abilities.Ability;
import common.Position;
import constants.constants_for_heroes.ConstantsForKnight;
import constants.constants_for_heroes.ConstantsForPyromancer;
import constants.constants_for_heroes.ConstantsForRogue;
import constants.constants_for_heroes.ConstantsForWizard;
import hero.Hero;
import hero.heroes.Knight;
import hero.heroes.Pyromancer;
import hero.heroes.Rogue;
import hero.heroes.Wizard;
import map.GameMap;
import map.LocationType;
public class Execute implements Ability {
protected float knightAmplifier;
protected float pyromancerAmplifier;
protected float rogueAmplifier;
protected float wizardAmplifier;
public Execute() {
this.knightAmplifier = ConstantsForKnight.ExecuteConstants.KNIGHT_AMPLIFIER;
this.pyromancerAmplifier = ConstantsForKnight.ExecuteConstants.PYROMANCER_AMPLIFIER;
this.rogueAmplifier = ConstantsForKnight.ExecuteConstants.ROGUE_AMPLIFIER;
this.wizardAmplifier = ConstantsForKnight.ExecuteConstants.WIZARD_AMPLIFIER;
}
@Override
public final int applyAbility(final Knight knight, final Hero attacker) {
final int damage = getDamageWithoutRaceModifier(knight, attacker,
ConstantsForKnight.INITIAL_HP, ConstantsForKnight.HP_ADDED_PER_LEVEL);
return Math.round(damage * knightAmplifier);
}
@Override
public final int applyAbility(final Pyromancer pyromancer, final Hero attacker) {
final int damage = getDamageWithoutRaceModifier(pyromancer, attacker,
ConstantsForPyromancer.INITIAL_HP, ConstantsForPyromancer.HP_ADDED_PER_LEVEL);
return Math.round(damage * pyromancerAmplifier);
}
@Override
public final int applyAbility(final Rogue rogue, final Hero attacker) {
final int damage = getDamageWithoutRaceModifier(rogue, attacker,
ConstantsForRogue.INITIAL_HP, ConstantsForRogue.HP_ADDED_PER_LEVEL);
return Math.round(damage * rogueAmplifier);
}
@Override
public final int applyAbility(final Wizard wizard, final Hero attacker) {
final int damage = getDamageWithoutRaceModifier(wizard, attacker,
ConstantsForWizard.INITIAL_HP, ConstantsForWizard.HP_ADDED_PER_LEVEL);
return Math.round(damage * wizardAmplifier);
}
@Override
public final int getTotalDamageForWizard(final Hero wizard, final Hero otherHero) {
float damage = ConstantsForKnight.ExecuteConstants.BASE_DAMAGE
+ ConstantsForKnight.ExecuteConstants.DAMAGE_PER_LEVEL * otherHero.getLevel();
final LocationType currentLocationType = getHeroLocation(wizard);
if (currentLocationType == ConstantsForKnight.ExecuteConstants.LOCATION_TYPE) {
damage *= ConstantsForKnight.ExecuteConstants.LOCATION_AMPLIFIER;
}
return Math.round(damage);
}
@Override
public final void increaseAmplifiersForStrategy() {
knightAmplifier += ConstantsForKnight.OFFENSE_INCREASE_RACE_AMPLIFIER;
pyromancerAmplifier += ConstantsForKnight.OFFENSE_INCREASE_RACE_AMPLIFIER;
rogueAmplifier += ConstantsForKnight.OFFENSE_INCREASE_RACE_AMPLIFIER;
wizardAmplifier += ConstantsForKnight.OFFENSE_INCREASE_RACE_AMPLIFIER;
}
@Override
public final void decreaseAmplifiersForStrategy() {
knightAmplifier -= ConstantsForKnight.DEFENSE_DECREASE_RACE_AMPLIFIER;
pyromancerAmplifier -= ConstantsForKnight.DEFENSE_DECREASE_RACE_AMPLIFIER;
rogueAmplifier -= ConstantsForKnight.DEFENSE_DECREASE_RACE_AMPLIFIER;
wizardAmplifier -= ConstantsForKnight.DEFENSE_DECREASE_RACE_AMPLIFIER;
}
@Override
public final void modifyAmplifiers(final float percent) {
pyromancerAmplifier += percent;
rogueAmplifier += percent;
wizardAmplifier += percent;
}
protected final int getDamageWithoutRaceModifier(final Hero attacked, final Hero attacker,
final int initialHp, final int hpAddedPerLevel) {
final int attackerLevel = attacker.getLevel();
final int opponentMaxHp = initialHp
+ hpAddedPerLevel * attacked.getLevel();
float hpPercentLimit = ConstantsForKnight.ExecuteConstants.HP_BASE_LIMIT_PERCENT
+ ConstantsForKnight.ExecuteConstants.HP_LIMIT_PER_LEVEL * attackerLevel;
if (hpPercentLimit > ConstantsForKnight.ExecuteConstants.HP_LIMIT_MAX) {
hpPercentLimit = ConstantsForKnight.ExecuteConstants.HP_LIMIT_MAX;
}
final int hpLimit = Math.round(hpPercentLimit * opponentMaxHp);
if (attacked.getHp() < hpLimit) {
return attacked.getHp();
}
float damage = ConstantsForKnight.ExecuteConstants.BASE_DAMAGE
+ ConstantsForKnight.ExecuteConstants.DAMAGE_PER_LEVEL * attackerLevel;
final LocationType currentLocationType = getHeroLocation(attacker);
if (currentLocationType == ConstantsForKnight.ExecuteConstants.LOCATION_TYPE) {
damage *= ConstantsForKnight.ExecuteConstants.LOCATION_AMPLIFIER;
}
return Math.round(damage);
}
protected final LocationType getHeroLocation(final Hero hero) {
final Position position = hero.getPosition();
final GameMap map = GameMap.getInstance();
return map.getLocationsType(position.getLine(), position.getColumn());
}
}
| [
"maria.gavenea@stud.acs.upb.ro"
] | maria.gavenea@stud.acs.upb.ro |
201fc971bd272fd589c65f0d7c677a73526032a6 | f4bd9b1a6068c8033a32b4374f0a7c11ead2c7e4 | /src/main/java/com/wyj/springboot/im/sockethandler/SocketRoomHandler.java | 74ad7e880db69b950725aa692bff1d4a3b069cd4 | [] | no_license | DK98amazing/springboot_im | 7acb770e084836eb365f5dbcd76b5065817ab2f7 | f9e70d820cffdad660cf829e5f4c5e806abbc67f | refs/heads/master | 2020-06-27T12:47:20.477891 | 2019-08-01T02:09:47 | 2019-08-01T02:09:47 | 199,957,748 | 0 | 0 | null | 2019-08-01T01:59:21 | 2019-08-01T01:59:20 | null | UTF-8 | Java | false | false | 4,259 | java | package com.wyj.springboot.im.sockethandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.wyj.springboot.im.entity.common.ResponseBean;
import com.wyj.springboot.im.sockethandler.entity.UserInCache;
import com.wyj.springboot.im.sockethandler.room.RoomContext;
import com.wyj.springboot.im.socketnio.NettySocketServer;
import com.wyj.springboot.im.tools.StringUtil;
/**
*
* @author wuyingjie
* @date 2017年11月24日
*/
@Component
public class SocketRoomHandler {
private static final Logger logger = LoggerFactory.getLogger(SocketRoomHandler.class);
private SocketIOServer server;
@Autowired
public SocketRoomHandler(NettySocketServer server) {
this.server = server.getServer();
}
@OnEvent(value="createRoom")
public void createRoom(SocketIOClient client, Object data, AckRequest request) {
UserInCache userInCache = SocketConnectedHandler.clientMap.get(client.getSessionId().toString());
RoomContext room = new RoomContext(userInCache);
userInCache.setRoomId(room.getRoomId()+"");
RoomContext.roomMap.put(room.getRoomId(), room);
client.joinRoom(userInCache.getRoomId());
request.sendAckData(room);
logger.info("{} create room({}) success.", userInCache.getUserId()+userInCache.getUsername(), userInCache.getRoomId());
}
@OnEvent(value="inRoom")
public void inRoom(SocketIOClient client, String roomId, AckRequest request) {
UserInCache userInCache = SocketConnectedHandler.clientMap.get(client.getSessionId().toString());
if (StringUtil.isEmpty(roomId)) {
request.sendAckData(ResponseBean.crtFailureResult("房间号不合法"));
return ;
}
RoomContext room = RoomContext.roomMap.get(roomId);
if (room == null) {
request.sendAckData(ResponseBean.crtFailureBean("房间不存在"));
}
if ((roomId).equals(userInCache.getRoomId())) {
request.sendAckData(ResponseBean.crtFailureResult("您已在该房间"));
return ;
}
if (!StringUtil.isEmpty(userInCache.getRoomId())) {
request.sendAckData(ResponseBean.crtFailureResult("您已在其他房间,请先退出房间"));
return ;
}
room.inRoom(userInCache);
userInCache.setRoomId(roomId);
client.joinRoom(roomId);
request.sendAckData(room);
server.getRoomOperations(roomId).sendEvent("onInRoom", userInCache.getUsername()+" come in room");
logger.info("{} in room {}", userInCache.getUserId()+userInCache.getUsername(), userInCache.getRoomId());
logger.info("房间里人员信息:{}", JSON.toJSON(room.getUsersInRoom().values()));
}
@OnEvent(value="quitRoom")
public void quitRoom(SocketIOClient client, Object data, AckRequest request) {
UserInCache userInCache = SocketConnectedHandler.clientMap.get(client.getSessionId().toString());
String roomId = userInCache.getRoomId();
ResponseBean bean = ResponseBean.crtSuccessBean();
if (!StringUtil.isEmpty(roomId)) {
RoomContext room = RoomContext.roomMap.get(roomId);
room.outRoom(userInCache.getUserId());
server.getRoomOperations(roomId).sendEvent("onQuitRoom", userInCache.getUsername()+" out of room");
client.leaveRoom(roomId+"");
userInCache.setRoomId("");
logger.info("{} exit room {}",userInCache.getUserId()+userInCache.getUsername(), userInCache.getRoomId());
if (room.getUsersInRoom().size() <= 0) {
logger.info("全部人都走光,删除房间 {}", roomId);
request.sendAckData(bean.toString());
return ;
}
if (room.getOwnerId() == userInCache.getUserId()) {
long nextOwner = room.getJoinedUserId().peekLast();
room.setOwnerId(nextOwner);
logger.info("房主退出房间,该房间已被移除,{}变为房主", nextOwner);
bean.setMessage("房主退出房间,该房间已被移除,"+nextOwner+"变为房主");
}
logger.info("房间里人员信息:{}", JSON.toJSON(room.getUsersInRoom().values()));
}
request.sendAckData(bean.toString());
}
}
| [
"997269684@qq.com"
] | 997269684@qq.com |
a06f1c9f66f0f878d3f34cb117a51b75b954fc93 | fad37f41e9a7aae325e142303ef02e1a6b254e8f | /subprojects/GUI/src/org/tranche/gui/project/EncryptedProjectsFrame.java | bb35b36239e11be2d06c943ad3f7744dab622f91 | [] | no_license | augie/tranche | d832f59a262d397628030ff6be3103a2822450d6 | 65f2f995dadb7fe84c6210c95bde0b1295291fce | refs/heads/master | 2016-09-03T07:18:36.654875 | 2012-06-03T18:53:01 | 2012-06-03T18:53:01 | 32,666,015 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 27,627 | java | /*
* Copyright 2005 The Regents of the University of Michigan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tranche.gui.project;
import org.tranche.project.ProjectSummary;
import org.tranche.gui.util.GUIUtil;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import org.tranche.gui.GenericLabel;
import org.tranche.gui.GenericTextField;
import org.tranche.gui.ErrorFrame;
import org.tranche.gui.GenericButton;
import org.tranche.gui.GenericFileFilter;
import org.tranche.gui.GenericFrame;
import org.tranche.gui.GenericOptionPane;
import org.tranche.gui.GenericMenu;
import org.tranche.gui.GenericMenuBar;
import org.tranche.gui.GenericMenuItem;
import org.tranche.gui.GenericPopupListener;
import org.tranche.gui.GenericScrollPane;
import org.tranche.gui.GenericTable;
import org.tranche.gui.PassphrasePool;
import org.tranche.gui.PassphrasePoolListener;
import org.tranche.gui.PassphraseFrame;
import org.tranche.gui.SortableTableModel;
import org.tranche.gui.Styles;
import org.tranche.hash.BigHash;
import org.tranche.security.SecurityUtil;
import org.tranche.util.IOUtil;
/**
* Frame for setting encrypted projects and associated passphrases.
* @author James "Augie" Hill - augman85@gmail.com
* @author Bryan Smith <bryanesmith at gmail dot com>
*/
public class EncryptedProjectsFrame extends GenericFrame implements WindowListener {
private EncryptedProjectsMenuBar epmb = new EncryptedProjectsMenuBar();
private EncrypedProjectsPopupMenu eppm = new EncrypedProjectsPopupMenu();
private GenericTable encProjectsTable;
private EncryptedProjectsTableModel encProjectsModel = new EncryptedProjectsTableModel();
// Callbacks used to return information about encrypted projects when frame closes.
private List<EncryptedProjectsCallback> callbacks = new ArrayList();
// error frame
private ErrorFrame ef = new ErrorFrame();
public EncryptedProjectsFrame() {
super("Passphrase Manager");
// set it to dispose of only this window on close
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setSize(350, 350);
setLayout(new BorderLayout());
// add the menu bar
add(epmb, BorderLayout.NORTH);
// set up the table
encProjectsTable = new GenericTable(encProjectsModel, ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
encProjectsTable.addMouseListener(new GenericPopupListener(eppm));
GenericScrollPane scrollPane = new GenericScrollPane(encProjectsTable);
scrollPane.setBorder(Styles.BORDER_NONE);
scrollPane.setBackground(Color.GRAY);
add(scrollPane, BorderLayout.CENTER);
// window
addWindowListener(this);
}
private void removeSelected() {
if (encProjectsTable.getSelectedRowCount() == 0) {
return;
}
int[] rows = encProjectsTable.getSelectedRows();
for (int row : rows) {
PassphrasePool.remove(encProjectsModel.getHash(row));
}
}
/**
* <p>Returns all encrypted projects with associated passphrases.</p>
* @return A map including all hashes with associated passphrases.
*/
public Map<BigHash, String> getEncryptedInformation() {
return PassphrasePool.getAll();
}
private class EncryptedProjectsMenuBar extends GenericMenuBar {
private JMenu encryptedProjectsMenu = new GenericMenu("Data Sets");
private JMenu selectionMenu = new GenericMenu("Selection");
// create the menu items
private JMenuItem loadListMenuItem = new GenericMenuItem("Load List");
private JMenuItem saveListMenuItem = new GenericMenuItem("Save List");
private JMenuItem addMenuItem = new GenericMenuItem("Add");
private JMenuItem removeMenuItem = new GenericMenuItem("Remove");
public EncryptedProjectsMenuBar() {
// initialize the abilities
removeMenuItem.setEnabled(false);
// add the listeners
loadListMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final JFileChooser jfc = GUIUtil.makeNewFileChooser();
Thread t = new Thread() {
@Override
public void run() {
// query for a file
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.setFileFilter(new GenericFileFilter(".txt.encrypted", "Encrypted Text (*.txt.encrypted)"));
jfc.showOpenDialog(EncryptedProjectsFrame.this);
// check for a submitted file
File selectedFile = jfc.getSelectedFile();
if (selectedFile == null) {
return;
}
// ask for the passphrase
PassphraseFrame pf = new PassphraseFrame();
pf.setDescription("This list is encrypted. What is the password?");
pf.setLocationRelativeTo(EncryptedProjectsFrame.this);
pf.setVisible(true);
String pass = pf.getPassphrase();
if (pass == null || pass.equals("")) {
return;
}
FileReader fr = null;
BufferedReader br = null;
try {
File decryptedFile = SecurityUtil.decryptDiskBacked(pass, selectedFile);
fr = new FileReader(decryptedFile);
br = new BufferedReader(fr);
// Avoid null pointer exceptions if file is empty
while (br.ready()) {
try {
// throwing away name
String name = br.readLine().trim();
String hash = br.readLine().trim();
String passphrase = br.readLine().trim();
// add this to the model
PassphrasePool.set(BigHash.createHashFromString(hash), passphrase);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception ee) {
ef.show(ee, EncryptedProjectsFrame.this);
} finally {
IOUtil.safeClose(br);
IOUtil.safeClose(fr);
}
}
};
t.setDaemon(true);
t.start();
}
});
saveListMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final JFileChooser jfc = GUIUtil.makeNewFileChooser();
Thread t = new Thread() {
@Override
public void run() {
try {
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.setFileFilter(new GenericFileFilter(".txt.encrypted", "Encrypted Text (*.txt.encrypted)"));
int action = jfc.showSaveDialog(EncryptedProjectsFrame.this);
File selectedFile = null;
// If user accepts, get file. Else, show message and throw exception
if (action == JFileChooser.APPROVE_OPTION) {
selectedFile = jfc.getSelectedFile();
} else {
return;
}
// ask for the passphrase
PassphraseFrame pf = new PassphraseFrame();
pf.setDescription("This list will be encrypted. What should the password be?");
pf.setLocationRelativeTo(EncryptedProjectsFrame.this);
pf.setVisible(true);
String pass = pf.getPassphrase();
if (pass == null || pass.equals("")) {
return;
}
// make sure the file extension is .txt.encrypted
String filePath = selectedFile.getCanonicalPath();
if (!filePath.substring(filePath.length() - 14, filePath.length()).equals(".txt.encrypted")) {
filePath = filePath + ".txt.encrypted";
selectedFile = new File(filePath);
}
OutputStream os = null;
FileOutputStream fos = null;
try {
// determine the file contents
String output = "";
for (BigHash hash : PassphrasePool.getAll().keySet()) {
output = output + "\n" + hash.toString() + "\n" + PassphrasePool.get(hash) + "\n";
}
System.out.println("----");
System.out.println(output);
System.out.println("----");
// output the file
fos = new FileOutputStream(selectedFile);
os = new PrintStream(fos);
os.write(SecurityUtil.encryptInMemory(pass, output.getBytes()));
// notify the user
GenericOptionPane.showMessageDialog(EncryptedProjectsFrame.this, "List saved.", "Success", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception ee) {
throw new Exception("The list could not be saved.");
} finally {
IOUtil.safeClose(fos);
IOUtil.safeClose(os);
}
} catch (Exception ee) {
ef.show(ee, EncryptedProjectsFrame.this);
}
}
};
t.setDaemon(true);
t.start();
}
});
addMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddEncryptedProjectFrame aepf = new AddEncryptedProjectFrame();
aepf.setLocationRelativeTo(EncryptedProjectsFrame.this);
aepf.setVisible(true);
}
});
removeMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread t = new Thread() {
@Override
public void run() {
removeSelected();
}
};
t.setDaemon(true);
t.start();
}
});
selectionMenu.addMenuListener(new MenuListener() {
public void menuSelected(MenuEvent e) {
if (encProjectsTable.getSelectedRowCount() > 0) {
removeMenuItem.setEnabled(true);
} else {
removeMenuItem.setEnabled(false);
}
}
public void menuDeselected(MenuEvent e) {
}
public void menuCanceled(MenuEvent e) {
}
});
// set the mnemonics
loadListMenuItem.setMnemonic('l');
saveListMenuItem.setMnemonic('s');
addMenuItem.setMnemonic('a');
removeMenuItem.setMnemonic('r');
// add the projects menu items
encryptedProjectsMenu.add(loadListMenuItem);
encryptedProjectsMenu.add(saveListMenuItem);
encryptedProjectsMenu.add(addMenuItem);
// add the project menu items
selectionMenu.add(removeMenuItem);
// set Mnemonics
encryptedProjectsMenu.setMnemonic('p');
selectionMenu.setMnemonic('s');
// add the menus
add(encryptedProjectsMenu);
add(selectionMenu);
}
}
// the table popup menu
private class EncrypedProjectsPopupMenu extends JPopupMenu {
// menu items
public JMenuItem removeSelectedMenuItem = new JMenuItem("Remove");
public EncrypedProjectsPopupMenu() {
// add the item listeners
removeSelectedMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread t = new Thread() {
@Override
public void run() {
removeSelected();
}
};
t.setDaemon(true);
t.start();
}
});
add(removeSelectedMenuItem);
addPopupMenuListener(new PopupMenuListener() {
public void popupMenuCanceled(PopupMenuEvent e) {
}
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
if (encProjectsTable.getSelectedRowCount() > 0) {
eppm.removeSelectedMenuItem.setEnabled(true);
} else {
eppm.removeSelectedMenuItem.setEnabled(false);
}
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
});
}
}
private class AddEncryptedProjectFrame extends GenericFrame {
private JTextField hashTextField = new GenericTextField();
private JPasswordField passphraseTextField = new JPasswordField(), passphraseAgainTextField = new JPasswordField();
public AddEncryptedProjectFrame() {
super("Add Encrypted Data Set");
// set a fixed preferred size
setSize(new Dimension(300, 150));
// set the default background
setBackground(Styles.COLOR_BACKGROUND);
// create and set the layout
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
// create and add the hash label
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = GridBagConstraints.RELATIVE;
gbc.gridy = 1;
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbc.weightx = 0;
gbc.insets = new Insets(10, 5, 0, 5);
JLabel hashLabel = new GenericLabel("Hash:");
add(hashLabel, gbc);
// create and add the hash text field
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.insets = new Insets(10, 0, 0, 5);
hashTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
executeAdd();
}
});
add(hashTextField, gbc);
// create and add the hash label
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridx = GridBagConstraints.RELATIVE;
gbc.gridy = 2;
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbc.weightx = 0;
gbc.insets = new Insets(10, 5, 0, 5);
JLabel passphraseLabel = new GenericLabel("Passphrase:");
add(passphraseLabel, gbc);
// create and add the hash text field
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.insets = new Insets(10, 0, 0, 5);
passphraseTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
executeAdd();
}
});
add(passphraseTextField, gbc);
// create and add the hash label
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridx = GridBagConstraints.RELATIVE;
gbc.gridy = 3;
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbc.weightx = 0;
gbc.insets = new Insets(10, 5, 0, 5);
JLabel passphraseAgainLabel = new GenericLabel("Passphrase Again:");
add(passphraseAgainLabel, gbc);
// create and add the hash text field
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.insets = new Insets(10, 0, 0, 5);
passphraseAgainTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
executeAdd();
}
});
add(passphraseAgainTextField, gbc);
// create and add the open project button
gbc.anchor = GridBagConstraints.SOUTH;
gbc.gridy = 4;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = GridBagConstraints.REMAINDER;
gbc.weighty = 1;
gbc.insets = new Insets(5, 0, 0, 0);
JButton addButton = new GenericButton("Add Encrypted Data Set");
addButton.setBorder(Styles.BORDER_BUTTON_TOP);
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
executeAdd();
}
});
add(addButton, gbc);
}
private void executeAdd() {
try {
BigHash hash = BigHash.createHashFromString(hashTextField.getText().trim());
// make sure the passphrases match
if (!passphraseTextField.getText().equals(passphraseAgainTextField.getText())) {
throw new Exception("Your two given passphrases do not match.");
}
String passphrase = new String(passphraseTextField.getPassword()).trim();
// add to the passphrase cache
PassphrasePool.set(hash, passphrase);
// close the window
dispose();
} catch (Exception e) {
ef.show(e, this);
}
}
}
// Window events
public void windowActivated(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
// For each listener, set encrypted project information
for (EncryptedProjectsCallback nextCallback : callbacks) {
nextCallback.returnHashInformation(getEncryptedInformation());
}
setVisible(false);
}
private class EncryptedProjectsTableModel extends SortableTableModel {
private final String[] headers = new String[]{"Hash", "Passphrase"};
private final List<BigHash> filteredList = new ArrayList<BigHash>();
public EncryptedProjectsTableModel() {
PassphrasePool.addListener(new PassphrasePoolListener() {
public void passphraseAdded(BigHash hash) {
addRow(hash);
}
public void passphraseUpdated(BigHash hash) {
int row = getRowOf(hash);
if (row >= 0) {
resort();
repaintRow(row);
} else {
addRow(hash);
}
}
public void passphraseRemoved(BigHash hash) {
removeRow(hash);
}
});
ProjectPool.addListener(new ProjectPoolListener() {
public void projectAdded(ProjectPoolEvent ppe) {
projectUpdated(ppe);
}
public void projectUpdated(ProjectPoolEvent ppe) {
int row = getRowOf(ppe.getProjectSummary().hash);
if (row >= 0) {
resort();
repaintRow(row);
}
}
public void projectRemoved(ProjectPoolEvent ppe) {
if (getRowOf(ppe.getProjectSummary().hash) >= 0) {
PassphrasePool.remove(ppe.getProjectSummary().hash);
}
}
});
}
private void addRow(BigHash hash) {
synchronized (filteredList) {
filteredList.add(hash);
}
// sort the table
resort();
// get the row of the added project
int row = getRowOf(hash);
if (row >= 0) {
repaintRowInserted(row);
}
}
private void removeRow(BigHash hash) {
int row = getRowOf(hash);
synchronized (filteredList) {
filteredList.remove(hash);
}
if (row >= 0) {
repaintRowDeleted(row);
}
}
public int getColumnCount() {
return headers.length;
}
@Override
public String getColumnName(int column) {
if (column < getColumnCount()) {
return headers[column];
} else {
return null;
}
}
public BigHash getHash(int row) {
return filteredList.get(row);
}
public int getRowOf(BigHash hash) {
return filteredList.indexOf(hash);
}
public int getRowCount() {
return PassphrasePool.size();
}
public Object getValueAt(int row, int column) {
ProjectSummary ps = ProjectPool.get(filteredList.get(row)).get(0);
Object returnVal = null;
if (getColumnName(column).equals("Hash")) {
if (ps != null) {
returnVal = ps.title;
} else {
returnVal = "";
}
} else if (getColumnName(column).equals("Passphrase")) {
returnVal = "**********";
}
return returnVal;
}
public void resort() {
sort(encProjectsTable.getPressedColumn());
}
public void sort(int column) {
if (column < 0 || column > getColumnCount()) {
return;
}
encProjectsTable.setPressedColumn(column);
Collections.sort(filteredList, new EPComparator(column));
}
private class EPComparator implements Comparator {
private int column;
public EPComparator(int column) {
this.column = column;
}
public int compare(Object o1, Object o2) {
if (encProjectsTable.getDirection()) {
Object temp = o1;
o1 = o2;
o2 = temp;
}
if (o1 == null && o2 == null) {
return 0;
} else if (o1 == null) {
return 1;
} else {
ProjectSummary ps1 = ProjectPool.get((BigHash) o1).get(0);
ProjectSummary ps2 = ProjectPool.get((BigHash) o2).get(0);
if (getColumnName(column).equals("Hash")) {
return ps1.title.compareTo(ps2.title);
} else {
return 0;
}
}
}
}
}
}
interface EncryptedProjectsCallback {
/**
* <p>Sets all information about hashes and associated passwords.</p>
*/
public void returnHashInformation(Map<BigHash, String> encryptedInfo);
}
| [
"augman85@4cde49d4-021f-11df-9f77-c71dee008b03"
] | augman85@4cde49d4-021f-11df-9f77-c71dee008b03 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.