blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
77e2b89494dd74c3811ef2eb9fca85c73abd1a77
| 4,784,593,575,007 |
06160c491affeb53479d2b52c5ccb805ad386805
|
/HouseCareRepository/src/main/java/br/com/wamais/houseCare/repository/crud/InventarioRepository.java
|
200204078cffc8eb3de59ae49ce40ef399404ce6
|
[] |
no_license
|
moeandre/housecare
|
https://github.com/moeandre/housecare
|
804410144fd4e2cb55af96c626ba6bb69a071df9
|
b2b7e377f6b2a388b5ed989cff01db474b9908f2
|
refs/heads/master
| 2023-02-07T17:27:42.111000 | 2020-04-23T13:36:13 | 2020-04-23T13:36:13 | 63,504,213 | 0 | 0 | null | false | 2023-02-02T00:51:10 | 2016-07-16T22:12:11 | 2020-04-23T13:41:15 | 2023-02-02T00:51:05 | 17,691 | 0 | 0 | 27 |
Java
| false | false |
package br.com.wamais.houseCare.repository.crud;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import br.com.wamais.houseCare.domain.Inventario;
import br.com.wamais.houseCare.domain.InventarioPK;
@Repository
public interface InventarioRepository extends JpaRepository<Inventario, InventarioPK> {
}
|
UTF-8
|
Java
| 369 |
java
|
InventarioRepository.java
|
Java
|
[] | null |
[] |
package br.com.wamais.houseCare.repository.crud;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import br.com.wamais.houseCare.domain.Inventario;
import br.com.wamais.houseCare.domain.InventarioPK;
@Repository
public interface InventarioRepository extends JpaRepository<Inventario, InventarioPK> {
}
| 369 | 0.845528 | 0.845528 | 12 | 29.75 | 29.577934 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
12
|
c1bbd8f895bb90fbf4cff1171ce3f6f119c44747
| 12,652,973,722,961 |
f4610cb851efe289f5473c9276046e51bb00639c
|
/src/galaxys_framework_helper/ExtraEntry.java
|
d4db49fcde24af9f97a96b7eca9cf04680958baa
|
[] |
no_license
|
romanbb/Public.XML-Framework-Helper
|
https://github.com/romanbb/Public.XML-Framework-Helper
|
cc8b771e75584b4a0b7fbd3d1770644d953ec445
|
0f9a4292875cfe3f1467dc128b0d0baa062dcc7e
|
refs/heads/master
| 2020-04-02T01:08:26.033000 | 2011-06-12T23:33:43 | 2011-06-12T23:33:43 | 1,877,841 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package galaxys_framework_helper;
/**
*
* @author roman
*/
public class ExtraEntry {
String type;
String name;
public ExtraEntry(String line) {
String[] split = line.split("\\s");
type = split[0];
name = split[1];
}
}
|
UTF-8
|
Java
| 397 |
java
|
ExtraEntry.java
|
Java
|
[
{
"context": "ckage galaxys_framework_helper;\n\n/**\n *\n * @author roman\n */\npublic class ExtraEntry {\n String ty",
"end": 157,
"score": 0.6908972859382629,
"start": 154,
"tag": "NAME",
"value": "rom"
},
{
"context": "e galaxys_framework_helper;\n\n/**\n *\n * @author roman\n */\npublic class ExtraEntry {\n String type",
"end": 159,
"score": 0.6973947286605835,
"start": 157,
"tag": "USERNAME",
"value": "an"
}
] | null |
[] |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package galaxys_framework_helper;
/**
*
* @author roman
*/
public class ExtraEntry {
String type;
String name;
public ExtraEntry(String line) {
String[] split = line.split("\\s");
type = split[0];
name = split[1];
}
}
| 397 | 0.5466 | 0.541562 | 22 | 17.045454 | 16.680084 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false |
12
|
24e50c31d09cf99ed291242eae673d2bff790556
| 20,083,267,091,388 |
4eb7d6ddfcd45c4453b6b2e180359ca02976d777
|
/src/main/java/notaql/model/vdata/ObjectVData.java
|
4ad807dba13e917ec46303863ef3e747daab03b5
|
[
"Apache-2.0"
] |
permissive
|
Cobbe/notaql
|
https://github.com/Cobbe/notaql
|
428421e47536ef5491dac71757dee36fc2e912e9
|
8f43ecc207ffc63356f6de86c1998f7266630220
|
refs/heads/master
| 2021-07-15T11:51:14.456000 | 2017-10-17T12:53:17 | 2017-10-17T12:53:17 | 106,414,184 | 0 | 0 | null | true | 2017-10-10T12:28:18 | 2017-10-10T12:28:18 | 2017-04-25T19:06:18 | 2015-07-20T15:16:00 | 461 | 0 | 0 | 0 | null | null | null |
/*
* Copyright 2015 by Thomas Lottermann
*
* 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 notaql.model.vdata;
import notaql.model.AttributeSpecification;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import java.util.stream.Collectors;
public class ObjectVData implements ConstructorVData {
private static final long serialVersionUID = 1326445906026136294L;
private List<AttributeSpecification> specifications;
private final static Logger logger = Logger.getLogger(ObjectVData.class.getName());
public ObjectVData() {
}
public ObjectVData(List<AttributeSpecification> specifications) {
this.specifications = specifications;
}
public ObjectVData(AttributeSpecification... specifications) {
init(specifications);
}
@Override
public void init(AttributeSpecification... specifications) {
this.specifications = Arrays.asList(specifications);
}
@Override
public String toString() {
final String join = specifications
.stream()
.map(s -> s.getOutputPath().toString() + "<-" + s.getVData().toString())
.collect(Collectors.joining(",\n"));
return "OBJECT(\n" + join + "\n)";
}
public List<AttributeSpecification> getSpecifications() {
return this.specifications;
}
}
|
UTF-8
|
Java
| 1,892 |
java
|
ObjectVData.java
|
Java
|
[
{
"context": "/*\n * Copyright 2015 by Thomas Lottermann\n *\n * Licensed under the Apache License, Version ",
"end": 41,
"score": 0.9998490214347839,
"start": 24,
"tag": "NAME",
"value": "Thomas Lottermann"
}
] | null |
[] |
/*
* Copyright 2015 by <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package notaql.model.vdata;
import notaql.model.AttributeSpecification;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import java.util.stream.Collectors;
public class ObjectVData implements ConstructorVData {
private static final long serialVersionUID = 1326445906026136294L;
private List<AttributeSpecification> specifications;
private final static Logger logger = Logger.getLogger(ObjectVData.class.getName());
public ObjectVData() {
}
public ObjectVData(List<AttributeSpecification> specifications) {
this.specifications = specifications;
}
public ObjectVData(AttributeSpecification... specifications) {
init(specifications);
}
@Override
public void init(AttributeSpecification... specifications) {
this.specifications = Arrays.asList(specifications);
}
@Override
public String toString() {
final String join = specifications
.stream()
.map(s -> s.getOutputPath().toString() + "<-" + s.getVData().toString())
.collect(Collectors.joining(",\n"));
return "OBJECT(\n" + join + "\n)";
}
public List<AttributeSpecification> getSpecifications() {
return this.specifications;
}
}
| 1,881 | 0.700846 | 0.686575 | 62 | 29.516129 | 27.621136 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.33871 | false | false |
12
|
abfc59bfd89dcb79e72c33510493f221ff9f8b4d
| 17,205,639,036,580 |
85137c0c83db462fdda5e7f9319cc6ff04554e4d
|
/chec/src/main/java/ht/tm/dev/chec/whois/information/WhoisResponse.java
|
d1c31e9fc0a05c762d99ecfd59e1110b798cc04d
|
[] |
no_license
|
reformtheempire/Trunk
|
https://github.com/reformtheempire/Trunk
|
55a6bc4602f35671a7cb16bc445a3c6ee432e321
|
49ee67ce6d12da1710588b6ba3d60795cc065c2b
|
refs/heads/master
| 2016-09-03T06:48:16.626000 | 2015-05-08T17:25:12 | 2015-05-08T17:25:12 | 24,238,205 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ht.tm.dev.chec.whois.information;
/**
* Used to hold a WHOIS response
*
* @author Thomas Mather
*
*/
public class WhoisResponse {
private String response;
public WhoisResponse(String response) {
this.response = response;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
|
UTF-8
|
Java
| 378 |
java
|
WhoisResponse.java
|
Java
|
[
{
"context": "**\n * Used to hold a WHOIS response\n * \n * @author Thomas Mather\n *\n */\npublic class WhoisResponse {\n\n\tprivate Str",
"end": 108,
"score": 0.9997228980064392,
"start": 95,
"tag": "NAME",
"value": "Thomas Mather"
}
] | null |
[] |
package ht.tm.dev.chec.whois.information;
/**
* Used to hold a WHOIS response
*
* @author <NAME>
*
*/
public class WhoisResponse {
private String response;
public WhoisResponse(String response) {
this.response = response;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
| 371 | 0.703704 | 0.703704 | 25 | 14.12 | 15.337067 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.72 | false | false |
12
|
f2b9832ad0d2e92765c5be8f67663ed46cf983a9
| 17,205,639,037,903 |
cf10bec87b87177973b45583f2bc1638029c4962
|
/src/main/com/kesun/dao/web/impl/DNotice.java
|
374c85c25d2aeb1e1d94626d0eb4eac1855daf80
|
[] |
no_license
|
GONXFREECSS/School-enterprise-cooperation-training-platform
|
https://github.com/GONXFREECSS/School-enterprise-cooperation-training-platform
|
8ba45213ba5c6f05c314246f7e67243d030c854f
|
8031773a62f837b1e416b187574d23df88dc9f6f
|
refs/heads/master
| 2020-03-27T06:05:42.204000 | 2018-08-25T08:37:44 | 2018-08-25T08:37:44 | 146,077,954 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package kesun.dao.web.impl;
import kesun.dao.DaoSupport;
import kesun.dao.web.INotice;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by heying on 2017/10/29.
*/
@Repository("dNotice")
public class DNotice extends DaoSupport implements INotice {
public DNotice() {
setMapperName("mapper.NoticeMapper");
}
public Boolean objectInUse(String id)
{
return false;
}
public List<?> findNotRead(Object obj){
return doFind("findNotRead",obj);
}
public List<?> findRead(Object obj){
return doFind("findRead",obj);
}
}
|
UTF-8
|
Java
| 623 |
java
|
DNotice.java
|
Java
|
[
{
"context": "sitory;\n\nimport java.util.List;\n\n/**\n * Created by heying on 2017/10/29.\n */\n@Repository(\"dNotice\")\npublic ",
"end": 187,
"score": 0.8219103813171387,
"start": 181,
"tag": "USERNAME",
"value": "heying"
}
] | null |
[] |
package kesun.dao.web.impl;
import kesun.dao.DaoSupport;
import kesun.dao.web.INotice;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by heying on 2017/10/29.
*/
@Repository("dNotice")
public class DNotice extends DaoSupport implements INotice {
public DNotice() {
setMapperName("mapper.NoticeMapper");
}
public Boolean objectInUse(String id)
{
return false;
}
public List<?> findNotRead(Object obj){
return doFind("findNotRead",obj);
}
public List<?> findRead(Object obj){
return doFind("findRead",obj);
}
}
| 623 | 0.672552 | 0.659711 | 28 | 21.25 | 18.178923 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.392857 | false | false |
12
|
5035ff80ac8c8486e093e0a9bf2c92341d86711f
| 10,161,892,656,654 |
946d03577c1ab18b0364b944400f1c69cd102ddb
|
/viewtest/src/main/java/com/java/viewtest/ViewTestActivity.java
|
1bf53ec6ca6da7c31185d1b30a9b684c00df7be8
|
[] |
no_license
|
shuangtianwutong/MyApplication
|
https://github.com/shuangtianwutong/MyApplication
|
b5a09736e3b43f0c9f2d94d16e028afc10aecb03
|
673d2daeafdb816e09d69399bf28d7e21ede1229
|
refs/heads/master
| 2021-06-13T07:51:19.993000 | 2021-02-27T15:07:55 | 2021-02-27T15:07:55 | 136,114,974 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.java.viewtest;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.java.widget.DepartureView;
public class ViewTestActivity extends AppCompatActivity {
private static final String TAG = " ViewTestActivity";
DepartureView departureView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_test);
departureView =findViewById(R.id.departure_center);
}
// 向左移动 20px
public void scrollLeft(View v) {
//departureView.scrollBy(20,0);
//departureView.startLoading();
ValueAnimator animator =ValueAnimator.ofInt(0,1).setDuration(4000);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float f=animation.getAnimatedFraction();
departureView.scrollTo((int)(100*f),0);
}
});
animator.start();
Log. i(TAG, "zrz2018--getScrollX 的值值值值值!!!!! ()" + departureView.getScrollX());
//departureView.invalidate();
}
public void scrollRight(View v) {
ObjectAnimator.ofFloat(departureView,"translationX",0,100).setDuration(3000).start();
/*departureView.startJump(new DepartureView.AnimationFinishListener() {
@Override
public void onFinish() {
Log. i(TAG, "zrz2018--onfinish()" );
}
});*/
//通过 log 可以得出 scrollto 的第一个参数代表移动到自身和所要移动的距离。如果固定写死。那么无论点击多少次
/* 都还是那样 */
}
// 向上移动 20px
public void scrollUp(View v) {
departureView.scrollBy(0,20);
//departureView.requestLayout();
}
// 向下移动 20px
public void scrollDown(View v) {
departureView.scrollBy(0,-20);
//departureView.requestLayout();
}
//平滑复位
public void reset2(View v) {
Log. i(TAG, "zrz2018--getScrollX 的值值值值值!!!!! ()" + departureView.getScrollX());
departureView.smoothReset();
}
}
|
UTF-8
|
Java
| 2,427 |
java
|
ViewTestActivity.java
|
Java
|
[] | null |
[] |
package com.java.viewtest;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.java.widget.DepartureView;
public class ViewTestActivity extends AppCompatActivity {
private static final String TAG = " ViewTestActivity";
DepartureView departureView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_test);
departureView =findViewById(R.id.departure_center);
}
// 向左移动 20px
public void scrollLeft(View v) {
//departureView.scrollBy(20,0);
//departureView.startLoading();
ValueAnimator animator =ValueAnimator.ofInt(0,1).setDuration(4000);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float f=animation.getAnimatedFraction();
departureView.scrollTo((int)(100*f),0);
}
});
animator.start();
Log. i(TAG, "zrz2018--getScrollX 的值值值值值!!!!! ()" + departureView.getScrollX());
//departureView.invalidate();
}
public void scrollRight(View v) {
ObjectAnimator.ofFloat(departureView,"translationX",0,100).setDuration(3000).start();
/*departureView.startJump(new DepartureView.AnimationFinishListener() {
@Override
public void onFinish() {
Log. i(TAG, "zrz2018--onfinish()" );
}
});*/
//通过 log 可以得出 scrollto 的第一个参数代表移动到自身和所要移动的距离。如果固定写死。那么无论点击多少次
/* 都还是那样 */
}
// 向上移动 20px
public void scrollUp(View v) {
departureView.scrollBy(0,20);
//departureView.requestLayout();
}
// 向下移动 20px
public void scrollDown(View v) {
departureView.scrollBy(0,-20);
//departureView.requestLayout();
}
//平滑复位
public void reset2(View v) {
Log. i(TAG, "zrz2018--getScrollX 的值值值值值!!!!! ()" + departureView.getScrollX());
departureView.smoothReset();
}
}
| 2,427 | 0.644474 | 0.623613 | 76 | 28.644737 | 25.351582 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.552632 | false | false |
12
|
32a4f5c6f07334ee5b2b0ef7c8d658777db67430
| 20,109,036,933,095 |
768ade2f00ea992bcc44efee2931dbc578218237
|
/template/TempServiceImpl.java
|
2ed4a0a5ae16ecb2112de286d9158adfc2971357
|
[
"Apache-2.0"
] |
permissive
|
zhao154811/mybatis-codegen
|
https://github.com/zhao154811/mybatis-codegen
|
c04baab78596406267e473fcab630c48e1e8cf7d
|
0c8d73b467f42c2cff1c9581b30642bac3dc94e0
|
refs/heads/master
| 2021-01-10T01:42:22.594000 | 2017-01-01T11:33:30 | 2017-01-01T11:33:30 | 47,235,174 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* All Rights Reserved
*/
package ${servicePkg}.impl;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ${mapperPkg}.${className}Mapper;
import ${servicePkg}.${className}Service;
import com.uudream.web.common.QueryInfo;
import java.util.Map;
import java.util.Collection;
import java.util.List;
import ${modelPkg}.${className};
/**
* @author ${author}
* @date ${date}
*/
@Service
public class ${className}ServiceImpl implements ${className}Service{
private final static Logger LOGGER = LoggerFactory.getLogger(${className}Service.class);
@Autowired
private ${className}Mapper ${lowerName}Mapper;
public int insert(${className} model) {
${className}ServiceImpl.LOGGER.debug("insert ${className}[{}]", ToStringBuilder.reflectionToString(model));
return ${lowerName}Mapper.insert(model);
}
public int update(${className} model) {
${className}ServiceImpl.LOGGER.debug("update ${className}[{}]", ToStringBuilder.reflectionToString(model));
return ${lowerName}Mapper.update(model);
}
public int delete(Number id) {
${className}ServiceImpl.LOGGER.debug("delete ${className} by id [{}]", id);
return ${lowerName}Mapper.delete(id);
}
public ${className} selectById(Number id) {
${className}ServiceImpl.LOGGER.debug("select ${className} by id [{}]", id);
return ${lowerName}Mapper.selectById(id);
}
public int selectCountByConditions(${className} model) {
${className}ServiceImpl.LOGGER.debug("select ${className} count by conditions [{}]", ToStringBuilder.reflectionToString(model));
return ${lowerName}Mapper.selectCountByConditions(model);
}
public Collection<${className}> selectByConditions(${className} model) {
${className}ServiceImpl.LOGGER.debug("select ${className} by conditions [{}]", ToStringBuilder.reflectionToString(model));
return ${lowerName}Mapper.selectByConditions(model);
}
public int selectCountByMap(Map<String, Object> paramsMap) {
${className}ServiceImpl.LOGGER.debug("select ${className} count by conditions [{}]", ToStringBuilder.reflectionToString(paramsMap));
return ${lowerName}Mapper.selectCountByMap(paramsMap);
}
public Collection<${className}> selectByMap(Map<String, Object> paramsMap) {
${className}ServiceImpl.LOGGER.debug("select ${className} by conditions [{}]", ToStringBuilder.reflectionToString(paramsMap));
return ${lowerName}Mapper.selectByMap(paramsMap);
}
public List<${className}> selectQueryInfo(QueryInfo info){
${className}ServiceImpl.LOGGER.debug("select ${className} by QueryInfo [{}]", ToStringBuilder.reflectionToString(info));
return ${lowerName}Mapper.selectQueryInfo(info);
}
public int selectQueryInfoSize(QueryInfo info){
${className}ServiceImpl.LOGGER.debug("select ${className} count by QueryInfo [{}]", ToStringBuilder.reflectionToString(info));
return ${lowerName}Mapper.selectQueryInfoSize(info);
}
}
|
UTF-8
|
Java
| 3,180 |
java
|
TempServiceImpl.java
|
Java
|
[] | null |
[] |
/**
* All Rights Reserved
*/
package ${servicePkg}.impl;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ${mapperPkg}.${className}Mapper;
import ${servicePkg}.${className}Service;
import com.uudream.web.common.QueryInfo;
import java.util.Map;
import java.util.Collection;
import java.util.List;
import ${modelPkg}.${className};
/**
* @author ${author}
* @date ${date}
*/
@Service
public class ${className}ServiceImpl implements ${className}Service{
private final static Logger LOGGER = LoggerFactory.getLogger(${className}Service.class);
@Autowired
private ${className}Mapper ${lowerName}Mapper;
public int insert(${className} model) {
${className}ServiceImpl.LOGGER.debug("insert ${className}[{}]", ToStringBuilder.reflectionToString(model));
return ${lowerName}Mapper.insert(model);
}
public int update(${className} model) {
${className}ServiceImpl.LOGGER.debug("update ${className}[{}]", ToStringBuilder.reflectionToString(model));
return ${lowerName}Mapper.update(model);
}
public int delete(Number id) {
${className}ServiceImpl.LOGGER.debug("delete ${className} by id [{}]", id);
return ${lowerName}Mapper.delete(id);
}
public ${className} selectById(Number id) {
${className}ServiceImpl.LOGGER.debug("select ${className} by id [{}]", id);
return ${lowerName}Mapper.selectById(id);
}
public int selectCountByConditions(${className} model) {
${className}ServiceImpl.LOGGER.debug("select ${className} count by conditions [{}]", ToStringBuilder.reflectionToString(model));
return ${lowerName}Mapper.selectCountByConditions(model);
}
public Collection<${className}> selectByConditions(${className} model) {
${className}ServiceImpl.LOGGER.debug("select ${className} by conditions [{}]", ToStringBuilder.reflectionToString(model));
return ${lowerName}Mapper.selectByConditions(model);
}
public int selectCountByMap(Map<String, Object> paramsMap) {
${className}ServiceImpl.LOGGER.debug("select ${className} count by conditions [{}]", ToStringBuilder.reflectionToString(paramsMap));
return ${lowerName}Mapper.selectCountByMap(paramsMap);
}
public Collection<${className}> selectByMap(Map<String, Object> paramsMap) {
${className}ServiceImpl.LOGGER.debug("select ${className} by conditions [{}]", ToStringBuilder.reflectionToString(paramsMap));
return ${lowerName}Mapper.selectByMap(paramsMap);
}
public List<${className}> selectQueryInfo(QueryInfo info){
${className}ServiceImpl.LOGGER.debug("select ${className} by QueryInfo [{}]", ToStringBuilder.reflectionToString(info));
return ${lowerName}Mapper.selectQueryInfo(info);
}
public int selectQueryInfoSize(QueryInfo info){
${className}ServiceImpl.LOGGER.debug("select ${className} count by QueryInfo [{}]", ToStringBuilder.reflectionToString(info));
return ${lowerName}Mapper.selectQueryInfoSize(info);
}
}
| 3,180 | 0.717296 | 0.716667 | 81 | 38.259258 | 38.618671 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.901235 | false | false |
12
|
2bfbf63df246da79fb3177c75c9c82697efa6b93
| 26,465,588,481,142 |
d5679b044cf8c65cd304e5a21cd35f6e4640ffe9
|
/Remidi Produktif/src/remidi/produktif/JayaBaru.java
|
0f796fa72444e7d0dff4c1641c7f6286887700a3
|
[] |
no_license
|
arifin-ilham/Remidi-rpl
|
https://github.com/arifin-ilham/Remidi-rpl
|
f1ca4b76526b3caf31c1242f7baa81d8acde0b2b
|
4f51af5b58e1a80807645360030d7c0f6ed2898b
|
refs/heads/master
| 2023-05-02T19:48:09.188000 | 2021-05-31T09:07:36 | 2021-05-31T09:07:36 | 372,446,230 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package remidi.produktif;
/**
*
* @author ilham
*/
public class JayaBaru {
private String size, harga;
private String merk, warna, jenis, kategori;
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getHarga() {
return harga;
}
public void setHarga(String harga) {
this.harga = harga;
}
public String getMerk() {
return merk;
}
public void setMerk(String merk) {
this.merk = merk;
}
public String getWarna() {
return warna;
}
public void setWarna(String warna) {
this.warna = warna;
}
public String getJenis() {
return jenis;
}
public void setJenis(String jenis) {
this.jenis = jenis;
}
public String getKategori() {
return kategori;
}
public void setKategori(String kategori) {
this.kategori = kategori;
}
public void tampilkanDetail(){
System.out.println("Size : " + getSize());
System.out.println("Harga : " + getHarga());
System.out.println("Merk : " + getMerk());
System.out.println("Warna : " + getWarna());
System.out.println("Jenis : "+ getJenis());
System.out.println("Kategori : "+ getKategori());
System.out.println();
}
}
|
UTF-8
|
Java
| 1,380 |
java
|
JayaBaru.java
|
Java
|
[
{
"context": ".\n */\npackage remidi.produktif;\n\n/**\n *\n * @author ilham\n */\npublic class JayaBaru {\n\nprivate String size,",
"end": 235,
"score": 0.990777313709259,
"start": 230,
"tag": "USERNAME",
"value": "ilham"
}
] | null |
[] |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package remidi.produktif;
/**
*
* @author ilham
*/
public class JayaBaru {
private String size, harga;
private String merk, warna, jenis, kategori;
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getHarga() {
return harga;
}
public void setHarga(String harga) {
this.harga = harga;
}
public String getMerk() {
return merk;
}
public void setMerk(String merk) {
this.merk = merk;
}
public String getWarna() {
return warna;
}
public void setWarna(String warna) {
this.warna = warna;
}
public String getJenis() {
return jenis;
}
public void setJenis(String jenis) {
this.jenis = jenis;
}
public String getKategori() {
return kategori;
}
public void setKategori(String kategori) {
this.kategori = kategori;
}
public void tampilkanDetail(){
System.out.println("Size : " + getSize());
System.out.println("Harga : " + getHarga());
System.out.println("Merk : " + getMerk());
System.out.println("Warna : " + getWarna());
System.out.println("Jenis : "+ getJenis());
System.out.println("Kategori : "+ getKategori());
System.out.println();
}
}
| 1,380 | 0.661594 | 0.661594 | 77 | 16.935064 | 17.842993 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.376623 | false | false |
12
|
12071d3d5178468408fc98d54eb52d8eb9044558
| 30,502,857,754,877 |
f72176aa3ae192c7f353b47af6a9b2c3da3638bc
|
/WooShop/src/main/java/poly/edu/service/impl/UserServiceImpl.java
|
02ad03fea07db682289b91fefedd48a8c45b4a41
|
[] |
no_license
|
letannguyen/shoppingclock
|
https://github.com/letannguyen/shoppingclock
|
4dec2ec891b74c216fe188556620362aff122ff0
|
5023479664d97a672757c3a87f44c3fef12d31e5
|
refs/heads/master
| 2023-06-14T19:11:10.640000 | 2021-07-09T16:43:34 | 2021-07-09T16:43:34 | 384,497,220 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package poly.edu.service.impl;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import poly.edu.entity.User;
import poly.edu.repository.UserRepository;
import poly.edu.service.UserService;
@Service
public class UserServiceImpl implements UserService {
UserRepository userRepository;
public UserServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public User findByUsername(String username) {
return userRepository.findByUsername(username);
}
@Override
public <S extends User> S save(S entity) {
return userRepository.save(entity);
}
@Override
public Page<User> findAll(Pageable pageable) {
return userRepository.findAll(pageable);
}
@Override
public List<User> findAll() {
return userRepository.findAll();
}
@Override
public List<User> findAllById(Iterable<String> ids) {
return userRepository.findAllById(ids);
}
@Override
public Optional<User> findById(String id) {
return userRepository.findById(id);
}
@Override
public <S extends User> List<S> saveAll(Iterable<S> entities) {
return userRepository.saveAll(entities);
}
@Override
public void flush() {
userRepository.flush();
}
@Override
public boolean existsById(String id) {
return userRepository.existsById(id);
}
@Override
public long count() {
return userRepository.count();
}
@Override
public void deleteById(String id) {
userRepository.deleteById(id);
}
@Override
public void delete(User entity) {
userRepository.delete(entity);
}
@Override
public void deleteAllById(Iterable<? extends String> ids) {
userRepository.deleteAllById(ids);
}
@Override
public void deleteAll() {
userRepository.deleteAll();
}
}
|
UTF-8
|
Java
| 1,793 |
java
|
UserServiceImpl.java
|
Java
|
[] | null |
[] |
package poly.edu.service.impl;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import poly.edu.entity.User;
import poly.edu.repository.UserRepository;
import poly.edu.service.UserService;
@Service
public class UserServiceImpl implements UserService {
UserRepository userRepository;
public UserServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public User findByUsername(String username) {
return userRepository.findByUsername(username);
}
@Override
public <S extends User> S save(S entity) {
return userRepository.save(entity);
}
@Override
public Page<User> findAll(Pageable pageable) {
return userRepository.findAll(pageable);
}
@Override
public List<User> findAll() {
return userRepository.findAll();
}
@Override
public List<User> findAllById(Iterable<String> ids) {
return userRepository.findAllById(ids);
}
@Override
public Optional<User> findById(String id) {
return userRepository.findById(id);
}
@Override
public <S extends User> List<S> saveAll(Iterable<S> entities) {
return userRepository.saveAll(entities);
}
@Override
public void flush() {
userRepository.flush();
}
@Override
public boolean existsById(String id) {
return userRepository.existsById(id);
}
@Override
public long count() {
return userRepository.count();
}
@Override
public void deleteById(String id) {
userRepository.deleteById(id);
}
@Override
public void delete(User entity) {
userRepository.delete(entity);
}
@Override
public void deleteAllById(Iterable<? extends String> ids) {
userRepository.deleteAllById(ids);
}
@Override
public void deleteAll() {
userRepository.deleteAll();
}
}
| 1,793 | 0.778583 | 0.778583 | 91 | 18.703297 | 18.814592 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.43956 | false | false |
12
|
1b2e820ff66bcd3d324301c1e902a53a68f2a1cd
| 30,502,857,755,031 |
471e8ec1e6261e3a20460256c77e3ac77c3ec753
|
/CommonCodeSegmentSelector/src/commonfragmentremoval/CommonSegmentTuple.java
|
fd899eb3cf75d8c3e0207d5b15878e8e057db3f8
|
[
"Apache-2.0"
] |
permissive
|
oscarkarnalim/c2s2
|
https://github.com/oscarkarnalim/c2s2
|
ce22848ad5c2a4041ae3cb3df4c6d064603639a5
|
370cc1b213e40d96b06c67c55eb1502ca91c2d49
|
refs/heads/main
| 2023-06-27T15:50:12.632000 | 2021-07-28T22:29:59 | 2021-07-28T22:29:59 | 306,541,110 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package commonfragmentremoval;
import java.util.ArrayList;
import support.LibTuple;
public class CommonSegmentTuple implements Comparable<CommonSegmentTuple> {
private String content;
// content as array
private ArrayList<String> contentArr;
// all variations given in content as arrays
private ArrayList<ArrayList<String>> contentArrVariations;
// generalised content as array
private ArrayList<String> generalisedContentArr;
// the occurrenc frequency
private int occFreq;
// storing the first source of the segment
private String firstSourcePath;
public CommonSegmentTuple(String content, ArrayList<LibTuple> firstContent, String firstSourcePath) {
super();
this.content = content;
this.contentArr = new ArrayList<>();
this.contentArrVariations = new ArrayList<>();
this.generalisedContentArr = new ArrayList<>();
for (int i = 0; i < firstContent.size(); i++) {
LibTuple c = firstContent.get(i);
this.contentArr.add(c.getRawText());
this.contentArrVariations.add(new ArrayList<String>());
this.generalisedContentArr.add(c.getText());
}
this.occFreq = 1;
this.firstSourcePath = firstSourcePath;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getOccFrequency() {
return this.occFreq;
}
public void addNewFragmentInstance(ArrayList<LibTuple> newContent) {
for (int i = 0; i < newContent.size(); i++) {
LibTuple c = newContent.get(i);
// if the token has many implementation variations, embed the new
// variation in the contentArrVariations
if (c.getRawText().hashCode() != this.contentArr.get(i).hashCode()
&& c.getRawText().equals(this.contentArr.get(i)) == false) {
// if no such element in the variations, add it
if (this.contentArrVariations.get(i).contains(c.getRawText()) == false)
this.contentArrVariations.get(i).add(c.getRawText());
}
}
this.occFreq++;
}
public int getScore() {
return this.getOccFrequency() * this.contentArr.size();
}
@Override
public int compareTo(CommonSegmentTuple arg0) {
// TODO Auto-generated method stub
if (this.getOccFrequency() != arg0.getOccFrequency())
return -(this.getOccFrequency() - arg0.getOccFrequency());
else
return -(this.getScore() - arg0.getScore());
}
public String getSmartContent() {
/*
* which automatically generalise some tokens if they are written in different
* format
*/
String out = "";
boolean isWithVariation = false;
// print the string in summary
for (int i = 0; i < contentArr.size(); i++) {
String s = contentArr.get(i);
// if there are many implementations, print a variable name
if (contentArrVariations.get(i).size() > 0) {
out = out + "$var_" + i + "$ ";
isWithVariation = true;
} else
out = out + s + " ";
}
if (isWithVariation) {
out = out + "\n\tImplementation variations:";
// explain the variables
for (int i = 0; i < contentArr.size(); i++) {
String s = contentArr.get(i);
// if there are many implementations, print all of it
if (contentArrVariations.get(i).size() > 0) {
// print the variable name and the possible values
out = out + "\n\t\t" + "$var_" + i + "$ = { " + s;
for (String t : contentArrVariations.get(i)) {
// print each variation
out = out + " | " + t;
}
out = out + " }";
}
}
}
out = out + "\n\tFully-generalised form: ";
// show the generalised form
for (int i = 0; i < generalisedContentArr.size(); i++) {
// get the generalised form
out = out + generalisedContentArr.get(i) + " ";
}
return out;
}
public String toString() {
return this.getSmartContent() + ":" + this.getScore();
}
public String getFirstSourcePath() {
return firstSourcePath;
}
public void setFirstSourcePath(String firstSourcePath) {
this.firstSourcePath = firstSourcePath;
}
public ArrayList<String> getFirstActualSegment() {
// get the first actual segment for this
return contentArr;
}
}
|
UTF-8
|
Java
| 4,024 |
java
|
CommonSegmentTuple.java
|
Java
|
[] | null |
[] |
package commonfragmentremoval;
import java.util.ArrayList;
import support.LibTuple;
public class CommonSegmentTuple implements Comparable<CommonSegmentTuple> {
private String content;
// content as array
private ArrayList<String> contentArr;
// all variations given in content as arrays
private ArrayList<ArrayList<String>> contentArrVariations;
// generalised content as array
private ArrayList<String> generalisedContentArr;
// the occurrenc frequency
private int occFreq;
// storing the first source of the segment
private String firstSourcePath;
public CommonSegmentTuple(String content, ArrayList<LibTuple> firstContent, String firstSourcePath) {
super();
this.content = content;
this.contentArr = new ArrayList<>();
this.contentArrVariations = new ArrayList<>();
this.generalisedContentArr = new ArrayList<>();
for (int i = 0; i < firstContent.size(); i++) {
LibTuple c = firstContent.get(i);
this.contentArr.add(c.getRawText());
this.contentArrVariations.add(new ArrayList<String>());
this.generalisedContentArr.add(c.getText());
}
this.occFreq = 1;
this.firstSourcePath = firstSourcePath;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getOccFrequency() {
return this.occFreq;
}
public void addNewFragmentInstance(ArrayList<LibTuple> newContent) {
for (int i = 0; i < newContent.size(); i++) {
LibTuple c = newContent.get(i);
// if the token has many implementation variations, embed the new
// variation in the contentArrVariations
if (c.getRawText().hashCode() != this.contentArr.get(i).hashCode()
&& c.getRawText().equals(this.contentArr.get(i)) == false) {
// if no such element in the variations, add it
if (this.contentArrVariations.get(i).contains(c.getRawText()) == false)
this.contentArrVariations.get(i).add(c.getRawText());
}
}
this.occFreq++;
}
public int getScore() {
return this.getOccFrequency() * this.contentArr.size();
}
@Override
public int compareTo(CommonSegmentTuple arg0) {
// TODO Auto-generated method stub
if (this.getOccFrequency() != arg0.getOccFrequency())
return -(this.getOccFrequency() - arg0.getOccFrequency());
else
return -(this.getScore() - arg0.getScore());
}
public String getSmartContent() {
/*
* which automatically generalise some tokens if they are written in different
* format
*/
String out = "";
boolean isWithVariation = false;
// print the string in summary
for (int i = 0; i < contentArr.size(); i++) {
String s = contentArr.get(i);
// if there are many implementations, print a variable name
if (contentArrVariations.get(i).size() > 0) {
out = out + "$var_" + i + "$ ";
isWithVariation = true;
} else
out = out + s + " ";
}
if (isWithVariation) {
out = out + "\n\tImplementation variations:";
// explain the variables
for (int i = 0; i < contentArr.size(); i++) {
String s = contentArr.get(i);
// if there are many implementations, print all of it
if (contentArrVariations.get(i).size() > 0) {
// print the variable name and the possible values
out = out + "\n\t\t" + "$var_" + i + "$ = { " + s;
for (String t : contentArrVariations.get(i)) {
// print each variation
out = out + " | " + t;
}
out = out + " }";
}
}
}
out = out + "\n\tFully-generalised form: ";
// show the generalised form
for (int i = 0; i < generalisedContentArr.size(); i++) {
// get the generalised form
out = out + generalisedContentArr.get(i) + " ";
}
return out;
}
public String toString() {
return this.getSmartContent() + ":" + this.getScore();
}
public String getFirstSourcePath() {
return firstSourcePath;
}
public void setFirstSourcePath(String firstSourcePath) {
this.firstSourcePath = firstSourcePath;
}
public ArrayList<String> getFirstActualSegment() {
// get the first actual segment for this
return contentArr;
}
}
| 4,024 | 0.676938 | 0.673956 | 143 | 27.13986 | 23.06743 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.27972 | false | false |
12
|
0dcff3ccf8c9d280a3108531a8388a15a0beb71f
| 36,696,200,584,029 |
87fab073420a71916270c2e76bade84c383f0381
|
/src/main/java/ui/dir/HeaderPanel.java
|
9dc82459c2ea1b9e820ec02b32b7d2c69dec9806
|
[] |
no_license
|
cslfiu/Proviz-Sensor-Application
|
https://github.com/cslfiu/Proviz-Sensor-Application
|
1ce1a6ec68558c99611e99594b0b09a1624eb35b
|
16dd69a7d508215e0a7d609fb7463c1627e78c19
|
refs/heads/master
| 2021-07-22T15:39:32.315000 | 2017-11-05T22:39:15 | 2017-11-05T22:39:15 | 92,319,338 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ui.dir;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* Created by bigbywolf on 1/6/17.
*/
public class HeaderPanel extends JPanel{
public HeaderPanel(){
try {
String username = System.getProperty("user.name");
String imagePath = "/home/" + username + "/provizclient.com.manager/src/main/Static/pro.png";
BufferedImage img = ImageIO.read(new File(imagePath));
ImageIcon icon = new ImageIcon(img);
JLabel label = new JLabel(icon);
add(label);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 722 |
java
|
HeaderPanel.java
|
Java
|
[
{
"context": "le;\nimport java.io.IOException;\n\n/**\n * Created by bigbywolf on 1/6/17.\n */\npublic class HeaderPanel extends J",
"end": 183,
"score": 0.9996460676193237,
"start": 174,
"tag": "USERNAME",
"value": "bigbywolf"
}
] | null |
[] |
package ui.dir;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* Created by bigbywolf on 1/6/17.
*/
public class HeaderPanel extends JPanel{
public HeaderPanel(){
try {
String username = System.getProperty("user.name");
String imagePath = "/home/" + username + "/provizclient.com.manager/src/main/Static/pro.png";
BufferedImage img = ImageIO.read(new File(imagePath));
ImageIcon icon = new ImageIcon(img);
JLabel label = new JLabel(icon);
add(label);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 722 | 0.616343 | 0.610803 | 28 | 24.785715 | 24.284559 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.464286 | false | false |
12
|
afbb63f414cbed4d292eca91ec99763f4bfe660d
| 9,904,194,624,750 |
281fc20ae4900efb21e46e8de4e7c1e476f0d132
|
/framework/impl/src/main/java/org/ajax4jsf/renderkit/ChameleonRenderKitImpl.java
|
b55cf08ef8ac8af319511e267c0111a618ed557a
|
[] |
no_license
|
nuxeo/richfaces-3.3
|
https://github.com/nuxeo/richfaces-3.3
|
c23b31e69668810219cf3376281f669fa4bf256f
|
485749c5f49ac6169d9187cc448110d477acab3b
|
refs/heads/master
| 2023-08-25T13:27:08.790000 | 2015-01-05T10:42:11 | 2015-01-05T10:42:11 | 10,627,040 | 3 | 5 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* License Agreement.
*
* Rich Faces - Natural Ajax for Java Server Faces (JSF)
*
* Copyright (C) 2007 Exadel, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation.
*
* 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
*/
package org.ajax4jsf.renderkit;
import java.io.OutputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import javax.faces.FactoryFinder;
import javax.faces.application.ApplicationFactory;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseStream;
import javax.faces.context.ResponseWriter;
import javax.faces.render.RenderKit;
import javax.faces.render.RenderKitFactory;
import javax.faces.render.Renderer;
import javax.faces.render.ResponseStateManager;
/**
* Wrapper for default applikation render kit. Only can append any
* custom renderers , all other methods delegate to default render kit.
*
* @see javax.faces.render.RenderKit
* @author shura
*
*/
public class ChameleonRenderKitImpl extends RenderKit implements ChameleonRenderKit {
private RenderKit defaultRenderKit = null;
public static final String RENDER_KIT_ID = "AJAX_HTML_BASIC";
private Map<String, Renderer> renderers;
//~ Constructors -------------------------------------------------------------------------------
public ChameleonRenderKitImpl()
{
renderers = new HashMap<String, Renderer>();
}
//~ Methods ------------------------------------------------------------------------------------
private String key(String componentFamily, String rendererType)
{
return componentFamily + "." + rendererType;
}
/**
* @param family
* @param rendererType
* @param renderer
*/
public void addRenderer(String family, String rendererType,
Renderer renderer) {
if (renderer instanceof ChameleonRenderer) {
// ChameleonRenderer chameleonRenderer = (ChameleonRenderer) renderer;
// chameleonRenderer.setConfiguration(getConfiguration().getRendererConfiguration(family,rendererType));
}
renderers.put(key(family, rendererType), renderer);
}
/**
* @param writer
* @param contentTypeList
* @param characterEncoding
* @return
*/
public ResponseWriter createResponseWriter(Writer writer,
String contentTypeList, String characterEncoding) {
return getDefaultRenderKit().createResponseWriter(writer, contentTypeList,
characterEncoding);
}
/**
* @param family
* @param rendererType
* @return
*/
public Renderer getRenderer(String family, String rendererType) {
Renderer renderer = (Renderer) renderers.get(key(family, rendererType));
if (renderer != null) {
return renderer;
}
return getDefaultRenderKit().getRenderer(family, rendererType);
}
/**
* @return
*/
public ResponseStateManager getResponseStateManager() {
return getDefaultRenderKit().getResponseStateManager();
}
/* (non-Javadoc)
* @see javax.faces.render.RenderKit#createResponseStream(java.io.OutputStream)
*/
public ResponseStream createResponseStream(OutputStream out)
{
return getDefaultRenderKit().createResponseStream(out);
}
/**
* TODO - create own implementation for @see javax.faces.component.UIViewRoot ,
* and get default renderKitId as value, setted at creation time.
* in this case, we can substitute concrete renderKit even if it pointed
* as value for <f:view> tag on 1.2 specification.
* @return Returns the defaultRenderer.
*/
protected RenderKit getDefaultRenderKit() {
if (defaultRenderKit == null)
{
String defaultRenderkitId = null;
FacesContext context = null;
RenderKitFactory rdf = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
try {
context = FacesContext.getCurrentInstance();
// IN JSF-RI verifications, context may be null !
if(null != context) {
defaultRenderkitId = context.getApplication()
.getDefaultRenderKitId();
} else {
ApplicationFactory appFactory =(ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
defaultRenderkitId = appFactory.getApplication().getDefaultRenderKitId();
}
} catch (Exception e) {
// TODO: handle exception
}
if(defaultRenderkitId == null ){
defaultRenderkitId = RenderKitFactory.HTML_BASIC_RENDER_KIT;
}
defaultRenderKit = rdf.getRenderKit(context, defaultRenderkitId);
}
return defaultRenderKit;
}
public void setDefaultRenderKit(RenderKit renderKit) {
// TODO Auto-generated method stub
this.defaultRenderKit = renderKit;
}
}
|
UTF-8
|
Java
| 5,662 |
java
|
ChameleonRenderKitImpl.java
|
Java
|
[
{
"context": "\n * @see javax.faces.render.RenderKit \r\n * @author shura\r\n *\r\n */\r\npublic class ChameleonRenderKitImpl ext",
"end": 1563,
"score": 0.9688502550125122,
"start": 1558,
"tag": "USERNAME",
"value": "shura"
}
] | null |
[] |
/**
* License Agreement.
*
* Rich Faces - Natural Ajax for Java Server Faces (JSF)
*
* Copyright (C) 2007 Exadel, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation.
*
* 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
*/
package org.ajax4jsf.renderkit;
import java.io.OutputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import javax.faces.FactoryFinder;
import javax.faces.application.ApplicationFactory;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseStream;
import javax.faces.context.ResponseWriter;
import javax.faces.render.RenderKit;
import javax.faces.render.RenderKitFactory;
import javax.faces.render.Renderer;
import javax.faces.render.ResponseStateManager;
/**
* Wrapper for default applikation render kit. Only can append any
* custom renderers , all other methods delegate to default render kit.
*
* @see javax.faces.render.RenderKit
* @author shura
*
*/
public class ChameleonRenderKitImpl extends RenderKit implements ChameleonRenderKit {
private RenderKit defaultRenderKit = null;
public static final String RENDER_KIT_ID = "AJAX_HTML_BASIC";
private Map<String, Renderer> renderers;
//~ Constructors -------------------------------------------------------------------------------
public ChameleonRenderKitImpl()
{
renderers = new HashMap<String, Renderer>();
}
//~ Methods ------------------------------------------------------------------------------------
private String key(String componentFamily, String rendererType)
{
return componentFamily + "." + rendererType;
}
/**
* @param family
* @param rendererType
* @param renderer
*/
public void addRenderer(String family, String rendererType,
Renderer renderer) {
if (renderer instanceof ChameleonRenderer) {
// ChameleonRenderer chameleonRenderer = (ChameleonRenderer) renderer;
// chameleonRenderer.setConfiguration(getConfiguration().getRendererConfiguration(family,rendererType));
}
renderers.put(key(family, rendererType), renderer);
}
/**
* @param writer
* @param contentTypeList
* @param characterEncoding
* @return
*/
public ResponseWriter createResponseWriter(Writer writer,
String contentTypeList, String characterEncoding) {
return getDefaultRenderKit().createResponseWriter(writer, contentTypeList,
characterEncoding);
}
/**
* @param family
* @param rendererType
* @return
*/
public Renderer getRenderer(String family, String rendererType) {
Renderer renderer = (Renderer) renderers.get(key(family, rendererType));
if (renderer != null) {
return renderer;
}
return getDefaultRenderKit().getRenderer(family, rendererType);
}
/**
* @return
*/
public ResponseStateManager getResponseStateManager() {
return getDefaultRenderKit().getResponseStateManager();
}
/* (non-Javadoc)
* @see javax.faces.render.RenderKit#createResponseStream(java.io.OutputStream)
*/
public ResponseStream createResponseStream(OutputStream out)
{
return getDefaultRenderKit().createResponseStream(out);
}
/**
* TODO - create own implementation for @see javax.faces.component.UIViewRoot ,
* and get default renderKitId as value, setted at creation time.
* in this case, we can substitute concrete renderKit even if it pointed
* as value for <f:view> tag on 1.2 specification.
* @return Returns the defaultRenderer.
*/
protected RenderKit getDefaultRenderKit() {
if (defaultRenderKit == null)
{
String defaultRenderkitId = null;
FacesContext context = null;
RenderKitFactory rdf = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
try {
context = FacesContext.getCurrentInstance();
// IN JSF-RI verifications, context may be null !
if(null != context) {
defaultRenderkitId = context.getApplication()
.getDefaultRenderKitId();
} else {
ApplicationFactory appFactory =(ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
defaultRenderkitId = appFactory.getApplication().getDefaultRenderKitId();
}
} catch (Exception e) {
// TODO: handle exception
}
if(defaultRenderkitId == null ){
defaultRenderkitId = RenderKitFactory.HTML_BASIC_RENDER_KIT;
}
defaultRenderKit = rdf.getRenderKit(context, defaultRenderkitId);
}
return defaultRenderKit;
}
public void setDefaultRenderKit(RenderKit renderKit) {
// TODO Auto-generated method stub
this.defaultRenderKit = renderKit;
}
}
| 5,662 | 0.646238 | 0.642706 | 163 | 32.736195 | 29.413662 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.760736 | false | false |
12
|
4c888aeeb32d11d909623fa2d7809734ee831448
| 35,261,681,529,101 |
69b7760a186f7749ddb804831fc5ed8a30a2bd29
|
/target/generated-sources/annotations/Clases/TipoPieza_.java
|
31392a7b621c892e34763cdf4ea8f8e4ced9eca7
|
[] |
no_license
|
Josereyrivera1997/IngenieriaSoftware1
|
https://github.com/Josereyrivera1997/IngenieriaSoftware1
|
b8ebd40c04858c69b1fb59df5a75861e1e7d132e
|
79e7b2d8175c7127f80796565f76e2196244779e
|
refs/heads/master
| 2023-07-01T16:52:35.673000 | 2021-08-05T04:36:18 | 2021-08-05T04:36:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Clases;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(TipoPieza.class)
public abstract class TipoPieza_ {
public static volatile SingularAttribute<TipoPieza, String> tipopieza;
public static volatile SingularAttribute<TipoPieza, Boolean> estado;
public static volatile SingularAttribute<TipoPieza, Integer> iDtipopieza;
}
|
UTF-8
|
Java
| 526 |
java
|
TipoPieza_.java
|
Java
|
[] | null |
[] |
package Clases;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(TipoPieza.class)
public abstract class TipoPieza_ {
public static volatile SingularAttribute<TipoPieza, String> tipopieza;
public static volatile SingularAttribute<TipoPieza, Boolean> estado;
public static volatile SingularAttribute<TipoPieza, Integer> iDtipopieza;
}
| 526 | 0.840304 | 0.840304 | 15 | 34 | 28.982754 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.866667 | false | false |
12
|
be3fd582c9b278f03070acae4217c2185da3e5f0
| 38,749,194,952,157 |
4ffa14e2a8ed9b1e2b27a5e0a86eed878629923c
|
/iDManager/src/main/java/com/hai/idmanager/view/base/BaseApplication.java
|
329b1636a963d8e376fe3bddf2b36c25517650a3
|
[] |
no_license
|
pinhai/IDManager-AS
|
https://github.com/pinhai/IDManager-AS
|
a9cc2811b66dde8930faaaa3b325acc9e6ba8725
|
aa0c4cb960a3cf33ffb8a651dcc0afa51039958c
|
refs/heads/master
| 2021-01-13T09:12:56.542000 | 2020-11-06T15:21:36 | 2020-11-06T15:21:36 | 69,076,479 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hai.idmanager.view.base;
import android.app.Application;
import android.content.Context;
import com.hai.securitylock.utils.PreferenceUtil;
public class BaseApplication extends Application {
public static final boolean debug = true;
private static BaseApplication instance;
public static Context getInstance() {
return instance;
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
PreferenceUtil.init(instance);
com.hai.idmanager.utils.PreferenceUtil.init(instance);
}
}
|
UTF-8
|
Java
| 528 |
java
|
BaseApplication.java
|
Java
|
[] | null |
[] |
package com.hai.idmanager.view.base;
import android.app.Application;
import android.content.Context;
import com.hai.securitylock.utils.PreferenceUtil;
public class BaseApplication extends Application {
public static final boolean debug = true;
private static BaseApplication instance;
public static Context getInstance() {
return instance;
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
PreferenceUtil.init(instance);
com.hai.idmanager.utils.PreferenceUtil.init(instance);
}
}
| 528 | 0.770833 | 0.770833 | 26 | 19.307692 | 18.830763 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.115385 | false | false |
12
|
366839d13f9c229ed6c08a182790c1e7a6c9c519
| 37,477,884,629,307 |
8f773f631125b4de7e14c6c5f275e5ee11ed8cb3
|
/src/Q303.java
|
0782cf4f978705c4993bedd2f0e8bfe56b9cdad3
|
[] |
no_license
|
mmelk057/Leet
|
https://github.com/mmelk057/Leet
|
88a08298c6a1b0b19abc4dfa7428fb5c228c2aa6
|
6e17bb188ac732f4b7f5707ca2f149454658540b
|
refs/heads/master
| 2020-05-31T09:51:50.390000 | 2020-02-22T02:15:17 | 2020-02-22T02:15:17 | 190,222,876 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Q303 {
int[] sumMappings;
public Q303(int[] nums) {
this.sumMappings = new int[nums.length];
int previousSum = 0;
for (int i = 0; i < nums.length; i++) {
previousSum += nums[i];
sumMappings[i] = previousSum;
}
}
public int sumRange(int i, int j) {
if ((i - 1) < 0) {
return sumMappings[j];
}
else{
return sumMappings[j] - sumMappings[i-1];
}
}
}
|
UTF-8
|
Java
| 494 |
java
|
Q303.java
|
Java
|
[] | null |
[] |
public class Q303 {
int[] sumMappings;
public Q303(int[] nums) {
this.sumMappings = new int[nums.length];
int previousSum = 0;
for (int i = 0; i < nums.length; i++) {
previousSum += nums[i];
sumMappings[i] = previousSum;
}
}
public int sumRange(int i, int j) {
if ((i - 1) < 0) {
return sumMappings[j];
}
else{
return sumMappings[j] - sumMappings[i-1];
}
}
}
| 494 | 0.473684 | 0.451417 | 22 | 21.454546 | 17.039331 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false |
12
|
b49ff75b320a9453fe3be1d39d94a83e604a7fdc
| 94,489,343,875 |
e167395e9dc79dfabe42d67f30eb556ebfa98dcf
|
/SelectionofNumbers.java
|
171a356f172ce45c0813ce5ee90d9c15f3e21ed0
|
[] |
no_license
|
khushbooc13/hackerEarth--Dynamic-Programming
|
https://github.com/khushbooc13/hackerEarth--Dynamic-Programming
|
d62a2b737e813c075344d0bd1b8f4d867ea41ae2
|
7023c4aaed2fa0ae488e72e7f96a306d7d83910e
|
refs/heads/master
| 2020-05-25T04:57:53.876000 | 2019-05-24T05:19:56 | 2019-05-24T05:19:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*You are given N numbers placed in a line. You have to select K numbers from those numbers.
The priority level of the numbers is different.
You can select numbers from end only. After selection the number gets erased from the line.
You want to maximize the sum of priority level of all the numbers. Your task is to find the maximum
sum of the priority values.*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class SelectionOfNumbers {
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
String[] s = br.readLine().trim().split(" ");
int n = Integer.parseInt(s[1]);
int k = Math.min(Integer.parseInt(s[0]), n);
s = br.readLine().trim().split(" ");
int a[] = new int[n];
for(int i = 0; i < n; i++) {
a[i] = Integer.parseInt(s[i]);
}
long sum = 0;
for(int i = n-1; i >= n-k; i--) {
sum += a[i];
}
int i = n-k+1;
long ans = sum;
while(i%n != 0) {
sum += a[(i-1+k)%n] - a[(i-1)%n];
if(ans < sum) ans = sum;
i++;
}
System.out.println(ans);
}
}
|
UTF-8
|
Java
| 1,143 |
java
|
SelectionofNumbers.java
|
Java
|
[] | null |
[] |
/*You are given N numbers placed in a line. You have to select K numbers from those numbers.
The priority level of the numbers is different.
You can select numbers from end only. After selection the number gets erased from the line.
You want to maximize the sum of priority level of all the numbers. Your task is to find the maximum
sum of the priority values.*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class SelectionOfNumbers {
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
String[] s = br.readLine().trim().split(" ");
int n = Integer.parseInt(s[1]);
int k = Math.min(Integer.parseInt(s[0]), n);
s = br.readLine().trim().split(" ");
int a[] = new int[n];
for(int i = 0; i < n; i++) {
a[i] = Integer.parseInt(s[i]);
}
long sum = 0;
for(int i = n-1; i >= n-k; i--) {
sum += a[i];
}
int i = n-k+1;
long ans = sum;
while(i%n != 0) {
sum += a[(i-1+k)%n] - a[(i-1)%n];
if(ans < sum) ans = sum;
i++;
}
System.out.println(ans);
}
}
| 1,143 | 0.653543 | 0.645669 | 34 | 32.64706 | 26.597084 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.088235 | false | false |
12
|
f4710657dc9238f95d1cc57af22eeec48977ed82
| 35,399,120,493,044 |
213bf1ebd717ffc5d26631ebda34714ad89c3abc
|
/output/java/src/main/java/org/elasticsearch/x_pack/cross_cluster_replication/auto_follow/create_auto_follow_pattern/CreateAutoFollowPatternRequest.java
|
7929c7636cd2200d11dd89a8c0b1f78a60e468bf
|
[] |
no_license
|
isabella232/elastic-client-generator
|
https://github.com/isabella232/elastic-client-generator
|
d92526b2f5f0ac89a05858aa639b8faa32eaa9ea
|
79bbecc0aa03c68344daa7b6687e2e8cec8fb3e5
|
refs/heads/master
| 2023-01-09T23:39:32.002000 | 2020-09-29T08:05:50 | 2020-09-29T08:05:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.elasticsearch.x_pack.cross_cluster_replication.auto_follow.create_auto_follow_pattern;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import org.elasticsearch.*;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.*;
import org.elasticsearch.internal.*;
import org.elasticsearch.common_options.time_unit.*;
import org.elasticsearch.common_abstractions.request.*;
public class CreateAutoFollowPatternRequest extends RequestBase<CreateAutoFollowPatternRequest> implements XContentable<CreateAutoFollowPatternRequest> {
static final ParseField FOLLOW_INDEX_PATTERN = new ParseField("follow_index_pattern");
private String _followIndexPattern;
public String getFollowIndexPattern() { return this._followIndexPattern; }
public CreateAutoFollowPatternRequest setFollowIndexPattern(String val) { this._followIndexPattern = val; return this; }
static final ParseField LEADER_INDEX_PATTERNS = new ParseField("leader_index_patterns");
private List<String> _leaderIndexPatterns;
public List<String> getLeaderIndexPatterns() { return this._leaderIndexPatterns; }
public CreateAutoFollowPatternRequest setLeaderIndexPatterns(List<String> val) { this._leaderIndexPatterns = val; return this; }
static final ParseField MAX_OUTSTANDING_READ_REQUESTS = new ParseField("max_outstanding_read_requests");
private long _maxOutstandingReadRequests;
private boolean _maxOutstandingReadRequests$isSet;
public long getMaxOutstandingReadRequests() { return this._maxOutstandingReadRequests; }
public CreateAutoFollowPatternRequest setMaxOutstandingReadRequests(long val) {
this._maxOutstandingReadRequests = val;
_maxOutstandingReadRequests$isSet = true;
return this;
}
static final ParseField MAX_OUTSTANDING_WRITE_REQUESTS = new ParseField("max_outstanding_write_requests");
private int _maxOutstandingWriteRequests;
private boolean _maxOutstandingWriteRequests$isSet;
public int getMaxOutstandingWriteRequests() { return this._maxOutstandingWriteRequests; }
public CreateAutoFollowPatternRequest setMaxOutstandingWriteRequests(int val) {
this._maxOutstandingWriteRequests = val;
_maxOutstandingWriteRequests$isSet = true;
return this;
}
static final ParseField MAX_POLL_TIMEOUT = new ParseField("max_poll_timeout");
private String _maxPollTimeout;
public String getMaxPollTimeout() { return this._maxPollTimeout; }
public CreateAutoFollowPatternRequest setMaxPollTimeout(String val) { this._maxPollTimeout = val; return this; }
static final ParseField MAX_READ_REQUEST_OPERATION_COUNT = new ParseField("max_read_request_operation_count");
private int _maxReadRequestOperationCount;
private boolean _maxReadRequestOperationCount$isSet;
public int getMaxReadRequestOperationCount() { return this._maxReadRequestOperationCount; }
public CreateAutoFollowPatternRequest setMaxReadRequestOperationCount(int val) {
this._maxReadRequestOperationCount = val;
_maxReadRequestOperationCount$isSet = true;
return this;
}
static final ParseField MAX_READ_REQUEST_SIZE = new ParseField("max_read_request_size");
private String _maxReadRequestSize;
public String getMaxReadRequestSize() { return this._maxReadRequestSize; }
public CreateAutoFollowPatternRequest setMaxReadRequestSize(String val) { this._maxReadRequestSize = val; return this; }
static final ParseField MAX_RETRY_DELAY = new ParseField("max_retry_delay");
private String _maxRetryDelay;
public String getMaxRetryDelay() { return this._maxRetryDelay; }
public CreateAutoFollowPatternRequest setMaxRetryDelay(String val) { this._maxRetryDelay = val; return this; }
static final ParseField MAX_WRITE_BUFFER_COUNT = new ParseField("max_write_buffer_count");
private int _maxWriteBufferCount;
private boolean _maxWriteBufferCount$isSet;
public int getMaxWriteBufferCount() { return this._maxWriteBufferCount; }
public CreateAutoFollowPatternRequest setMaxWriteBufferCount(int val) {
this._maxWriteBufferCount = val;
_maxWriteBufferCount$isSet = true;
return this;
}
static final ParseField MAX_WRITE_BUFFER_SIZE = new ParseField("max_write_buffer_size");
private String _maxWriteBufferSize;
public String getMaxWriteBufferSize() { return this._maxWriteBufferSize; }
public CreateAutoFollowPatternRequest setMaxWriteBufferSize(String val) { this._maxWriteBufferSize = val; return this; }
static final ParseField MAX_WRITE_REQUEST_OPERATION_COUNT = new ParseField("max_write_request_operation_count");
private int _maxWriteRequestOperationCount;
private boolean _maxWriteRequestOperationCount$isSet;
public int getMaxWriteRequestOperationCount() { return this._maxWriteRequestOperationCount; }
public CreateAutoFollowPatternRequest setMaxWriteRequestOperationCount(int val) {
this._maxWriteRequestOperationCount = val;
_maxWriteRequestOperationCount$isSet = true;
return this;
}
static final ParseField MAX_WRITE_REQUEST_SIZE = new ParseField("max_write_request_size");
private String _maxWriteRequestSize;
public String getMaxWriteRequestSize() { return this._maxWriteRequestSize; }
public CreateAutoFollowPatternRequest setMaxWriteRequestSize(String val) { this._maxWriteRequestSize = val; return this; }
static final ParseField REMOTE_CLUSTER = new ParseField("remote_cluster");
private String _remoteCluster;
public String getRemoteCluster() { return this._remoteCluster; }
public CreateAutoFollowPatternRequest setRemoteCluster(String val) { this._remoteCluster = val; return this; }
@Override
public void toXContentInternal(XContentBuilder builder, ToXContent.Params params) throws IOException {
super.toXContentInternal(builder, params);
if (_followIndexPattern != null) {
builder.field(FOLLOW_INDEX_PATTERN.getPreferredName(), _followIndexPattern);
}
if (_leaderIndexPatterns != null) {
builder.array(LEADER_INDEX_PATTERNS.getPreferredName(), _leaderIndexPatterns);
}
if (_maxOutstandingReadRequests$isSet) {
builder.field(MAX_OUTSTANDING_READ_REQUESTS.getPreferredName(), _maxOutstandingReadRequests);
}
if (_maxOutstandingWriteRequests$isSet) {
builder.field(MAX_OUTSTANDING_WRITE_REQUESTS.getPreferredName(), _maxOutstandingWriteRequests);
}
if (_maxPollTimeout != null) {
builder.field(MAX_POLL_TIMEOUT.getPreferredName(), _maxPollTimeout);
}
if (_maxReadRequestOperationCount$isSet) {
builder.field(MAX_READ_REQUEST_OPERATION_COUNT.getPreferredName(), _maxReadRequestOperationCount);
}
if (_maxReadRequestSize != null) {
builder.field(MAX_READ_REQUEST_SIZE.getPreferredName(), _maxReadRequestSize);
}
if (_maxRetryDelay != null) {
builder.field(MAX_RETRY_DELAY.getPreferredName(), _maxRetryDelay);
}
if (_maxWriteBufferCount$isSet) {
builder.field(MAX_WRITE_BUFFER_COUNT.getPreferredName(), _maxWriteBufferCount);
}
if (_maxWriteBufferSize != null) {
builder.field(MAX_WRITE_BUFFER_SIZE.getPreferredName(), _maxWriteBufferSize);
}
if (_maxWriteRequestOperationCount$isSet) {
builder.field(MAX_WRITE_REQUEST_OPERATION_COUNT.getPreferredName(), _maxWriteRequestOperationCount);
}
if (_maxWriteRequestSize != null) {
builder.field(MAX_WRITE_REQUEST_SIZE.getPreferredName(), _maxWriteRequestSize);
}
if (_remoteCluster != null) {
builder.field(REMOTE_CLUSTER.getPreferredName(), _remoteCluster);
}
}
@Override
public CreateAutoFollowPatternRequest fromXContent(XContentParser parser) throws IOException, XContentParseException {
return CreateAutoFollowPatternRequest.PARSER.apply(parser, null);
}
public static final ObjectParser<CreateAutoFollowPatternRequest, Void> PARSER =
new ObjectParser<>(CreateAutoFollowPatternRequest.class.getName(), false, CreateAutoFollowPatternRequest::new);
static {
PARSER.declareString(CreateAutoFollowPatternRequest::setFollowIndexPattern, FOLLOW_INDEX_PATTERN);
PARSER.declareStringArray(CreateAutoFollowPatternRequest::setLeaderIndexPatterns, LEADER_INDEX_PATTERNS);
PARSER.declareLong(CreateAutoFollowPatternRequest::setMaxOutstandingReadRequests, MAX_OUTSTANDING_READ_REQUESTS);
PARSER.declareInt(CreateAutoFollowPatternRequest::setMaxOutstandingWriteRequests, MAX_OUTSTANDING_WRITE_REQUESTS);
PARSER.declareString(CreateAutoFollowPatternRequest::setMaxPollTimeout, MAX_POLL_TIMEOUT);
PARSER.declareInt(CreateAutoFollowPatternRequest::setMaxReadRequestOperationCount, MAX_READ_REQUEST_OPERATION_COUNT);
PARSER.declareString(CreateAutoFollowPatternRequest::setMaxReadRequestSize, MAX_READ_REQUEST_SIZE);
PARSER.declareString(CreateAutoFollowPatternRequest::setMaxRetryDelay, MAX_RETRY_DELAY);
PARSER.declareInt(CreateAutoFollowPatternRequest::setMaxWriteBufferCount, MAX_WRITE_BUFFER_COUNT);
PARSER.declareString(CreateAutoFollowPatternRequest::setMaxWriteBufferSize, MAX_WRITE_BUFFER_SIZE);
PARSER.declareInt(CreateAutoFollowPatternRequest::setMaxWriteRequestOperationCount, MAX_WRITE_REQUEST_OPERATION_COUNT);
PARSER.declareString(CreateAutoFollowPatternRequest::setMaxWriteRequestSize, MAX_WRITE_REQUEST_SIZE);
PARSER.declareString(CreateAutoFollowPatternRequest::setRemoteCluster, REMOTE_CLUSTER);
}
}
|
UTF-8
|
Java
| 9,415 |
java
|
CreateAutoFollowPatternRequest.java
|
Java
|
[] | null |
[] |
package org.elasticsearch.x_pack.cross_cluster_replication.auto_follow.create_auto_follow_pattern;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import org.elasticsearch.*;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.*;
import org.elasticsearch.internal.*;
import org.elasticsearch.common_options.time_unit.*;
import org.elasticsearch.common_abstractions.request.*;
public class CreateAutoFollowPatternRequest extends RequestBase<CreateAutoFollowPatternRequest> implements XContentable<CreateAutoFollowPatternRequest> {
static final ParseField FOLLOW_INDEX_PATTERN = new ParseField("follow_index_pattern");
private String _followIndexPattern;
public String getFollowIndexPattern() { return this._followIndexPattern; }
public CreateAutoFollowPatternRequest setFollowIndexPattern(String val) { this._followIndexPattern = val; return this; }
static final ParseField LEADER_INDEX_PATTERNS = new ParseField("leader_index_patterns");
private List<String> _leaderIndexPatterns;
public List<String> getLeaderIndexPatterns() { return this._leaderIndexPatterns; }
public CreateAutoFollowPatternRequest setLeaderIndexPatterns(List<String> val) { this._leaderIndexPatterns = val; return this; }
static final ParseField MAX_OUTSTANDING_READ_REQUESTS = new ParseField("max_outstanding_read_requests");
private long _maxOutstandingReadRequests;
private boolean _maxOutstandingReadRequests$isSet;
public long getMaxOutstandingReadRequests() { return this._maxOutstandingReadRequests; }
public CreateAutoFollowPatternRequest setMaxOutstandingReadRequests(long val) {
this._maxOutstandingReadRequests = val;
_maxOutstandingReadRequests$isSet = true;
return this;
}
static final ParseField MAX_OUTSTANDING_WRITE_REQUESTS = new ParseField("max_outstanding_write_requests");
private int _maxOutstandingWriteRequests;
private boolean _maxOutstandingWriteRequests$isSet;
public int getMaxOutstandingWriteRequests() { return this._maxOutstandingWriteRequests; }
public CreateAutoFollowPatternRequest setMaxOutstandingWriteRequests(int val) {
this._maxOutstandingWriteRequests = val;
_maxOutstandingWriteRequests$isSet = true;
return this;
}
static final ParseField MAX_POLL_TIMEOUT = new ParseField("max_poll_timeout");
private String _maxPollTimeout;
public String getMaxPollTimeout() { return this._maxPollTimeout; }
public CreateAutoFollowPatternRequest setMaxPollTimeout(String val) { this._maxPollTimeout = val; return this; }
static final ParseField MAX_READ_REQUEST_OPERATION_COUNT = new ParseField("max_read_request_operation_count");
private int _maxReadRequestOperationCount;
private boolean _maxReadRequestOperationCount$isSet;
public int getMaxReadRequestOperationCount() { return this._maxReadRequestOperationCount; }
public CreateAutoFollowPatternRequest setMaxReadRequestOperationCount(int val) {
this._maxReadRequestOperationCount = val;
_maxReadRequestOperationCount$isSet = true;
return this;
}
static final ParseField MAX_READ_REQUEST_SIZE = new ParseField("max_read_request_size");
private String _maxReadRequestSize;
public String getMaxReadRequestSize() { return this._maxReadRequestSize; }
public CreateAutoFollowPatternRequest setMaxReadRequestSize(String val) { this._maxReadRequestSize = val; return this; }
static final ParseField MAX_RETRY_DELAY = new ParseField("max_retry_delay");
private String _maxRetryDelay;
public String getMaxRetryDelay() { return this._maxRetryDelay; }
public CreateAutoFollowPatternRequest setMaxRetryDelay(String val) { this._maxRetryDelay = val; return this; }
static final ParseField MAX_WRITE_BUFFER_COUNT = new ParseField("max_write_buffer_count");
private int _maxWriteBufferCount;
private boolean _maxWriteBufferCount$isSet;
public int getMaxWriteBufferCount() { return this._maxWriteBufferCount; }
public CreateAutoFollowPatternRequest setMaxWriteBufferCount(int val) {
this._maxWriteBufferCount = val;
_maxWriteBufferCount$isSet = true;
return this;
}
static final ParseField MAX_WRITE_BUFFER_SIZE = new ParseField("max_write_buffer_size");
private String _maxWriteBufferSize;
public String getMaxWriteBufferSize() { return this._maxWriteBufferSize; }
public CreateAutoFollowPatternRequest setMaxWriteBufferSize(String val) { this._maxWriteBufferSize = val; return this; }
static final ParseField MAX_WRITE_REQUEST_OPERATION_COUNT = new ParseField("max_write_request_operation_count");
private int _maxWriteRequestOperationCount;
private boolean _maxWriteRequestOperationCount$isSet;
public int getMaxWriteRequestOperationCount() { return this._maxWriteRequestOperationCount; }
public CreateAutoFollowPatternRequest setMaxWriteRequestOperationCount(int val) {
this._maxWriteRequestOperationCount = val;
_maxWriteRequestOperationCount$isSet = true;
return this;
}
static final ParseField MAX_WRITE_REQUEST_SIZE = new ParseField("max_write_request_size");
private String _maxWriteRequestSize;
public String getMaxWriteRequestSize() { return this._maxWriteRequestSize; }
public CreateAutoFollowPatternRequest setMaxWriteRequestSize(String val) { this._maxWriteRequestSize = val; return this; }
static final ParseField REMOTE_CLUSTER = new ParseField("remote_cluster");
private String _remoteCluster;
public String getRemoteCluster() { return this._remoteCluster; }
public CreateAutoFollowPatternRequest setRemoteCluster(String val) { this._remoteCluster = val; return this; }
@Override
public void toXContentInternal(XContentBuilder builder, ToXContent.Params params) throws IOException {
super.toXContentInternal(builder, params);
if (_followIndexPattern != null) {
builder.field(FOLLOW_INDEX_PATTERN.getPreferredName(), _followIndexPattern);
}
if (_leaderIndexPatterns != null) {
builder.array(LEADER_INDEX_PATTERNS.getPreferredName(), _leaderIndexPatterns);
}
if (_maxOutstandingReadRequests$isSet) {
builder.field(MAX_OUTSTANDING_READ_REQUESTS.getPreferredName(), _maxOutstandingReadRequests);
}
if (_maxOutstandingWriteRequests$isSet) {
builder.field(MAX_OUTSTANDING_WRITE_REQUESTS.getPreferredName(), _maxOutstandingWriteRequests);
}
if (_maxPollTimeout != null) {
builder.field(MAX_POLL_TIMEOUT.getPreferredName(), _maxPollTimeout);
}
if (_maxReadRequestOperationCount$isSet) {
builder.field(MAX_READ_REQUEST_OPERATION_COUNT.getPreferredName(), _maxReadRequestOperationCount);
}
if (_maxReadRequestSize != null) {
builder.field(MAX_READ_REQUEST_SIZE.getPreferredName(), _maxReadRequestSize);
}
if (_maxRetryDelay != null) {
builder.field(MAX_RETRY_DELAY.getPreferredName(), _maxRetryDelay);
}
if (_maxWriteBufferCount$isSet) {
builder.field(MAX_WRITE_BUFFER_COUNT.getPreferredName(), _maxWriteBufferCount);
}
if (_maxWriteBufferSize != null) {
builder.field(MAX_WRITE_BUFFER_SIZE.getPreferredName(), _maxWriteBufferSize);
}
if (_maxWriteRequestOperationCount$isSet) {
builder.field(MAX_WRITE_REQUEST_OPERATION_COUNT.getPreferredName(), _maxWriteRequestOperationCount);
}
if (_maxWriteRequestSize != null) {
builder.field(MAX_WRITE_REQUEST_SIZE.getPreferredName(), _maxWriteRequestSize);
}
if (_remoteCluster != null) {
builder.field(REMOTE_CLUSTER.getPreferredName(), _remoteCluster);
}
}
@Override
public CreateAutoFollowPatternRequest fromXContent(XContentParser parser) throws IOException, XContentParseException {
return CreateAutoFollowPatternRequest.PARSER.apply(parser, null);
}
public static final ObjectParser<CreateAutoFollowPatternRequest, Void> PARSER =
new ObjectParser<>(CreateAutoFollowPatternRequest.class.getName(), false, CreateAutoFollowPatternRequest::new);
static {
PARSER.declareString(CreateAutoFollowPatternRequest::setFollowIndexPattern, FOLLOW_INDEX_PATTERN);
PARSER.declareStringArray(CreateAutoFollowPatternRequest::setLeaderIndexPatterns, LEADER_INDEX_PATTERNS);
PARSER.declareLong(CreateAutoFollowPatternRequest::setMaxOutstandingReadRequests, MAX_OUTSTANDING_READ_REQUESTS);
PARSER.declareInt(CreateAutoFollowPatternRequest::setMaxOutstandingWriteRequests, MAX_OUTSTANDING_WRITE_REQUESTS);
PARSER.declareString(CreateAutoFollowPatternRequest::setMaxPollTimeout, MAX_POLL_TIMEOUT);
PARSER.declareInt(CreateAutoFollowPatternRequest::setMaxReadRequestOperationCount, MAX_READ_REQUEST_OPERATION_COUNT);
PARSER.declareString(CreateAutoFollowPatternRequest::setMaxReadRequestSize, MAX_READ_REQUEST_SIZE);
PARSER.declareString(CreateAutoFollowPatternRequest::setMaxRetryDelay, MAX_RETRY_DELAY);
PARSER.declareInt(CreateAutoFollowPatternRequest::setMaxWriteBufferCount, MAX_WRITE_BUFFER_COUNT);
PARSER.declareString(CreateAutoFollowPatternRequest::setMaxWriteBufferSize, MAX_WRITE_BUFFER_SIZE);
PARSER.declareInt(CreateAutoFollowPatternRequest::setMaxWriteRequestOperationCount, MAX_WRITE_REQUEST_OPERATION_COUNT);
PARSER.declareString(CreateAutoFollowPatternRequest::setMaxWriteRequestSize, MAX_WRITE_REQUEST_SIZE);
PARSER.declareString(CreateAutoFollowPatternRequest::setRemoteCluster, REMOTE_CLUSTER);
}
}
| 9,415 | 0.791184 | 0.791184 | 178 | 51.887642 | 40.392021 | 153 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.842697 | false | false |
12
|
b391e38979a4e9bda9bb7bd5ef49e3c9ac9e5167
| 6,176,162,976,500 |
f066861c155c7b48396fe1d35304d5dcbd6e7a3d
|
/trainnig/src/main/java/interfaceandarray/Solution.java
|
64fcad50a49e4f5f920bfb69a8615ddf6511f328
|
[] |
no_license
|
Dheerajmishrajnv/Java_Trainning
|
https://github.com/Dheerajmishrajnv/Java_Trainning
|
a0de430f67134587a8e190f86f212a4164653bf5
|
4ea3d7424027f831d2348b59820002d5aeea28e9
|
refs/heads/master
| 2023-06-16T19:54:35.020000 | 2021-07-09T06:51:45 | 2021-07-09T06:51:45 | 384,318,542 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package interfaceandarray;
import java.util.*;
public class Solution {
public static void main(String[] args) {
int c[] = new int[5];
Scanner inputObj = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
c[i] = inputObj.nextInt();
}
for (int element : c) {
System.out.println(element);
}
InterfaceImpl obj = new InterfaceImpl();
obj.add();
obj.sub();
add(1, 2, 3, 4);
Inheritence I = new Inheritence();
I.checkInheritence();
}
public static int add(int... value) {
int sum = 0;
for (int element : value) {
sum = sum + element;
}
System.out.println(sum);
return 0;
}
}
|
UTF-8
|
Java
| 623 |
java
|
Solution.java
|
Java
|
[] | null |
[] |
package interfaceandarray;
import java.util.*;
public class Solution {
public static void main(String[] args) {
int c[] = new int[5];
Scanner inputObj = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
c[i] = inputObj.nextInt();
}
for (int element : c) {
System.out.println(element);
}
InterfaceImpl obj = new InterfaceImpl();
obj.add();
obj.sub();
add(1, 2, 3, 4);
Inheritence I = new Inheritence();
I.checkInheritence();
}
public static int add(int... value) {
int sum = 0;
for (int element : value) {
sum = sum + element;
}
System.out.println(sum);
return 0;
}
}
| 623 | 0.609952 | 0.595506 | 33 | 17.878788 | 14.13733 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.060606 | false | false |
12
|
cdb32d3f9deb1049d625f747dce617c5c434247f
| 3,238,405,406,696 |
501d486b791b8a45bef1f19545e3839e9622a46f
|
/src/main/java/com/company/currencyExchange/NBPService.java
|
0764a36efdc8e313993e432bd25a850d7fc352df
|
[] |
no_license
|
MrMT-95/currencyExchange
|
https://github.com/MrMT-95/currencyExchange
|
8ac5875ca738b0a934bc79676278100ef4ec12ea
|
148b77498089641388324653a19f7a4e94ea7071
|
refs/heads/master
| 2023-06-04T03:22:35.410000 | 2021-06-27T16:47:59 | 2021-06-27T16:47:59 | 380,790,292 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.company.currencyExchange;
public interface NBPService {
Rate getExchangeRate(Currency currency);
}
|
UTF-8
|
Java
| 116 |
java
|
NBPService.java
|
Java
|
[] | null |
[] |
package com.company.currencyExchange;
public interface NBPService {
Rate getExchangeRate(Currency currency);
}
| 116 | 0.801724 | 0.801724 | 5 | 22.200001 | 18.345572 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
12
|
2d4973bfb943369976d804806c253cf7ce82af6c
| 2,877,628,130,871 |
a494927cce16b37f57b457e67cab91863c55c39d
|
/src/ui/editor/EPatsTable.java
|
4e56a110d8cd17d68f1aedb21efd4ddf69656478
|
[] |
no_license
|
GenericAdaptiveScheduling/GenTool
|
https://github.com/GenericAdaptiveScheduling/GenTool
|
cdd1f1c7153a3055371e2baa9cf2c08e61ab8b01
|
e6045def4fd18c872e84ef9385ea44243ca3e90c
|
refs/heads/master
| 2020-04-16T14:28:43.276000 | 2019-01-29T07:57:29 | 2019-01-29T07:57:29 | 165,668,224 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ui.editor;
import java.util.Vector;
import kernel.Context;
public class EPatsTable {
Vector<Context> pats = new Vector<>();
public EPatsTable() {
// TODO Auto-generated constructor stub
}
public void addPattern(Context pattern) {
this.pats.add(pattern);
}
public Vector<Context> getPatterns() {
return this.pats;
}
public Vector<String> getPatNames() {
Vector<String> result = new Vector<>();
for(Context pattern: this.pats)
result.add(pattern.getContextname());
return result;
}
public void printPatTable() {
for(Context pattern: this.pats)
pattern.printContext();
}
}
|
UTF-8
|
Java
| 651 |
java
|
EPatsTable.java
|
Java
|
[] | null |
[] |
package ui.editor;
import java.util.Vector;
import kernel.Context;
public class EPatsTable {
Vector<Context> pats = new Vector<>();
public EPatsTable() {
// TODO Auto-generated constructor stub
}
public void addPattern(Context pattern) {
this.pats.add(pattern);
}
public Vector<Context> getPatterns() {
return this.pats;
}
public Vector<String> getPatNames() {
Vector<String> result = new Vector<>();
for(Context pattern: this.pats)
result.add(pattern.getContextname());
return result;
}
public void printPatTable() {
for(Context pattern: this.pats)
pattern.printContext();
}
}
| 651 | 0.668203 | 0.668203 | 33 | 17.727272 | 15.90935 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.272727 | false | false |
12
|
48c518e6277284f0b31abae8107fb6dc458d30f8
| 21,577,915,696,502 |
22f4ebcfe9f90507c6df289a8d6abe183995072e
|
/Projet_RodentRevenge/src/model/Entite.java
|
9833ff2e85afa4edbf37428730fc0c80b5bc625a
|
[] |
no_license
|
Wargle/-MyRodentRevenge
|
https://github.com/Wargle/-MyRodentRevenge
|
2c44c58a82fb47a77b2881b0eb9fa26f3fabffb7
|
b86f4ac421903f5f5f7d3152fc674b2d6a647895
|
refs/heads/master
| 2021-09-02T02:37:11.031000 | 2017-12-29T19:34:02 | 2017-12-29T19:34:02 | 111,032,407 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import javafx.scene.image.Image;
/**
* Classe abstraite d'un élément du Jeu
* @author Alexis Arnould
*/
public abstract class Entite {
protected GestPosition refGest;
protected Image image;
protected double x = 2, y = 3;
protected String TYPE, CODE;
public Entite(GestPosition g, double x, double y, String img){
double size = (int) Level.params.get("IMAGE_SIZE");
refGest = g;
image = new Image(img, size, size, true, true);
this.x = x;
this.y = y;
}
public void setImage(Image i) { image = i; }
public Image getImage() { return image; }
public double getX() { return x; }
public void setX(double x) { this.x = x; }
public double getY() { return y; }
public void setY(double y) { this.y = y; }
public abstract boolean deplacer(Position cp);
public String getTYPE() { return TYPE; }
public String getCODE() { return CODE; }
public GestPosition getGest() { return refGest; }
/**
* Notifie au Gestionnaire qu'elle a bougée
* @param oC : l'ancienne coordonnée x de l'Entite
* @param oL : l'ancienne coordonnée y de l'Entite
*/
protected void notifyMove(double oC, double oL) {
refGest.changePosition(oC, x, oL, y);
}
}
|
UTF-8
|
Java
| 1,580 |
java
|
Entite.java
|
Java
|
[
{
"context": "* Classe abstraite d'un élément du Jeu\r\n * @author Alexis Arnould\r\n */\r\npublic abstract class Entite {\r\n protect",
"end": 315,
"score": 0.999859631061554,
"start": 301,
"tag": "NAME",
"value": "Alexis Arnould"
}
] | null |
[] |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import javafx.scene.image.Image;
/**
* Classe abstraite d'un élément du Jeu
* @author <NAME>
*/
public abstract class Entite {
protected GestPosition refGest;
protected Image image;
protected double x = 2, y = 3;
protected String TYPE, CODE;
public Entite(GestPosition g, double x, double y, String img){
double size = (int) Level.params.get("IMAGE_SIZE");
refGest = g;
image = new Image(img, size, size, true, true);
this.x = x;
this.y = y;
}
public void setImage(Image i) { image = i; }
public Image getImage() { return image; }
public double getX() { return x; }
public void setX(double x) { this.x = x; }
public double getY() { return y; }
public void setY(double y) { this.y = y; }
public abstract boolean deplacer(Position cp);
public String getTYPE() { return TYPE; }
public String getCODE() { return CODE; }
public GestPosition getGest() { return refGest; }
/**
* Notifie au Gestionnaire qu'elle a bougée
* @param oC : l'ancienne coordonnée x de l'Entite
* @param oL : l'ancienne coordonnée y de l'Entite
*/
protected void notifyMove(double oC, double oL) {
refGest.changePosition(oC, x, oL, y);
}
}
| 1,572 | 0.598095 | 0.596825 | 57 | 25.631578 | 22.06023 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false |
12
|
2cd89385322e45d82ab35469f6e1783f69997e05
| 2,216,203,178,023 |
d5d84e1832d5369136e230709cecfbd5238d0b35
|
/src/main/java/com/zhoulei/service/OrderdtoService.java
|
840d0756abb52e3a04f8c96af9860f6de4ed5062
|
[] |
no_license
|
LeichouA/productsell
|
https://github.com/LeichouA/productsell
|
fbc7fece6fa537897fd5b76dec4ba0521fbfbc34
|
6519221598d640d57af36257fbb35804e439ea9e
|
refs/heads/master
| 2020-06-08T21:21:48.142000 | 2019-08-12T09:40:50 | 2019-08-12T09:40:50 | 193,308,778 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zhoulei.service;
import com.zhoulei.dto.Orderdto;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
public interface OrderdtoService {
Orderdto create(Orderdto orderdto);
Orderdto findByone(String orderId);
Page<Orderdto> orderlist(String buyerOpendid, Pageable pageable);
Orderdto cancel(Orderdto orderdto);
Orderdto finished(Orderdto orderdto);
Orderdto paid(Orderdto orderdto);
Page<Orderdto> findList(Pageable pageable);
}
|
UTF-8
|
Java
| 520 |
java
|
OrderdtoService.java
|
Java
|
[] | null |
[] |
package com.zhoulei.service;
import com.zhoulei.dto.Orderdto;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
public interface OrderdtoService {
Orderdto create(Orderdto orderdto);
Orderdto findByone(String orderId);
Page<Orderdto> orderlist(String buyerOpendid, Pageable pageable);
Orderdto cancel(Orderdto orderdto);
Orderdto finished(Orderdto orderdto);
Orderdto paid(Orderdto orderdto);
Page<Orderdto> findList(Pageable pageable);
}
| 520 | 0.773077 | 0.773077 | 22 | 22.636364 | 21.862267 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false |
12
|
6e92e8176dc259815620a89e30ebf2f5793b55cb
| 30,081,950,945,569 |
3f8b3ace7e5aab179ffd0df5b162eaa4172b03f4
|
/Biblioteca-de-livros-com-cadastro/CodeFont/Pn7X.java
|
01ce0a6e4fa8d47bed13b5fc7f19a2fe834af6ff
|
[] |
no_license
|
Davidson-Moura/Java
|
https://github.com/Davidson-Moura/Java
|
932bd1e6f27522bb32bbef42b8181e825ee9bba4
|
bb4a55acb213cca48152591df558837bdaee7306
|
refs/heads/main
| 2023-04-28T18:06:52.504000 | 2021-05-26T11:47:19 | 2021-05-26T11:47:19 | 370,657,514 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import lp2g15.biblioteca.*;
import java.util.*;
import java.time.LocalDate;
import java.io.*;
public class Pn7X{
static String nomeArquivoLivros="livros.dat";
static String nomeArquivoUsuarios="usuarios.dat";
static Biblioteca biblioteca;
public static void main(String[] args){
try{biblioteca= new Biblioteca(nomeArquivoLivros,nomeArquivoUsuarios);}catch(Exception e){}
Scanner in = new Scanner( System.in );
String line="lk";
int r=0;
try{
Manutencao(1);
}catch(Exception e){
System.out.println("Erro: "+e);
}
while(true){
System.out.println("1- Manutencao\n2- Cadastro\n3- Emprestimos\n4- Relatorio\n5- Sair\n");
while(true){
try{
System.out.println("Digite a opcao: ");
line = in.nextLine();
r=Integer.parseInt(line);
if(r>0 && r<6){
break;
}else{
throw new Exception();
}
}catch(Exception e2){
System.out.println("Digite apenas numeros de 1 a 5!");
}
}
switch (r) {
case 1:
System.out.println("1- Le arquivo\n2- Salvar em arquivo\n");
while(true){
try{
System.out.println("Digite a opcao: ");
line = in.nextLine();
r=Integer.parseInt(line);
if(r>0 && r<3){
break;
}else{
throw new Exception();
}
}catch(Exception e2){
System.out.println("Erro : Digite apenas numeros de 1 a 2!");
}
}
try{
Manutencao(r);
}catch(Exception e){
System.out.println("Erro: "+e);
}
break;
case 2:
System.out.println("1- Cadastrar livro\n2- Cadastrar usuario\n");
while(true){
try{
System.out.println("Digite a opcao: ");
line = in.nextLine();
r=Integer.parseInt(line);
if(r>0 && r<3){
break;
}else{
throw new Exception();
}
}catch(Exception e2){
System.out.println("Erro : Digite apenas numeros de 1 a 2!");
}
}
try{
Cadastro(r);
Manutencao(2);
}catch(Exception e){
System.out.println("Erro: "+e);
}
break;
case 3:
System.out.println("1- Fazer emprestimo do livro\n2- Devolve um livro\n 3- Exibe devolção\n");
while(true){
try{
System.out.println("Digite a opcao: ");
line = in.nextLine();
r=Integer.parseInt(line);
if(r>0 && r<4){
break;
}else{
throw new Exception();
}
}catch(Exception e2){
System.out.println("Erro : Digite apenas numeros de 1 a 2!");
}
}
try{
Emprestimo(r);
Manutencao(2);
}catch(Exception e){
System.out.println("Erro: "+e);
}
break;
case 4:
System.out.println("1- Exibir Livros\n2- Exibir usuarios\n3- Exibir detalhes de livro\n4-Exibir detalhes de usuario");
while(true){
try{
System.out.println("Digite a opcao: ");
line = in.nextLine();
r=Integer.parseInt(line);
if(r>0 && r<5){
break;
}else{
throw new Exception();
}
}catch(Exception e2){
System.out.println("Erro : Digite apenas numeros de 1 a 2!");
}
}
try{
Relatorio(r);
}catch(Exception e){
System.out.println("Erro: "+e);
}
break;
case 5:
try{
Manutencao(2);
}catch(Exception e){
System.out.println(e);
}
System.exit(1);
break;
default:
break;
}
}
}
//------------------------------------------------------------------------------------------------------------------------
public static void Manutencao(int i)throws Exception{//1=le arquivo; 2= salva arquivos
try{
if(i==1){
biblioteca.leArquivo();
}else if(i==2){
biblioteca.salvaArquivo();
}
}catch(Exception e){
System.out.println("Erro: "+e);
}
}
//------------------------------------------------------------------------------------------------------------------------
public static void Cadastro(int i)throws Exception{//1==cadastrar livro; 2== cadastrar usuario;
Scanner in = new Scanner( System.in );
String line="lk";
if(i==1){
Livro livro=RecebeLivro();
System.out.println("info livro: \n"+livro.toString()+"\n");
while(true){
try{
System.out.println("Deseja salvar o livro(S/N): ");
line = in.nextLine();
if(line.compareTo("S")==0){
biblioteca.cadastraLivro(livro.getCodLivro(),livro);
Manutencao(2);
break;
}else if(line.compareTo("N")==0){
break;
}else{
System.out.println("O sistema aceita apenas 'S' ou 'N'.\n");
}
}catch(Exception e2){
System.out.println("Erro inesperado: "+e2+"\n");
}
}
}else if(i==2){
Usuario usuario=RecebeUsuario();
System.out.println("info usuario: \n"+usuario.toString()+"\n");
while(true){
try{
System.out.println("Deseja salvar o usuario(S/N): ");
line = in.nextLine();
if(line.compareTo("S")==0){
biblioteca.cadastraUsuario(Integer.toString(usuario.getCodUsuario()),usuario);
Manutencao(2);
break;
}else if(line.compareTo("N")==0){
break;
}else{
System.out.println("O sistema aceita apenas 'S' ou 'N'.\n");
}
}catch(Exception e2){
System.out.println("Erro inesperado: "+e2+"\n");
}
}
}
}
//------------------------------------------------------------------------------------------------------------------------
public static Livro RecebeLivro()throws Exception{
Scanner in = new Scanner( System.in );
String line="lk";
String codLivro;
String categoria, titulo;
int quantidade;
while(true){
try{
System.out.println("Digite o codigo do livro: ");
line = in.nextLine();
codLivro=line;
break;
}catch(Exception e2){
System.out.println("Erro inesperado: "+e2+"\n");
}
}
while(true){
try{
System.out.println("Digite a categoria: ");
line = in.nextLine();
categoria=line;
break;
}catch(Exception e2){
System.out.println("Erro inesperado: "+e2+"\n");
}
}
while(true){
try{
System.out.println("Digite o titulo: ");
line = in.nextLine();
titulo=line;
break;
}catch(Exception e2){
System.out.println("Erro inesperado: "+e2+"\n");
}
}
while(true){
try{
System.out.println("Digite a quantidade: ");
line = in.nextLine();
quantidade=Integer.parseInt(line);
break;
}catch(Exception e2){
System.out.println("Numero invalido, digite apenas numeros.\n");
}
}
return new Livro(codLivro,titulo,categoria,quantidade);
}
//------------------------------------------------------------------------------------------------------------------------
public static Usuario RecebeUsuario()throws Exception{
Scanner in = new Scanner( System.in );
String line="lk";
String nom;
String datNac;
String endere;
int cod, dia, mes, ano;
String codLivro;
while(true){
try{
System.out.println("Digite o nome: ");
line = in.nextLine();
nom=line;
break;
}catch(Exception e2){
System.out.println("Erro inesperado: "+e2+"\n");
}
}
while(true){
try{
System.out.println("Digite o codigo do usuario: ");
line = in.nextLine();
cod=Integer.parseInt(line);
break;
}catch(Exception e2){
System.out.println("Numero invalido, digite apenas numeros.\n");
}
}
while(true){
int a=0;
System.out.println("Digite a data de nascimento(xx/xx/xxxx): ");
datNac = in.nextLine();
try{
if(datNac.length()!=10){throw new Exception ("Data invalida, use o formato xx/xx/xxxx ou xx-xx-xxxx.\n");}
dia=Integer.parseInt(datNac.substring(0,2));
if(dia>31){throw new Exception ("Dia invalido.\n");}
a=1;
}catch(Exception e){
System.out.println(e);
}
if(a==1){
try{
mes=Integer.parseInt(datNac.substring(3,5));
if(mes>12){throw new Exception ();}
a=2;
}catch(Exception c){
System.out.println("Mes invalido!");
}
}
if(a==2){
try{
ano=Integer.parseInt(datNac.substring(6,10));
if(ano>3000){throw new Exception ();}
break;
}catch(Exception f){
System.out.println ("Ano invalido!");
}
}
}
while(true){
try{
System.out.println("Digite a endereco: ");
line = in.nextLine();
endere=line;
break;
}catch(Exception e2){
System.out.println("Erro inesperado: "+e2+"\n");
}
}
return new Usuario(nom, datNac, endere,cod);
}
//------------------------------------------------------------------------------------------------------------------------
public static void Emprestimo(int i){ // 1== fazer emprestimo do livro; 2==devolve o livro; 3== Exibe devolção;
switch (i) {
case 1:
Emp();
break;
case 2:
Dev();
break;
case 3:
ExibirDevolu();
break;
default:
break;
}
}
public static void Emp(){
Scanner in = new Scanner( System.in );
String line="lk";
Exibir();
Livro codli;
Usuario codus;
while(true){
try{
System.out.println("Digite o codigo do Livro: ");
line = in.nextLine();
codli=biblioteca.getLivro(line);
if(codli!=null){
break;
}else{
throw new Exception("Livro Invalido!!");
}
}catch(Exception e2){
System.out.println("Erro: "+e2+"\n");
}
}
while(true){
try{
System.out.println("Digite o codigo do Usuario: ");
line = in.nextLine();
codus=biblioteca.getUsuario(line);
if(codus!=null){
break;
}else{
throw new Exception("Usuario Invalido!!");
}
}catch(Exception e2){
System.out.println("Erro: Usuario invalido\n");
}
}
try{
biblioteca.emprestaLivro(codus,codli);System.out.println("\nEmprestimo foi bem sucedido.");
}catch(Exception e){
System.out.println("Erro: "+e);
}
}
public static void Dev(){
Exibir();
Scanner in = new Scanner( System.in );
String line="lk";
Livro codli;
Usuario codus;
while(true){
try{
System.out.println("Digite o codigo do Livro: ");
line = in.nextLine();
codli=biblioteca.getLivro(line);
if(codli!=null){
break;
}else{
throw new Exception("Livro Invalido!!");
}
}catch(Exception e2){
System.out.println("Erro: Livro invalido!\n");
}
}
while(true){
try{
System.out.println("Digite o codigo do Usuario: ");
line = in.nextLine();
codus=biblioteca.getUsuario(line);
if(codus!=null){
break;
}else{
throw new Exception("Usuario Invalido!!");
}
}catch(Exception e2){
System.out.println("Erro: Usuario invalido!\n");
}
}
try{
biblioteca.devolveLivro(codus,codli);System.out.println("\nDevolucao foi bem sucedido.");
}catch(Exception e){
System.out.println("Erro: "+e);
}
}
public static void ExibirDevolu(){
Scanner in = new Scanner( System.in );
String line="lk";
Exibir();
String codli;
String codus;
while(true){
try{
System.out.println("Digite o codigo do Livro: ");
line = in.nextLine();
biblioteca.getLivro(line);
codli=line;
if(codli!=null){
break;
}else{
throw new Exception("Livro Invalido!!");
}
}catch(Exception e2){
System.out.println("Erro: Livro invalido!\n");
}
}
while(true){
try{
System.out.println("Digite o codigo do Usuario: ");
line = in.nextLine();
biblioteca.getUsuario(line);
codus=line;
if(codus!=null){
break;
}else{
throw new Exception("Usuario Invalido!!");
}
}catch(Exception e2){
System.out.println("Erro: Usuario invalido!\n");
}
}
try{
Usuario u = biblioteca.getUsuario(codus);
System.out.println("Devolucao do usuario "+codus+":\n"+u.getEmprest(codli).toString());
}catch(Exception e){
System.out.println("Erro: "+e);
}
}
public static void Exibir(){
Scanner in = new Scanner( System.in );
String line="lk";
int r=0;
try{
System.out.println("1-Exibir livros e usuarios.\n2-Exibir livros.\n3-Nao exibir nada.");
while(true){
try{
System.out.println("Digite a opcao escolida: ");
line = in.nextLine();
r=Integer.parseInt(line);
if(r>0 && r<4){
break;
}else{
throw new Exception("Digite apenas valores de 1 a 3.\n");
}
}catch(Exception e2){
System.out.println("Erro: "+e2+"\n");
}
}
switch (r) {
case 1:
try{
System.out.println("Livros:\n"+biblioteca.imprimeLivros());
}catch(NullPointerException e){
}
try{
System.out.println("Usuarios:\n"+biblioteca.imprimeUsuarios());
}catch(NullPointerException e){
}
break;
case 2:
System.out.println("Livros:\n"+biblioteca.imprimeLivros());
break;
case 3:
break;
default:
break;
}
}catch(Exception e){
System.out.println("Erro: "+e);
}
}
//------------------------------------------------------------------------------------------------------------------------
public static void Relatorio(int i){// livros;usuarios;detalhe usuario;detalhe livro
Scanner in = new Scanner( System.in );
String line="lk";
try{
switch (i) {
case 1:
System.out.println(biblioteca.imprimeLivros());
break;
case 2:
System.out.println(biblioteca.imprimeUsuarios());
break;
case 3:
Livro cod;
while(true){
try{
System.out.println("Digite o codigo do Livro: ");
line = in.nextLine();
cod=biblioteca.getLivro(line);
if(cod!=null){
break;
}
}catch(Exception e2){
System.out.println("Erro: Livro invalido!\n");
}
}
System.out.println(cod.toString()+"\n"+cod.toHisotico());
break;
case 4:
Usuario cod1;
while(true){
try{
System.out.println("Digite o codigo do Usuario: ");
line = in.nextLine();
cod1=biblioteca.getUsuario(line);
if(cod1!=null){
break;
}
}catch(Exception e2){
System.out.println("Erro: Usuario invalido!\n");
}
}
System.out.println(cod1.toString()+"\n"+cod1.toHisotico());
break;
default:
break;
}
}catch(Exception e){
System.out.println("Erro: "+e);
}
}
//------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------
}
|
UTF-8
|
Java
| 22,298 |
java
|
Pn7X.java
|
Java
|
[] | null |
[] |
import lp2g15.biblioteca.*;
import java.util.*;
import java.time.LocalDate;
import java.io.*;
public class Pn7X{
static String nomeArquivoLivros="livros.dat";
static String nomeArquivoUsuarios="usuarios.dat";
static Biblioteca biblioteca;
public static void main(String[] args){
try{biblioteca= new Biblioteca(nomeArquivoLivros,nomeArquivoUsuarios);}catch(Exception e){}
Scanner in = new Scanner( System.in );
String line="lk";
int r=0;
try{
Manutencao(1);
}catch(Exception e){
System.out.println("Erro: "+e);
}
while(true){
System.out.println("1- Manutencao\n2- Cadastro\n3- Emprestimos\n4- Relatorio\n5- Sair\n");
while(true){
try{
System.out.println("Digite a opcao: ");
line = in.nextLine();
r=Integer.parseInt(line);
if(r>0 && r<6){
break;
}else{
throw new Exception();
}
}catch(Exception e2){
System.out.println("Digite apenas numeros de 1 a 5!");
}
}
switch (r) {
case 1:
System.out.println("1- Le arquivo\n2- Salvar em arquivo\n");
while(true){
try{
System.out.println("Digite a opcao: ");
line = in.nextLine();
r=Integer.parseInt(line);
if(r>0 && r<3){
break;
}else{
throw new Exception();
}
}catch(Exception e2){
System.out.println("Erro : Digite apenas numeros de 1 a 2!");
}
}
try{
Manutencao(r);
}catch(Exception e){
System.out.println("Erro: "+e);
}
break;
case 2:
System.out.println("1- Cadastrar livro\n2- Cadastrar usuario\n");
while(true){
try{
System.out.println("Digite a opcao: ");
line = in.nextLine();
r=Integer.parseInt(line);
if(r>0 && r<3){
break;
}else{
throw new Exception();
}
}catch(Exception e2){
System.out.println("Erro : Digite apenas numeros de 1 a 2!");
}
}
try{
Cadastro(r);
Manutencao(2);
}catch(Exception e){
System.out.println("Erro: "+e);
}
break;
case 3:
System.out.println("1- Fazer emprestimo do livro\n2- Devolve um livro\n 3- Exibe devolção\n");
while(true){
try{
System.out.println("Digite a opcao: ");
line = in.nextLine();
r=Integer.parseInt(line);
if(r>0 && r<4){
break;
}else{
throw new Exception();
}
}catch(Exception e2){
System.out.println("Erro : Digite apenas numeros de 1 a 2!");
}
}
try{
Emprestimo(r);
Manutencao(2);
}catch(Exception e){
System.out.println("Erro: "+e);
}
break;
case 4:
System.out.println("1- Exibir Livros\n2- Exibir usuarios\n3- Exibir detalhes de livro\n4-Exibir detalhes de usuario");
while(true){
try{
System.out.println("Digite a opcao: ");
line = in.nextLine();
r=Integer.parseInt(line);
if(r>0 && r<5){
break;
}else{
throw new Exception();
}
}catch(Exception e2){
System.out.println("Erro : Digite apenas numeros de 1 a 2!");
}
}
try{
Relatorio(r);
}catch(Exception e){
System.out.println("Erro: "+e);
}
break;
case 5:
try{
Manutencao(2);
}catch(Exception e){
System.out.println(e);
}
System.exit(1);
break;
default:
break;
}
}
}
//------------------------------------------------------------------------------------------------------------------------
public static void Manutencao(int i)throws Exception{//1=le arquivo; 2= salva arquivos
try{
if(i==1){
biblioteca.leArquivo();
}else if(i==2){
biblioteca.salvaArquivo();
}
}catch(Exception e){
System.out.println("Erro: "+e);
}
}
//------------------------------------------------------------------------------------------------------------------------
public static void Cadastro(int i)throws Exception{//1==cadastrar livro; 2== cadastrar usuario;
Scanner in = new Scanner( System.in );
String line="lk";
if(i==1){
Livro livro=RecebeLivro();
System.out.println("info livro: \n"+livro.toString()+"\n");
while(true){
try{
System.out.println("Deseja salvar o livro(S/N): ");
line = in.nextLine();
if(line.compareTo("S")==0){
biblioteca.cadastraLivro(livro.getCodLivro(),livro);
Manutencao(2);
break;
}else if(line.compareTo("N")==0){
break;
}else{
System.out.println("O sistema aceita apenas 'S' ou 'N'.\n");
}
}catch(Exception e2){
System.out.println("Erro inesperado: "+e2+"\n");
}
}
}else if(i==2){
Usuario usuario=RecebeUsuario();
System.out.println("info usuario: \n"+usuario.toString()+"\n");
while(true){
try{
System.out.println("Deseja salvar o usuario(S/N): ");
line = in.nextLine();
if(line.compareTo("S")==0){
biblioteca.cadastraUsuario(Integer.toString(usuario.getCodUsuario()),usuario);
Manutencao(2);
break;
}else if(line.compareTo("N")==0){
break;
}else{
System.out.println("O sistema aceita apenas 'S' ou 'N'.\n");
}
}catch(Exception e2){
System.out.println("Erro inesperado: "+e2+"\n");
}
}
}
}
//------------------------------------------------------------------------------------------------------------------------
public static Livro RecebeLivro()throws Exception{
Scanner in = new Scanner( System.in );
String line="lk";
String codLivro;
String categoria, titulo;
int quantidade;
while(true){
try{
System.out.println("Digite o codigo do livro: ");
line = in.nextLine();
codLivro=line;
break;
}catch(Exception e2){
System.out.println("Erro inesperado: "+e2+"\n");
}
}
while(true){
try{
System.out.println("Digite a categoria: ");
line = in.nextLine();
categoria=line;
break;
}catch(Exception e2){
System.out.println("Erro inesperado: "+e2+"\n");
}
}
while(true){
try{
System.out.println("Digite o titulo: ");
line = in.nextLine();
titulo=line;
break;
}catch(Exception e2){
System.out.println("Erro inesperado: "+e2+"\n");
}
}
while(true){
try{
System.out.println("Digite a quantidade: ");
line = in.nextLine();
quantidade=Integer.parseInt(line);
break;
}catch(Exception e2){
System.out.println("Numero invalido, digite apenas numeros.\n");
}
}
return new Livro(codLivro,titulo,categoria,quantidade);
}
//------------------------------------------------------------------------------------------------------------------------
public static Usuario RecebeUsuario()throws Exception{
Scanner in = new Scanner( System.in );
String line="lk";
String nom;
String datNac;
String endere;
int cod, dia, mes, ano;
String codLivro;
while(true){
try{
System.out.println("Digite o nome: ");
line = in.nextLine();
nom=line;
break;
}catch(Exception e2){
System.out.println("Erro inesperado: "+e2+"\n");
}
}
while(true){
try{
System.out.println("Digite o codigo do usuario: ");
line = in.nextLine();
cod=Integer.parseInt(line);
break;
}catch(Exception e2){
System.out.println("Numero invalido, digite apenas numeros.\n");
}
}
while(true){
int a=0;
System.out.println("Digite a data de nascimento(xx/xx/xxxx): ");
datNac = in.nextLine();
try{
if(datNac.length()!=10){throw new Exception ("Data invalida, use o formato xx/xx/xxxx ou xx-xx-xxxx.\n");}
dia=Integer.parseInt(datNac.substring(0,2));
if(dia>31){throw new Exception ("Dia invalido.\n");}
a=1;
}catch(Exception e){
System.out.println(e);
}
if(a==1){
try{
mes=Integer.parseInt(datNac.substring(3,5));
if(mes>12){throw new Exception ();}
a=2;
}catch(Exception c){
System.out.println("Mes invalido!");
}
}
if(a==2){
try{
ano=Integer.parseInt(datNac.substring(6,10));
if(ano>3000){throw new Exception ();}
break;
}catch(Exception f){
System.out.println ("Ano invalido!");
}
}
}
while(true){
try{
System.out.println("Digite a endereco: ");
line = in.nextLine();
endere=line;
break;
}catch(Exception e2){
System.out.println("Erro inesperado: "+e2+"\n");
}
}
return new Usuario(nom, datNac, endere,cod);
}
//------------------------------------------------------------------------------------------------------------------------
public static void Emprestimo(int i){ // 1== fazer emprestimo do livro; 2==devolve o livro; 3== Exibe devolção;
switch (i) {
case 1:
Emp();
break;
case 2:
Dev();
break;
case 3:
ExibirDevolu();
break;
default:
break;
}
}
public static void Emp(){
Scanner in = new Scanner( System.in );
String line="lk";
Exibir();
Livro codli;
Usuario codus;
while(true){
try{
System.out.println("Digite o codigo do Livro: ");
line = in.nextLine();
codli=biblioteca.getLivro(line);
if(codli!=null){
break;
}else{
throw new Exception("Livro Invalido!!");
}
}catch(Exception e2){
System.out.println("Erro: "+e2+"\n");
}
}
while(true){
try{
System.out.println("Digite o codigo do Usuario: ");
line = in.nextLine();
codus=biblioteca.getUsuario(line);
if(codus!=null){
break;
}else{
throw new Exception("Usuario Invalido!!");
}
}catch(Exception e2){
System.out.println("Erro: Usuario invalido\n");
}
}
try{
biblioteca.emprestaLivro(codus,codli);System.out.println("\nEmprestimo foi bem sucedido.");
}catch(Exception e){
System.out.println("Erro: "+e);
}
}
public static void Dev(){
Exibir();
Scanner in = new Scanner( System.in );
String line="lk";
Livro codli;
Usuario codus;
while(true){
try{
System.out.println("Digite o codigo do Livro: ");
line = in.nextLine();
codli=biblioteca.getLivro(line);
if(codli!=null){
break;
}else{
throw new Exception("Livro Invalido!!");
}
}catch(Exception e2){
System.out.println("Erro: Livro invalido!\n");
}
}
while(true){
try{
System.out.println("Digite o codigo do Usuario: ");
line = in.nextLine();
codus=biblioteca.getUsuario(line);
if(codus!=null){
break;
}else{
throw new Exception("Usuario Invalido!!");
}
}catch(Exception e2){
System.out.println("Erro: Usuario invalido!\n");
}
}
try{
biblioteca.devolveLivro(codus,codli);System.out.println("\nDevolucao foi bem sucedido.");
}catch(Exception e){
System.out.println("Erro: "+e);
}
}
public static void ExibirDevolu(){
Scanner in = new Scanner( System.in );
String line="lk";
Exibir();
String codli;
String codus;
while(true){
try{
System.out.println("Digite o codigo do Livro: ");
line = in.nextLine();
biblioteca.getLivro(line);
codli=line;
if(codli!=null){
break;
}else{
throw new Exception("Livro Invalido!!");
}
}catch(Exception e2){
System.out.println("Erro: Livro invalido!\n");
}
}
while(true){
try{
System.out.println("Digite o codigo do Usuario: ");
line = in.nextLine();
biblioteca.getUsuario(line);
codus=line;
if(codus!=null){
break;
}else{
throw new Exception("Usuario Invalido!!");
}
}catch(Exception e2){
System.out.println("Erro: Usuario invalido!\n");
}
}
try{
Usuario u = biblioteca.getUsuario(codus);
System.out.println("Devolucao do usuario "+codus+":\n"+u.getEmprest(codli).toString());
}catch(Exception e){
System.out.println("Erro: "+e);
}
}
public static void Exibir(){
Scanner in = new Scanner( System.in );
String line="lk";
int r=0;
try{
System.out.println("1-Exibir livros e usuarios.\n2-Exibir livros.\n3-Nao exibir nada.");
while(true){
try{
System.out.println("Digite a opcao escolida: ");
line = in.nextLine();
r=Integer.parseInt(line);
if(r>0 && r<4){
break;
}else{
throw new Exception("Digite apenas valores de 1 a 3.\n");
}
}catch(Exception e2){
System.out.println("Erro: "+e2+"\n");
}
}
switch (r) {
case 1:
try{
System.out.println("Livros:\n"+biblioteca.imprimeLivros());
}catch(NullPointerException e){
}
try{
System.out.println("Usuarios:\n"+biblioteca.imprimeUsuarios());
}catch(NullPointerException e){
}
break;
case 2:
System.out.println("Livros:\n"+biblioteca.imprimeLivros());
break;
case 3:
break;
default:
break;
}
}catch(Exception e){
System.out.println("Erro: "+e);
}
}
//------------------------------------------------------------------------------------------------------------------------
public static void Relatorio(int i){// livros;usuarios;detalhe usuario;detalhe livro
Scanner in = new Scanner( System.in );
String line="lk";
try{
switch (i) {
case 1:
System.out.println(biblioteca.imprimeLivros());
break;
case 2:
System.out.println(biblioteca.imprimeUsuarios());
break;
case 3:
Livro cod;
while(true){
try{
System.out.println("Digite o codigo do Livro: ");
line = in.nextLine();
cod=biblioteca.getLivro(line);
if(cod!=null){
break;
}
}catch(Exception e2){
System.out.println("Erro: Livro invalido!\n");
}
}
System.out.println(cod.toString()+"\n"+cod.toHisotico());
break;
case 4:
Usuario cod1;
while(true){
try{
System.out.println("Digite o codigo do Usuario: ");
line = in.nextLine();
cod1=biblioteca.getUsuario(line);
if(cod1!=null){
break;
}
}catch(Exception e2){
System.out.println("Erro: Usuario invalido!\n");
}
}
System.out.println(cod1.toString()+"\n"+cod1.toHisotico());
break;
default:
break;
}
}catch(Exception e){
System.out.println("Erro: "+e);
}
}
//------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------
}
| 22,298 | 0.352427 | 0.345923 | 645 | 32.561241 | 24.893972 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.462016 | false | false |
12
|
2ee0492513e09a012f3ec6d2112548162f0de5e1
| 30,081,950,944,337 |
fef5296397f9b950a11455e880a919537390aea0
|
/enterprise/j2ee.ejbjarproject/src/org/netbeans/modules/j2ee/ejbjarproject/EjbJarProject.java
|
637f86b3d6eba50aa81e8041789a437436f1c7de
|
[
"Apache-2.0"
] |
permissive
|
apache/netbeans
|
https://github.com/apache/netbeans
|
5a4d6fa9e4f230b33e44519a479d66e47a381289
|
28d308b400bbe439ac0ac84b64d823ce0b69272e
|
refs/heads/master
| 2023-08-29T15:32:41.838000 | 2023-08-29T09:48:59 | 2023-08-29T09:48:59 | 102,083,576 | 1,692 | 718 |
Apache-2.0
| false | 2023-09-14T19:41:05 | 2017-09-01T07:00:11 | 2023-09-14T09:51:47 | 2023-09-14T19:41:04 | 381,002 | 2,386 | 791 | 718 |
Java
| false | false |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.j2ee.ejbjarproject;
import java.awt.Dialog;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Icon;
import javax.swing.SwingUtilities;
import org.netbeans.api.java.classpath.ClassPath;
import org.netbeans.api.java.classpath.GlobalPathRegistry;
import org.netbeans.api.java.project.JavaProjectConstants;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectManager;
import org.netbeans.api.project.ant.AntArtifact;
import org.netbeans.api.project.ant.AntBuildExtender;
import org.netbeans.modules.j2ee.api.ejbjar.EjbJar;
import org.netbeans.modules.j2ee.api.ejbjar.EjbProjectConstants;
import org.netbeans.modules.j2ee.dd.api.ejb.EjbJarMetadata;
import org.netbeans.modules.j2ee.metadata.model.api.MetadataModel;
import org.netbeans.modules.j2ee.spi.ejbjar.support.EjbJarSupport;
import org.netbeans.modules.java.api.common.Roots;
import org.netbeans.modules.j2ee.deployment.devmodules.spi.ArtifactListener.Artifact;
import org.netbeans.modules.j2ee.ejbjarproject.jaxws.EjbProjectJAXWSClientSupport;
import org.netbeans.modules.j2ee.ejbjarproject.jaxws.EjbProjectJAXWSSupport;
import org.netbeans.modules.j2ee.ejbjarproject.ui.EjbJarLogicalViewProvider;
import org.netbeans.modules.j2ee.ejbjarproject.ui.customizer.EjbJarProjectProperties;
import org.netbeans.api.project.SourceGroup;
import org.netbeans.modules.j2ee.common.SharabilityUtility;
import org.netbeans.modules.javaee.project.api.ant.ArtifactCopyOnSaveSupport;
import org.netbeans.modules.java.api.common.classpath.ClassPathModifier;
import org.netbeans.modules.java.api.common.classpath.ClassPathSupport;
import org.netbeans.modules.java.api.common.classpath.ClassPathProviderImpl;
import org.netbeans.modules.java.api.common.project.ui.ClassPathUiSupport;
import org.netbeans.modules.javaee.project.api.ant.DeployOnSaveUtils;
import org.netbeans.modules.javaee.project.api.ant.ui.J2EEProjectProperties;
import org.netbeans.modules.j2ee.common.ui.BrokenServerSupport;
import org.netbeans.modules.j2ee.spi.ejbjar.EjbJarFactory;
import org.netbeans.modules.j2ee.spi.ejbjar.support.EjbEnterpriseReferenceContainerSupport;
import org.netbeans.modules.websvc.api.jaxws.client.JAXWSClientSupport;
import org.netbeans.modules.websvc.jaxws.api.JAXWSSupport;
import org.netbeans.modules.websvc.jaxws.spi.JAXWSSupportFactory;
import org.netbeans.modules.websvc.spi.client.WebServicesClientSupportFactory;
import org.netbeans.modules.websvc.spi.jaxws.client.JAXWSClientSupportFactory;
import org.netbeans.spi.project.SubprojectProvider;
import org.netbeans.spi.project.ant.AntArtifactProvider;
import org.netbeans.spi.project.ant.AntBuildExtenderFactory;
import org.netbeans.spi.project.ant.AntBuildExtenderImplementation;
import org.netbeans.spi.project.support.ant.AntProjectHelper;
import org.netbeans.spi.project.support.ant.GeneratedFilesHelper;
import org.netbeans.spi.project.support.ant.ProjectXmlSavedHook;
import org.netbeans.spi.project.ui.PrivilegedTemplates;
import org.netbeans.spi.project.ui.RecommendedTemplates;
import org.netbeans.spi.project.support.ant.ReferenceHelper;
import org.netbeans.spi.project.support.ant.PropertyEvaluator;
import org.netbeans.spi.project.ui.ProjectOpenedHook;
import org.openide.filesystems.FileChangeListener;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.lookup.Lookups;
import org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment;
import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eePlatform;
import org.netbeans.modules.j2ee.ejbjarproject.classpath.ClassPathSupportCallbackImpl;
import org.netbeans.modules.j2ee.ejbjarproject.ui.BrokenReferencesAlertPanel;
import org.netbeans.modules.javaee.project.api.ui.UserProjectSettings;
import org.netbeans.modules.j2ee.deployment.devmodules.api.InstanceRemovedException;
import org.netbeans.api.j2ee.core.Profile;
import org.netbeans.api.java.platform.JavaPlatform;
import org.netbeans.api.java.project.classpath.ProjectClassPathModifier;
import org.netbeans.api.project.ProjectUtils;
import org.netbeans.api.project.ui.ProjectProblems;
import org.netbeans.modules.javaee.project.api.PersistenceProviderSupplierImpl;
import org.netbeans.modules.javaee.project.api.ant.AntProjectConstants;
import org.netbeans.modules.j2ee.common.ServerUtil;
import org.netbeans.modules.javaee.project.api.WhiteListUpdater;
import org.netbeans.modules.javaee.project.spi.JavaEEProjectSettingsImplementation;
import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eeModule.Type;
import org.netbeans.modules.j2ee.deployment.devmodules.spi.ArtifactListener;
import org.netbeans.modules.j2ee.deployment.devmodules.spi.J2eeModuleProvider.DeployOnSaveSupport;
import org.netbeans.modules.j2ee.ejbjarproject.ui.customizer.CustomizerProviderImpl;
import org.netbeans.modules.j2ee.persistence.spi.entitymanagergenerator.EntityManagerGenerationStrategyResolverFactory;
import org.netbeans.modules.j2ee.spi.ejbjar.EjbJarImplementation;
import org.netbeans.modules.j2ee.spi.ejbjar.EjbJarImplementation2;
import org.netbeans.modules.java.api.common.SourceRoots;
import org.netbeans.modules.java.api.common.ant.UpdateHelper;
import org.netbeans.modules.java.api.common.ant.UpdateImplementation;
import org.netbeans.modules.java.api.common.project.ProjectProperties;
import org.netbeans.modules.java.api.common.queries.QuerySupport;
import org.netbeans.modules.javaee.project.api.JavaEEProjectSettingConstants;
import org.netbeans.modules.javaee.project.api.ant.AntProjectUtil;
import org.netbeans.modules.javaee.project.api.problems.PlatformUpdatedCallBackImpl;
import org.netbeans.spi.java.project.support.ui.BrokenReferencesSupport;
import org.netbeans.spi.project.AuxiliaryConfiguration;
import org.netbeans.spi.project.support.ant.EditableProperties;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.util.NbBundle;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.netbeans.modules.websvc.api.webservices.WebServicesSupport;
import org.netbeans.modules.websvc.api.client.WebServicesClientSupport;
import org.netbeans.modules.websvc.spi.webservices.WebServicesSupportFactory;
import org.netbeans.spi.java.project.support.ExtraSourceJavadocSupport;
import org.netbeans.spi.java.project.support.LookupMergerSupport;
import org.netbeans.spi.project.support.LookupProviderSupport;
import org.netbeans.spi.project.support.ant.AntBasedProjectRegistration;
import org.netbeans.spi.project.ui.support.UILookupMergerSupport;
import org.netbeans.spi.queries.FileEncodingQueryImplementation;
import org.netbeans.spi.whitelist.support.WhiteListQueryMergerSupport;
import org.openide.filesystems.FileChangeAdapter;
import org.openide.filesystems.FileEvent;
import org.openide.filesystems.FileLock;
import org.openide.filesystems.FileRenameEvent;
import org.openide.filesystems.FileStateInvalidException;
import org.openide.filesystems.FileSystem.AtomicAction;
import org.openide.util.Exceptions;
import org.openide.xml.XMLUtil;
/**
* Represents one ejb module project
* @author Chris Webster
*/
@AntBasedProjectRegistration(
iconResource="org/netbeans/modules/j2ee/ejbjarproject/ui/resources/ejbjarProjectIcon.gif",
type=EjbJarProjectType.TYPE,
sharedNamespace=EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE,
privateNamespace=EjbJarProjectType.PRIVATE_CONFIGURATION_NAMESPACE
)
public class EjbJarProject implements Project, FileChangeListener {
private final Icon PROJECT_ICON = ImageUtilities.loadImageIcon("org/netbeans/modules/j2ee/ejbjarproject/ui/resources/ejbjarProjectIcon.gif", false); // NOI18N
private static final Logger LOGGER = Logger.getLogger(EjbJarProject.class.getName());
private final AuxiliaryConfiguration aux;
private final AntProjectHelper helper;
private final PropertyEvaluator eval;
private final ReferenceHelper refHelper;
private FileObject libFolder = null;
private final GeneratedFilesHelper genFilesHelper;
private Lookup lookup;
private final UpdateHelper updateHelper;
private final EjbJarProvider ejbModule;
private final CopyOnSaveSupport css;
private final ArtifactCopyOnSaveSupport artifactSupport;
private final DeployOnSaveSupport deployOnSaveSupport;
private final EjbJar apiEjbJar;
private WebServicesSupport apiWebServicesSupport;
private JAXWSSupport apiJaxwsSupport;
private EjbProjectJAXWSSupport jaxwsSupport;
private WebServicesClientSupport apiWebServicesClientSupport;
private JAXWSClientSupport apiJAXWSClientSupport;
private EjbJarWebServicesSupport ejbJarWebServicesSupport;
private EjbJarWebServicesClientSupport ejbJarWebServicesClientSupport;
private EjbProjectJAXWSClientSupport jaxWsClientSupport;
private SourceRoots sourceRoots;
private SourceRoots testRoots;
private final ClassPathModifier classPathModifier;
private PropertyChangeListener j2eePlatformListener;
private AntBuildExtender buildExtender;
private final ClassPathProviderImpl cpProvider;
private ClassPathUiSupport.Callback classPathUiSupportCallback;
private WhiteListUpdater whiteListUpdater;
// set to true when project customizer is being closed and changes persisted
private final ThreadLocal<Boolean> projectPropertiesSave;
// TODO: AB: replace the code in EjbJarProjectProperties.setNewServerInstanceValue with this
/*private String propJ2eeServerInstance;
private PropertyChangeListener evalListener = new PropertyChangeListener() {
public void propertyChange(final PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if (propertyName == null || propertyName.equals(EjbJarProjectProperties.J2EE_SERVER_INSTANCE)) {
org.openide.util.RequestProcessor.getDefault().post(new Runnable() {
public void run() {
ProjectManager.mutex().writeAccess(new Runnable() {
public void run() {
// try to unregister the old J2EE platform
String oldJ2eeServerInstance = null;
if (propJ2eeServerInstance != null) {
oldJ2eeServerInstance = propJ2eeServerInstance;
} else {
oldJ2eeServerInstance = (String)evt.getOldValue();
}
if (oldJ2eeServerInstance != null) {
J2eePlatform oldJ2eePlatform = Deployment.getDefault().getJ2eePlatform(oldJ2eeServerInstance);
unregisterJ2eePlatformListener(oldJ2eePlatform);
propJ2eeServerInstance = null;
}
// now register the new platform
//String newJ2eeServerInstance = (String)evt.getNewValue();
EditableProperties props = helper.getProperties(AntProjectHelper.PRIVATE_PROPERTIES_PATH);
//if (newJ2eeServerInstance == null)
String newJ2eeServerInstance = props.getProperty(EjbJarProjectProperties.J2EE_SERVER_INSTANCE);
if (newJ2eeServerInstance != null) {
J2eePlatform newJ2eePlatform = Deployment.getDefault().getJ2eePlatform(newJ2eeServerInstance);
registerJ2eePlatformListener(newJ2eePlatform);
propJ2eeServerInstance = newJ2eeServerInstance;
putJ2eePlatformClassPath(newJ2eePlatform, props);
String serverType = Deployment.getDefault().getServerID(newJ2eeServerInstance);
props.setProperty(EjbJarProjectProperties.J2EE_SERVER_TYPE, serverType);
// TODO: AB: should update wscompile classpath too
helper.putProperties(AntProjectHelper.PRIVATE_PROPERTIES_PATH, props);
try {
ProjectManager.getDefault().saveProject(EjbJarProject.this);
}
catch (IOException e) {
ErrorManager.getDefault().notify(e);
}
}
}
});
}
});
}
}
};*/
public EjbJarProject(final AntProjectHelper helper) throws IOException {
this.projectPropertiesSave = new ThreadLocal<Boolean>() {
@Override
protected Boolean initialValue() {
return Boolean.FALSE;
}
};
this.helper = helper;
eval = createEvaluator();
aux = helper.createAuxiliaryConfiguration();
refHelper = new ReferenceHelper(helper, aux, helper.getStandardPropertyEvaluator());
buildExtender = AntBuildExtenderFactory.createAntExtender(new EjbExtenderImplementation());
genFilesHelper = new GeneratedFilesHelper(helper, buildExtender);
UpdateImplementation updateProject = new UpdateProjectImpl(this, helper, aux, genFilesHelper);
this.updateHelper = new UpdateHelper(updateProject, helper);
this.cpProvider = new ClassPathProviderImpl(helper, evaluator(), getSourceRoots(), getTestSourceRoots(),
ProjectProperties.BUILD_CLASSES_DIR, EjbJarProjectProperties.DIST_JAR, ProjectProperties.BUILD_TEST_CLASSES_DIR,
new String[] {"javac.classpath", EjbJarProjectProperties.J2EE_PLATFORM_CLASSPATH }, // NOI18N
new String[] {ProjectProperties.JAVAC_PROCESSORPATH},
new String[] {"javac.test.classpath", EjbJarProjectProperties.J2EE_PLATFORM_CLASSPATH }, // NOI18N
new String[] {"debug.classpath", EjbJarProjectProperties.J2EE_PLATFORM_CLASSPATH }, // NOI18N
new String[] {"run.test.classpath", EjbJarProjectProperties.J2EE_PLATFORM_CLASSPATH },
new String[] {ProjectProperties.ENDORSED_CLASSPATH}); // NOI18N
ejbModule = new EjbJarProvider(this, helper, cpProvider);
apiEjbJar = EjbJarFactory.createEjbJar(new EjbJarImpl2(ejbModule));
ejbJarWebServicesSupport = new EjbJarWebServicesSupport(this, helper, refHelper);
jaxwsSupport = new EjbProjectJAXWSSupport(this, helper);
ejbJarWebServicesClientSupport = new EjbJarWebServicesClientSupport(this, helper, refHelper);
jaxWsClientSupport = new EjbProjectJAXWSClientSupport(this,helper);
apiWebServicesSupport = WebServicesSupportFactory.createWebServicesSupport(ejbJarWebServicesSupport);
apiJaxwsSupport = JAXWSSupportFactory.createJAXWSSupport(jaxwsSupport);
apiWebServicesClientSupport = WebServicesClientSupportFactory.createWebServicesClientSupport(ejbJarWebServicesClientSupport);
apiJAXWSClientSupport = JAXWSClientSupportFactory.createJAXWSClientSupport(jaxWsClientSupport);
classPathModifier = new ClassPathModifier(this, this.updateHelper, eval, refHelper,
new ClassPathSupportCallbackImpl(helper), createClassPathModifierCallback(),
getClassPathUiSupportCallback());
lookup = createLookup(aux, cpProvider);
css = new CopyOnSaveSupport();
artifactSupport = new ArtifactCopySupport();
deployOnSaveSupport = new DeployOnSaveSupportProxy();
ProjectManager.mutex().postWriteRequest(
new Runnable () {
@Override
public void run() {
try {
updateProjectXML ();
} catch (IOException ioe) {
LOGGER.log(Level.INFO, null, ioe);
}
}
}
);
// whitelist updater listens on project properties and pays attention to whitelist changes
whiteListUpdater = new WhiteListUpdaterImpl(this);
}
public void setProjectPropertiesSave(boolean value) {
this.projectPropertiesSave.set(value);
}
private ClassPathModifier.Callback createClassPathModifierCallback() {
return new ClassPathModifier.Callback() {
@Override
public String getClassPathProperty(SourceGroup sg, String type) {
assert sg != null : "SourceGroup cannot be null"; //NOI18N
assert type != null : "Type cannot be null"; //NOI18N
final String[] classPathProperty = getClassPathProvider().getPropertyName (sg, type);
if (classPathProperty == null || classPathProperty.length == 0) {
throw new UnsupportedOperationException ("Modification of [" + sg.getRootFolder().getPath() +", " + type + "] is not supported"); //NOI18N
}
return classPathProperty[0];
}
@Override
public String getElementName(String classpathProperty) {
if (ProjectProperties.JAVAC_CLASSPATH.equals(classpathProperty)) {
return ClassPathSupportCallbackImpl.ELEMENT_INCLUDED_LIBRARIES;
}
return null;
}
};
}
public synchronized ClassPathUiSupport.Callback getClassPathUiSupportCallback() {
if (classPathUiSupportCallback == null) {
classPathUiSupportCallback = new ClassPathUiSupport.Callback() {
@Override
public void initItem(ClassPathSupport.Item item) {
if (item.getType() != ClassPathSupport.Item.TYPE_LIBRARY || !item.getLibrary().getType().equals(J2eePlatform.LIBRARY_TYPE)) {
item.setAdditionalProperty(ClassPathSupportCallbackImpl.INCLUDE_IN_DEPLOYMENT, "true");
}
}
};
}
return classPathUiSupportCallback;
}
/**
* Returns the project directory
* @return the directory the project is located in
*/
@Override
public FileObject getProjectDirectory() {
return helper.getProjectDirectory();
}
@Override
public String toString() {
return "EjbJarProject[" + getProjectDirectory() + "]"; // NOI18N
}
private PropertyEvaluator createEvaluator() {
return helper.getStandardPropertyEvaluator();
}
public PropertyEvaluator evaluator() {
return eval;
}
public ReferenceHelper getReferenceHelper () {
return this.refHelper;
}
public UpdateHelper getUpdateHelper() {
return updateHelper;
}
@Override
public Lookup getLookup() {
return lookup;
}
public AntProjectHelper getAntProjectHelper() {
return helper;
}
public DeployOnSaveSupport getDeployOnSaveSupport() {
return deployOnSaveSupport;
}
private Lookup createLookup(AuxiliaryConfiguration aux, ClassPathProviderImpl cpProvider) {
SubprojectProvider spp = refHelper.createSubprojectProvider();
FileEncodingQueryImplementation encodingQuery = QuerySupport.createFileEncodingQuery(evaluator(), EjbJarProjectProperties.SOURCE_ENCODING);
final EjbJarLogicalViewProvider lvp = new EjbJarLogicalViewProvider(this, updateHelper, evaluator(), spp, refHelper, ejbModule);
Lookup base = Lookups.fixed(new Object[] {
EjbJarProject.this, // never cast an externally obtained Project to EjbJarProject - use lookup instead
buildExtender,
QuerySupport.createProjectInformation(helper, this, PROJECT_ICON),
aux,
helper.createCacheDirectoryProvider(),
helper.createAuxiliaryProperties(),
new ProjectWebServicesSupportProvider(), // implementation of WebServicesClientSupportProvider commented out
spp,
EjbEnterpriseReferenceContainerSupport.createEnterpriseReferenceContainer(this, helper),
EjbJarSupport.createEjbJarProvider(this, apiEjbJar),
EjbJarSupport.createEjbJarsInProject(apiEjbJar),
ejbModule, //implements J2eeModuleProvider
// FIXME this is just fallback for code searching for the old SPI in lookup
// remove in next release
new EjbJarImpl(apiEjbJar),
lvp,
new CustomizerProviderImpl( this, updateHelper, evaluator(), refHelper ),
LookupMergerSupport.createClassPathProviderMerger(cpProvider),
QuerySupport.createCompiledSourceForBinaryQuery(helper, evaluator(), getSourceRoots(), getTestSourceRoots()),
QuerySupport.createJavadocForBinaryQuery(helper, evaluator()),
QuerySupport.createAnnotationProcessingQuery(helper, eval, ProjectProperties.ANNOTATION_PROCESSING_ENABLED, ProjectProperties.ANNOTATION_PROCESSING_ENABLED_IN_EDITOR, ProjectProperties.ANNOTATION_PROCESSING_RUN_ALL_PROCESSORS, ProjectProperties.ANNOTATION_PROCESSING_PROCESSORS_LIST, ProjectProperties.ANNOTATION_PROCESSING_SOURCE_OUTPUT, ProjectProperties.ANNOTATION_PROCESSING_PROCESSOR_OPTIONS),
new AntArtifactProviderImpl(),
new ProjectXmlSavedHookImpl(),
UILookupMergerSupport.createProjectOpenHookMerger(new ProjectOpenedHookImpl()),
QuerySupport.createUnitTestForSourceQuery(getSourceRoots(), getTestSourceRoots()),
QuerySupport.createSourceLevelQuery2(evaluator()),
QuerySupport.createSources(this, helper, evaluator(),
getSourceRoots(),
getTestSourceRoots(),
Roots.propertyBased(new String[]{EjbJarProjectProperties.META_INF}, new String[]{NbBundle.getMessage(EjbJarLogicalViewProvider.class, "LBL_Node_DocBase")}, false, null, null),
Roots.nonSourceRoots(ProjectProperties.BUILD_DIR, EjbJarProjectProperties.DIST_DIR)),
QuerySupport.createSharabilityQuery(helper, evaluator(), getSourceRoots(), getTestSourceRoots(),
EjbJarProjectProperties.META_INF),
QuerySupport.createFileBuiltQuery(helper, evaluator(), getSourceRoots(), getTestSourceRoots()),
encodingQuery,
new RecommendedTemplatesImpl(updateHelper),
refHelper,
ProjectClassPathModifier.extenderForModifier(classPathModifier),
classPathModifier,
new EjbJarProjectOperations(this),
new EjbJarPersistenceProvider(this, evaluator(), cpProvider),
new PersistenceProviderSupplierImpl(this),
EntityManagerGenerationStrategyResolverFactory.createInstance(this),
new EjbJarJPASupport(this),
ServerUtil.createServerStatusProvider(getEjbModule()),
new EjbJarJPAModuleInfo(this),
new EjbJarJPATargetInfo(this),
UILookupMergerSupport.createPrivilegedTemplatesMerger(),
UILookupMergerSupport.createRecommendedTemplatesMerger(),
LookupProviderSupport.createSourcesMerger(),
LookupProviderSupport.createActionProviderMerger(),
WhiteListQueryMergerSupport.createWhiteListQueryMerger(),
QuerySupport.createTemplateAttributesProvider(helper, encodingQuery),
ExtraSourceJavadocSupport.createExtraSourceQueryImplementation(this, helper, eval),
LookupMergerSupport.createSFBLookupMerger(),
ExtraSourceJavadocSupport.createExtraJavadocQueryImplementation(this, helper, eval),
LookupMergerSupport.createJFBLookupMerger(),
QuerySupport.createBinaryForSourceQueryImplementation(getSourceRoots(), getTestSourceRoots(), helper, eval),
new JavaEEProjectSettingsImpl(this),
BrokenReferencesSupport.createReferenceProblemsProvider(helper, refHelper, eval, lvp.getBreakableProperties(), lvp.getPlatformProperties()),
BrokenReferencesSupport.createPlatformVersionProblemProvider(helper, eval, PlatformUpdatedCallBackImpl.create(EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE, updateHelper), JavaPlatform.getDefault().getSpecification().getName(), ProjectProperties.PLATFORM_ACTIVE, ProjectProperties.JAVAC_SOURCE, ProjectProperties.JAVAC_TARGET),
UILookupMergerSupport.createProjectProblemsProviderMerger(),
// TODO: AB: maybe add "this" to the lookup. You should not cast a Project to EjbJarProject, but use the lookup instead.
});
lookup = base;
return LookupProviderSupport.createCompositeLookup(base, "Projects/org-netbeans-modules-j2ee-ejbjarproject/Lookup"); //NOI18N
}
public ClassPathProviderImpl getClassPathProvider () {
return this.cpProvider;
}
String getBuildXmlName() {
String storedName = helper.getStandardPropertyEvaluator().getProperty(EjbJarProjectProperties.BUILD_FILE);
return storedName == null ? GeneratedFilesHelper.BUILD_XML_PATH : storedName;
}
// Package private methods -------------------------------------------------
/**
* Returns the source roots of this project
* @return project's source roots
*/
public synchronized SourceRoots getSourceRoots() {
if (this.sourceRoots == null) { //Local caching, no project metadata access
this.sourceRoots = SourceRoots.create(this.updateHelper, evaluator(), getReferenceHelper(), EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE, "source-roots", false, "src.{0}{1}.dir"); //NOI18N
}
return this.sourceRoots;
}
public synchronized SourceRoots getTestSourceRoots() {
if (this.testRoots == null) { //Local caching, no project metadata access
this.testRoots = SourceRoots.create(this.updateHelper, evaluator(), getReferenceHelper(), EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE, "test-roots", true, "test.{0}{1}.dir"); //NOI18N
}
return this.testRoots;
}
WebServicesSupport getAPIWebServicesSupport() {
return apiWebServicesSupport;
}
JAXWSSupport getAPIJAXWSSupport () {
return apiJaxwsSupport;
}
WebServicesClientSupport getAPIWebServicesClientSupport () {
return apiWebServicesClientSupport;
}
JAXWSClientSupport getAPIJAXWSClientSupport () {
return apiJAXWSClientSupport;
}
/*public EjbJarProjectProperties getEjbJarProjectProperties() {
return new EjbJarProjectProperties (this, helper, refHelper);
}*/
public EjbJarProvider getEjbModule() {
return ejbModule;
}
public EjbJar getAPIEjbJar() {
return apiEjbJar;
}
/** Last time in ms when the Broken References alert was shown. */
private static long brokenAlertLastTime = 0;
/** Is Broken References alert shown now? */
private static boolean brokenAlertShown = false;
/** Timeout within which request to show alert will be ignored. */
private static int BROKEN_ALERT_TIMEOUT = 1000;
private static synchronized void showBrokenReferencesAlert() {
// Do not show alert if it is already shown or if it was shown
// in last BROKEN_ALERT_TIMEOUT milliseconds or if user do not wish it.
if (brokenAlertShown ||
brokenAlertLastTime+BROKEN_ALERT_TIMEOUT > System.currentTimeMillis() ||
!UserProjectSettings.getDefault().isShowAgainBrokenRefAlert()) {
return;
}
brokenAlertShown = true;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
Object ok = NbBundle.getMessage(BrokenReferencesAlertPanel.class,"MSG_Broken_References_OK");
DialogDescriptor dd = new DialogDescriptor(new BrokenReferencesAlertPanel(),
NbBundle.getMessage(BrokenReferencesAlertPanel.class, "MSG_Broken_References_Title"),
true, new Object[] {ok}, ok, DialogDescriptor.DEFAULT_ALIGN, null, null);
Dialog dlg = null;
try {
dlg = DialogDisplayer.getDefault().createDialog(dd);
dlg.setVisible(true);
} finally {
if (dlg != null) {
dlg.dispose();
}
}
} finally {
synchronized (EjbJarProject.class) {
brokenAlertLastTime = System.currentTimeMillis();
brokenAlertShown = false;
}
}
}
});
}
/** Return configured project name. */
public String getName() {
return ProjectUtils.getInformation(this).getName();
}
/** Store configured project name. */
public void setName(final String name) {
ProjectManager.mutex().writeAccess(new Runnable() {
@Override
public void run() {
Element data = helper.getPrimaryConfigurationData(true);
// XXX replace by XMLUtil when that has findElement, findText, etc.
NodeList nl = data.getElementsByTagNameNS(EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE, "name"); //NOI18N
Element nameEl;
if (nl.getLength() == 1) {
nameEl = (Element) nl.item(0);
NodeList deadKids = nameEl.getChildNodes();
while (deadKids.getLength() > 0) {
nameEl.removeChild(deadKids.item(0));
}
} else {
nameEl = data.getOwnerDocument().createElementNS(EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE, "name"); //NOI18N
data.insertBefore(nameEl, /* OK if null */data.getChildNodes().item(0));
}
nameEl.appendChild(data.getOwnerDocument().createTextNode(name));
helper.putPrimaryConfigurationData(data, true);
}
});
}
private void updateProjectXML () throws IOException {
Element element = aux.getConfigurationFragment("data","http://www.netbeans.org/ns/EjbJar-project/1",true); //NOI18N
if (element != null) {
Document doc = element.getOwnerDocument();
Element newRoot = doc.createElementNS (EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE,"data"); //NOI18N
XMLUtil.copyDocument (element, newRoot, EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE);
Element srcRoots = doc.createElementNS(EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE, "source-roots"); //NOI18N
Element root = doc.createElementNS (EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE,"root"); //NOI18N
root.setAttribute ("id","src.dir"); //NOI18N
srcRoots.appendChild(root);
newRoot.appendChild (srcRoots);
Element tstRoots = doc.createElementNS(EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE,"test-roots"); //NOI18N
root = doc.createElementNS (EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE,"root"); //NOI18N
root.setAttribute ("id","test.src.dir"); //NOI18N
tstRoots.appendChild (root);
newRoot.appendChild (tstRoots);
helper.putPrimaryConfigurationData (newRoot, true);
ProjectManager.getDefault().saveProject(this);
}
}
@Override
public void fileAttributeChanged (org.openide.filesystems.FileAttributeEvent fe) {
}
@Override
public void fileChanged (org.openide.filesystems.FileEvent fe) {
}
@Override
public void fileDataCreated (org.openide.filesystems.FileEvent fe) {
FileObject fo = fe.getFile ();
checkLibraryFolder (fo);
}
@Override
public void fileDeleted (org.openide.filesystems.FileEvent fe) {
}
public void registerJ2eePlatformListener(final J2eePlatform platform) {
// listen to classpath changes
j2eePlatformListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(J2eePlatform.PROP_CLASSPATH)) {
ProjectManager.mutex().writeAccess(new Runnable() {
@Override
public void run() {
EditableProperties ep = helper.getProperties(
AntProjectHelper.PRIVATE_PROPERTIES_PATH);
EditableProperties projectProps = helper.getProperties(
AntProjectHelper.PROJECT_PROPERTIES_PATH);
Map<String, String> roots = J2EEProjectProperties.extractPlatformLibrariesRoot(platform);
String classpath = J2EEProjectProperties.toClasspathString(platform.getClasspathEntries(), roots);
ep.setProperty(EjbJarProjectProperties.J2EE_PLATFORM_CLASSPATH, classpath);
helper.putProperties(AntProjectHelper.PRIVATE_PROPERTIES_PATH, ep);
try {
ProjectManager.getDefault().saveProject(EjbJarProject.this);
} catch (IOException e) {
Exceptions.printStackTrace(e);
}
}
});
}
}
};
platform.addPropertyChangeListener(j2eePlatformListener);
}
public void unregisterJ2eePlatformListener(J2eePlatform platform) {
if (j2eePlatformListener != null) {
platform.removePropertyChangeListener(j2eePlatformListener);
}
}
@Override
public void fileFolderCreated (FileEvent fe) {
}
@Override
public void fileRenamed (FileRenameEvent fe) {
FileObject fo = fe.getFile ();
checkLibraryFolder (fo);
}
private void checkLibraryFolder (FileObject fo) {
if (!FileUtil.isArchiveFile(fo)) {
return;
}
if (fo.getParent ().equals (libFolder)) {
try {
classPathModifier.addRoots(new URL[] {FileUtil.getArchiveRoot(fo.toURL())}, ProjectProperties.JAVAC_CLASSPATH);
}
catch (IOException e) {
Exceptions.printStackTrace(e);
}
}
}
private String getProperty(String path, String name) {
return helper.getProperties(path).getProperty(name);
}
// Private innerclasses ----------------------------------------------------
private final class ProjectXmlSavedHookImpl extends ProjectXmlSavedHook {
ProjectXmlSavedHookImpl() {}
@Override
protected void projectXmlSaved() throws IOException {
int state = genFilesHelper.getBuildScriptState(
GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
EjbJarProject.class.getResource("resources/build-impl.xsl"));
final Boolean projectPropertiesSave = EjbJarProject.this.projectPropertiesSave.get();
if ((projectPropertiesSave && (state & GeneratedFilesHelper.FLAG_MODIFIED) == GeneratedFilesHelper.FLAG_MODIFIED) ||
state == (GeneratedFilesHelper.FLAG_UNKNOWN | GeneratedFilesHelper.FLAG_MODIFIED |
GeneratedFilesHelper.FLAG_OLD_PROJECT_XML | GeneratedFilesHelper.FLAG_OLD_STYLESHEET)) { //missing genfiles.properties
try {
AntProjectUtil.backupBuildImplFile(updateHelper);
genFilesHelper.generateBuildScriptFromStylesheet(
GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
EjbJarProject.class.getResource("resources/build-impl.xsl"));
} catch (IOException e) {
Exceptions.printStackTrace(e);
} catch (IllegalStateException e) {
Exceptions.printStackTrace(e);
}
} else {
genFilesHelper.refreshBuildScript(GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
EjbJarProject.class.getResource("resources/build-impl.xsl"),
false);
}
genFilesHelper.refreshBuildScript(
getBuildXmlName(),
EjbJarProject.class.getResource("resources/build.xsl"),
false);
}
}
private final class ProjectOpenedHookImpl extends ProjectOpenedHook {
ProjectOpenedHookImpl() {}
@Override
protected void projectOpened() {
evaluator().addPropertyChangeListener(EjbJarProject.this.ejbModule);
EjbJarLogicalViewProvider logicalViewProvider = EjbJarProject.this.getLookup().lookup(EjbJarLogicalViewProvider.class);
if (logicalViewProvider != null) {
logicalViewProvider.initialize();
}
try {
//Check libraries and add them to classpath automatically
String libFolderName = helper.getStandardPropertyEvaluator ().getProperty (EjbJarProjectProperties.LIBRARIES_DIR);
//EjbJarProjectProperties ejbpp = getEjbJarProjectProperties();
//DDDataObject initialization to be ready to listen on changes (#49656)
try {
FileObject ddFO = ejbModule.getDeploymentDescriptor();
if (ddFO != null) {
DataObject.find(ddFO);
}
} catch (org.openide.loaders.DataObjectNotFoundException ex) {}
// Register copy on save support
css.initialize();
FileObject lf = null;
if (libFolderName != null) {
lf = helper.resolveFileObject(libFolderName);
}
if (lf != null && lf.isFolder()) {
libFolder = lf;
FileObject[] children = libFolder.getChildren ();
List<URL> libs = new LinkedList<URL>();
for (int i = 0; i < children.length; i++) {
if (FileUtil.isArchiveFile(children[i])) {
libs.add(FileUtil.getArchiveRoot(children[i].toURL()));
}
}
classPathModifier.addRoots(libs.toArray(new URL[libs.size()]), ProjectProperties.JAVAC_CLASSPATH);
libFolder.addFileChangeListener (EjbJarProject.this);
}
// Check up on build scripts.
int flags = genFilesHelper.getBuildScriptState(
GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
EjbJarProject.class.getResource("resources/build-impl.xsl"));
if ((flags & GeneratedFilesHelper.FLAG_MODIFIED) != 0
&& (flags & GeneratedFilesHelper.FLAG_OLD_PROJECT_XML) != 0) {
AntProjectUtil.backupBuildImplFile(updateHelper);
genFilesHelper.generateBuildScriptFromStylesheet(
GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
EjbJarProject.class.getResource("resources/build-impl.xsl"));
} else {
genFilesHelper.refreshBuildScript(
GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
EjbJarProject.class.getResource("resources/build-impl.xsl"), true);
}
genFilesHelper.refreshBuildScript(
getBuildXmlName(),
EjbJarProject.class.getResource("resources/build.xsl"), // NOI18N
true);
String servInstID = getProperty(AntProjectHelper.PRIVATE_PROPERTIES_PATH, EjbJarProjectProperties.J2EE_SERVER_INSTANCE);
String serverType = null;
J2eePlatform platform = Deployment.getDefault().getJ2eePlatform(servInstID);
if (platform != null) {
// updates j2ee.platform.cp & wscompile.cp & reg. j2ee platform listener
EjbJarProjectProperties.setServerInstance(EjbJarProject.this, EjbJarProject.this.helper, servInstID);
} else {
// if there is some server instance of the type which was used
// previously do not ask and use it
serverType = getProperty(AntProjectHelper.PROJECT_PROPERTIES_PATH, EjbJarProjectProperties.J2EE_SERVER_TYPE);
if (serverType != null) {
String instanceID = J2EEProjectProperties.getMatchingInstance(serverType, Type.EJB, EjbJarProject.this.getAPIEjbJar().getJ2eeProfile());
if (instanceID != null) {
EjbJarProjectProperties.setServerInstance(EjbJarProject.this, EjbJarProject.this.helper, instanceID);
platform = Deployment.getDefault().getJ2eePlatform(instanceID);
}
}
if (platform == null) {
BrokenServerSupport.showAlert();
}
}
// UI Logging
Utils.logUI(NbBundle.getBundle(EjbJarProject.class), "UI_EJB_PROJECT_OPENED", // NOI18N
new Object[] {(serverType != null ? serverType : Deployment.getDefault().getServerID(servInstID)), servInstID});
String serverName = ""; // NOI18N
try {
if (servInstID != null) {
serverName = Deployment.getDefault().getServerInstance(servInstID).getServerDisplayName();
}
}
catch (InstanceRemovedException ier) {
// ignore
}
Profile profile = EjbJarProject.this.getEjbModule().getJ2eeProfile();
Utils.logUsage(EjbJarProject.class, "USG_PROJECT_OPEN_EJB", new Object[] { serverName, profile }); // NOI18N
} catch (IOException e) {
LOGGER.log(Level.INFO, null, e);
}
// register project's classpaths to GlobalPathRegistry;
GlobalPathRegistry.getDefault().register(ClassPath.BOOT, cpProvider.getProjectClassPaths(ClassPath.BOOT));
GlobalPathRegistry.getDefault().register(ClassPath.SOURCE, cpProvider.getProjectClassPaths(ClassPath.SOURCE));
GlobalPathRegistry.getDefault().register(ClassPath.COMPILE, cpProvider.getProjectClassPaths(ClassPath.COMPILE));
// initialize the server configuration
// it MUST BE called AFTER classpaths are registered to GlobalPathRegistry!
// EJB DDProvider (used here) needs classpath set correctly when resolving Java Extents for annotations
ejbModule.getConfigSupport().ensureConfigurationReady();
try {
getProjectDirectory().getFileSystem().runAtomicAction(new AtomicAction() {
@Override
public void run() throws IOException {
ProjectManager.mutex().writeAccess(new Runnable() {
@Override
public void run() {
updateProject();
}
});
}
});
} catch (IOException e) {
LOGGER.log(Level.INFO, null, e);
}
String compileOnSave = getProperty(AntProjectHelper.PROJECT_PROPERTIES_PATH, EjbJarProjectProperties.J2EE_COMPILE_ON_SAVE);
if (Boolean.parseBoolean(compileOnSave)) {
Deployment.getDefault().enableCompileOnSaveSupport(ejbModule);
}
artifactSupport.enableArtifactSynchronization(true);
if (logicalViewProvider != null && logicalViewProvider.hasBrokenLinks()) {
ProjectProblems.showAlert(EjbJarProject.this);
}
if(apiWebServicesSupport.isBroken(EjbJarProject.this)) {
apiWebServicesSupport.showBrokenAlert(EjbJarProject.this);
}
else if(WebServicesClientSupport.isBroken(EjbJarProject.this)) {
WebServicesClientSupport.showBrokenAlert(EjbJarProject.this);
}
}
private void updateProject() {
// Make it easier to run headless builds on the same machine at least.
EditableProperties ep = helper.getProperties(AntProjectHelper.PRIVATE_PROPERTIES_PATH);
ep.setProperty("netbeans.user", System.getProperty("netbeans.user"));
//remove jaxws.endorsed.dir property
ep.remove("jaxws.endorsed.dir");
// #134642 - use Ant task from copylibs library
SharabilityUtility.makeSureProjectHasCopyLibsLibrary(helper, refHelper);
//update lib references in project properties
EditableProperties props = updateHelper.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH);
if (props.getProperty(EjbJarProjectProperties.J2EE_DEPLOY_ON_SAVE) == null) {
String server = evaluator().getProperty(EjbJarProjectProperties.J2EE_SERVER_INSTANCE);
props.setProperty(EjbJarProjectProperties.J2EE_DEPLOY_ON_SAVE,
server == null ? "false" : DeployOnSaveUtils.isDeployOnSaveSupported(server));
}
if (props.getProperty(EjbJarProjectProperties.J2EE_COMPILE_ON_SAVE) == null) {
props.setProperty(EjbJarProjectProperties.J2EE_COMPILE_ON_SAVE,
props.getProperty(EjbJarProjectProperties.J2EE_DEPLOY_ON_SAVE));
}
J2EEProjectProperties.removeObsoleteLibraryLocations(ep);
J2EEProjectProperties.removeObsoleteLibraryLocations(props);
if (!props.containsKey(ProjectProperties.INCLUDES)) {
props.setProperty(ProjectProperties.INCLUDES, "**"); // NOI18N
}
if (!props.containsKey(ProjectProperties.EXCLUDES)) {
props.setProperty(ProjectProperties.EXCLUDES, ""); // NOI18N
}
if (!props.containsKey("build.generated.sources.dir")) { // NOI18N
props.setProperty("build.generated.sources.dir", "${build.dir}/generated-sources"); // NOI18N
}
if (!props.containsKey(ProjectProperties.ANNOTATION_PROCESSING_ENABLED))props.setProperty(ProjectProperties.ANNOTATION_PROCESSING_ENABLED, "true"); //NOI18N
if (!props.containsKey(ProjectProperties.ANNOTATION_PROCESSING_ENABLED_IN_EDITOR))props.setProperty(ProjectProperties.ANNOTATION_PROCESSING_ENABLED_IN_EDITOR, "true"); //NOI18N
if (!props.containsKey(ProjectProperties.ANNOTATION_PROCESSING_RUN_ALL_PROCESSORS))props.setProperty(ProjectProperties.ANNOTATION_PROCESSING_RUN_ALL_PROCESSORS, "true"); //NOI18N
if (!props.containsKey(ProjectProperties.ANNOTATION_PROCESSING_PROCESSORS_LIST))props.setProperty(ProjectProperties.ANNOTATION_PROCESSING_PROCESSORS_LIST, ""); //NOI18N
if (!props.containsKey(ProjectProperties.ANNOTATION_PROCESSING_SOURCE_OUTPUT))props.setProperty(ProjectProperties.ANNOTATION_PROCESSING_SOURCE_OUTPUT, "${build.generated.sources.dir}/ap-source-output"); //NOI18N
if (!props.containsKey(ProjectProperties.JAVAC_PROCESSORPATH))props.setProperty(ProjectProperties.JAVAC_PROCESSORPATH,"${" + ProjectProperties.JAVAC_CLASSPATH + "}"); //NOI18N
if (!props.containsKey("javac.test.processorpath"))props.setProperty("javac.test.processorpath", "${" + ProjectProperties.JAVAC_TEST_CLASSPATH + "}"); // NOI18N
updateHelper.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH, props);
helper.putProperties(AntProjectHelper.PRIVATE_PROPERTIES_PATH, ep);
// update a dual build directory project to use a single build directory
ep = updateHelper.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH);
String earBuildDir = ep.getProperty(EjbJarProjectProperties.BUILD_EAR_CLASSES_DIR);
if (null != earBuildDir) {
// there is an BUILD_EAR_CLASSES_DIR property... we may
// need to change its value
String buildDir = ep.getProperty(ProjectProperties.BUILD_CLASSES_DIR);
if (null != buildDir) {
// there is a value that we may need to change the
// BUILD_EAR_CLASSES_DIR property value to match.
if (!buildDir.equals(earBuildDir)) {
// the values do not match... update the property and save it
ep.setProperty(EjbJarProjectProperties.BUILD_EAR_CLASSES_DIR,
buildDir);
updateHelper.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH,
ep);
}
// else {
// the values match and we don't need to do anything
// }
}
// else {
// the project doesn't have a BUILD_CLASSES_DIR property
// ** This is not an expected state, but if the project
// properties evolve, this property may go away...
// }
}
// else {
// there isn't a BUILD_EAR_CLASSES_DIR in this project...
// so we should not create one, by setting it.
// }
try {
ProjectManager.getDefault().saveProject(EjbJarProject.this);
} catch (IOException e) {
Exceptions.printStackTrace(e);
}
}
@Override
protected void projectClosed() {
evaluator().removePropertyChangeListener(EjbJarProject.this.ejbModule);
// unregister j2ee platform classpath change listener
/*EjbJarProjectProperties wpp = getEjbJarProjectProperties();
String servInstID = (String)wpp.get(EjbJarProjectProperties.J2EE_SERVER_INSTANCE);*/
String servInstID = getProperty(AntProjectHelper.PRIVATE_PROPERTIES_PATH, EjbJarProjectProperties.J2EE_SERVER_INSTANCE);
J2eePlatform platform = Deployment.getDefault().getJ2eePlatform(servInstID);
if (platform != null) {
unregisterJ2eePlatformListener(platform);
}
// Probably unnecessary, but just in case:
try {
ProjectManager.getDefault().saveProject(EjbJarProject.this);
} catch (IOException e) {
Exceptions.printStackTrace(e);
}
// Unregister copy on save support
try {
css.cleanup();
}
catch (FileStateInvalidException e) {
LOGGER.log(Level.INFO, null, e);
}
artifactSupport.enableArtifactSynchronization(false);
Deployment.getDefault().disableCompileOnSaveSupport(ejbModule);
// unregister project's classpaths to GlobalPathRegistry
GlobalPathRegistry.getDefault().unregister(ClassPath.BOOT, cpProvider.getProjectClassPaths(ClassPath.BOOT));
GlobalPathRegistry.getDefault().unregister(ClassPath.SOURCE, cpProvider.getProjectClassPaths(ClassPath.SOURCE));
GlobalPathRegistry.getDefault().unregister(ClassPath.COMPILE, cpProvider.getProjectClassPaths(ClassPath.COMPILE));
}
}
/**
* Exports the main JAR as an official build product for use from other scripts.
* The type of the artifact will be {@link AntArtifact#TYPE_JAR}.
*/
private final class AntArtifactProviderImpl implements AntArtifactProvider {
@Override
public AntArtifact[] getBuildArtifacts() {
return new AntArtifact[] {
helper.createSimpleAntArtifact(JavaProjectConstants.ARTIFACT_TYPE_JAR, "dist.jar", helper.getStandardPropertyEvaluator(), "dist", "clean"), // NOI18N
helper.createSimpleAntArtifact(EjbProjectConstants.ARTIFACT_TYPE_EJBJAR, "dist.jar", helper.getStandardPropertyEvaluator(), "dist", "clean"), // NOI18N
helper.createSimpleAntArtifact(EjbProjectConstants.ARTIFACT_TYPE_J2EE_MODULE_IN_EAR_ARCHIVE, "dist.ear.jar", helper.getStandardPropertyEvaluator(), "dist-ear", "clean-ear") // NOI18N
};
}
}
private class DeployOnSaveSupportProxy implements DeployOnSaveSupport {
@Override
public synchronized void addArtifactListener(ArtifactListener listener) {
css.addArtifactListener(listener);
artifactSupport.addArtifactListener(listener);
}
@Override
public synchronized void removeArtifactListener(ArtifactListener listener) {
css.removeArtifactListener(listener);
artifactSupport.removeArtifactListener(listener);
}
@Override
public boolean containsIdeArtifacts() {
return DeployOnSaveUtils.containsIdeArtifacts(eval, updateHelper, "build.classes.dir");
}
}
/**
* This class handle copying of meta-inf resources to appropriate place in build
* dir. This class is used in true Deploy On Save.
*
* Class should not request project lock from FS listener methods
* (deadlock prone).
*/
public class CopyOnSaveSupport extends FileChangeAdapter implements PropertyChangeListener {
private static final String META_INF_FOLDER = "META-INF";
private FileObject metaBase = null;
private String metaBaseValue = null;
private File resources = null;
private String buildClasses = null;
private final List<ArtifactListener> listeners = new CopyOnWriteArrayList<ArtifactListener>();
/** Creates a new instance of CopyOnSaveSupport */
public CopyOnSaveSupport() {
super();
}
public void addArtifactListener(ArtifactListener listener) {
listeners.add(listener);
}
public void removeArtifactListener(ArtifactListener listener) {
listeners.remove(listener);
}
private boolean isCopyOnSaveEnabled() {
return Boolean.parseBoolean(EjbJarProject.this.evaluator().getProperty(EjbJarProjectProperties.J2EE_COMPILE_ON_SAVE));
}
public void initialize() throws FileStateInvalidException {
EjbJarProject.this.evaluator().addPropertyChangeListener(this);
if (!isCopyOnSaveEnabled()) {
return;
}
metaBase = getEjbModule().getMetaInf();
metaBaseValue = evaluator().getProperty(EjbJarProjectProperties.META_INF);
if (resources != null) {
FileUtil.removeFileChangeListener(this, resources);
}
resources = getEjbModule().getResourceDirectory();
buildClasses = evaluator().getProperty(ProjectProperties.BUILD_CLASSES_DIR);
if (metaBase != null) {
metaBase.getFileSystem().addFileChangeListener(this);
}
if (resources != null) {
FileUtil.addFileChangeListener(this, resources);
}
LOGGER.log(Level.FINE, "Meta directory is {0}", metaBaseValue);
}
public void cleanup() throws FileStateInvalidException {
if (metaBase != null) {
metaBase.getFileSystem().removeFileChangeListener(this);
}
if (resources != null) {
FileUtil.removeFileChangeListener(this, resources);
resources = null;
}
EjbJarProject.this.evaluator().removePropertyChangeListener(this);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (EjbJarProjectProperties.META_INF.equals(evt.getPropertyName())
|| EjbJarProjectProperties.J2EE_COMPILE_ON_SAVE.equals(evt.getPropertyName())
|| EjbJarProjectProperties.RESOURCE_DIR.equals(evt.getPropertyName())) {
try {
cleanup();
initialize();
} catch (org.openide.filesystems.FileStateInvalidException e) {
LOGGER.log(Level.INFO, null, e);
}
} else if (ProjectProperties.BUILD_CLASSES_DIR.equals(evt.getPropertyName())) {
// TODO copy all files ?
Object value = evt.getNewValue();
buildClasses = value == null ? null : value.toString();
}
}
@Override
public void fileChanged(FileEvent fe) {
try {
if (!handleResource(fe)) {
handleCopyFileToDestDir(fe.getFile());
}
} catch (IOException e) {
LOGGER.log(Level.INFO, null, e);
}
}
@Override
public void fileFolderCreated(FileEvent fe) {
try {
if (!handleResource(fe)) {
handleCopyFileToDestDir(fe.getFile());
}
} catch (IOException e) {
LOGGER.log(Level.INFO, null, e);
}
}
@Override
public void fileDataCreated(FileEvent fe) {
try {
if (!handleResource(fe)) {
handleCopyFileToDestDir(fe.getFile());
}
} catch (IOException e) {
LOGGER.log(Level.INFO, null, e);
}
}
@Override
public void fileRenamed(FileRenameEvent fe) {
try {
if (handleResource(fe)) {
return;
}
FileObject fo = fe.getFile();
FileObject metaBase = getEjbModule().resolveMetaInf(metaBaseValue);
if (metaBase != null && FileUtil.isParentOf(metaBase, fo)) {
// inside docbase
handleCopyFileToDestDir(fo);
FileObject parent = fo.getParent();
String path;
if (FileUtil.isParentOf(metaBase, parent)) {
path = META_INF_FOLDER + "/" + FileUtil.getRelativePath(metaBase, fo.getParent()) +
"/" + fe.getName() + "." + fe.getExt();
} else {
path = META_INF_FOLDER + "/" + fe.getName() + "." + fe.getExt();
}
if (!isSynchronizationAppropriate(path)) {
return;
}
handleDeleteFileInDestDir(path);
}
} catch (IOException e) {
LOGGER.log(Level.INFO, null, e);
}
}
@Override
public void fileDeleted(FileEvent fe) {
try {
if (handleResource(fe)) {
return;
}
FileObject fo = fe.getFile();
FileObject metaBase = getEjbModule().resolveMetaInf(metaBaseValue);
if (metaBase != null && FileUtil.isParentOf(metaBase, fo)) {
// inside docbase
String path = META_INF_FOLDER + "/" + FileUtil.getRelativePath(metaBase, fo); // NOI18N
if (!isSynchronizationAppropriate(path)) {
return;
}
handleDeleteFileInDestDir(path);
}
} catch (IOException e) {
LOGGER.log(Level.INFO, null, e);
}
}
private boolean isSynchronizationAppropriate(String filePath) {
return true;
}
private void fireArtifactChange(Iterable<ArtifactListener.Artifact> files) {
for (ArtifactListener listener : listeners) {
listener.artifactsUpdated(files);
}
}
private boolean handleResource(FileEvent fe) {
// this may happen in broken project - see issue #191516
// in any case it can't be resource event when resources is null
if (resources == null) {
return false;
}
FileObject resourceFo = FileUtil.toFileObject(resources);
if (resourceFo != null
&& (resourceFo.equals(fe.getFile()) || FileUtil.isParentOf(resourceFo, fe.getFile()))) {
fireArtifactChange(Collections.singleton(
Artifact.forFile(FileUtil.toFile(fe.getFile())).serverResource()));
return true;
}
return false;
}
private void handleDeleteFileInDestDir(String resourcePath) throws IOException {
File deleted = null;
FileObject ejbBuildBase = buildClasses == null ? null : helper.resolveFileObject(buildClasses);
if (ejbBuildBase != null) {
// project was built
FileObject toDelete = ejbBuildBase.getFileObject(resourcePath);
if (toDelete != null) {
deleted = FileUtil.toFile(toDelete);
toDelete.delete();
}
if (deleted != null) {
fireArtifactChange(Collections.singleton(ArtifactListener.Artifact.forFile(deleted)));
}
}
}
private void handleCopyFileToDestDir(FileObject fo) throws IOException {
if (fo.isVirtual()) {
return;
}
FileObject metaBase = getEjbModule().resolveMetaInf(metaBaseValue);
if (metaBase != null && FileUtil.isParentOf(metaBase, fo)) {
// inside docbase
String path = META_INF_FOLDER + "/" + FileUtil.getRelativePath(metaBase, fo); // NOI18N
if (!isSynchronizationAppropriate(path)) {
return;
}
FileObject ejbBuildBase = buildClasses == null ? null : helper.resolveFileObject(buildClasses);
if (ejbBuildBase != null) {
// project was built
if (FileUtil.isParentOf(metaBase, ejbBuildBase) || FileUtil.isParentOf(ejbBuildBase, metaBase)) {
//cannot copy into self
return;
}
FileObject destFile = ensureDestinationFileExists(ejbBuildBase, path, fo.isFolder());
if (!fo.isFolder()) {
InputStream is = null;
OutputStream os = null;
FileLock fl = null;
try {
is = fo.getInputStream();
fl = destFile.lock();
os = destFile.getOutputStream(fl);
FileUtil.copy(is, os);
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (fl != null) {
fl.releaseLock();
}
File file = FileUtil.toFile(destFile);
if (file != null) {
fireArtifactChange(Collections.singleton(ArtifactListener.Artifact.forFile(file)));
}
}
} else {
File file = FileUtil.toFile(destFile);
if (file != null) {
fireArtifactChange(Collections.singleton(ArtifactListener.Artifact.forFile(file)));
}
}
}
}
}
/**
* Returns the destination (parent) directory needed to create file
* with relative path path under ejbBuilBase.
*/
private FileObject ensureDestinationFileExists(FileObject ejbBuildBase, String path, boolean isFolder) throws IOException {
FileObject current = ejbBuildBase;
StringTokenizer st = new StringTokenizer(path, "/");
while (st.hasMoreTokens()) {
String pathItem = st.nextToken();
FileObject newCurrent = current.getFileObject(pathItem);
if (newCurrent == null) {
// need to create it
if (isFolder || st.hasMoreTokens()) {
// create a folder
newCurrent = FileUtil.createFolder(current, pathItem);
assert newCurrent != null : "ejbBuildBase: " + ejbBuildBase + ", path: " + path + ", isFolder: " + isFolder;
} else {
newCurrent = FileUtil.createData(current, pathItem);
assert newCurrent != null : "ejbBuildBase: " + ejbBuildBase + ", path: " + path + ", isFolder: " + isFolder;
}
}
current = newCurrent;
}
assert current != null : "ejbBuildBase: " + ejbBuildBase + ", path: " + path + ", isFolder: " + isFolder;
return current;
}
}
private class ArtifactCopySupport extends ArtifactCopyOnSaveSupport {
public ArtifactCopySupport() {
super("build.classes.dir", evaluator(), getAntProjectHelper()); // NOI18N
}
@Override
public List<ArtifactCopyOnSaveSupport.Item> getArtifacts() {
final AntProjectHelper helper = getAntProjectHelper();
ClassPathSupport cs = new ClassPathSupport(evaluator(), getReferenceHelper(), helper,
getUpdateHelper(), new ClassPathSupportCallbackImpl(helper));
List<ArtifactCopyOnSaveSupport.Item> result = new ArrayList<ArtifactCopyOnSaveSupport.Item>();
for (ClassPathSupport.Item item : cs.itemsList(
helper.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH).getProperty(ProjectProperties.JAVAC_CLASSPATH),
ClassPathSupportCallbackImpl.ELEMENT_INCLUDED_LIBRARIES)) {
if (!item.isBroken() && (item.getType() == ClassPathSupport.Item.TYPE_ARTIFACT
|| item.getType() == ClassPathSupport.Item.TYPE_LIBRARY
|| item.getType() == ClassPathSupport.Item.TYPE_LIBRARY)) {
String included = item.getAdditionalProperty(ClassPathSupportCallbackImpl.INCLUDE_IN_DEPLOYMENT);
String dirs = item.getAdditionalProperty(AntProjectConstants.DESTINATION_DIRECTORY);
if (Boolean.parseBoolean(included)) {
result.add(new Item(item,
new ItemDescription("", RelocationType.fromString(dirs))));
}
}
}
return result;
}
@Override
protected Artifact filterArtifact(Artifact artifact, RelocationType type) {
if (type == RelocationType.ROOT) {
return artifact.relocatable();
} else if (type == RelocationType.LIB) {
return artifact.relocatable("lib"); // NOI18N
}
return artifact;
}
}
// List of primarily supported templates
private static final String[] TYPES = new String[] {
"java-classes", // NOI18N
"ejb-deployment-descriptor",// NOI18N
"ejb-types_2_1", // NOI18N
"ejb-types", // NOI18N
"ejb-types-server", // NOI18N
"web-services", // NOI18N
"message-handler", // NOI18N
"wsdl", // NOI18N
"j2ee-14-types", // NOI18N
"j2ee-types", // NOI18N
"java-beans", // NOI18N
"java-main-class", // NOI18N
"persistence", // NOI18N
"oasis-XML-catalogs", // NOI18N
"XML", // NOI18N
"ant-script", // NOI18N
"ant-task", // NOI18N
"junit", // NOI18N
"simple-files" // NOI18N
};
/**
* Supported template categories for Java EE 5 projects.
*/
private static final String[] JAVAEE5_TYPES = new String[] {
"java-classes", // NOI18N
"ejb-deployment-descriptor",// NOI18N
"ejb-types", // NOI18N
"ejb-types-server", // NOI18N
"ejb-types_3_0", // NOI18N
"web-services", // NOI18N
"web-service-clients", // NOI18N
"wsdl", // NOI18N
"j2ee-types", // NOI18N
"java-beans", // NOI18N
"java-main-class", // NOI18N
"persistence", // NOI18N
"oasis-XML-catalogs", // NOI18N
"XML", // NOI18N
"ant-script", // NOI18N
"ant-task", // NOI18N
"junit", // NOI18N
"simple-files" // NOI18N
};
/**
* Supported template categories for Java EE 6 projects (full?).
*/
private static final String[] JAVAEE6_TYPES = new String[] {
"java-classes", // NOI18N
"ejb-deployment-descriptor",// NOI18N
"ejb-types", // NOI18N
"ejb-types-server", // NOI18N
"ejb-types_3_1", // NOI18N
"ejb-types_3_1_full", // NOI18N
"web-services", // NOI18N
"web-service-clients", // NOI18N
"wsdl", // NOI18N
"j2ee-types", // NOI18N
"java-beans", // NOI18N
"java-main-class", // NOI18N
"persistence", // NOI18N
"oasis-XML-catalogs", // NOI18N
"XML", // NOI18N
"ant-script", // NOI18N
"ant-task", // NOI18N
"junit", // NOI18N
"simple-files" // NOI18N
};
/**
* Supported template categories for archive projects.
*/
private static final String[] ARCHIVE_TYPES = new String[] {
"ejb-deployment-descriptor", // NOI18N
"deployment-descriptor", // NOI18N
"XML", // NOI18N
};
private static final String[] PRIVILEGED_NAMES = new String[] {
"Templates/J2EE/Session", // NOI18N
"Templates/J2EE/TimerSession", // NOI18N
"Templates/J2EE/Entity", // NOI18N
"Templates/J2EE/RelatedCMP", // NOI18N
"Templates/J2EE/Message", //NOI18N
"Templates/Classes/Class.java", // NOI18N
"Templates/Classes/Package", // NOI18N
"Templates/WebServices/WebService.java", // NOI18N
"Templates/WebServices/MessageHandler" // NOI18N
};
private static final String[] PRIVILEGED_NAMES_EE5 = new String[] {
"Templates/J2EE/Session", // NOI18N
"Templates/J2EE/Message", // NOI18N
"Templates/Classes/Class.java", // NOI18N
"Templates/Classes/Package", // NOI18N
"Templates/Persistence/Entity.java", // NOI18N
"Templates/Persistence/RelatedCMP", // NOI18N
"Templates/WebServices/WebService.java", // NOI18N
"Templates/WebServices/WebServiceClient" // NOI18N
};
private static final String[] PRIVILEGED_NAMES_EE6 = new String[] {
"Templates/J2EE/TimerSession" // NOI18N
};
private static final String[] PRIVILEGED_NAMES_ARCHIVE = new String[] {
"Templates/J2EE/ejbJarXml", // NOI18N
};
private final class RecommendedTemplatesImpl implements RecommendedTemplates, PrivilegedTemplates {
private transient boolean isEE5 = false;
private transient boolean isEE6Plus = false;//if project support ee6 full version or above
private transient boolean checked = false;
private transient boolean isArchive = false;
private transient UpdateHelper helper = null;
RecommendedTemplatesImpl(UpdateHelper helper) {
this.helper = helper;
}
@Override
public String[] getRecommendedTypes() {
checkEnvironment();
String[] retVal = null;
if (isArchive) {
retVal = ARCHIVE_TYPES;
} else if (isEE5) {
retVal = JAVAEE5_TYPES;
} else if (isEE6Plus) {
retVal = JAVAEE6_TYPES;
} else {
retVal = TYPES;
}
return retVal;
}
@Override
public String[] getPrivilegedTemplates() {
checkEnvironment();
List<String> privileged = new ArrayList<String>();
if (isArchive) {
privileged.addAll(Arrays.asList(PRIVILEGED_NAMES_ARCHIVE));
} else if (isEE5) {
privileged.addAll(Arrays.asList(PRIVILEGED_NAMES_EE5));
} else if (isEE6Plus) {
privileged.addAll(Arrays.asList(PRIVILEGED_NAMES_EE5));
privileged.addAll(Arrays.asList(PRIVILEGED_NAMES_EE6));
} else {
privileged.addAll(Arrays.asList(PRIVILEGED_NAMES));
}
return privileged.toArray(new String[privileged.size()]);
}
private void checkEnvironment() {
if (!checked) {
Profile version=Profile.fromPropertiesString(evaluator().getProperty(EjbJarProjectProperties.J2EE_PLATFORM));
isEE5 = Profile.JAVA_EE_5==version;
isEE6Plus = version.isAtLeast(Profile.JAVA_EE_6_WEB);
final Object srcType = helper.getAntProjectHelper().
getStandardPropertyEvaluator().getProperty(EjbJarProjectProperties.JAVA_SOURCE_BASED);
if ("false".equals(srcType)) {
isArchive = true;
}
checked = true;
}
}
}
// FIXME this is just fallback for code searching for the old SPI in lookup
// remove in next release
@SuppressWarnings("deprecation")
private static class EjbJarImpl implements EjbJarImplementation {
private final EjbJar apiModule;
public EjbJarImpl(EjbJar apiModule) {
this.apiModule = apiModule;
}
@Override
public FileObject getDeploymentDescriptor() {
return apiModule.getDeploymentDescriptor();
}
@Override
public String getJ2eePlatformVersion() {
return apiModule.getJ2eePlatformVersion();
}
@Override
public FileObject[] getJavaSources() {
return apiModule.getJavaSources();
}
@Override
public FileObject getMetaInf() {
return apiModule.getMetaInf();
}
@Override
public MetadataModel<EjbJarMetadata> getMetadataModel() {
return apiModule.getMetadataModel();
}
}
private static class EjbJarImpl2 implements EjbJarImplementation2 {
private final EjbJarProvider provider;
public EjbJarImpl2(EjbJarProvider provider) {
this.provider = provider;
}
@Override
public FileObject getDeploymentDescriptor() {
return provider.getDeploymentDescriptor();
}
@Override
public Profile getJ2eeProfile() {
return provider.getJ2eeProfile();
}
@Override
public FileObject[] getJavaSources() {
return provider.getJavaSources();
}
@Override
public FileObject getMetaInf() {
return provider.getMetaInf();
}
@Override
public MetadataModel<EjbJarMetadata> getMetadataModel() {
return provider.getMetadataModel();
}
}
private class EjbExtenderImplementation implements AntBuildExtenderImplementation {
//add targets here as required by the external plugins..
@Override
public List<String> getExtensibleTargets() {
String[] targets = new String[] {
"-do-init", "-init-check", "-post-clean", "jar", "-pre-pre-compile","-do-compile","-do-compile-single", "-pre-dist" //NOI18N
};
return Arrays.asList(targets);
}
@Override
public Project getOwningProject() {
return EjbJarProject.this;
}
}
private final class WhiteListUpdaterImpl extends WhiteListUpdater {
public WhiteListUpdaterImpl(Project project) {
super(project);
}
@Override
public void addSettingListener() {
evaluator().addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(JavaEEProjectSettingConstants.J2EE_SERVER_INSTANCE)){
checkWhiteLists();
}
if (evt.getPropertyName().equals(ProjectProperties.JAVAC_CLASSPATH)){
// if classpath changes refresh whitelists as well:
updateWhitelist(null, getServerWhiteList());
}
}
});
}
}
private class JavaEEProjectSettingsImpl implements JavaEEProjectSettingsImplementation {
private final EjbJarProject project;
public JavaEEProjectSettingsImpl(EjbJarProject project) {
this.project = project;
}
@Override
public void setProfile(Profile profile) {
setInSharedProperties(JavaEEProjectSettingConstants.J2EE_PLATFORM, profile.toPropertiesString());
}
@Override
public Profile getProfile() {
return ejbModule.getJ2eeProfile();
}
@Override
public void setBrowserID(String browserID) {
// Does not make sense for EJB project - simply do nothing
}
@Override
public String getBrowserID() {
// Does not make sense for EJB project - simply do nothing
return null;
}
@Override
public void setServerInstanceID(String serverInstanceID) {
setInPrivateProperties(JavaEEProjectSettingConstants.J2EE_SERVER_INSTANCE, serverInstanceID);
}
@Override
public String getServerInstanceID() {
return evaluator().getProperty(JavaEEProjectSettingConstants.J2EE_SERVER_INSTANCE);
}
private void setInSharedProperties(String key, String value) {
setInProperties(key, value, AntProjectHelper.PROJECT_PROPERTIES_PATH);
}
private void setInPrivateProperties(String key, String value) {
setInProperties(key, value, AntProjectHelper.PRIVATE_PROPERTIES_PATH);
}
private void setInProperties(String key, String value, String propertiesPath) {
try {
UpdateHelper helper = project.getUpdateHelper();
EditableProperties projectProperties = helper.getProperties(propertiesPath);
projectProperties.setProperty(key, value);
helper.putProperties(propertiesPath, projectProperties);
ProjectManager.getDefault().saveProject(project);
} catch (IOException ex) {
LOGGER.log(Level.WARNING, "Project properties couldn't be saved.", ex);
}
}
}
}
|
UTF-8
|
Java
| 82,796 |
java
|
EjbJarProject.java
|
Java
|
[
{
"context": "**\n * Represents one ejb module project\n * @author Chris Webster\n */\n@AntBasedProjectRegistration(\n iconResourc",
"end": 8536,
"score": 0.9995341300964355,
"start": 8523,
"tag": "NAME",
"value": "Chris Webster"
}
] | null |
[] |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.j2ee.ejbjarproject;
import java.awt.Dialog;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Icon;
import javax.swing.SwingUtilities;
import org.netbeans.api.java.classpath.ClassPath;
import org.netbeans.api.java.classpath.GlobalPathRegistry;
import org.netbeans.api.java.project.JavaProjectConstants;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectManager;
import org.netbeans.api.project.ant.AntArtifact;
import org.netbeans.api.project.ant.AntBuildExtender;
import org.netbeans.modules.j2ee.api.ejbjar.EjbJar;
import org.netbeans.modules.j2ee.api.ejbjar.EjbProjectConstants;
import org.netbeans.modules.j2ee.dd.api.ejb.EjbJarMetadata;
import org.netbeans.modules.j2ee.metadata.model.api.MetadataModel;
import org.netbeans.modules.j2ee.spi.ejbjar.support.EjbJarSupport;
import org.netbeans.modules.java.api.common.Roots;
import org.netbeans.modules.j2ee.deployment.devmodules.spi.ArtifactListener.Artifact;
import org.netbeans.modules.j2ee.ejbjarproject.jaxws.EjbProjectJAXWSClientSupport;
import org.netbeans.modules.j2ee.ejbjarproject.jaxws.EjbProjectJAXWSSupport;
import org.netbeans.modules.j2ee.ejbjarproject.ui.EjbJarLogicalViewProvider;
import org.netbeans.modules.j2ee.ejbjarproject.ui.customizer.EjbJarProjectProperties;
import org.netbeans.api.project.SourceGroup;
import org.netbeans.modules.j2ee.common.SharabilityUtility;
import org.netbeans.modules.javaee.project.api.ant.ArtifactCopyOnSaveSupport;
import org.netbeans.modules.java.api.common.classpath.ClassPathModifier;
import org.netbeans.modules.java.api.common.classpath.ClassPathSupport;
import org.netbeans.modules.java.api.common.classpath.ClassPathProviderImpl;
import org.netbeans.modules.java.api.common.project.ui.ClassPathUiSupport;
import org.netbeans.modules.javaee.project.api.ant.DeployOnSaveUtils;
import org.netbeans.modules.javaee.project.api.ant.ui.J2EEProjectProperties;
import org.netbeans.modules.j2ee.common.ui.BrokenServerSupport;
import org.netbeans.modules.j2ee.spi.ejbjar.EjbJarFactory;
import org.netbeans.modules.j2ee.spi.ejbjar.support.EjbEnterpriseReferenceContainerSupport;
import org.netbeans.modules.websvc.api.jaxws.client.JAXWSClientSupport;
import org.netbeans.modules.websvc.jaxws.api.JAXWSSupport;
import org.netbeans.modules.websvc.jaxws.spi.JAXWSSupportFactory;
import org.netbeans.modules.websvc.spi.client.WebServicesClientSupportFactory;
import org.netbeans.modules.websvc.spi.jaxws.client.JAXWSClientSupportFactory;
import org.netbeans.spi.project.SubprojectProvider;
import org.netbeans.spi.project.ant.AntArtifactProvider;
import org.netbeans.spi.project.ant.AntBuildExtenderFactory;
import org.netbeans.spi.project.ant.AntBuildExtenderImplementation;
import org.netbeans.spi.project.support.ant.AntProjectHelper;
import org.netbeans.spi.project.support.ant.GeneratedFilesHelper;
import org.netbeans.spi.project.support.ant.ProjectXmlSavedHook;
import org.netbeans.spi.project.ui.PrivilegedTemplates;
import org.netbeans.spi.project.ui.RecommendedTemplates;
import org.netbeans.spi.project.support.ant.ReferenceHelper;
import org.netbeans.spi.project.support.ant.PropertyEvaluator;
import org.netbeans.spi.project.ui.ProjectOpenedHook;
import org.openide.filesystems.FileChangeListener;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.lookup.Lookups;
import org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment;
import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eePlatform;
import org.netbeans.modules.j2ee.ejbjarproject.classpath.ClassPathSupportCallbackImpl;
import org.netbeans.modules.j2ee.ejbjarproject.ui.BrokenReferencesAlertPanel;
import org.netbeans.modules.javaee.project.api.ui.UserProjectSettings;
import org.netbeans.modules.j2ee.deployment.devmodules.api.InstanceRemovedException;
import org.netbeans.api.j2ee.core.Profile;
import org.netbeans.api.java.platform.JavaPlatform;
import org.netbeans.api.java.project.classpath.ProjectClassPathModifier;
import org.netbeans.api.project.ProjectUtils;
import org.netbeans.api.project.ui.ProjectProblems;
import org.netbeans.modules.javaee.project.api.PersistenceProviderSupplierImpl;
import org.netbeans.modules.javaee.project.api.ant.AntProjectConstants;
import org.netbeans.modules.j2ee.common.ServerUtil;
import org.netbeans.modules.javaee.project.api.WhiteListUpdater;
import org.netbeans.modules.javaee.project.spi.JavaEEProjectSettingsImplementation;
import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eeModule.Type;
import org.netbeans.modules.j2ee.deployment.devmodules.spi.ArtifactListener;
import org.netbeans.modules.j2ee.deployment.devmodules.spi.J2eeModuleProvider.DeployOnSaveSupport;
import org.netbeans.modules.j2ee.ejbjarproject.ui.customizer.CustomizerProviderImpl;
import org.netbeans.modules.j2ee.persistence.spi.entitymanagergenerator.EntityManagerGenerationStrategyResolverFactory;
import org.netbeans.modules.j2ee.spi.ejbjar.EjbJarImplementation;
import org.netbeans.modules.j2ee.spi.ejbjar.EjbJarImplementation2;
import org.netbeans.modules.java.api.common.SourceRoots;
import org.netbeans.modules.java.api.common.ant.UpdateHelper;
import org.netbeans.modules.java.api.common.ant.UpdateImplementation;
import org.netbeans.modules.java.api.common.project.ProjectProperties;
import org.netbeans.modules.java.api.common.queries.QuerySupport;
import org.netbeans.modules.javaee.project.api.JavaEEProjectSettingConstants;
import org.netbeans.modules.javaee.project.api.ant.AntProjectUtil;
import org.netbeans.modules.javaee.project.api.problems.PlatformUpdatedCallBackImpl;
import org.netbeans.spi.java.project.support.ui.BrokenReferencesSupport;
import org.netbeans.spi.project.AuxiliaryConfiguration;
import org.netbeans.spi.project.support.ant.EditableProperties;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.util.NbBundle;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.netbeans.modules.websvc.api.webservices.WebServicesSupport;
import org.netbeans.modules.websvc.api.client.WebServicesClientSupport;
import org.netbeans.modules.websvc.spi.webservices.WebServicesSupportFactory;
import org.netbeans.spi.java.project.support.ExtraSourceJavadocSupport;
import org.netbeans.spi.java.project.support.LookupMergerSupport;
import org.netbeans.spi.project.support.LookupProviderSupport;
import org.netbeans.spi.project.support.ant.AntBasedProjectRegistration;
import org.netbeans.spi.project.ui.support.UILookupMergerSupport;
import org.netbeans.spi.queries.FileEncodingQueryImplementation;
import org.netbeans.spi.whitelist.support.WhiteListQueryMergerSupport;
import org.openide.filesystems.FileChangeAdapter;
import org.openide.filesystems.FileEvent;
import org.openide.filesystems.FileLock;
import org.openide.filesystems.FileRenameEvent;
import org.openide.filesystems.FileStateInvalidException;
import org.openide.filesystems.FileSystem.AtomicAction;
import org.openide.util.Exceptions;
import org.openide.xml.XMLUtil;
/**
* Represents one ejb module project
* @author <NAME>
*/
@AntBasedProjectRegistration(
iconResource="org/netbeans/modules/j2ee/ejbjarproject/ui/resources/ejbjarProjectIcon.gif",
type=EjbJarProjectType.TYPE,
sharedNamespace=EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE,
privateNamespace=EjbJarProjectType.PRIVATE_CONFIGURATION_NAMESPACE
)
public class EjbJarProject implements Project, FileChangeListener {
private final Icon PROJECT_ICON = ImageUtilities.loadImageIcon("org/netbeans/modules/j2ee/ejbjarproject/ui/resources/ejbjarProjectIcon.gif", false); // NOI18N
private static final Logger LOGGER = Logger.getLogger(EjbJarProject.class.getName());
private final AuxiliaryConfiguration aux;
private final AntProjectHelper helper;
private final PropertyEvaluator eval;
private final ReferenceHelper refHelper;
private FileObject libFolder = null;
private final GeneratedFilesHelper genFilesHelper;
private Lookup lookup;
private final UpdateHelper updateHelper;
private final EjbJarProvider ejbModule;
private final CopyOnSaveSupport css;
private final ArtifactCopyOnSaveSupport artifactSupport;
private final DeployOnSaveSupport deployOnSaveSupport;
private final EjbJar apiEjbJar;
private WebServicesSupport apiWebServicesSupport;
private JAXWSSupport apiJaxwsSupport;
private EjbProjectJAXWSSupport jaxwsSupport;
private WebServicesClientSupport apiWebServicesClientSupport;
private JAXWSClientSupport apiJAXWSClientSupport;
private EjbJarWebServicesSupport ejbJarWebServicesSupport;
private EjbJarWebServicesClientSupport ejbJarWebServicesClientSupport;
private EjbProjectJAXWSClientSupport jaxWsClientSupport;
private SourceRoots sourceRoots;
private SourceRoots testRoots;
private final ClassPathModifier classPathModifier;
private PropertyChangeListener j2eePlatformListener;
private AntBuildExtender buildExtender;
private final ClassPathProviderImpl cpProvider;
private ClassPathUiSupport.Callback classPathUiSupportCallback;
private WhiteListUpdater whiteListUpdater;
// set to true when project customizer is being closed and changes persisted
private final ThreadLocal<Boolean> projectPropertiesSave;
// TODO: AB: replace the code in EjbJarProjectProperties.setNewServerInstanceValue with this
/*private String propJ2eeServerInstance;
private PropertyChangeListener evalListener = new PropertyChangeListener() {
public void propertyChange(final PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if (propertyName == null || propertyName.equals(EjbJarProjectProperties.J2EE_SERVER_INSTANCE)) {
org.openide.util.RequestProcessor.getDefault().post(new Runnable() {
public void run() {
ProjectManager.mutex().writeAccess(new Runnable() {
public void run() {
// try to unregister the old J2EE platform
String oldJ2eeServerInstance = null;
if (propJ2eeServerInstance != null) {
oldJ2eeServerInstance = propJ2eeServerInstance;
} else {
oldJ2eeServerInstance = (String)evt.getOldValue();
}
if (oldJ2eeServerInstance != null) {
J2eePlatform oldJ2eePlatform = Deployment.getDefault().getJ2eePlatform(oldJ2eeServerInstance);
unregisterJ2eePlatformListener(oldJ2eePlatform);
propJ2eeServerInstance = null;
}
// now register the new platform
//String newJ2eeServerInstance = (String)evt.getNewValue();
EditableProperties props = helper.getProperties(AntProjectHelper.PRIVATE_PROPERTIES_PATH);
//if (newJ2eeServerInstance == null)
String newJ2eeServerInstance = props.getProperty(EjbJarProjectProperties.J2EE_SERVER_INSTANCE);
if (newJ2eeServerInstance != null) {
J2eePlatform newJ2eePlatform = Deployment.getDefault().getJ2eePlatform(newJ2eeServerInstance);
registerJ2eePlatformListener(newJ2eePlatform);
propJ2eeServerInstance = newJ2eeServerInstance;
putJ2eePlatformClassPath(newJ2eePlatform, props);
String serverType = Deployment.getDefault().getServerID(newJ2eeServerInstance);
props.setProperty(EjbJarProjectProperties.J2EE_SERVER_TYPE, serverType);
// TODO: AB: should update wscompile classpath too
helper.putProperties(AntProjectHelper.PRIVATE_PROPERTIES_PATH, props);
try {
ProjectManager.getDefault().saveProject(EjbJarProject.this);
}
catch (IOException e) {
ErrorManager.getDefault().notify(e);
}
}
}
});
}
});
}
}
};*/
public EjbJarProject(final AntProjectHelper helper) throws IOException {
this.projectPropertiesSave = new ThreadLocal<Boolean>() {
@Override
protected Boolean initialValue() {
return Boolean.FALSE;
}
};
this.helper = helper;
eval = createEvaluator();
aux = helper.createAuxiliaryConfiguration();
refHelper = new ReferenceHelper(helper, aux, helper.getStandardPropertyEvaluator());
buildExtender = AntBuildExtenderFactory.createAntExtender(new EjbExtenderImplementation());
genFilesHelper = new GeneratedFilesHelper(helper, buildExtender);
UpdateImplementation updateProject = new UpdateProjectImpl(this, helper, aux, genFilesHelper);
this.updateHelper = new UpdateHelper(updateProject, helper);
this.cpProvider = new ClassPathProviderImpl(helper, evaluator(), getSourceRoots(), getTestSourceRoots(),
ProjectProperties.BUILD_CLASSES_DIR, EjbJarProjectProperties.DIST_JAR, ProjectProperties.BUILD_TEST_CLASSES_DIR,
new String[] {"javac.classpath", EjbJarProjectProperties.J2EE_PLATFORM_CLASSPATH }, // NOI18N
new String[] {ProjectProperties.JAVAC_PROCESSORPATH},
new String[] {"javac.test.classpath", EjbJarProjectProperties.J2EE_PLATFORM_CLASSPATH }, // NOI18N
new String[] {"debug.classpath", EjbJarProjectProperties.J2EE_PLATFORM_CLASSPATH }, // NOI18N
new String[] {"run.test.classpath", EjbJarProjectProperties.J2EE_PLATFORM_CLASSPATH },
new String[] {ProjectProperties.ENDORSED_CLASSPATH}); // NOI18N
ejbModule = new EjbJarProvider(this, helper, cpProvider);
apiEjbJar = EjbJarFactory.createEjbJar(new EjbJarImpl2(ejbModule));
ejbJarWebServicesSupport = new EjbJarWebServicesSupport(this, helper, refHelper);
jaxwsSupport = new EjbProjectJAXWSSupport(this, helper);
ejbJarWebServicesClientSupport = new EjbJarWebServicesClientSupport(this, helper, refHelper);
jaxWsClientSupport = new EjbProjectJAXWSClientSupport(this,helper);
apiWebServicesSupport = WebServicesSupportFactory.createWebServicesSupport(ejbJarWebServicesSupport);
apiJaxwsSupport = JAXWSSupportFactory.createJAXWSSupport(jaxwsSupport);
apiWebServicesClientSupport = WebServicesClientSupportFactory.createWebServicesClientSupport(ejbJarWebServicesClientSupport);
apiJAXWSClientSupport = JAXWSClientSupportFactory.createJAXWSClientSupport(jaxWsClientSupport);
classPathModifier = new ClassPathModifier(this, this.updateHelper, eval, refHelper,
new ClassPathSupportCallbackImpl(helper), createClassPathModifierCallback(),
getClassPathUiSupportCallback());
lookup = createLookup(aux, cpProvider);
css = new CopyOnSaveSupport();
artifactSupport = new ArtifactCopySupport();
deployOnSaveSupport = new DeployOnSaveSupportProxy();
ProjectManager.mutex().postWriteRequest(
new Runnable () {
@Override
public void run() {
try {
updateProjectXML ();
} catch (IOException ioe) {
LOGGER.log(Level.INFO, null, ioe);
}
}
}
);
// whitelist updater listens on project properties and pays attention to whitelist changes
whiteListUpdater = new WhiteListUpdaterImpl(this);
}
public void setProjectPropertiesSave(boolean value) {
this.projectPropertiesSave.set(value);
}
private ClassPathModifier.Callback createClassPathModifierCallback() {
return new ClassPathModifier.Callback() {
@Override
public String getClassPathProperty(SourceGroup sg, String type) {
assert sg != null : "SourceGroup cannot be null"; //NOI18N
assert type != null : "Type cannot be null"; //NOI18N
final String[] classPathProperty = getClassPathProvider().getPropertyName (sg, type);
if (classPathProperty == null || classPathProperty.length == 0) {
throw new UnsupportedOperationException ("Modification of [" + sg.getRootFolder().getPath() +", " + type + "] is not supported"); //NOI18N
}
return classPathProperty[0];
}
@Override
public String getElementName(String classpathProperty) {
if (ProjectProperties.JAVAC_CLASSPATH.equals(classpathProperty)) {
return ClassPathSupportCallbackImpl.ELEMENT_INCLUDED_LIBRARIES;
}
return null;
}
};
}
public synchronized ClassPathUiSupport.Callback getClassPathUiSupportCallback() {
if (classPathUiSupportCallback == null) {
classPathUiSupportCallback = new ClassPathUiSupport.Callback() {
@Override
public void initItem(ClassPathSupport.Item item) {
if (item.getType() != ClassPathSupport.Item.TYPE_LIBRARY || !item.getLibrary().getType().equals(J2eePlatform.LIBRARY_TYPE)) {
item.setAdditionalProperty(ClassPathSupportCallbackImpl.INCLUDE_IN_DEPLOYMENT, "true");
}
}
};
}
return classPathUiSupportCallback;
}
/**
* Returns the project directory
* @return the directory the project is located in
*/
@Override
public FileObject getProjectDirectory() {
return helper.getProjectDirectory();
}
@Override
public String toString() {
return "EjbJarProject[" + getProjectDirectory() + "]"; // NOI18N
}
private PropertyEvaluator createEvaluator() {
return helper.getStandardPropertyEvaluator();
}
public PropertyEvaluator evaluator() {
return eval;
}
public ReferenceHelper getReferenceHelper () {
return this.refHelper;
}
public UpdateHelper getUpdateHelper() {
return updateHelper;
}
@Override
public Lookup getLookup() {
return lookup;
}
public AntProjectHelper getAntProjectHelper() {
return helper;
}
public DeployOnSaveSupport getDeployOnSaveSupport() {
return deployOnSaveSupport;
}
private Lookup createLookup(AuxiliaryConfiguration aux, ClassPathProviderImpl cpProvider) {
SubprojectProvider spp = refHelper.createSubprojectProvider();
FileEncodingQueryImplementation encodingQuery = QuerySupport.createFileEncodingQuery(evaluator(), EjbJarProjectProperties.SOURCE_ENCODING);
final EjbJarLogicalViewProvider lvp = new EjbJarLogicalViewProvider(this, updateHelper, evaluator(), spp, refHelper, ejbModule);
Lookup base = Lookups.fixed(new Object[] {
EjbJarProject.this, // never cast an externally obtained Project to EjbJarProject - use lookup instead
buildExtender,
QuerySupport.createProjectInformation(helper, this, PROJECT_ICON),
aux,
helper.createCacheDirectoryProvider(),
helper.createAuxiliaryProperties(),
new ProjectWebServicesSupportProvider(), // implementation of WebServicesClientSupportProvider commented out
spp,
EjbEnterpriseReferenceContainerSupport.createEnterpriseReferenceContainer(this, helper),
EjbJarSupport.createEjbJarProvider(this, apiEjbJar),
EjbJarSupport.createEjbJarsInProject(apiEjbJar),
ejbModule, //implements J2eeModuleProvider
// FIXME this is just fallback for code searching for the old SPI in lookup
// remove in next release
new EjbJarImpl(apiEjbJar),
lvp,
new CustomizerProviderImpl( this, updateHelper, evaluator(), refHelper ),
LookupMergerSupport.createClassPathProviderMerger(cpProvider),
QuerySupport.createCompiledSourceForBinaryQuery(helper, evaluator(), getSourceRoots(), getTestSourceRoots()),
QuerySupport.createJavadocForBinaryQuery(helper, evaluator()),
QuerySupport.createAnnotationProcessingQuery(helper, eval, ProjectProperties.ANNOTATION_PROCESSING_ENABLED, ProjectProperties.ANNOTATION_PROCESSING_ENABLED_IN_EDITOR, ProjectProperties.ANNOTATION_PROCESSING_RUN_ALL_PROCESSORS, ProjectProperties.ANNOTATION_PROCESSING_PROCESSORS_LIST, ProjectProperties.ANNOTATION_PROCESSING_SOURCE_OUTPUT, ProjectProperties.ANNOTATION_PROCESSING_PROCESSOR_OPTIONS),
new AntArtifactProviderImpl(),
new ProjectXmlSavedHookImpl(),
UILookupMergerSupport.createProjectOpenHookMerger(new ProjectOpenedHookImpl()),
QuerySupport.createUnitTestForSourceQuery(getSourceRoots(), getTestSourceRoots()),
QuerySupport.createSourceLevelQuery2(evaluator()),
QuerySupport.createSources(this, helper, evaluator(),
getSourceRoots(),
getTestSourceRoots(),
Roots.propertyBased(new String[]{EjbJarProjectProperties.META_INF}, new String[]{NbBundle.getMessage(EjbJarLogicalViewProvider.class, "LBL_Node_DocBase")}, false, null, null),
Roots.nonSourceRoots(ProjectProperties.BUILD_DIR, EjbJarProjectProperties.DIST_DIR)),
QuerySupport.createSharabilityQuery(helper, evaluator(), getSourceRoots(), getTestSourceRoots(),
EjbJarProjectProperties.META_INF),
QuerySupport.createFileBuiltQuery(helper, evaluator(), getSourceRoots(), getTestSourceRoots()),
encodingQuery,
new RecommendedTemplatesImpl(updateHelper),
refHelper,
ProjectClassPathModifier.extenderForModifier(classPathModifier),
classPathModifier,
new EjbJarProjectOperations(this),
new EjbJarPersistenceProvider(this, evaluator(), cpProvider),
new PersistenceProviderSupplierImpl(this),
EntityManagerGenerationStrategyResolverFactory.createInstance(this),
new EjbJarJPASupport(this),
ServerUtil.createServerStatusProvider(getEjbModule()),
new EjbJarJPAModuleInfo(this),
new EjbJarJPATargetInfo(this),
UILookupMergerSupport.createPrivilegedTemplatesMerger(),
UILookupMergerSupport.createRecommendedTemplatesMerger(),
LookupProviderSupport.createSourcesMerger(),
LookupProviderSupport.createActionProviderMerger(),
WhiteListQueryMergerSupport.createWhiteListQueryMerger(),
QuerySupport.createTemplateAttributesProvider(helper, encodingQuery),
ExtraSourceJavadocSupport.createExtraSourceQueryImplementation(this, helper, eval),
LookupMergerSupport.createSFBLookupMerger(),
ExtraSourceJavadocSupport.createExtraJavadocQueryImplementation(this, helper, eval),
LookupMergerSupport.createJFBLookupMerger(),
QuerySupport.createBinaryForSourceQueryImplementation(getSourceRoots(), getTestSourceRoots(), helper, eval),
new JavaEEProjectSettingsImpl(this),
BrokenReferencesSupport.createReferenceProblemsProvider(helper, refHelper, eval, lvp.getBreakableProperties(), lvp.getPlatformProperties()),
BrokenReferencesSupport.createPlatformVersionProblemProvider(helper, eval, PlatformUpdatedCallBackImpl.create(EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE, updateHelper), JavaPlatform.getDefault().getSpecification().getName(), ProjectProperties.PLATFORM_ACTIVE, ProjectProperties.JAVAC_SOURCE, ProjectProperties.JAVAC_TARGET),
UILookupMergerSupport.createProjectProblemsProviderMerger(),
// TODO: AB: maybe add "this" to the lookup. You should not cast a Project to EjbJarProject, but use the lookup instead.
});
lookup = base;
return LookupProviderSupport.createCompositeLookup(base, "Projects/org-netbeans-modules-j2ee-ejbjarproject/Lookup"); //NOI18N
}
public ClassPathProviderImpl getClassPathProvider () {
return this.cpProvider;
}
String getBuildXmlName() {
String storedName = helper.getStandardPropertyEvaluator().getProperty(EjbJarProjectProperties.BUILD_FILE);
return storedName == null ? GeneratedFilesHelper.BUILD_XML_PATH : storedName;
}
// Package private methods -------------------------------------------------
/**
* Returns the source roots of this project
* @return project's source roots
*/
public synchronized SourceRoots getSourceRoots() {
if (this.sourceRoots == null) { //Local caching, no project metadata access
this.sourceRoots = SourceRoots.create(this.updateHelper, evaluator(), getReferenceHelper(), EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE, "source-roots", false, "src.{0}{1}.dir"); //NOI18N
}
return this.sourceRoots;
}
public synchronized SourceRoots getTestSourceRoots() {
if (this.testRoots == null) { //Local caching, no project metadata access
this.testRoots = SourceRoots.create(this.updateHelper, evaluator(), getReferenceHelper(), EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE, "test-roots", true, "test.{0}{1}.dir"); //NOI18N
}
return this.testRoots;
}
WebServicesSupport getAPIWebServicesSupport() {
return apiWebServicesSupport;
}
JAXWSSupport getAPIJAXWSSupport () {
return apiJaxwsSupport;
}
WebServicesClientSupport getAPIWebServicesClientSupport () {
return apiWebServicesClientSupport;
}
JAXWSClientSupport getAPIJAXWSClientSupport () {
return apiJAXWSClientSupport;
}
/*public EjbJarProjectProperties getEjbJarProjectProperties() {
return new EjbJarProjectProperties (this, helper, refHelper);
}*/
public EjbJarProvider getEjbModule() {
return ejbModule;
}
public EjbJar getAPIEjbJar() {
return apiEjbJar;
}
/** Last time in ms when the Broken References alert was shown. */
private static long brokenAlertLastTime = 0;
/** Is Broken References alert shown now? */
private static boolean brokenAlertShown = false;
/** Timeout within which request to show alert will be ignored. */
private static int BROKEN_ALERT_TIMEOUT = 1000;
private static synchronized void showBrokenReferencesAlert() {
// Do not show alert if it is already shown or if it was shown
// in last BROKEN_ALERT_TIMEOUT milliseconds or if user do not wish it.
if (brokenAlertShown ||
brokenAlertLastTime+BROKEN_ALERT_TIMEOUT > System.currentTimeMillis() ||
!UserProjectSettings.getDefault().isShowAgainBrokenRefAlert()) {
return;
}
brokenAlertShown = true;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
Object ok = NbBundle.getMessage(BrokenReferencesAlertPanel.class,"MSG_Broken_References_OK");
DialogDescriptor dd = new DialogDescriptor(new BrokenReferencesAlertPanel(),
NbBundle.getMessage(BrokenReferencesAlertPanel.class, "MSG_Broken_References_Title"),
true, new Object[] {ok}, ok, DialogDescriptor.DEFAULT_ALIGN, null, null);
Dialog dlg = null;
try {
dlg = DialogDisplayer.getDefault().createDialog(dd);
dlg.setVisible(true);
} finally {
if (dlg != null) {
dlg.dispose();
}
}
} finally {
synchronized (EjbJarProject.class) {
brokenAlertLastTime = System.currentTimeMillis();
brokenAlertShown = false;
}
}
}
});
}
/** Return configured project name. */
public String getName() {
return ProjectUtils.getInformation(this).getName();
}
/** Store configured project name. */
public void setName(final String name) {
ProjectManager.mutex().writeAccess(new Runnable() {
@Override
public void run() {
Element data = helper.getPrimaryConfigurationData(true);
// XXX replace by XMLUtil when that has findElement, findText, etc.
NodeList nl = data.getElementsByTagNameNS(EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE, "name"); //NOI18N
Element nameEl;
if (nl.getLength() == 1) {
nameEl = (Element) nl.item(0);
NodeList deadKids = nameEl.getChildNodes();
while (deadKids.getLength() > 0) {
nameEl.removeChild(deadKids.item(0));
}
} else {
nameEl = data.getOwnerDocument().createElementNS(EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE, "name"); //NOI18N
data.insertBefore(nameEl, /* OK if null */data.getChildNodes().item(0));
}
nameEl.appendChild(data.getOwnerDocument().createTextNode(name));
helper.putPrimaryConfigurationData(data, true);
}
});
}
private void updateProjectXML () throws IOException {
Element element = aux.getConfigurationFragment("data","http://www.netbeans.org/ns/EjbJar-project/1",true); //NOI18N
if (element != null) {
Document doc = element.getOwnerDocument();
Element newRoot = doc.createElementNS (EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE,"data"); //NOI18N
XMLUtil.copyDocument (element, newRoot, EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE);
Element srcRoots = doc.createElementNS(EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE, "source-roots"); //NOI18N
Element root = doc.createElementNS (EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE,"root"); //NOI18N
root.setAttribute ("id","src.dir"); //NOI18N
srcRoots.appendChild(root);
newRoot.appendChild (srcRoots);
Element tstRoots = doc.createElementNS(EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE,"test-roots"); //NOI18N
root = doc.createElementNS (EjbJarProjectType.PROJECT_CONFIGURATION_NAMESPACE,"root"); //NOI18N
root.setAttribute ("id","test.src.dir"); //NOI18N
tstRoots.appendChild (root);
newRoot.appendChild (tstRoots);
helper.putPrimaryConfigurationData (newRoot, true);
ProjectManager.getDefault().saveProject(this);
}
}
@Override
public void fileAttributeChanged (org.openide.filesystems.FileAttributeEvent fe) {
}
@Override
public void fileChanged (org.openide.filesystems.FileEvent fe) {
}
@Override
public void fileDataCreated (org.openide.filesystems.FileEvent fe) {
FileObject fo = fe.getFile ();
checkLibraryFolder (fo);
}
@Override
public void fileDeleted (org.openide.filesystems.FileEvent fe) {
}
public void registerJ2eePlatformListener(final J2eePlatform platform) {
// listen to classpath changes
j2eePlatformListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(J2eePlatform.PROP_CLASSPATH)) {
ProjectManager.mutex().writeAccess(new Runnable() {
@Override
public void run() {
EditableProperties ep = helper.getProperties(
AntProjectHelper.PRIVATE_PROPERTIES_PATH);
EditableProperties projectProps = helper.getProperties(
AntProjectHelper.PROJECT_PROPERTIES_PATH);
Map<String, String> roots = J2EEProjectProperties.extractPlatformLibrariesRoot(platform);
String classpath = J2EEProjectProperties.toClasspathString(platform.getClasspathEntries(), roots);
ep.setProperty(EjbJarProjectProperties.J2EE_PLATFORM_CLASSPATH, classpath);
helper.putProperties(AntProjectHelper.PRIVATE_PROPERTIES_PATH, ep);
try {
ProjectManager.getDefault().saveProject(EjbJarProject.this);
} catch (IOException e) {
Exceptions.printStackTrace(e);
}
}
});
}
}
};
platform.addPropertyChangeListener(j2eePlatformListener);
}
public void unregisterJ2eePlatformListener(J2eePlatform platform) {
if (j2eePlatformListener != null) {
platform.removePropertyChangeListener(j2eePlatformListener);
}
}
@Override
public void fileFolderCreated (FileEvent fe) {
}
@Override
public void fileRenamed (FileRenameEvent fe) {
FileObject fo = fe.getFile ();
checkLibraryFolder (fo);
}
private void checkLibraryFolder (FileObject fo) {
if (!FileUtil.isArchiveFile(fo)) {
return;
}
if (fo.getParent ().equals (libFolder)) {
try {
classPathModifier.addRoots(new URL[] {FileUtil.getArchiveRoot(fo.toURL())}, ProjectProperties.JAVAC_CLASSPATH);
}
catch (IOException e) {
Exceptions.printStackTrace(e);
}
}
}
private String getProperty(String path, String name) {
return helper.getProperties(path).getProperty(name);
}
// Private innerclasses ----------------------------------------------------
private final class ProjectXmlSavedHookImpl extends ProjectXmlSavedHook {
ProjectXmlSavedHookImpl() {}
@Override
protected void projectXmlSaved() throws IOException {
int state = genFilesHelper.getBuildScriptState(
GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
EjbJarProject.class.getResource("resources/build-impl.xsl"));
final Boolean projectPropertiesSave = EjbJarProject.this.projectPropertiesSave.get();
if ((projectPropertiesSave && (state & GeneratedFilesHelper.FLAG_MODIFIED) == GeneratedFilesHelper.FLAG_MODIFIED) ||
state == (GeneratedFilesHelper.FLAG_UNKNOWN | GeneratedFilesHelper.FLAG_MODIFIED |
GeneratedFilesHelper.FLAG_OLD_PROJECT_XML | GeneratedFilesHelper.FLAG_OLD_STYLESHEET)) { //missing genfiles.properties
try {
AntProjectUtil.backupBuildImplFile(updateHelper);
genFilesHelper.generateBuildScriptFromStylesheet(
GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
EjbJarProject.class.getResource("resources/build-impl.xsl"));
} catch (IOException e) {
Exceptions.printStackTrace(e);
} catch (IllegalStateException e) {
Exceptions.printStackTrace(e);
}
} else {
genFilesHelper.refreshBuildScript(GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
EjbJarProject.class.getResource("resources/build-impl.xsl"),
false);
}
genFilesHelper.refreshBuildScript(
getBuildXmlName(),
EjbJarProject.class.getResource("resources/build.xsl"),
false);
}
}
private final class ProjectOpenedHookImpl extends ProjectOpenedHook {
ProjectOpenedHookImpl() {}
@Override
protected void projectOpened() {
evaluator().addPropertyChangeListener(EjbJarProject.this.ejbModule);
EjbJarLogicalViewProvider logicalViewProvider = EjbJarProject.this.getLookup().lookup(EjbJarLogicalViewProvider.class);
if (logicalViewProvider != null) {
logicalViewProvider.initialize();
}
try {
//Check libraries and add them to classpath automatically
String libFolderName = helper.getStandardPropertyEvaluator ().getProperty (EjbJarProjectProperties.LIBRARIES_DIR);
//EjbJarProjectProperties ejbpp = getEjbJarProjectProperties();
//DDDataObject initialization to be ready to listen on changes (#49656)
try {
FileObject ddFO = ejbModule.getDeploymentDescriptor();
if (ddFO != null) {
DataObject.find(ddFO);
}
} catch (org.openide.loaders.DataObjectNotFoundException ex) {}
// Register copy on save support
css.initialize();
FileObject lf = null;
if (libFolderName != null) {
lf = helper.resolveFileObject(libFolderName);
}
if (lf != null && lf.isFolder()) {
libFolder = lf;
FileObject[] children = libFolder.getChildren ();
List<URL> libs = new LinkedList<URL>();
for (int i = 0; i < children.length; i++) {
if (FileUtil.isArchiveFile(children[i])) {
libs.add(FileUtil.getArchiveRoot(children[i].toURL()));
}
}
classPathModifier.addRoots(libs.toArray(new URL[libs.size()]), ProjectProperties.JAVAC_CLASSPATH);
libFolder.addFileChangeListener (EjbJarProject.this);
}
// Check up on build scripts.
int flags = genFilesHelper.getBuildScriptState(
GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
EjbJarProject.class.getResource("resources/build-impl.xsl"));
if ((flags & GeneratedFilesHelper.FLAG_MODIFIED) != 0
&& (flags & GeneratedFilesHelper.FLAG_OLD_PROJECT_XML) != 0) {
AntProjectUtil.backupBuildImplFile(updateHelper);
genFilesHelper.generateBuildScriptFromStylesheet(
GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
EjbJarProject.class.getResource("resources/build-impl.xsl"));
} else {
genFilesHelper.refreshBuildScript(
GeneratedFilesHelper.BUILD_IMPL_XML_PATH,
EjbJarProject.class.getResource("resources/build-impl.xsl"), true);
}
genFilesHelper.refreshBuildScript(
getBuildXmlName(),
EjbJarProject.class.getResource("resources/build.xsl"), // NOI18N
true);
String servInstID = getProperty(AntProjectHelper.PRIVATE_PROPERTIES_PATH, EjbJarProjectProperties.J2EE_SERVER_INSTANCE);
String serverType = null;
J2eePlatform platform = Deployment.getDefault().getJ2eePlatform(servInstID);
if (platform != null) {
// updates j2ee.platform.cp & wscompile.cp & reg. j2ee platform listener
EjbJarProjectProperties.setServerInstance(EjbJarProject.this, EjbJarProject.this.helper, servInstID);
} else {
// if there is some server instance of the type which was used
// previously do not ask and use it
serverType = getProperty(AntProjectHelper.PROJECT_PROPERTIES_PATH, EjbJarProjectProperties.J2EE_SERVER_TYPE);
if (serverType != null) {
String instanceID = J2EEProjectProperties.getMatchingInstance(serverType, Type.EJB, EjbJarProject.this.getAPIEjbJar().getJ2eeProfile());
if (instanceID != null) {
EjbJarProjectProperties.setServerInstance(EjbJarProject.this, EjbJarProject.this.helper, instanceID);
platform = Deployment.getDefault().getJ2eePlatform(instanceID);
}
}
if (platform == null) {
BrokenServerSupport.showAlert();
}
}
// UI Logging
Utils.logUI(NbBundle.getBundle(EjbJarProject.class), "UI_EJB_PROJECT_OPENED", // NOI18N
new Object[] {(serverType != null ? serverType : Deployment.getDefault().getServerID(servInstID)), servInstID});
String serverName = ""; // NOI18N
try {
if (servInstID != null) {
serverName = Deployment.getDefault().getServerInstance(servInstID).getServerDisplayName();
}
}
catch (InstanceRemovedException ier) {
// ignore
}
Profile profile = EjbJarProject.this.getEjbModule().getJ2eeProfile();
Utils.logUsage(EjbJarProject.class, "USG_PROJECT_OPEN_EJB", new Object[] { serverName, profile }); // NOI18N
} catch (IOException e) {
LOGGER.log(Level.INFO, null, e);
}
// register project's classpaths to GlobalPathRegistry;
GlobalPathRegistry.getDefault().register(ClassPath.BOOT, cpProvider.getProjectClassPaths(ClassPath.BOOT));
GlobalPathRegistry.getDefault().register(ClassPath.SOURCE, cpProvider.getProjectClassPaths(ClassPath.SOURCE));
GlobalPathRegistry.getDefault().register(ClassPath.COMPILE, cpProvider.getProjectClassPaths(ClassPath.COMPILE));
// initialize the server configuration
// it MUST BE called AFTER classpaths are registered to GlobalPathRegistry!
// EJB DDProvider (used here) needs classpath set correctly when resolving Java Extents for annotations
ejbModule.getConfigSupport().ensureConfigurationReady();
try {
getProjectDirectory().getFileSystem().runAtomicAction(new AtomicAction() {
@Override
public void run() throws IOException {
ProjectManager.mutex().writeAccess(new Runnable() {
@Override
public void run() {
updateProject();
}
});
}
});
} catch (IOException e) {
LOGGER.log(Level.INFO, null, e);
}
String compileOnSave = getProperty(AntProjectHelper.PROJECT_PROPERTIES_PATH, EjbJarProjectProperties.J2EE_COMPILE_ON_SAVE);
if (Boolean.parseBoolean(compileOnSave)) {
Deployment.getDefault().enableCompileOnSaveSupport(ejbModule);
}
artifactSupport.enableArtifactSynchronization(true);
if (logicalViewProvider != null && logicalViewProvider.hasBrokenLinks()) {
ProjectProblems.showAlert(EjbJarProject.this);
}
if(apiWebServicesSupport.isBroken(EjbJarProject.this)) {
apiWebServicesSupport.showBrokenAlert(EjbJarProject.this);
}
else if(WebServicesClientSupport.isBroken(EjbJarProject.this)) {
WebServicesClientSupport.showBrokenAlert(EjbJarProject.this);
}
}
private void updateProject() {
// Make it easier to run headless builds on the same machine at least.
EditableProperties ep = helper.getProperties(AntProjectHelper.PRIVATE_PROPERTIES_PATH);
ep.setProperty("netbeans.user", System.getProperty("netbeans.user"));
//remove jaxws.endorsed.dir property
ep.remove("jaxws.endorsed.dir");
// #134642 - use Ant task from copylibs library
SharabilityUtility.makeSureProjectHasCopyLibsLibrary(helper, refHelper);
//update lib references in project properties
EditableProperties props = updateHelper.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH);
if (props.getProperty(EjbJarProjectProperties.J2EE_DEPLOY_ON_SAVE) == null) {
String server = evaluator().getProperty(EjbJarProjectProperties.J2EE_SERVER_INSTANCE);
props.setProperty(EjbJarProjectProperties.J2EE_DEPLOY_ON_SAVE,
server == null ? "false" : DeployOnSaveUtils.isDeployOnSaveSupported(server));
}
if (props.getProperty(EjbJarProjectProperties.J2EE_COMPILE_ON_SAVE) == null) {
props.setProperty(EjbJarProjectProperties.J2EE_COMPILE_ON_SAVE,
props.getProperty(EjbJarProjectProperties.J2EE_DEPLOY_ON_SAVE));
}
J2EEProjectProperties.removeObsoleteLibraryLocations(ep);
J2EEProjectProperties.removeObsoleteLibraryLocations(props);
if (!props.containsKey(ProjectProperties.INCLUDES)) {
props.setProperty(ProjectProperties.INCLUDES, "**"); // NOI18N
}
if (!props.containsKey(ProjectProperties.EXCLUDES)) {
props.setProperty(ProjectProperties.EXCLUDES, ""); // NOI18N
}
if (!props.containsKey("build.generated.sources.dir")) { // NOI18N
props.setProperty("build.generated.sources.dir", "${build.dir}/generated-sources"); // NOI18N
}
if (!props.containsKey(ProjectProperties.ANNOTATION_PROCESSING_ENABLED))props.setProperty(ProjectProperties.ANNOTATION_PROCESSING_ENABLED, "true"); //NOI18N
if (!props.containsKey(ProjectProperties.ANNOTATION_PROCESSING_ENABLED_IN_EDITOR))props.setProperty(ProjectProperties.ANNOTATION_PROCESSING_ENABLED_IN_EDITOR, "true"); //NOI18N
if (!props.containsKey(ProjectProperties.ANNOTATION_PROCESSING_RUN_ALL_PROCESSORS))props.setProperty(ProjectProperties.ANNOTATION_PROCESSING_RUN_ALL_PROCESSORS, "true"); //NOI18N
if (!props.containsKey(ProjectProperties.ANNOTATION_PROCESSING_PROCESSORS_LIST))props.setProperty(ProjectProperties.ANNOTATION_PROCESSING_PROCESSORS_LIST, ""); //NOI18N
if (!props.containsKey(ProjectProperties.ANNOTATION_PROCESSING_SOURCE_OUTPUT))props.setProperty(ProjectProperties.ANNOTATION_PROCESSING_SOURCE_OUTPUT, "${build.generated.sources.dir}/ap-source-output"); //NOI18N
if (!props.containsKey(ProjectProperties.JAVAC_PROCESSORPATH))props.setProperty(ProjectProperties.JAVAC_PROCESSORPATH,"${" + ProjectProperties.JAVAC_CLASSPATH + "}"); //NOI18N
if (!props.containsKey("javac.test.processorpath"))props.setProperty("javac.test.processorpath", "${" + ProjectProperties.JAVAC_TEST_CLASSPATH + "}"); // NOI18N
updateHelper.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH, props);
helper.putProperties(AntProjectHelper.PRIVATE_PROPERTIES_PATH, ep);
// update a dual build directory project to use a single build directory
ep = updateHelper.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH);
String earBuildDir = ep.getProperty(EjbJarProjectProperties.BUILD_EAR_CLASSES_DIR);
if (null != earBuildDir) {
// there is an BUILD_EAR_CLASSES_DIR property... we may
// need to change its value
String buildDir = ep.getProperty(ProjectProperties.BUILD_CLASSES_DIR);
if (null != buildDir) {
// there is a value that we may need to change the
// BUILD_EAR_CLASSES_DIR property value to match.
if (!buildDir.equals(earBuildDir)) {
// the values do not match... update the property and save it
ep.setProperty(EjbJarProjectProperties.BUILD_EAR_CLASSES_DIR,
buildDir);
updateHelper.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH,
ep);
}
// else {
// the values match and we don't need to do anything
// }
}
// else {
// the project doesn't have a BUILD_CLASSES_DIR property
// ** This is not an expected state, but if the project
// properties evolve, this property may go away...
// }
}
// else {
// there isn't a BUILD_EAR_CLASSES_DIR in this project...
// so we should not create one, by setting it.
// }
try {
ProjectManager.getDefault().saveProject(EjbJarProject.this);
} catch (IOException e) {
Exceptions.printStackTrace(e);
}
}
@Override
protected void projectClosed() {
evaluator().removePropertyChangeListener(EjbJarProject.this.ejbModule);
// unregister j2ee platform classpath change listener
/*EjbJarProjectProperties wpp = getEjbJarProjectProperties();
String servInstID = (String)wpp.get(EjbJarProjectProperties.J2EE_SERVER_INSTANCE);*/
String servInstID = getProperty(AntProjectHelper.PRIVATE_PROPERTIES_PATH, EjbJarProjectProperties.J2EE_SERVER_INSTANCE);
J2eePlatform platform = Deployment.getDefault().getJ2eePlatform(servInstID);
if (platform != null) {
unregisterJ2eePlatformListener(platform);
}
// Probably unnecessary, but just in case:
try {
ProjectManager.getDefault().saveProject(EjbJarProject.this);
} catch (IOException e) {
Exceptions.printStackTrace(e);
}
// Unregister copy on save support
try {
css.cleanup();
}
catch (FileStateInvalidException e) {
LOGGER.log(Level.INFO, null, e);
}
artifactSupport.enableArtifactSynchronization(false);
Deployment.getDefault().disableCompileOnSaveSupport(ejbModule);
// unregister project's classpaths to GlobalPathRegistry
GlobalPathRegistry.getDefault().unregister(ClassPath.BOOT, cpProvider.getProjectClassPaths(ClassPath.BOOT));
GlobalPathRegistry.getDefault().unregister(ClassPath.SOURCE, cpProvider.getProjectClassPaths(ClassPath.SOURCE));
GlobalPathRegistry.getDefault().unregister(ClassPath.COMPILE, cpProvider.getProjectClassPaths(ClassPath.COMPILE));
}
}
/**
* Exports the main JAR as an official build product for use from other scripts.
* The type of the artifact will be {@link AntArtifact#TYPE_JAR}.
*/
private final class AntArtifactProviderImpl implements AntArtifactProvider {
@Override
public AntArtifact[] getBuildArtifacts() {
return new AntArtifact[] {
helper.createSimpleAntArtifact(JavaProjectConstants.ARTIFACT_TYPE_JAR, "dist.jar", helper.getStandardPropertyEvaluator(), "dist", "clean"), // NOI18N
helper.createSimpleAntArtifact(EjbProjectConstants.ARTIFACT_TYPE_EJBJAR, "dist.jar", helper.getStandardPropertyEvaluator(), "dist", "clean"), // NOI18N
helper.createSimpleAntArtifact(EjbProjectConstants.ARTIFACT_TYPE_J2EE_MODULE_IN_EAR_ARCHIVE, "dist.ear.jar", helper.getStandardPropertyEvaluator(), "dist-ear", "clean-ear") // NOI18N
};
}
}
private class DeployOnSaveSupportProxy implements DeployOnSaveSupport {
@Override
public synchronized void addArtifactListener(ArtifactListener listener) {
css.addArtifactListener(listener);
artifactSupport.addArtifactListener(listener);
}
@Override
public synchronized void removeArtifactListener(ArtifactListener listener) {
css.removeArtifactListener(listener);
artifactSupport.removeArtifactListener(listener);
}
@Override
public boolean containsIdeArtifacts() {
return DeployOnSaveUtils.containsIdeArtifacts(eval, updateHelper, "build.classes.dir");
}
}
/**
* This class handle copying of meta-inf resources to appropriate place in build
* dir. This class is used in true Deploy On Save.
*
* Class should not request project lock from FS listener methods
* (deadlock prone).
*/
public class CopyOnSaveSupport extends FileChangeAdapter implements PropertyChangeListener {
private static final String META_INF_FOLDER = "META-INF";
private FileObject metaBase = null;
private String metaBaseValue = null;
private File resources = null;
private String buildClasses = null;
private final List<ArtifactListener> listeners = new CopyOnWriteArrayList<ArtifactListener>();
/** Creates a new instance of CopyOnSaveSupport */
public CopyOnSaveSupport() {
super();
}
public void addArtifactListener(ArtifactListener listener) {
listeners.add(listener);
}
public void removeArtifactListener(ArtifactListener listener) {
listeners.remove(listener);
}
private boolean isCopyOnSaveEnabled() {
return Boolean.parseBoolean(EjbJarProject.this.evaluator().getProperty(EjbJarProjectProperties.J2EE_COMPILE_ON_SAVE));
}
public void initialize() throws FileStateInvalidException {
EjbJarProject.this.evaluator().addPropertyChangeListener(this);
if (!isCopyOnSaveEnabled()) {
return;
}
metaBase = getEjbModule().getMetaInf();
metaBaseValue = evaluator().getProperty(EjbJarProjectProperties.META_INF);
if (resources != null) {
FileUtil.removeFileChangeListener(this, resources);
}
resources = getEjbModule().getResourceDirectory();
buildClasses = evaluator().getProperty(ProjectProperties.BUILD_CLASSES_DIR);
if (metaBase != null) {
metaBase.getFileSystem().addFileChangeListener(this);
}
if (resources != null) {
FileUtil.addFileChangeListener(this, resources);
}
LOGGER.log(Level.FINE, "Meta directory is {0}", metaBaseValue);
}
public void cleanup() throws FileStateInvalidException {
if (metaBase != null) {
metaBase.getFileSystem().removeFileChangeListener(this);
}
if (resources != null) {
FileUtil.removeFileChangeListener(this, resources);
resources = null;
}
EjbJarProject.this.evaluator().removePropertyChangeListener(this);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (EjbJarProjectProperties.META_INF.equals(evt.getPropertyName())
|| EjbJarProjectProperties.J2EE_COMPILE_ON_SAVE.equals(evt.getPropertyName())
|| EjbJarProjectProperties.RESOURCE_DIR.equals(evt.getPropertyName())) {
try {
cleanup();
initialize();
} catch (org.openide.filesystems.FileStateInvalidException e) {
LOGGER.log(Level.INFO, null, e);
}
} else if (ProjectProperties.BUILD_CLASSES_DIR.equals(evt.getPropertyName())) {
// TODO copy all files ?
Object value = evt.getNewValue();
buildClasses = value == null ? null : value.toString();
}
}
@Override
public void fileChanged(FileEvent fe) {
try {
if (!handleResource(fe)) {
handleCopyFileToDestDir(fe.getFile());
}
} catch (IOException e) {
LOGGER.log(Level.INFO, null, e);
}
}
@Override
public void fileFolderCreated(FileEvent fe) {
try {
if (!handleResource(fe)) {
handleCopyFileToDestDir(fe.getFile());
}
} catch (IOException e) {
LOGGER.log(Level.INFO, null, e);
}
}
@Override
public void fileDataCreated(FileEvent fe) {
try {
if (!handleResource(fe)) {
handleCopyFileToDestDir(fe.getFile());
}
} catch (IOException e) {
LOGGER.log(Level.INFO, null, e);
}
}
@Override
public void fileRenamed(FileRenameEvent fe) {
try {
if (handleResource(fe)) {
return;
}
FileObject fo = fe.getFile();
FileObject metaBase = getEjbModule().resolveMetaInf(metaBaseValue);
if (metaBase != null && FileUtil.isParentOf(metaBase, fo)) {
// inside docbase
handleCopyFileToDestDir(fo);
FileObject parent = fo.getParent();
String path;
if (FileUtil.isParentOf(metaBase, parent)) {
path = META_INF_FOLDER + "/" + FileUtil.getRelativePath(metaBase, fo.getParent()) +
"/" + fe.getName() + "." + fe.getExt();
} else {
path = META_INF_FOLDER + "/" + fe.getName() + "." + fe.getExt();
}
if (!isSynchronizationAppropriate(path)) {
return;
}
handleDeleteFileInDestDir(path);
}
} catch (IOException e) {
LOGGER.log(Level.INFO, null, e);
}
}
@Override
public void fileDeleted(FileEvent fe) {
try {
if (handleResource(fe)) {
return;
}
FileObject fo = fe.getFile();
FileObject metaBase = getEjbModule().resolveMetaInf(metaBaseValue);
if (metaBase != null && FileUtil.isParentOf(metaBase, fo)) {
// inside docbase
String path = META_INF_FOLDER + "/" + FileUtil.getRelativePath(metaBase, fo); // NOI18N
if (!isSynchronizationAppropriate(path)) {
return;
}
handleDeleteFileInDestDir(path);
}
} catch (IOException e) {
LOGGER.log(Level.INFO, null, e);
}
}
private boolean isSynchronizationAppropriate(String filePath) {
return true;
}
private void fireArtifactChange(Iterable<ArtifactListener.Artifact> files) {
for (ArtifactListener listener : listeners) {
listener.artifactsUpdated(files);
}
}
private boolean handleResource(FileEvent fe) {
// this may happen in broken project - see issue #191516
// in any case it can't be resource event when resources is null
if (resources == null) {
return false;
}
FileObject resourceFo = FileUtil.toFileObject(resources);
if (resourceFo != null
&& (resourceFo.equals(fe.getFile()) || FileUtil.isParentOf(resourceFo, fe.getFile()))) {
fireArtifactChange(Collections.singleton(
Artifact.forFile(FileUtil.toFile(fe.getFile())).serverResource()));
return true;
}
return false;
}
private void handleDeleteFileInDestDir(String resourcePath) throws IOException {
File deleted = null;
FileObject ejbBuildBase = buildClasses == null ? null : helper.resolveFileObject(buildClasses);
if (ejbBuildBase != null) {
// project was built
FileObject toDelete = ejbBuildBase.getFileObject(resourcePath);
if (toDelete != null) {
deleted = FileUtil.toFile(toDelete);
toDelete.delete();
}
if (deleted != null) {
fireArtifactChange(Collections.singleton(ArtifactListener.Artifact.forFile(deleted)));
}
}
}
private void handleCopyFileToDestDir(FileObject fo) throws IOException {
if (fo.isVirtual()) {
return;
}
FileObject metaBase = getEjbModule().resolveMetaInf(metaBaseValue);
if (metaBase != null && FileUtil.isParentOf(metaBase, fo)) {
// inside docbase
String path = META_INF_FOLDER + "/" + FileUtil.getRelativePath(metaBase, fo); // NOI18N
if (!isSynchronizationAppropriate(path)) {
return;
}
FileObject ejbBuildBase = buildClasses == null ? null : helper.resolveFileObject(buildClasses);
if (ejbBuildBase != null) {
// project was built
if (FileUtil.isParentOf(metaBase, ejbBuildBase) || FileUtil.isParentOf(ejbBuildBase, metaBase)) {
//cannot copy into self
return;
}
FileObject destFile = ensureDestinationFileExists(ejbBuildBase, path, fo.isFolder());
if (!fo.isFolder()) {
InputStream is = null;
OutputStream os = null;
FileLock fl = null;
try {
is = fo.getInputStream();
fl = destFile.lock();
os = destFile.getOutputStream(fl);
FileUtil.copy(is, os);
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (fl != null) {
fl.releaseLock();
}
File file = FileUtil.toFile(destFile);
if (file != null) {
fireArtifactChange(Collections.singleton(ArtifactListener.Artifact.forFile(file)));
}
}
} else {
File file = FileUtil.toFile(destFile);
if (file != null) {
fireArtifactChange(Collections.singleton(ArtifactListener.Artifact.forFile(file)));
}
}
}
}
}
/**
* Returns the destination (parent) directory needed to create file
* with relative path path under ejbBuilBase.
*/
private FileObject ensureDestinationFileExists(FileObject ejbBuildBase, String path, boolean isFolder) throws IOException {
FileObject current = ejbBuildBase;
StringTokenizer st = new StringTokenizer(path, "/");
while (st.hasMoreTokens()) {
String pathItem = st.nextToken();
FileObject newCurrent = current.getFileObject(pathItem);
if (newCurrent == null) {
// need to create it
if (isFolder || st.hasMoreTokens()) {
// create a folder
newCurrent = FileUtil.createFolder(current, pathItem);
assert newCurrent != null : "ejbBuildBase: " + ejbBuildBase + ", path: " + path + ", isFolder: " + isFolder;
} else {
newCurrent = FileUtil.createData(current, pathItem);
assert newCurrent != null : "ejbBuildBase: " + ejbBuildBase + ", path: " + path + ", isFolder: " + isFolder;
}
}
current = newCurrent;
}
assert current != null : "ejbBuildBase: " + ejbBuildBase + ", path: " + path + ", isFolder: " + isFolder;
return current;
}
}
private class ArtifactCopySupport extends ArtifactCopyOnSaveSupport {
public ArtifactCopySupport() {
super("build.classes.dir", evaluator(), getAntProjectHelper()); // NOI18N
}
@Override
public List<ArtifactCopyOnSaveSupport.Item> getArtifacts() {
final AntProjectHelper helper = getAntProjectHelper();
ClassPathSupport cs = new ClassPathSupport(evaluator(), getReferenceHelper(), helper,
getUpdateHelper(), new ClassPathSupportCallbackImpl(helper));
List<ArtifactCopyOnSaveSupport.Item> result = new ArrayList<ArtifactCopyOnSaveSupport.Item>();
for (ClassPathSupport.Item item : cs.itemsList(
helper.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH).getProperty(ProjectProperties.JAVAC_CLASSPATH),
ClassPathSupportCallbackImpl.ELEMENT_INCLUDED_LIBRARIES)) {
if (!item.isBroken() && (item.getType() == ClassPathSupport.Item.TYPE_ARTIFACT
|| item.getType() == ClassPathSupport.Item.TYPE_LIBRARY
|| item.getType() == ClassPathSupport.Item.TYPE_LIBRARY)) {
String included = item.getAdditionalProperty(ClassPathSupportCallbackImpl.INCLUDE_IN_DEPLOYMENT);
String dirs = item.getAdditionalProperty(AntProjectConstants.DESTINATION_DIRECTORY);
if (Boolean.parseBoolean(included)) {
result.add(new Item(item,
new ItemDescription("", RelocationType.fromString(dirs))));
}
}
}
return result;
}
@Override
protected Artifact filterArtifact(Artifact artifact, RelocationType type) {
if (type == RelocationType.ROOT) {
return artifact.relocatable();
} else if (type == RelocationType.LIB) {
return artifact.relocatable("lib"); // NOI18N
}
return artifact;
}
}
// List of primarily supported templates
private static final String[] TYPES = new String[] {
"java-classes", // NOI18N
"ejb-deployment-descriptor",// NOI18N
"ejb-types_2_1", // NOI18N
"ejb-types", // NOI18N
"ejb-types-server", // NOI18N
"web-services", // NOI18N
"message-handler", // NOI18N
"wsdl", // NOI18N
"j2ee-14-types", // NOI18N
"j2ee-types", // NOI18N
"java-beans", // NOI18N
"java-main-class", // NOI18N
"persistence", // NOI18N
"oasis-XML-catalogs", // NOI18N
"XML", // NOI18N
"ant-script", // NOI18N
"ant-task", // NOI18N
"junit", // NOI18N
"simple-files" // NOI18N
};
/**
* Supported template categories for Java EE 5 projects.
*/
private static final String[] JAVAEE5_TYPES = new String[] {
"java-classes", // NOI18N
"ejb-deployment-descriptor",// NOI18N
"ejb-types", // NOI18N
"ejb-types-server", // NOI18N
"ejb-types_3_0", // NOI18N
"web-services", // NOI18N
"web-service-clients", // NOI18N
"wsdl", // NOI18N
"j2ee-types", // NOI18N
"java-beans", // NOI18N
"java-main-class", // NOI18N
"persistence", // NOI18N
"oasis-XML-catalogs", // NOI18N
"XML", // NOI18N
"ant-script", // NOI18N
"ant-task", // NOI18N
"junit", // NOI18N
"simple-files" // NOI18N
};
/**
* Supported template categories for Java EE 6 projects (full?).
*/
private static final String[] JAVAEE6_TYPES = new String[] {
"java-classes", // NOI18N
"ejb-deployment-descriptor",// NOI18N
"ejb-types", // NOI18N
"ejb-types-server", // NOI18N
"ejb-types_3_1", // NOI18N
"ejb-types_3_1_full", // NOI18N
"web-services", // NOI18N
"web-service-clients", // NOI18N
"wsdl", // NOI18N
"j2ee-types", // NOI18N
"java-beans", // NOI18N
"java-main-class", // NOI18N
"persistence", // NOI18N
"oasis-XML-catalogs", // NOI18N
"XML", // NOI18N
"ant-script", // NOI18N
"ant-task", // NOI18N
"junit", // NOI18N
"simple-files" // NOI18N
};
/**
* Supported template categories for archive projects.
*/
private static final String[] ARCHIVE_TYPES = new String[] {
"ejb-deployment-descriptor", // NOI18N
"deployment-descriptor", // NOI18N
"XML", // NOI18N
};
private static final String[] PRIVILEGED_NAMES = new String[] {
"Templates/J2EE/Session", // NOI18N
"Templates/J2EE/TimerSession", // NOI18N
"Templates/J2EE/Entity", // NOI18N
"Templates/J2EE/RelatedCMP", // NOI18N
"Templates/J2EE/Message", //NOI18N
"Templates/Classes/Class.java", // NOI18N
"Templates/Classes/Package", // NOI18N
"Templates/WebServices/WebService.java", // NOI18N
"Templates/WebServices/MessageHandler" // NOI18N
};
private static final String[] PRIVILEGED_NAMES_EE5 = new String[] {
"Templates/J2EE/Session", // NOI18N
"Templates/J2EE/Message", // NOI18N
"Templates/Classes/Class.java", // NOI18N
"Templates/Classes/Package", // NOI18N
"Templates/Persistence/Entity.java", // NOI18N
"Templates/Persistence/RelatedCMP", // NOI18N
"Templates/WebServices/WebService.java", // NOI18N
"Templates/WebServices/WebServiceClient" // NOI18N
};
private static final String[] PRIVILEGED_NAMES_EE6 = new String[] {
"Templates/J2EE/TimerSession" // NOI18N
};
private static final String[] PRIVILEGED_NAMES_ARCHIVE = new String[] {
"Templates/J2EE/ejbJarXml", // NOI18N
};
private final class RecommendedTemplatesImpl implements RecommendedTemplates, PrivilegedTemplates {
private transient boolean isEE5 = false;
private transient boolean isEE6Plus = false;//if project support ee6 full version or above
private transient boolean checked = false;
private transient boolean isArchive = false;
private transient UpdateHelper helper = null;
RecommendedTemplatesImpl(UpdateHelper helper) {
this.helper = helper;
}
@Override
public String[] getRecommendedTypes() {
checkEnvironment();
String[] retVal = null;
if (isArchive) {
retVal = ARCHIVE_TYPES;
} else if (isEE5) {
retVal = JAVAEE5_TYPES;
} else if (isEE6Plus) {
retVal = JAVAEE6_TYPES;
} else {
retVal = TYPES;
}
return retVal;
}
@Override
public String[] getPrivilegedTemplates() {
checkEnvironment();
List<String> privileged = new ArrayList<String>();
if (isArchive) {
privileged.addAll(Arrays.asList(PRIVILEGED_NAMES_ARCHIVE));
} else if (isEE5) {
privileged.addAll(Arrays.asList(PRIVILEGED_NAMES_EE5));
} else if (isEE6Plus) {
privileged.addAll(Arrays.asList(PRIVILEGED_NAMES_EE5));
privileged.addAll(Arrays.asList(PRIVILEGED_NAMES_EE6));
} else {
privileged.addAll(Arrays.asList(PRIVILEGED_NAMES));
}
return privileged.toArray(new String[privileged.size()]);
}
private void checkEnvironment() {
if (!checked) {
Profile version=Profile.fromPropertiesString(evaluator().getProperty(EjbJarProjectProperties.J2EE_PLATFORM));
isEE5 = Profile.JAVA_EE_5==version;
isEE6Plus = version.isAtLeast(Profile.JAVA_EE_6_WEB);
final Object srcType = helper.getAntProjectHelper().
getStandardPropertyEvaluator().getProperty(EjbJarProjectProperties.JAVA_SOURCE_BASED);
if ("false".equals(srcType)) {
isArchive = true;
}
checked = true;
}
}
}
// FIXME this is just fallback for code searching for the old SPI in lookup
// remove in next release
@SuppressWarnings("deprecation")
private static class EjbJarImpl implements EjbJarImplementation {
private final EjbJar apiModule;
public EjbJarImpl(EjbJar apiModule) {
this.apiModule = apiModule;
}
@Override
public FileObject getDeploymentDescriptor() {
return apiModule.getDeploymentDescriptor();
}
@Override
public String getJ2eePlatformVersion() {
return apiModule.getJ2eePlatformVersion();
}
@Override
public FileObject[] getJavaSources() {
return apiModule.getJavaSources();
}
@Override
public FileObject getMetaInf() {
return apiModule.getMetaInf();
}
@Override
public MetadataModel<EjbJarMetadata> getMetadataModel() {
return apiModule.getMetadataModel();
}
}
private static class EjbJarImpl2 implements EjbJarImplementation2 {
private final EjbJarProvider provider;
public EjbJarImpl2(EjbJarProvider provider) {
this.provider = provider;
}
@Override
public FileObject getDeploymentDescriptor() {
return provider.getDeploymentDescriptor();
}
@Override
public Profile getJ2eeProfile() {
return provider.getJ2eeProfile();
}
@Override
public FileObject[] getJavaSources() {
return provider.getJavaSources();
}
@Override
public FileObject getMetaInf() {
return provider.getMetaInf();
}
@Override
public MetadataModel<EjbJarMetadata> getMetadataModel() {
return provider.getMetadataModel();
}
}
private class EjbExtenderImplementation implements AntBuildExtenderImplementation {
//add targets here as required by the external plugins..
@Override
public List<String> getExtensibleTargets() {
String[] targets = new String[] {
"-do-init", "-init-check", "-post-clean", "jar", "-pre-pre-compile","-do-compile","-do-compile-single", "-pre-dist" //NOI18N
};
return Arrays.asList(targets);
}
@Override
public Project getOwningProject() {
return EjbJarProject.this;
}
}
private final class WhiteListUpdaterImpl extends WhiteListUpdater {
public WhiteListUpdaterImpl(Project project) {
super(project);
}
@Override
public void addSettingListener() {
evaluator().addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(JavaEEProjectSettingConstants.J2EE_SERVER_INSTANCE)){
checkWhiteLists();
}
if (evt.getPropertyName().equals(ProjectProperties.JAVAC_CLASSPATH)){
// if classpath changes refresh whitelists as well:
updateWhitelist(null, getServerWhiteList());
}
}
});
}
}
private class JavaEEProjectSettingsImpl implements JavaEEProjectSettingsImplementation {
private final EjbJarProject project;
public JavaEEProjectSettingsImpl(EjbJarProject project) {
this.project = project;
}
@Override
public void setProfile(Profile profile) {
setInSharedProperties(JavaEEProjectSettingConstants.J2EE_PLATFORM, profile.toPropertiesString());
}
@Override
public Profile getProfile() {
return ejbModule.getJ2eeProfile();
}
@Override
public void setBrowserID(String browserID) {
// Does not make sense for EJB project - simply do nothing
}
@Override
public String getBrowserID() {
// Does not make sense for EJB project - simply do nothing
return null;
}
@Override
public void setServerInstanceID(String serverInstanceID) {
setInPrivateProperties(JavaEEProjectSettingConstants.J2EE_SERVER_INSTANCE, serverInstanceID);
}
@Override
public String getServerInstanceID() {
return evaluator().getProperty(JavaEEProjectSettingConstants.J2EE_SERVER_INSTANCE);
}
private void setInSharedProperties(String key, String value) {
setInProperties(key, value, AntProjectHelper.PROJECT_PROPERTIES_PATH);
}
private void setInPrivateProperties(String key, String value) {
setInProperties(key, value, AntProjectHelper.PRIVATE_PROPERTIES_PATH);
}
private void setInProperties(String key, String value, String propertiesPath) {
try {
UpdateHelper helper = project.getUpdateHelper();
EditableProperties projectProperties = helper.getProperties(propertiesPath);
projectProperties.setProperty(key, value);
helper.putProperties(propertiesPath, projectProperties);
ProjectManager.getDefault().saveProject(project);
} catch (IOException ex) {
LOGGER.log(Level.WARNING, "Project properties couldn't be saved.", ex);
}
}
}
}
| 82,789 | 0.610331 | 0.604679 | 1,755 | 46.17664 | 36.815666 | 414 | false | false | 0 | 0 | 0 | 0 | 70 | 0.001691 | 0.623932 | false | false |
12
|
f5433c0830c1beeb3038b1970b111f9223ee46f2
| 33,028,298,540,797 |
f8b777ad8fe90b0bb19f5f0d0ce948e51747ea68
|
/personinfocollecter/src/main/java/com/hufeiya/personinfocollecter/MyApplication.java
|
9f60ca8ecf5508597dfa1cb0ddb3f251368f7d93
|
[] |
no_license
|
hufeiya/PeronalInfoDEMO
|
https://github.com/hufeiya/PeronalInfoDEMO
|
2e2e2ad0afc88805f977a834e03e74c18f967914
|
0ad62546f7982dd60d1aebad35d1bdb452b1bd70
|
refs/heads/master
| 2020-05-29T14:41:22.858000 | 2016-07-29T09:29:42 | 2016-07-29T09:29:42 | 60,460,768 | 4 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hufeiya.personinfocollecter;
import android.app.Application;
import android.content.Context;
import org.xutils.x;
/**
* Created by hufeiya on 16-7-22.
*/
public class MyApplication extends Application{
public static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
x.Ext.init(this);
x.Ext.setDebug(BuildConfig.DEBUG); // 是否输出debug日志, 开启debug会影响性能.
}
}
|
UTF-8
|
Java
| 500 |
java
|
MyApplication.java
|
Java
|
[
{
"context": ".Context;\n\nimport org.xutils.x;\n\n/**\n * Created by hufeiya on 16-7-22.\n */\npublic class MyApplication extend",
"end": 154,
"score": 0.9996588230133057,
"start": 147,
"tag": "USERNAME",
"value": "hufeiya"
}
] | null |
[] |
package com.hufeiya.personinfocollecter;
import android.app.Application;
import android.content.Context;
import org.xutils.x;
/**
* Created by hufeiya on 16-7-22.
*/
public class MyApplication extends Application{
public static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
x.Ext.init(this);
x.Ext.setDebug(BuildConfig.DEBUG); // 是否输出debug日志, 开启debug会影响性能.
}
}
| 500 | 0.689873 | 0.679325 | 21 | 21.571428 | 19.271423 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.47619 | false | false |
12
|
580c6b619ec80a46bf01f8da35803d62902553ee
| 12,008,728,566,078 |
beb3783ab791be67aea62d572c28be4a2015b03f
|
/sum-of-positive/java/1/Positive.java
|
9f9bc706d20d02ed237cf854d1473d272044858b
|
[
"BSD-2-Clause-Views"
] |
permissive
|
prayatma/codewars
|
https://github.com/prayatma/codewars
|
0c95bdff772e35493e68f3915ffd860c0e35489f
|
34cb63bd1ef7497c3a9ad5fdebe7ed91456ab227
|
refs/heads/master
| 2021-02-07T19:27:15.553000 | 2020-03-01T01:36:13 | 2020-03-01T01:36:13 | 244,068,080 | 0 | 0 |
NOASSERTION
| true | 2020-03-01T01:30:23 | 2020-03-01T01:30:23 | 2019-12-10T10:51:36 | 2019-09-07T02:43:32 | 449 | 0 | 0 | 0 | null | false | false |
public class Positive{
public static int sum(int[] arr) {
return java.util.Arrays.stream(arr)
.filter(n -> n > 0)
.sum();
}
}
|
UTF-8
|
Java
| 145 |
java
|
Positive.java
|
Java
|
[] | null |
[] |
public class Positive{
public static int sum(int[] arr) {
return java.util.Arrays.stream(arr)
.filter(n -> n > 0)
.sum();
}
}
| 145 | 0.57931 | 0.572414 | 7 | 19.857143 | 13.860825 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false |
12
|
673ad56500f0283b16d8e899f6728266d26b206d
| 10,428,180,628,097 |
f823f023ce0835c62a35c3fad6f03df26802b0cf
|
/apps/dolly-backend/src/main/java/no/nav/dolly/provider/api/TestpersonController.java
|
36100c6bb7ae2b5c3c381721d8088fb04888f3c8
|
[
"MIT"
] |
permissive
|
abdukerim/testnorge
|
https://github.com/abdukerim/testnorge
|
b4778f97f9a51d3591aa29d7ef8bfb1c1f11cdd9
|
31ea38d2286db6de244eb1ab71c4751cc01f8d05
|
refs/heads/master
| 2023-08-23T11:49:12.549000 | 2021-11-03T14:10:23 | 2021-11-03T14:10:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package no.nav.dolly.provider.api;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import no.nav.dolly.bestilling.service.DollyBestillingService;
import no.nav.dolly.domain.jpa.Bestilling;
import no.nav.dolly.domain.resultset.RsDollyRelasjonRequest;
import no.nav.dolly.domain.resultset.RsDollyUpdateRequest;
import no.nav.dolly.domain.resultset.RsIdentBeskrivelse;
import no.nav.dolly.domain.resultset.entity.bestilling.RsBestillingStatus;
import no.nav.dolly.domain.resultset.entity.testident.RsWhereAmI;
import no.nav.dolly.domain.testperson.IdentAttributesResponse;
import no.nav.dolly.exceptions.NotFoundException;
import no.nav.dolly.service.BestillingService;
import no.nav.dolly.service.IdentService;
import no.nav.dolly.service.NavigasjonService;
import no.nav.dolly.service.PersonService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
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.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import static java.lang.String.format;
import static java.util.Collections.singletonList;
import static no.nav.dolly.config.CachingConfig.CACHE_BESTILLING;
import static no.nav.dolly.config.CachingConfig.CACHE_GRUPPE;
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "api/v1/ident")
public class TestpersonController {
private final BestillingService bestillingService;
private final DollyBestillingService dollyBestillingService;
private final MapperFacade mapperFacade;
private final IdentService identService;
private final PersonService personService;
private final NavigasjonService navigasjonService;
@Operation(description = "Legge til egenskaper på person/endre person i TPS og øvrige systemer")
@PutMapping("/{ident}/leggtilpaaperson")
@CacheEvict(value = {CACHE_GRUPPE, CACHE_BESTILLING}, allEntries = true)
@ResponseStatus(HttpStatus.OK)
public RsBestillingStatus endrePerson(@PathVariable String ident, @RequestBody RsDollyUpdateRequest request) {
Bestilling bestilling = bestillingService.saveBestilling(request, ident);
dollyBestillingService.oppdaterPersonAsync(request, bestilling);
return mapperFacade.map(bestilling, RsBestillingStatus.class);
}
@CacheEvict(value = CACHE_GRUPPE, allEntries = true)
@Operation(description = "Endre status beskrivelse på testperson")
@PutMapping("/{ident}/beskrivelse")
@ResponseStatus(HttpStatus.OK)
public IdentAttributesResponse oppdaterTestidentBeskrivelse(@PathVariable String ident, @RequestBody RsIdentBeskrivelse beskrivelse) {
return mapperFacade.map(identService.saveIdentBeskrivelse(ident, beskrivelse.getBeskrivelse()), IdentAttributesResponse.class);
}
@CacheEvict(value = CACHE_GRUPPE, allEntries = true)
@Operation(description = "Endre status \"i-bruk\" på testperson")
@PutMapping("/{ident}/ibruk")
@ResponseStatus(HttpStatus.OK)
public IdentAttributesResponse oppdaterTestidentIbruk(@PathVariable String ident, @RequestParam boolean iBruk) {
return mapperFacade.map(identService.saveIdentIBruk(ident, iBruk), IdentAttributesResponse.class);
}
@Operation(description = "Koble eksisterende personer i Dolly ")
@PutMapping("/{ident}/relasjon")
@ResponseStatus(HttpStatus.OK)
@CacheEvict(value = {CACHE_GRUPPE, CACHE_BESTILLING}, allEntries = true)
public RsBestillingStatus koblePerson(@Parameter(description = "Ident for hovedperson", required = true)
@PathVariable("ident") String ident,
@RequestBody RsDollyRelasjonRequest request) {
Bestilling bestilling = bestillingService.saveBestilling(ident, request);
dollyBestillingService.relasjonPersonAsync(ident, request, bestilling);
return mapperFacade.map(bestilling, RsBestillingStatus.class);
}
@Operation(description = "Slett test ident")
@CacheEvict(value = {CACHE_BESTILLING, CACHE_GRUPPE}, allEntries = true)
@Transactional
@DeleteMapping("/{ident}")
public void deleteTestident(@PathVariable String ident) {
if (identService.slettTestident(ident) == 0) {
throw new NotFoundException(format("Testperson med ident %s ble ikke funnet.", ident));
}
bestillingService.slettBestillingByTestIdent(ident);
personService.recyclePersoner(singletonList(ident));
}
@Operation(description = "Naviger til ønsket testperson")
@Transactional
@GetMapping("/naviger/{ident}")
public RsWhereAmI navigerTilTestident(@PathVariable String ident) {
return navigasjonService.navigerTilIdent(ident);
}
}
|
UTF-8
|
Java
| 5,344 |
java
|
TestpersonController.java
|
Java
|
[] | null |
[] |
package no.nav.dolly.provider.api;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import no.nav.dolly.bestilling.service.DollyBestillingService;
import no.nav.dolly.domain.jpa.Bestilling;
import no.nav.dolly.domain.resultset.RsDollyRelasjonRequest;
import no.nav.dolly.domain.resultset.RsDollyUpdateRequest;
import no.nav.dolly.domain.resultset.RsIdentBeskrivelse;
import no.nav.dolly.domain.resultset.entity.bestilling.RsBestillingStatus;
import no.nav.dolly.domain.resultset.entity.testident.RsWhereAmI;
import no.nav.dolly.domain.testperson.IdentAttributesResponse;
import no.nav.dolly.exceptions.NotFoundException;
import no.nav.dolly.service.BestillingService;
import no.nav.dolly.service.IdentService;
import no.nav.dolly.service.NavigasjonService;
import no.nav.dolly.service.PersonService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
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.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import static java.lang.String.format;
import static java.util.Collections.singletonList;
import static no.nav.dolly.config.CachingConfig.CACHE_BESTILLING;
import static no.nav.dolly.config.CachingConfig.CACHE_GRUPPE;
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "api/v1/ident")
public class TestpersonController {
private final BestillingService bestillingService;
private final DollyBestillingService dollyBestillingService;
private final MapperFacade mapperFacade;
private final IdentService identService;
private final PersonService personService;
private final NavigasjonService navigasjonService;
@Operation(description = "Legge til egenskaper på person/endre person i TPS og øvrige systemer")
@PutMapping("/{ident}/leggtilpaaperson")
@CacheEvict(value = {CACHE_GRUPPE, CACHE_BESTILLING}, allEntries = true)
@ResponseStatus(HttpStatus.OK)
public RsBestillingStatus endrePerson(@PathVariable String ident, @RequestBody RsDollyUpdateRequest request) {
Bestilling bestilling = bestillingService.saveBestilling(request, ident);
dollyBestillingService.oppdaterPersonAsync(request, bestilling);
return mapperFacade.map(bestilling, RsBestillingStatus.class);
}
@CacheEvict(value = CACHE_GRUPPE, allEntries = true)
@Operation(description = "Endre status beskrivelse på testperson")
@PutMapping("/{ident}/beskrivelse")
@ResponseStatus(HttpStatus.OK)
public IdentAttributesResponse oppdaterTestidentBeskrivelse(@PathVariable String ident, @RequestBody RsIdentBeskrivelse beskrivelse) {
return mapperFacade.map(identService.saveIdentBeskrivelse(ident, beskrivelse.getBeskrivelse()), IdentAttributesResponse.class);
}
@CacheEvict(value = CACHE_GRUPPE, allEntries = true)
@Operation(description = "Endre status \"i-bruk\" på testperson")
@PutMapping("/{ident}/ibruk")
@ResponseStatus(HttpStatus.OK)
public IdentAttributesResponse oppdaterTestidentIbruk(@PathVariable String ident, @RequestParam boolean iBruk) {
return mapperFacade.map(identService.saveIdentIBruk(ident, iBruk), IdentAttributesResponse.class);
}
@Operation(description = "Koble eksisterende personer i Dolly ")
@PutMapping("/{ident}/relasjon")
@ResponseStatus(HttpStatus.OK)
@CacheEvict(value = {CACHE_GRUPPE, CACHE_BESTILLING}, allEntries = true)
public RsBestillingStatus koblePerson(@Parameter(description = "Ident for hovedperson", required = true)
@PathVariable("ident") String ident,
@RequestBody RsDollyRelasjonRequest request) {
Bestilling bestilling = bestillingService.saveBestilling(ident, request);
dollyBestillingService.relasjonPersonAsync(ident, request, bestilling);
return mapperFacade.map(bestilling, RsBestillingStatus.class);
}
@Operation(description = "Slett test ident")
@CacheEvict(value = {CACHE_BESTILLING, CACHE_GRUPPE}, allEntries = true)
@Transactional
@DeleteMapping("/{ident}")
public void deleteTestident(@PathVariable String ident) {
if (identService.slettTestident(ident) == 0) {
throw new NotFoundException(format("Testperson med ident %s ble ikke funnet.", ident));
}
bestillingService.slettBestillingByTestIdent(ident);
personService.recyclePersoner(singletonList(ident));
}
@Operation(description = "Naviger til ønsket testperson")
@Transactional
@GetMapping("/naviger/{ident}")
public RsWhereAmI navigerTilTestident(@PathVariable String ident) {
return navigasjonService.navigerTilIdent(ident);
}
}
| 5,344 | 0.775613 | 0.774864 | 114 | 45.842106 | 31.78866 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.675439 | false | false |
12
|
3a0d65da6b5a08d40e90282b7db28f0b1b4e3973
| 14,800,457,308,041 |
774ad58925938ca93ff6481f6fab22bcc711a76d
|
/src/Arrays/LargestSquare.java
|
b99a8fcd29c8de8883d41140cf24976651e0c182
|
[] |
no_license
|
leiwang8224/algorithm2
|
https://github.com/leiwang8224/algorithm2
|
b26326bf6d851d5b3f30dd860e79bf02dc9a7ade
|
532fcd603cd1631af1468ecd5f9bffa353a25242
|
refs/heads/master
| 2022-06-12T05:55:56.635000 | 2022-06-03T23:10:41 | 2022-06-03T23:10:41 | 127,375,815 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Arrays;
import java.util.Arrays;
public class LargestSquare {
public static void main(String[] args) {
char[][] input = new char[3][4];
input[0][0] = '1';
input[0][1] = '1';
input[0][2] = '0';
input[0][3] = '1';
input[1][0] = '1';
input[1][1] = '1';
input[1][2] = '0';
input[1][3] = '1';
input[2][0] = '1';
input[2][1] = '1';
input[2][2] = '1';
input[2][3] = '1';
System.out.println(largestSquareDP(input));
System.out.println(largestSquareBruteForce(input));
}
// Let the given binary matrix be M[R][C]. The idea of the algorithm is to
// construct an auxiliary size matrix S[][] in which each entry S[i][j]
// represents size of the square sub-matrix with all 1s including M[i][j]
// where M[i][j] is the rightmost and bottommost entry in sub-matrix.
private static int largestSquareDP(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
int numRows = matrix.length;
int numCols = matrix[0].length;
int[][] t = new int[numRows][numCols];
// left col
for (int index = 0; index < numRows; index ++) {
t[index][0] = Character.getNumericValue(matrix[index][0]);
}
// top row
for (int index = 0; index < numCols; index ++) {
t[0][index] = Character.getNumericValue(matrix[0][index]);
}
// cells inside
for (int row = 1; row < numRows; row++) {
for (int col = 1; col < numCols; col++) {
if (matrix[row][col] == '1') {
int min = Math.min(t[row-1][col], t[row-1][col-1]);
min = Math.min(min, t[row][col-1]);
t[row][col] = min + 1;
} else {
t[row][col] = 0;
}
}
}
// find the max entry
int max = 0;
//get maximal length
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
if (t[row][col] > max) {
max = t[row][col];
}
}
}
for (int[] row : t) {
System.out.println(Arrays.toString(row));
}
return max * max;
}
//
// We use a variable to contain the size of the largest square found so far
// and another variable to store the size of the current, both initialized
// to 0. Starting from the left uppermost point in the matrix, we search for a
// 1. No operation needs to be done for a 0. Whenever a 1 is found, we try to
// find out the largest square that can be formed including that 1. For this,
// we move diagonally (right and downwards), i.e. we increment the row index
// and column index temporarily and then check whether all the elements of that
// row and column are 1 or not. If all the elements happen to be 1, we move
// diagonally further as previously. If even one element turns out to be 0,
// we stop this diagonal movement and update the size of the largest square.
// Now we, continue the traversal of the matrix from the element next to the
// initial 1 found, till all the elements of the matrix have been traversed.
private static int largestSquareBruteForce(char[][] matrix) {
int numRows = matrix.length;
int numCols = numRows > 0 ? matrix[0].length : 0;
int maxsqlen = 0;
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
if (matrix[row][col] == '1') {
int sqlen = 1;
boolean flag = true;
while (sqlen + row < numRows && sqlen + col < numCols && flag) {
for (int k = col; k <= sqlen + col; k++) {
if (matrix[row + sqlen][k] == '0') {
flag = false;
break;
}
}
for (int k = row; k <= sqlen + row; k++) {
if (matrix[k][col + sqlen] == '0') {
flag = false;
break;
}
}
if (flag) sqlen++;
}
if (maxsqlen < sqlen) {
maxsqlen = sqlen;
}
}
}
}
return maxsqlen * maxsqlen;
}
}
|
UTF-8
|
Java
| 4,651 |
java
|
LargestSquare.java
|
Java
|
[] | null |
[] |
package Arrays;
import java.util.Arrays;
public class LargestSquare {
public static void main(String[] args) {
char[][] input = new char[3][4];
input[0][0] = '1';
input[0][1] = '1';
input[0][2] = '0';
input[0][3] = '1';
input[1][0] = '1';
input[1][1] = '1';
input[1][2] = '0';
input[1][3] = '1';
input[2][0] = '1';
input[2][1] = '1';
input[2][2] = '1';
input[2][3] = '1';
System.out.println(largestSquareDP(input));
System.out.println(largestSquareBruteForce(input));
}
// Let the given binary matrix be M[R][C]. The idea of the algorithm is to
// construct an auxiliary size matrix S[][] in which each entry S[i][j]
// represents size of the square sub-matrix with all 1s including M[i][j]
// where M[i][j] is the rightmost and bottommost entry in sub-matrix.
private static int largestSquareDP(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
int numRows = matrix.length;
int numCols = matrix[0].length;
int[][] t = new int[numRows][numCols];
// left col
for (int index = 0; index < numRows; index ++) {
t[index][0] = Character.getNumericValue(matrix[index][0]);
}
// top row
for (int index = 0; index < numCols; index ++) {
t[0][index] = Character.getNumericValue(matrix[0][index]);
}
// cells inside
for (int row = 1; row < numRows; row++) {
for (int col = 1; col < numCols; col++) {
if (matrix[row][col] == '1') {
int min = Math.min(t[row-1][col], t[row-1][col-1]);
min = Math.min(min, t[row][col-1]);
t[row][col] = min + 1;
} else {
t[row][col] = 0;
}
}
}
// find the max entry
int max = 0;
//get maximal length
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
if (t[row][col] > max) {
max = t[row][col];
}
}
}
for (int[] row : t) {
System.out.println(Arrays.toString(row));
}
return max * max;
}
//
// We use a variable to contain the size of the largest square found so far
// and another variable to store the size of the current, both initialized
// to 0. Starting from the left uppermost point in the matrix, we search for a
// 1. No operation needs to be done for a 0. Whenever a 1 is found, we try to
// find out the largest square that can be formed including that 1. For this,
// we move diagonally (right and downwards), i.e. we increment the row index
// and column index temporarily and then check whether all the elements of that
// row and column are 1 or not. If all the elements happen to be 1, we move
// diagonally further as previously. If even one element turns out to be 0,
// we stop this diagonal movement and update the size of the largest square.
// Now we, continue the traversal of the matrix from the element next to the
// initial 1 found, till all the elements of the matrix have been traversed.
private static int largestSquareBruteForce(char[][] matrix) {
int numRows = matrix.length;
int numCols = numRows > 0 ? matrix[0].length : 0;
int maxsqlen = 0;
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
if (matrix[row][col] == '1') {
int sqlen = 1;
boolean flag = true;
while (sqlen + row < numRows && sqlen + col < numCols && flag) {
for (int k = col; k <= sqlen + col; k++) {
if (matrix[row + sqlen][k] == '0') {
flag = false;
break;
}
}
for (int k = row; k <= sqlen + row; k++) {
if (matrix[k][col + sqlen] == '0') {
flag = false;
break;
}
}
if (flag) sqlen++;
}
if (maxsqlen < sqlen) {
maxsqlen = sqlen;
}
}
}
}
return maxsqlen * maxsqlen;
}
}
| 4,651 | 0.476027 | 0.458611 | 127 | 35.622047 | 25.795967 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.614173 | false | false |
12
|
77f31594a03b7b01913c8c9ebf469d983850fcd6
| 17,549,236,416,263 |
7d06726efa10d628d0579062880d2e166ea47664
|
/mongo/src/igor/yarkov/crypto/mongo/UnsupportedIndexTypeException.java
|
be9ef3807d7179398dbf8e3c97303e3765b60bbe
|
[] |
no_license
|
iyarkov/db-encrypt
|
https://github.com/iyarkov/db-encrypt
|
c0d9fa4f07ba84b0be5c18ac7ac6111ad590768b
|
3f51f90e3b68f5d994d2af8f5a8b82124850429a
|
refs/heads/master
| 2016-08-04T15:46:22.970000 | 2015-07-29T15:17:00 | 2015-07-29T15:17:00 | 39,782,173 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package igor.yarkov.crypto.mongo;
public class UnsupportedIndexTypeException extends RuntimeException {
public UnsupportedIndexTypeException(Class recordClass) {
super("Unsupported index type for class " + recordClass.getName());
}
}
|
UTF-8
|
Java
| 252 |
java
|
UnsupportedIndexTypeException.java
|
Java
|
[] | null |
[] |
package igor.yarkov.crypto.mongo;
public class UnsupportedIndexTypeException extends RuntimeException {
public UnsupportedIndexTypeException(Class recordClass) {
super("Unsupported index type for class " + recordClass.getName());
}
}
| 252 | 0.765873 | 0.765873 | 8 | 30.5 | 31.184933 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
12
|
c57a2e5c9f5ac971a63a1c68c78e27b40baa95b1
| 26,920,855,057,457 |
17c30fed606a8b1c8f07f3befbef6ccc78288299
|
/P9_8_0_0/src/main/java/android/view/textclassifier/-$Lambda$Sy__B53nI_asuVbYEz1JE9PRAk8.java
|
97933345a3de56996b87edbfde2c1532489ce5c1
|
[] |
no_license
|
EggUncle/HwFrameWorkSource
|
https://github.com/EggUncle/HwFrameWorkSource
|
4e67f1b832a2f68f5eaae065c90215777b8633a7
|
162e751d0952ca13548f700aad987852b969a4ad
|
refs/heads/master
| 2020-04-06T14:29:22.781000 | 2018-11-09T05:05:03 | 2018-11-09T05:05:03 | 157,543,151 | 1 | 0 | null | true | 2018-11-14T12:08:01 | 2018-11-14T12:08:01 | 2018-11-14T12:07:41 | 2018-11-09T05:05:10 | 26,058 | 0 | 0 | 0 | null | false | null |
package android.view.textclassifier;
import java.util.function.ToIntFunction;
final /* synthetic */ class -$Lambda$Sy__B53nI_asuVbYEz1JE9PRAk8 implements ToIntFunction {
private final /* synthetic */ int $m$0(Object arg0) {
return ((SpanSpec) arg0).mStart;
}
public final int applyAsInt(Object obj) {
return $m$0(obj);
}
}
|
UTF-8
|
Java
| 358 |
java
|
-$Lambda$Sy__B53nI_asuVbYEz1JE9PRAk8.java
|
Java
|
[] | null |
[] |
package android.view.textclassifier;
import java.util.function.ToIntFunction;
final /* synthetic */ class -$Lambda$Sy__B53nI_asuVbYEz1JE9PRAk8 implements ToIntFunction {
private final /* synthetic */ int $m$0(Object arg0) {
return ((SpanSpec) arg0).mStart;
}
public final int applyAsInt(Object obj) {
return $m$0(obj);
}
}
| 358 | 0.678771 | 0.653631 | 13 | 26.538462 | 27.1339 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false |
12
|
8e93ccd5723f0103df41f1e273b569351ab2509a
| 25,031,069,455,510 |
6092cbae5816a60b8124bb1921e6a90d7c7c8279
|
/java01/src/step33/exam12/MemberAdd.java
|
8a6014518c868b848f9a71c64115ea23c3227439
|
[] |
no_license
|
kyeonghunmin/mkh
|
https://github.com/kyeonghunmin/mkh
|
847326c0effa8ec85a7e90554beee74eac9c854c
|
5e4fd583d889205654fc6cfc41db37430b6a3173
|
refs/heads/master
| 2020-12-24T20:14:33.579000 | 2016-05-12T08:30:23 | 2016-05-12T08:30:23 | 56,681,395 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
// 주제 : SQL 맵퍼인 mybatis 적용하기 - MemberDao에 적용하기 - insert
package step33.exam12;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MemberAdd {
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext(
"step33/exam12/application-context.xml");
MemberDao memberDao = (MemberDao)context.getBean("memberDao");
Member member = new Member();
member.setName("세종대왕");
member.setEmail("sae@test.com");
member.setPassword("1111");
member.setTel("1111-1111");
memberDao.insert(member);
System.out.println("입력 성공");
}
}
|
UTF-8
|
Java
| 954 |
java
|
MemberAdd.java
|
Java
|
[
{
"context": "Member member = new Member();\n member.setName(\"세종대왕\");\n member.setEmail(\"sae@test.com\");\n membe",
"end": 731,
"score": 0.9998281598091125,
"start": 727,
"tag": "NAME",
"value": "세종대왕"
},
{
"context": "\n member.setName(\"세종대왕\");\n member.setEmail(\"sae@test.com\");\n member.setPassword(\"1111\");\n member.set",
"end": 768,
"score": 0.999927818775177,
"start": 756,
"tag": "EMAIL",
"value": "sae@test.com"
},
{
"context": "setEmail(\"sae@test.com\");\n member.setPassword(\"1111\");\n member.setTel(\"1111-1111\");\n \n membe",
"end": 800,
"score": 0.9991494417190552,
"start": 796,
"tag": "PASSWORD",
"value": "1111"
}
] | null |
[] |
// 주제 : SQL 맵퍼인 mybatis 적용하기 - MemberDao에 적용하기 - insert
package step33.exam12;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MemberAdd {
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext(
"step33/exam12/application-context.xml");
MemberDao memberDao = (MemberDao)context.getBean("memberDao");
Member member = new Member();
member.setName("세종대왕");
member.setEmail("<EMAIL>");
member.setPassword("<PASSWORD>");
member.setTel("1111-1111");
memberDao.insert(member);
System.out.println("입력 성공");
}
}
| 955 | 0.743956 | 0.721978 | 31 | 28.387096 | 23.729221 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.516129 | false | false |
12
|
b9a451f6450b62f36099cbe742d11aeef3ce6978
| 24,421,184,063,877 |
bf05293f6d5beec5a9f501845fa4e6b7697f32e5
|
/src/main/java/ml/icitap/mapo/hr/report/entity/Report.java
|
6e4a3578d0b3b4d023510f90184aaab1a721f197
|
[] |
no_license
|
mertikub/mapo-hr
|
https://github.com/mertikub/mapo-hr
|
85374ffbad9fdd96b6169a4c4e7aa25850867375
|
d23834317f8c20e8c1661ec4e219dce228c8d535
|
refs/heads/master
| 2018-10-14T08:58:17.363000 | 2018-10-10T21:37:02 | 2018-10-10T21:37:02 | 106,617,861 | 0 | 0 | null | false | 2018-11-21T21:51:09 | 2017-10-11T22:55:33 | 2018-11-20T20:11:33 | 2018-11-21T21:51:09 | 50,764 | 0 | 0 | 2 |
Java
| false | null |
package ml.icitap.mapo.hr.report.entity;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderColumn;
import ml.icitap.mapo.hr.backend.data.entity.AbstractEntity;
import ml.icitap.mapo.hr.backend.data.entity.Property;
@Entity
public class Report extends AbstractEntity{
private String name;
@ManyToMany(cascade = {CascadeType.ALL}, fetch=FetchType.EAGER)
@JoinTable(
name="REPORT_PROPERTIES",
joinColumns = {@JoinColumn(name="report_id")},
inverseJoinColumns = {@JoinColumn(name="property_id")}
)
@OrderColumn(name="id")
private Set<ReportProperty> properties = new HashSet<>();
@ManyToMany(cascade = {CascadeType.ALL}, fetch=FetchType.EAGER)
@JoinTable(
name="REPORT_HEADERS",
joinColumns = {@JoinColumn(name="report_id")},
inverseJoinColumns = {@JoinColumn(name="property_id")}
)
@OrderColumn(name="id")
private Set<ReportProperty> headers = new HashSet<>();
@ManyToOne(cascade= {CascadeType.ALL, CascadeType.PERSIST})
@JoinColumn(name="group_by_property")
private ReportProperty groupByProperty;
@OneToMany(mappedBy="report", fetch=FetchType.EAGER, cascade=CascadeType.ALL, orphanRemoval=true)
private Set<SearchCriteria> searchCriterias =new HashSet<>();
private boolean editable = false;
public Report() { }
public Report(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<ReportProperty> getProperties() {
return Collections.unmodifiableSet(properties);
}
public List<Property> getSortedProperties(){
return this.properties.stream().sorted(Comparator.comparing(ReportProperty::getIndex,
Comparator.nullsLast(Comparator.comparing(x -> x)))).map(r -> r.getProperty()).collect(Collectors.toList());
}
public void setProperties(Set<ReportProperty> properties) {
this.properties.clear();
if(properties != null)
this.properties.addAll(properties);
}
public Report addProperty(ReportProperty property) {
this.properties.add(property);
return this;
}
public Report property(Property property) {
this.properties.add(ReportProperty.of(property));
return this;
}
public Report removeProperty(ReportProperty property) {
this.properties.remove(property);
return this;
}
public Set<ReportProperty> getHeaders() {
return Collections.unmodifiableSet(headers);
}
public void setHeaders(Set<ReportProperty> headers) {
this.headers = headers;
}
public Report addHeader(ReportProperty header) {
this.headers.add(header);
return this;
}
public Report header(Property header) {
this.headers.add(ReportProperty.of(header));
return this;
}
public Report removeHeader(ReportProperty header) {
this.properties.remove(header);
return this;
}
public boolean hasHeader() {
return headers != null &&!headers.isEmpty();
}
public void ifHasGroupBy(Consumer<ReportProperty> consumer) {
if(groupByProperty != null) {
consumer.accept(groupByProperty);
}
}
public ReportProperty getGroupByProperty() {
return groupByProperty;
}
public void setGroupByProperty(ReportProperty groupByProperty) {
this.groupByProperty = groupByProperty;
}
public Report groupBy(Property property) {
setGroupByProperty(ReportProperty.of(property));
return this;
}
public Set<SearchCriteria> getSearchCriterias() {
return Collections.unmodifiableSet(searchCriterias);
}
public void setSearchCriterias(Set<SearchCriteria> searchCriterias) {
this.searchCriterias.clear();
if(searchCriterias != null) {
this.searchCriterias.addAll(searchCriterias);
}
}
public Report addSearchCriteria(SearchCriteria criteria) {
criteria.setReport(this);
this.searchCriterias.add(criteria);
return this;
}
public boolean isEditable() {
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
}
}
|
UTF-8
|
Java
| 4,572 |
java
|
Report.java
|
Java
|
[] | null |
[] |
package ml.icitap.mapo.hr.report.entity;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderColumn;
import ml.icitap.mapo.hr.backend.data.entity.AbstractEntity;
import ml.icitap.mapo.hr.backend.data.entity.Property;
@Entity
public class Report extends AbstractEntity{
private String name;
@ManyToMany(cascade = {CascadeType.ALL}, fetch=FetchType.EAGER)
@JoinTable(
name="REPORT_PROPERTIES",
joinColumns = {@JoinColumn(name="report_id")},
inverseJoinColumns = {@JoinColumn(name="property_id")}
)
@OrderColumn(name="id")
private Set<ReportProperty> properties = new HashSet<>();
@ManyToMany(cascade = {CascadeType.ALL}, fetch=FetchType.EAGER)
@JoinTable(
name="REPORT_HEADERS",
joinColumns = {@JoinColumn(name="report_id")},
inverseJoinColumns = {@JoinColumn(name="property_id")}
)
@OrderColumn(name="id")
private Set<ReportProperty> headers = new HashSet<>();
@ManyToOne(cascade= {CascadeType.ALL, CascadeType.PERSIST})
@JoinColumn(name="group_by_property")
private ReportProperty groupByProperty;
@OneToMany(mappedBy="report", fetch=FetchType.EAGER, cascade=CascadeType.ALL, orphanRemoval=true)
private Set<SearchCriteria> searchCriterias =new HashSet<>();
private boolean editable = false;
public Report() { }
public Report(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<ReportProperty> getProperties() {
return Collections.unmodifiableSet(properties);
}
public List<Property> getSortedProperties(){
return this.properties.stream().sorted(Comparator.comparing(ReportProperty::getIndex,
Comparator.nullsLast(Comparator.comparing(x -> x)))).map(r -> r.getProperty()).collect(Collectors.toList());
}
public void setProperties(Set<ReportProperty> properties) {
this.properties.clear();
if(properties != null)
this.properties.addAll(properties);
}
public Report addProperty(ReportProperty property) {
this.properties.add(property);
return this;
}
public Report property(Property property) {
this.properties.add(ReportProperty.of(property));
return this;
}
public Report removeProperty(ReportProperty property) {
this.properties.remove(property);
return this;
}
public Set<ReportProperty> getHeaders() {
return Collections.unmodifiableSet(headers);
}
public void setHeaders(Set<ReportProperty> headers) {
this.headers = headers;
}
public Report addHeader(ReportProperty header) {
this.headers.add(header);
return this;
}
public Report header(Property header) {
this.headers.add(ReportProperty.of(header));
return this;
}
public Report removeHeader(ReportProperty header) {
this.properties.remove(header);
return this;
}
public boolean hasHeader() {
return headers != null &&!headers.isEmpty();
}
public void ifHasGroupBy(Consumer<ReportProperty> consumer) {
if(groupByProperty != null) {
consumer.accept(groupByProperty);
}
}
public ReportProperty getGroupByProperty() {
return groupByProperty;
}
public void setGroupByProperty(ReportProperty groupByProperty) {
this.groupByProperty = groupByProperty;
}
public Report groupBy(Property property) {
setGroupByProperty(ReportProperty.of(property));
return this;
}
public Set<SearchCriteria> getSearchCriterias() {
return Collections.unmodifiableSet(searchCriterias);
}
public void setSearchCriterias(Set<SearchCriteria> searchCriterias) {
this.searchCriterias.clear();
if(searchCriterias != null) {
this.searchCriterias.addAll(searchCriterias);
}
}
public Report addSearchCriteria(SearchCriteria criteria) {
criteria.setReport(this);
this.searchCriterias.add(criteria);
return this;
}
public boolean isEditable() {
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
}
}
| 4,572 | 0.725284 | 0.725284 | 173 | 24.427746 | 22.957909 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.537572 | false | false |
14
|
72554a1ac80111657d026b835963a79647b52cd1
| 10,754,598,178,053 |
3132fa71a40dcb4b337c4ea9af73dcc61dac2e61
|
/leetcode/src/palin_1.java
|
adb9f707742e7d40a24379e0cd55a3b968bc3eb1
|
[] |
no_license
|
henrygatech/InterviewQS
|
https://github.com/henrygatech/InterviewQS
|
1c43980d9864cbe2734441209f7870df214a6e12
|
d09caa69b87950de196e5e375416a526db0c21f7
|
refs/heads/master
| 2016-09-05T12:03:43.523000 | 2015-01-13T01:18:42 | 2015-01-13T01:18:42 | 29,165,686 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.ArrayList;
/**
* Created by Henry on 2014/12/11.
*/
public class palin_1 {
public ArrayList<ArrayList<String>> partition(String s) {
int n = s.length();
boolean[][] dp = new boolean[n][n];
for(int i = 0;i<n;i++){
dp[i][i] = true;
}
for(int i = n-1;i>=0;i--){
for(int j = i;j<n;j++){
if(j-i<2&&s.charAt(i)==s.charAt(j)){
dp[i][j] = true;
}
else if(j-i>=2&&s.charAt(i)==s.charAt(j)){
dp[i][j] = dp[i+1][j-1];
}
}
}
ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
dfs(s,ret,list,dp);
return ret;
}
public void dfs(String s,ArrayList<ArrayList<String>> ret, ArrayList<String> list,boolean[][] dp){
if(s.length()==0){
ret.add((ArrayList<String>)list.clone());
return;
}
if(s.length()<0){
return;
}
for(int i = 1;i<=s.length();i++){
String prefix = s.substring(0,i);
String suffix = s.substring(i);
if(dp[0][i-1]==true){
list.add(prefix);
dfs(suffix,ret,list,dp);
list.remove(list.size()-1);
}
}
}
public static void main(String[] args){
palin_1 p = new palin_1();
//p.partition("seeslaveidemonstrateyetartsnomedievalsees");
ArrayList<ArrayList<String>> ret = p.partition("aab");
for(int i = 0;i<ret.size();i++){
for(int j = 0;j<ret.get(i).size();j++){
System.out.print(ret.get(i).get(j));
System.out.print(";");
}
System.out.println();
}
}
}
|
UTF-8
|
Java
| 1,869 |
java
|
palin_1.java
|
Java
|
[
{
"context": "import java.util.ArrayList;\n\n/**\n * Created by Henry on 2014/12/11.\n */\npublic class palin_1 {\n pub",
"end": 52,
"score": 0.9995771646499634,
"start": 47,
"tag": "NAME",
"value": "Henry"
}
] | null |
[] |
import java.util.ArrayList;
/**
* Created by Henry on 2014/12/11.
*/
public class palin_1 {
public ArrayList<ArrayList<String>> partition(String s) {
int n = s.length();
boolean[][] dp = new boolean[n][n];
for(int i = 0;i<n;i++){
dp[i][i] = true;
}
for(int i = n-1;i>=0;i--){
for(int j = i;j<n;j++){
if(j-i<2&&s.charAt(i)==s.charAt(j)){
dp[i][j] = true;
}
else if(j-i>=2&&s.charAt(i)==s.charAt(j)){
dp[i][j] = dp[i+1][j-1];
}
}
}
ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
dfs(s,ret,list,dp);
return ret;
}
public void dfs(String s,ArrayList<ArrayList<String>> ret, ArrayList<String> list,boolean[][] dp){
if(s.length()==0){
ret.add((ArrayList<String>)list.clone());
return;
}
if(s.length()<0){
return;
}
for(int i = 1;i<=s.length();i++){
String prefix = s.substring(0,i);
String suffix = s.substring(i);
if(dp[0][i-1]==true){
list.add(prefix);
dfs(suffix,ret,list,dp);
list.remove(list.size()-1);
}
}
}
public static void main(String[] args){
palin_1 p = new palin_1();
//p.partition("seeslaveidemonstrateyetartsnomedievalsees");
ArrayList<ArrayList<String>> ret = p.partition("aab");
for(int i = 0;i<ret.size();i++){
for(int j = 0;j<ret.get(i).size();j++){
System.out.print(ret.get(i).get(j));
System.out.print(";");
}
System.out.println();
}
}
}
| 1,869 | 0.456394 | 0.441948 | 65 | 27.753845 | 21.94681 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.723077 | false | false |
14
|
7d8471d1e68dd03ec4d64cd0d2a2fc0a34997d06
| 20,229,296,027,881 |
ccb2a94d496c7bf898939378f1e98bde6b14d44d
|
/src/com/comunus/projectReport/serviceI/ServiceImpl/CommonServiceImpl.java
|
0df9101617653aca4de57750e08c495e5eaae668
|
[] |
no_license
|
kishan-hub/Projects-Report
|
https://github.com/kishan-hub/Projects-Report
|
9eb66ba3853536d66b67ba59947f0f5ee8803aa0
|
9e528896c326d64ef2d69e2830f23ab940351f4d
|
refs/heads/master
| 2023-08-05T05:19:57.924000 | 2023-07-31T08:36:16 | 2023-07-31T08:36:16 | 312,250,266 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.comunus.projectReport.serviceI.ServiceImpl;
import com.comunus.projectReport.daoI.CommonDAOI;
import com.comunus.projectReport.daoI.daoImpl.CommonDAOImpl;
import com.comunus.projectReport.dto.LoginDTO;
import com.comunus.projectReport.serviceI.CommonServiceI;
public class CommonServiceImpl implements CommonServiceI {
@Override
public String getLogin(LoginDTO loginDto) {
// TODO Auto-generated method stub
CommonDAOI commonDaoI=new CommonDAOImpl();
return commonDaoI.getLogin(loginDto);
}
}
|
UTF-8
|
Java
| 538 |
java
|
CommonServiceImpl.java
|
Java
|
[] | null |
[] |
package com.comunus.projectReport.serviceI.ServiceImpl;
import com.comunus.projectReport.daoI.CommonDAOI;
import com.comunus.projectReport.daoI.daoImpl.CommonDAOImpl;
import com.comunus.projectReport.dto.LoginDTO;
import com.comunus.projectReport.serviceI.CommonServiceI;
public class CommonServiceImpl implements CommonServiceI {
@Override
public String getLogin(LoginDTO loginDto) {
// TODO Auto-generated method stub
CommonDAOI commonDaoI=new CommonDAOImpl();
return commonDaoI.getLogin(loginDto);
}
}
| 538 | 0.79368 | 0.79368 | 17 | 29.647058 | 24.107458 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.882353 | false | false |
14
|
a231f77f39b1af2b8f90632937e42cf76082654b
| 22,016,002,413,927 |
b9b0a807365723046101dd3b9a4f924c0b7faa99
|
/taxii-server/src/main/java/io/digitalstate/taxii/mongo/repository/CollectionMembershipsRepository.java
|
11b779463925a5ac9e49d8cf48dad05e33db1809
|
[] |
no_license
|
StephenOTT/TAXII-springboot-bpmn
|
https://github.com/StephenOTT/TAXII-springboot-bpmn
|
b922223197a6cba3ccd2abdb58925ff670977d4f
|
31959c1466d94a892ada9718ee8af8c35490fe9d
|
refs/heads/master
| 2020-04-12T16:22:49.523000 | 2019-05-09T23:51:12 | 2019-05-09T23:51:12 | 162,610,835 | 12 | 5 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package io.digitalstate.taxii.mongo.repository;
import io.digitalstate.taxii.mongo.model.document.CollectionMembershipDocument;
import io.digitalstate.taxii.mongo.repository.impl.collection.CollectionMembershipsRepositoryCustom;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface CollectionMembershipsRepository extends MongoRepository<CollectionMembershipDocument, String>, CollectionMembershipsRepositoryCustom {
}
|
UTF-8
|
Java
| 454 |
java
|
CollectionMembershipsRepository.java
|
Java
|
[] | null |
[] |
package io.digitalstate.taxii.mongo.repository;
import io.digitalstate.taxii.mongo.model.document.CollectionMembershipDocument;
import io.digitalstate.taxii.mongo.repository.impl.collection.CollectionMembershipsRepositoryCustom;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface CollectionMembershipsRepository extends MongoRepository<CollectionMembershipDocument, String>, CollectionMembershipsRepositoryCustom {
}
| 454 | 0.885463 | 0.885463 | 9 | 49.444443 | 51.357376 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false |
14
|
54bbaac098c142f0cbf7f390e67842cd337afeae
| 6,081,673,716,787 |
93d1f0d7142eb2a1e5d0692bfda01b6c770c6f12
|
/src/com/cpvsn/db/service/wetan/DemandService.java
|
9140e08e2d9c5e4416f3968035ea2c4e696b2267
|
[] |
no_license
|
belonghu/ks_ndb_api
|
https://github.com/belonghu/ks_ndb_api
|
261f191279220437cca8de606f5601fc4b133736
|
a2c0b7abb1318acb57b07d1b08df0313cacd9ad7
|
refs/heads/master
| 2019-06-17T00:23:25.644000 | 2017-08-07T07:51:21 | 2017-08-07T07:51:21 | 99,551,422 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.cpvsn.db.service.wetan;
import com.cpvsn.db.pojo.req.common.WetanReqAction;
/**
* Created by pingli on 2016/12/24.
*/
public interface DemandService {
/**
* 保存修改后的邮件记录的内容
*/
void saveDemandProgramsContent(WetanReqAction action);
}
|
UTF-8
|
Java
| 292 |
java
|
DemandService.java
|
Java
|
[
{
"context": "pojo.req.common.WetanReqAction;\n\n/**\n * Created by pingli on 2016/12/24.\n */\npublic interface DemandService",
"end": 114,
"score": 0.9993155002593994,
"start": 108,
"tag": "USERNAME",
"value": "pingli"
}
] | null |
[] |
package com.cpvsn.db.service.wetan;
import com.cpvsn.db.pojo.req.common.WetanReqAction;
/**
* Created by pingli on 2016/12/24.
*/
public interface DemandService {
/**
* 保存修改后的邮件记录的内容
*/
void saveDemandProgramsContent(WetanReqAction action);
}
| 292 | 0.703008 | 0.672932 | 14 | 18 | 19.675945 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.214286 | false | false |
14
|
03969fb6948b348ff239ba55d70e7cc66b1ed193
| 28,398,323,818,150 |
8c720ec0181e022287c2129488934bf0e2a94f1d
|
/src/main/java/com/example/recycleviewdragsortdemo/ItemTouchHelperViewHolder.java
|
6f591cc861d43c9dfee1020d83184f7126ddbd99
|
[
"Apache-2.0"
] |
permissive
|
wuyinlei/ItemTouchHelperRecycleView
|
https://github.com/wuyinlei/ItemTouchHelperRecycleView
|
c0ef30592165e9d399a3560f48d14120501c6642
|
1dce471c846a94af4c62ad2991c606e6dde2faa5
|
refs/heads/master
| 2021-01-09T21:51:27.772000 | 2016-03-15T16:05:30 | 2016-03-15T16:05:30 | 53,958,699 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.recycleviewdragsortdemo;
/**
* Created by 若兰 on 2016/3/15.
* 一个懂得了编程乐趣的小白,希望自己
* 能够在这个道路上走的很远,也希望自己学习到的
* 知识可以帮助更多的人,分享就是学习的一种乐趣
* QQ:1069584784
* csdn:http://blog.csdn.net/wuyinlei
*/
public interface ItemTouchHelperViewHolder {
/**
* Called when the {@link ItemTouchHelper} first registers an item as being moved or swiped.
* Implementations should update the item view to indicate it's active state.
*/
void onItemSelected();
/**
* Called when the {@link ItemTouchHelper} has completed the move or swipe, and the active item
* state should be cleared.
*/
void onItemClear();
}
|
UTF-8
|
Java
| 782 |
java
|
ItemTouchHelperViewHolder.java
|
Java
|
[
{
"context": "ample.recycleviewdragsortdemo;\n\n/**\n * Created by 若兰 on 2016/3/15.\n * 一个懂得了编程乐趣的小白,希望自己\n * 能够在这个道路上走的很",
"end": 66,
"score": 0.900162935256958,
"start": 64,
"tag": "NAME",
"value": "若兰"
},
{
"context": "种乐趣\n * QQ:1069584784\n * csdn:http://blog.csdn.net/wuyinlei\n */\n\npublic interface ItemTouchHelperViewHolder {",
"end": 208,
"score": 0.9993359446525574,
"start": 200,
"tag": "USERNAME",
"value": "wuyinlei"
}
] | null |
[] |
package com.example.recycleviewdragsortdemo;
/**
* Created by 若兰 on 2016/3/15.
* 一个懂得了编程乐趣的小白,希望自己
* 能够在这个道路上走的很远,也希望自己学习到的
* 知识可以帮助更多的人,分享就是学习的一种乐趣
* QQ:1069584784
* csdn:http://blog.csdn.net/wuyinlei
*/
public interface ItemTouchHelperViewHolder {
/**
* Called when the {@link ItemTouchHelper} first registers an item as being moved or swiped.
* Implementations should update the item view to indicate it's active state.
*/
void onItemSelected();
/**
* Called when the {@link ItemTouchHelper} has completed the move or swipe, and the active item
* state should be cleared.
*/
void onItemClear();
}
| 782 | 0.696049 | 0.670213 | 26 | 24.307692 | 28.177691 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.192308 | false | false |
14
|
9b81419710db53edda74070e0f8e032efd3ff92f
| 27,513,560,538,082 |
4e2d9edbaf1125b1d9f089d6f27808b0cab71e82
|
/src/main/java/com/chuange/aishijing/service/impl/alipay/.svn/text-base/AlipayServiceImpl.java.svn-base
|
457506df012d15b0c0a4838e594a867daacb87f2
|
[] |
no_license
|
yuany22/Interface
|
https://github.com/yuany22/Interface
|
ec146afc1c617b7d848276aa103f455ca5690979
|
0bbc3417423e44b33eeacb30a12706e18e58ee28
|
refs/heads/master
| 2020-05-03T08:48:11.239000 | 2019-03-30T09:12:12 | 2019-03-30T09:12:12 | 178,536,651 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.chuange.aishijing.service.impl.alipay;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.util.Date;
import java.util.Map;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.chuange.aishijing.alipayBean.AlipayOrderBean;
import com.chuange.aishijing.alipayBean.OrderBean;
import com.chuange.aishijing.dao.alipay.AlipayReporsitory;
import com.chuange.aishijing.service.alipay.AlipayService;
import com.chuange.aishijing.util.AlipayConfig;
@Service
@Transactional
public class AlipayServiceImpl implements AlipayService{
public String APP_ID=AlipayConfig.APPID;
public String APP_Private_key=AlipayConfig.RSA_PRIVATE_KEY;
public String charset=AlipayConfig.CHARSET;
public String format=AlipayConfig.FORMAT;
public String url=AlipayConfig.URL;
public String alipay_public_key=AlipayConfig.ALIPAY_PUBLIC_KEY;
public String signtype=AlipayConfig.SIGNTYPE;
public String orderStr="";
@Autowired
private AlipayReporsitory alipayReporsitory;
DateFormat dateFormat=new DateFormat() {
@Override
public Date parse(String source, ParsePosition pos) {
// TODO Auto-generated method stub
return null;
}
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
// TODO Auto-generated method stub
return null;
}
};
@Override
public String getAlipayOrderStr(OrderBean order) {
// TODO Auto-generated method stub
order.setOrderId("1");
AlipayOrderBean alipayOrder=new AlipayOrderBean();
alipayOrder.setBuyerPayAmount(0.01);
alipayOrder.setClubOrderId(order.getOrderId());
alipayOrder.setInvoiceAmount(order.getInvoiceAmount());
alipayOrder.setOutTradeNo(order.getOutTradeNo());
alipayOrder.setReceiptAmount(order.getReceiptAmount());
alipayOrder.setRefundFee(order.getRefundFee());
alipayOrder.setTotalAmount(order.getTotalAmount());
alipayOrder.setTradeStatus(order.getTradeStatus());
try {
//实例化客户端(网关,appid,app私钥,格式(utf8),编码,支付宝公钥,加密类型)取得预付订单信息
AlipayClient alipayClient=new DefaultAlipayClient(url, APP_ID, APP_Private_key,
format, charset, alipay_public_key, signtype);
//实例化具体api中对应接口
AlipayTradeAppPayRequest ali_request=new AlipayTradeAppPayRequest();
//实例化sdk model
AlipayTradeAppPayModel model=new AlipayTradeAppPayModel();
//传入业务参数
model.setBody(order.getBody());//商品描述信息
model.setSubject(order.getSubject());
model.setOutTradeNo(order.getOutTradeNo());
model.setTimeoutExpress("30ms");
model.setTotalAmount(order.getTotalAmount().toString());
model.setProductCode("QUICK_MSECURITY_PAY");//销售产品码
ali_request.setBizModel(model);
ali_request.setNotifyUrl(AlipayConfig.notify_url);//服务器地址
ali_request.setReturnUrl(AlipayConfig.return_url);//同步回调地址 app
//调用sdk接口
AlipayTradeAppPayResponse alipayTradeAppPayResponse=alipayClient.sdkExecute(ali_request);
orderStr=alipayTradeAppPayResponse.getBody();
this.createOrderInfo(alipayOrder);
}catch (AlipayApiException e) {
// TODO: handle exception
e.printStackTrace();
}
return orderStr;
}
/**
* 想支付宝发起订单查询请求
*/
@Override
public Byte checkAlipay(String OutTradeNo) {
try {
//实例化客户端(网关,appid,app私钥,格式(utf8),编码,支付宝公钥,加密类型)取得预付订单信息
AlipayClient alipayClient=new DefaultAlipayClient(url, APP_ID, APP_Private_key,
format, charset, alipay_public_key, signtype);
//实例化具体api中对应接口
AlipayTradeQueryRequest alipayTradeQueryRequest=new AlipayTradeQueryRequest();
alipayTradeQueryRequest.setBizContent("{"+
"\"out_trade_no\":\""+OutTradeNo+"\""+
"}");
AlipayTradeQueryResponse alipayTradeQueryResponse=alipayClient.execute(alipayTradeQueryRequest);
if(alipayTradeQueryResponse.isSuccess()) {
AlipayOrderBean order=this.selectByOutTradeNo(OutTradeNo);
//修改数据库支付订单表
order.setTradeNo(alipayTradeQueryResponse.getTradeNo());
order.setBuyerLogonId(alipayTradeQueryResponse.getBuyerLogonId());
order.setTotalAmount(Double.valueOf(alipayTradeQueryResponse.getTotalAmount()));
order.setReceiptAmount(Double.valueOf(alipayTradeQueryResponse.getReceiptAmount()));
order.setInvoiceAmount(Double.valueOf(alipayTradeQueryResponse.getInvoiceAmount()));
order.setBuyerPayAmount(Double.valueOf(alipayTradeQueryResponse.getBuyerPayAmount()));
switch(alipayTradeQueryResponse.getTradeStatus()) {
case "TRADE_FINISHED":
order.setTradeStatus((byte) 3);
break;
case "TRADE_SUCCESS":
order.setTradeStatus((byte) 2);
break;
case "TRADE_CLOSED":
order.setTradeStatus((byte) 1);
break;
case "WAIT_BUYER__PAY":
order.setTradeStatus((byte) 0);
break;
default:
break;
}
this.updateByPrimarykey(order);
return order.getTradeStatus();
}else {
//调用接口失败
}
} catch (AlipayApiException e) {
// TODO: handle exception
e.printStackTrace();
}
return 0;
}
@Override
public void createOrderInfo(AlipayOrderBean alipayOrder) {
// TODO Auto-generated method stub
alipayReporsitory.save(alipayOrder);
}
/**
*
* @param conversionParams
* @return
* 功能:支付宝页面跳转同步通知页面
版本:3.2
日期:2011-03-17
//***********页面功能说明***********
该页面可在本机电脑测试
可放入HTML等美化页面的代码、商户业务逻辑程序代码
TRADE_FINISHED(表示交易已经成功结束,并不能再对该交易做后续操作);
TRADE_SUCCESS(表示交易已经成功结束,可以对该交易做后续操作,如:分润、退款等);
//********************************
*/
public String returnUrl(Map<String, String> conversionParams) {
//商户订单号
String out_trade_no = conversionParams.get("out_trade_no");
//支付宝交易号
String trade_no =conversionParams.get("trade_no");
//获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
//计算得出通知验证结果
//boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
boolean verify_result;
try {
verify_result = AlipaySignature.rsaCheckV1(conversionParams, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2");
String tradeStatus=conversionParams.get("trade_status");//交易状态
if(verify_result){//验证成功
//////////////////////////////////////////////////////////////////////////////////////////
//请在这里加上商户的业务逻辑程序代码
//该页面可做页面美工编辑
switch(tradeStatus) {
case "TRADE_FINISHED" ://交易结束并不能退款
// alipayorder.setTradeStatus((byte) 3);
break;
case "TRADE_SUCCESS" ://交易支付成功
// alipayorder.setTradeStatus((byte) 2);
break;
case "TRADE_CLOSED" ://未付款 交易超时关闭 支付完成全额退款
// alipayorder.setTradeStatus((byte) 1);
break;
case "WAIT_BUYER_PAY" ://交易创建并等待买家付款
//alipayorder.setTradeStatus((byte) 0);
break;
default:
break;
}
}else{
//该页面可做页面美工编辑
// out.clear();
// out.println("验证失败");
}
} catch (AlipayApiException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// out.clear();
// out.println("验证成功<br />");
//——请根据您的业务逻辑来编写程序(以上代码仅作参考)——
//////////////////////////////////////////////////////////////////////////////////////////
return "";
}
/**
* 异步逻辑处理
*/
@Override
public String notify(Map<String, String> conversionParams) {
// TODO Auto-generated method stub
boolean signVerified=false;
try {
//验证签名
signVerified=AlipaySignature.rsaCheckV1(conversionParams, alipay_public_key, charset, signtype);
} catch (AlipayApiException e) {
// TODO: handle exception
e.printStackTrace();
}
//验签通过
if (signVerified) {
String appId=conversionParams.get("app_id");
String notifyTime=conversionParams.get("notify_time");//通知时间
String gmtCreate=conversionParams.get("gmt_create");//交易创建时间
String gmtPayment=conversionParams.get("gmt_payment");//交易付款时间
String gmtRefund=conversionParams.get("gmt_refund");//交易退款时间
String gmtClose=conversionParams.get("gmt_close");//交易结束时间
String tradeno=conversionParams.get("trade_no");//支付宝的交易号
String outTradeNo=conversionParams.get("out_trade_no");//获取商户之前传给支付宝的订单
String outBizNo=conversionParams.get("out_biz_no");//商户业务号(退款通知中返回退款申请的流水号)
String buyerLogonId=conversionParams.get("buyer_logon_id");//买家支付宝账号
String sellerId=conversionParams.get("seller_id");//卖家支付宝账号
String sellerEmail=conversionParams.get("seller_email");//卖家支付宝账号
String totalAmount=conversionParams.get("total_amount");//订单金额
String receiptAmount=conversionParams.get("receipt_amount");//实收金额
String invoiceAmount=conversionParams.get("invoice_amount");//开票金额
String buyerPayAmount=conversionParams.get("buyer_pay_amount");//付款金额
String tradeStatus=conversionParams.get("trade_status");//交易状态
//需要检验的值(out——trade_no,totalamount,sellerid,appid)
AlipayOrderBean alipayorder=this.selectByOutTradeNo(outTradeNo);
if(alipayorder != null && totalAmount.equals(alipayorder.getTotalAmount().toString())&&APP_ID.equals(appId)){
//alipayorder.setNotifyTime((notifyTime));
//alipayorder.setGmtCreate(gmtCreate);
//alipayorder.setGmtPayment(gmtPayment);
//alipayorder.setGmtRefund(gmtRefund);
//alipayorder.setGmtClose(gmtClose);
alipayorder.setTradeNo(tradeno);
alipayorder.setOutBizNo(outBizNo);
alipayorder.setBuyerLogonId(buyerLogonId);
alipayorder.setSellerId(sellerId);
alipayorder.setSellerId(sellerEmail);
alipayorder.setTotalAmount(Double.valueOf(totalAmount));
alipayorder.setReceiptAmount(Double.valueOf(receiptAmount));
alipayorder.setInvoiceAmount(Double.valueOf(invoiceAmount));
alipayorder.setBuyerPayAmount(Double.valueOf(buyerPayAmount));
switch(tradeStatus) {
case "TRADE_FINISHED" ://交易结束并不能退款
alipayorder.setTradeStatus((byte) 3);
break;
case "TRADE_SUCCESS" ://交易支付成功
alipayorder.setTradeStatus((byte) 2);
break;
case "TRADE_CLOSED" ://未付款 交易超时关闭 支付完成全额退款
alipayorder.setTradeStatus((byte) 1);
break;
case "WAIT_BUYER_PAY" ://交易创建并等待买家付款
alipayorder.setTradeStatus((byte) 0);
break;
default:
break;
}
AlipayOrderBean returnResult=this.updateByPrimarykey(alipayorder);
if(tradeStatus.equals("TRADE_SUCCESS")) {
if(returnResult != null) {
return "success";
}else {
return "fail";
}
}else {
return "fail";
}
}else {
//日志打印,与校验值不一致,返回fail
return "fail";
}
}else {
//日志打印验签不通过
return "fail";
}
}
@Override
public AlipayOrderBean selectByOutTradeNo(String outTradeNo) {
// TODO Auto-generated method stub
return alipayReporsitory.findByOutTradeNo(outTradeNo);
}
@Override
public AlipayOrderBean updateByPrimarykey(AlipayOrderBean alipayOrder) {
// TODO Auto-generated method stub
return alipayReporsitory.saveAndFlush(alipayOrder);
}
}
|
UTF-8
|
Java
| 12,494 |
AlipayServiceImpl.java.svn-base
|
Java
|
[] | null |
[] |
package com.chuange.aishijing.service.impl.alipay;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.util.Date;
import java.util.Map;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.chuange.aishijing.alipayBean.AlipayOrderBean;
import com.chuange.aishijing.alipayBean.OrderBean;
import com.chuange.aishijing.dao.alipay.AlipayReporsitory;
import com.chuange.aishijing.service.alipay.AlipayService;
import com.chuange.aishijing.util.AlipayConfig;
@Service
@Transactional
public class AlipayServiceImpl implements AlipayService{
public String APP_ID=AlipayConfig.APPID;
public String APP_Private_key=AlipayConfig.RSA_PRIVATE_KEY;
public String charset=AlipayConfig.CHARSET;
public String format=AlipayConfig.FORMAT;
public String url=AlipayConfig.URL;
public String alipay_public_key=AlipayConfig.ALIPAY_PUBLIC_KEY;
public String signtype=AlipayConfig.SIGNTYPE;
public String orderStr="";
@Autowired
private AlipayReporsitory alipayReporsitory;
DateFormat dateFormat=new DateFormat() {
@Override
public Date parse(String source, ParsePosition pos) {
// TODO Auto-generated method stub
return null;
}
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
// TODO Auto-generated method stub
return null;
}
};
@Override
public String getAlipayOrderStr(OrderBean order) {
// TODO Auto-generated method stub
order.setOrderId("1");
AlipayOrderBean alipayOrder=new AlipayOrderBean();
alipayOrder.setBuyerPayAmount(0.01);
alipayOrder.setClubOrderId(order.getOrderId());
alipayOrder.setInvoiceAmount(order.getInvoiceAmount());
alipayOrder.setOutTradeNo(order.getOutTradeNo());
alipayOrder.setReceiptAmount(order.getReceiptAmount());
alipayOrder.setRefundFee(order.getRefundFee());
alipayOrder.setTotalAmount(order.getTotalAmount());
alipayOrder.setTradeStatus(order.getTradeStatus());
try {
//实例化客户端(网关,appid,app私钥,格式(utf8),编码,支付宝公钥,加密类型)取得预付订单信息
AlipayClient alipayClient=new DefaultAlipayClient(url, APP_ID, APP_Private_key,
format, charset, alipay_public_key, signtype);
//实例化具体api中对应接口
AlipayTradeAppPayRequest ali_request=new AlipayTradeAppPayRequest();
//实例化sdk model
AlipayTradeAppPayModel model=new AlipayTradeAppPayModel();
//传入业务参数
model.setBody(order.getBody());//商品描述信息
model.setSubject(order.getSubject());
model.setOutTradeNo(order.getOutTradeNo());
model.setTimeoutExpress("30ms");
model.setTotalAmount(order.getTotalAmount().toString());
model.setProductCode("QUICK_MSECURITY_PAY");//销售产品码
ali_request.setBizModel(model);
ali_request.setNotifyUrl(AlipayConfig.notify_url);//服务器地址
ali_request.setReturnUrl(AlipayConfig.return_url);//同步回调地址 app
//调用sdk接口
AlipayTradeAppPayResponse alipayTradeAppPayResponse=alipayClient.sdkExecute(ali_request);
orderStr=alipayTradeAppPayResponse.getBody();
this.createOrderInfo(alipayOrder);
}catch (AlipayApiException e) {
// TODO: handle exception
e.printStackTrace();
}
return orderStr;
}
/**
* 想支付宝发起订单查询请求
*/
@Override
public Byte checkAlipay(String OutTradeNo) {
try {
//实例化客户端(网关,appid,app私钥,格式(utf8),编码,支付宝公钥,加密类型)取得预付订单信息
AlipayClient alipayClient=new DefaultAlipayClient(url, APP_ID, APP_Private_key,
format, charset, alipay_public_key, signtype);
//实例化具体api中对应接口
AlipayTradeQueryRequest alipayTradeQueryRequest=new AlipayTradeQueryRequest();
alipayTradeQueryRequest.setBizContent("{"+
"\"out_trade_no\":\""+OutTradeNo+"\""+
"}");
AlipayTradeQueryResponse alipayTradeQueryResponse=alipayClient.execute(alipayTradeQueryRequest);
if(alipayTradeQueryResponse.isSuccess()) {
AlipayOrderBean order=this.selectByOutTradeNo(OutTradeNo);
//修改数据库支付订单表
order.setTradeNo(alipayTradeQueryResponse.getTradeNo());
order.setBuyerLogonId(alipayTradeQueryResponse.getBuyerLogonId());
order.setTotalAmount(Double.valueOf(alipayTradeQueryResponse.getTotalAmount()));
order.setReceiptAmount(Double.valueOf(alipayTradeQueryResponse.getReceiptAmount()));
order.setInvoiceAmount(Double.valueOf(alipayTradeQueryResponse.getInvoiceAmount()));
order.setBuyerPayAmount(Double.valueOf(alipayTradeQueryResponse.getBuyerPayAmount()));
switch(alipayTradeQueryResponse.getTradeStatus()) {
case "TRADE_FINISHED":
order.setTradeStatus((byte) 3);
break;
case "TRADE_SUCCESS":
order.setTradeStatus((byte) 2);
break;
case "TRADE_CLOSED":
order.setTradeStatus((byte) 1);
break;
case "WAIT_BUYER__PAY":
order.setTradeStatus((byte) 0);
break;
default:
break;
}
this.updateByPrimarykey(order);
return order.getTradeStatus();
}else {
//调用接口失败
}
} catch (AlipayApiException e) {
// TODO: handle exception
e.printStackTrace();
}
return 0;
}
@Override
public void createOrderInfo(AlipayOrderBean alipayOrder) {
// TODO Auto-generated method stub
alipayReporsitory.save(alipayOrder);
}
/**
*
* @param conversionParams
* @return
* 功能:支付宝页面跳转同步通知页面
版本:3.2
日期:2011-03-17
//***********页面功能说明***********
该页面可在本机电脑测试
可放入HTML等美化页面的代码、商户业务逻辑程序代码
TRADE_FINISHED(表示交易已经成功结束,并不能再对该交易做后续操作);
TRADE_SUCCESS(表示交易已经成功结束,可以对该交易做后续操作,如:分润、退款等);
//********************************
*/
public String returnUrl(Map<String, String> conversionParams) {
//商户订单号
String out_trade_no = conversionParams.get("out_trade_no");
//支付宝交易号
String trade_no =conversionParams.get("trade_no");
//获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
//计算得出通知验证结果
//boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
boolean verify_result;
try {
verify_result = AlipaySignature.rsaCheckV1(conversionParams, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2");
String tradeStatus=conversionParams.get("trade_status");//交易状态
if(verify_result){//验证成功
//////////////////////////////////////////////////////////////////////////////////////////
//请在这里加上商户的业务逻辑程序代码
//该页面可做页面美工编辑
switch(tradeStatus) {
case "TRADE_FINISHED" ://交易结束并不能退款
// alipayorder.setTradeStatus((byte) 3);
break;
case "TRADE_SUCCESS" ://交易支付成功
// alipayorder.setTradeStatus((byte) 2);
break;
case "TRADE_CLOSED" ://未付款 交易超时关闭 支付完成全额退款
// alipayorder.setTradeStatus((byte) 1);
break;
case "WAIT_BUYER_PAY" ://交易创建并等待买家付款
//alipayorder.setTradeStatus((byte) 0);
break;
default:
break;
}
}else{
//该页面可做页面美工编辑
// out.clear();
// out.println("验证失败");
}
} catch (AlipayApiException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// out.clear();
// out.println("验证成功<br />");
//——请根据您的业务逻辑来编写程序(以上代码仅作参考)——
//////////////////////////////////////////////////////////////////////////////////////////
return "";
}
/**
* 异步逻辑处理
*/
@Override
public String notify(Map<String, String> conversionParams) {
// TODO Auto-generated method stub
boolean signVerified=false;
try {
//验证签名
signVerified=AlipaySignature.rsaCheckV1(conversionParams, alipay_public_key, charset, signtype);
} catch (AlipayApiException e) {
// TODO: handle exception
e.printStackTrace();
}
//验签通过
if (signVerified) {
String appId=conversionParams.get("app_id");
String notifyTime=conversionParams.get("notify_time");//通知时间
String gmtCreate=conversionParams.get("gmt_create");//交易创建时间
String gmtPayment=conversionParams.get("gmt_payment");//交易付款时间
String gmtRefund=conversionParams.get("gmt_refund");//交易退款时间
String gmtClose=conversionParams.get("gmt_close");//交易结束时间
String tradeno=conversionParams.get("trade_no");//支付宝的交易号
String outTradeNo=conversionParams.get("out_trade_no");//获取商户之前传给支付宝的订单
String outBizNo=conversionParams.get("out_biz_no");//商户业务号(退款通知中返回退款申请的流水号)
String buyerLogonId=conversionParams.get("buyer_logon_id");//买家支付宝账号
String sellerId=conversionParams.get("seller_id");//卖家支付宝账号
String sellerEmail=conversionParams.get("seller_email");//卖家支付宝账号
String totalAmount=conversionParams.get("total_amount");//订单金额
String receiptAmount=conversionParams.get("receipt_amount");//实收金额
String invoiceAmount=conversionParams.get("invoice_amount");//开票金额
String buyerPayAmount=conversionParams.get("buyer_pay_amount");//付款金额
String tradeStatus=conversionParams.get("trade_status");//交易状态
//需要检验的值(out——trade_no,totalamount,sellerid,appid)
AlipayOrderBean alipayorder=this.selectByOutTradeNo(outTradeNo);
if(alipayorder != null && totalAmount.equals(alipayorder.getTotalAmount().toString())&&APP_ID.equals(appId)){
//alipayorder.setNotifyTime((notifyTime));
//alipayorder.setGmtCreate(gmtCreate);
//alipayorder.setGmtPayment(gmtPayment);
//alipayorder.setGmtRefund(gmtRefund);
//alipayorder.setGmtClose(gmtClose);
alipayorder.setTradeNo(tradeno);
alipayorder.setOutBizNo(outBizNo);
alipayorder.setBuyerLogonId(buyerLogonId);
alipayorder.setSellerId(sellerId);
alipayorder.setSellerId(sellerEmail);
alipayorder.setTotalAmount(Double.valueOf(totalAmount));
alipayorder.setReceiptAmount(Double.valueOf(receiptAmount));
alipayorder.setInvoiceAmount(Double.valueOf(invoiceAmount));
alipayorder.setBuyerPayAmount(Double.valueOf(buyerPayAmount));
switch(tradeStatus) {
case "TRADE_FINISHED" ://交易结束并不能退款
alipayorder.setTradeStatus((byte) 3);
break;
case "TRADE_SUCCESS" ://交易支付成功
alipayorder.setTradeStatus((byte) 2);
break;
case "TRADE_CLOSED" ://未付款 交易超时关闭 支付完成全额退款
alipayorder.setTradeStatus((byte) 1);
break;
case "WAIT_BUYER_PAY" ://交易创建并等待买家付款
alipayorder.setTradeStatus((byte) 0);
break;
default:
break;
}
AlipayOrderBean returnResult=this.updateByPrimarykey(alipayorder);
if(tradeStatus.equals("TRADE_SUCCESS")) {
if(returnResult != null) {
return "success";
}else {
return "fail";
}
}else {
return "fail";
}
}else {
//日志打印,与校验值不一致,返回fail
return "fail";
}
}else {
//日志打印验签不通过
return "fail";
}
}
@Override
public AlipayOrderBean selectByOutTradeNo(String outTradeNo) {
// TODO Auto-generated method stub
return alipayReporsitory.findByOutTradeNo(outTradeNo);
}
@Override
public AlipayOrderBean updateByPrimarykey(AlipayOrderBean alipayOrder) {
// TODO Auto-generated method stub
return alipayReporsitory.saveAndFlush(alipayOrder);
}
}
| 12,494 | 0.724722 | 0.721585 | 324 | 33.432098 | 25.480778 | 126 | false | false | 0 | 0 | 0 | 0 | 91 | 0.016314 | 3.182099 | false | false |
14
|
|
592e52137f636b1c78e54d14b320ca3ee5d1004a
| 29,480,655,540,918 |
d265cccf853b8ce0785736a43a860dd6d4d496d6
|
/zzbxxbspt/src/main/java/com/gdin/dzzwsyb/zzbxxbspt/web/model/Message.java
|
75ccfeff88e43ee721c9fa71140a0a6c21068903
|
[] |
no_license
|
PanzerkleinVv/zzbxxbspt
|
https://github.com/PanzerkleinVv/zzbxxbspt
|
36e3d95b75701b71403006a617dca7232cad6de6
|
1218d37a4011ae49a4e42cc736b6265ef76acf11
|
refs/heads/master
| 2022-12-27T06:54:34.843000 | 2020-01-03T09:22:41 | 2020-01-03T09:22:41 | 220,430,827 | 0 | 0 | null | false | 2022-12-16T03:32:15 | 2019-11-08T09:18:39 | 2020-01-03T09:22:52 | 2022-12-16T03:32:11 | 21,964 | 0 | 0 | 17 |
JavaScript
| false | false |
package com.gdin.dzzwsyb.zzbxxbspt.web.model;
public class Message {
private boolean flag;
private String content;
private Object object;
public Message() {
}
public Message(boolean flag, String content) {
this.flag = flag;
this.content = content;
}
public Message(boolean flag, String content, Object object) {
this.flag = flag;
this.content = content;
this.object = object;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}
|
UTF-8
|
Java
| 807 |
java
|
Message.java
|
Java
|
[] | null |
[] |
package com.gdin.dzzwsyb.zzbxxbspt.web.model;
public class Message {
private boolean flag;
private String content;
private Object object;
public Message() {
}
public Message(boolean flag, String content) {
this.flag = flag;
this.content = content;
}
public Message(boolean flag, String content, Object object) {
this.flag = flag;
this.content = content;
this.object = object;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}
| 807 | 0.648079 | 0.648079 | 50 | 14.14 | 15.561503 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.22 | false | false |
14
|
a283b88b388a391afad20f5f8e796e36fb423d50
| 14,181,982,056,704 |
b0dae6fbb2038b3dd0018440b2bdb3b9e1a84a45
|
/src/main/java/game/rules/impl/CardComparatorFactory.java
|
0a26524775a86c5eaa9088368cba1d452541cff3
|
[] |
no_license
|
akabat/CardGame
|
https://github.com/akabat/CardGame
|
d7ba387b964b711c5a66cffd32c3111f26b0b5c6
|
267aa8f1cb1e1cffd548cf83ebb15e56bf5729ec
|
refs/heads/master
| 2021-01-09T02:53:57.984000 | 2020-02-21T20:10:08 | 2020-02-21T20:10:08 | 242,222,526 | 0 | 0 | null | false | 2020-10-13T19:44:33 | 2020-02-21T20:13:26 | 2020-02-21T20:22:20 | 2020-10-13T19:44:31 | 14 | 0 | 0 | 1 |
Java
| false | false |
package game.rules.impl;
import game.model.deck.ADeck;
import game.rules.ACardComparator;
public class CardComparatorFactory {
public enum CardComparatorType {
HIGHER_RANK_WIN,
LOWER_RANK_WIN
}
public static ACardComparator makeComparator(CardComparatorType eType, ADeck deck) {
ACardComparator comparingRule = null;
switch(eType) {
case HIGHER_RANK_WIN:
comparingRule = new HigherRankWinRule(deck);
break;
case LOWER_RANK_WIN:
comparingRule = new LowerRankWinRule(deck);
break;
}
return comparingRule;
}
}
|
UTF-8
|
Java
| 683 |
java
|
CardComparatorFactory.java
|
Java
|
[] | null |
[] |
package game.rules.impl;
import game.model.deck.ADeck;
import game.rules.ACardComparator;
public class CardComparatorFactory {
public enum CardComparatorType {
HIGHER_RANK_WIN,
LOWER_RANK_WIN
}
public static ACardComparator makeComparator(CardComparatorType eType, ADeck deck) {
ACardComparator comparingRule = null;
switch(eType) {
case HIGHER_RANK_WIN:
comparingRule = new HigherRankWinRule(deck);
break;
case LOWER_RANK_WIN:
comparingRule = new LowerRankWinRule(deck);
break;
}
return comparingRule;
}
}
| 683 | 0.600293 | 0.600293 | 26 | 24.26923 | 20.402786 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.423077 | false | false |
14
|
3d04a845b9c907d464a42966f10b77eb35422d9d
| 30,820,685,364,847 |
57f484bc51709d7debd56c949e4037a5966b6c5b
|
/grid/events/SimpleEntryEvent.java
|
9beab5bfae41a8d6d557fa5c7b0ea1145f2af051
|
[] |
no_license
|
xiangmujbl/adf2
|
https://github.com/xiangmujbl/adf2
|
a8c8eb5524b63e3a01fffdf25a45d3bd5e5de53d
|
cb6a2914633f93ed82cfbe778925e5b904d589c0
|
refs/heads/master
| 2020-03-22T17:02:14.618000 | 2018-10-19T02:05:19 | 2018-10-19T02:05:19 | 140,368,043 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/* */ package com.jnj.adf.dataservice.adfcoreignite.grid.events;
/* */
/* */ import com.gemstone.gemfire.cache.EntryEvent;
/* */ import com.gemstone.gemfire.cache.Operation;
/* */ import com.gemstone.gemfire.cache.Region;
/* */ import com.gemstone.gemfire.cache.SerializedCacheValue;
/* */ import com.gemstone.gemfire.cache.TransactionId;
/* */ import com.gemstone.gemfire.distributed.DistributedMember;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class SimpleEntryEvent<K, V>
/* */ implements EntryEvent<K, V>
/* */ {
/* */ private Region<K, V> r;
/* */ private Operation op;
/* */ private Object arg;
/* */ private K key;
/* */ private V oldValue;
/* */ private SerializedCacheValue<V> soldValue;
/* */ private V newValue;
/* */ private SerializedCacheValue<V> snewValue;
/* */
/* */ public SimpleEntryEvent(EntryEvent<K, V> src)
/* */ {
/* 31 */ this.r = src.getRegion();
/* 32 */ this.op = src.getOperation();
/* 33 */ this.arg = src.getCallbackArgument();
/* 34 */ this.key = src.getKey();
/* 35 */ this.oldValue = src.getOldValue();
/* 36 */ this.soldValue = src.getSerializedOldValue();
/* 37 */ this.newValue = src.getNewValue();
/* 38 */ this.snewValue = src.getSerializedNewValue();
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */ public SimpleEntryEvent(Region<K, V> r, Operation op, Object arg, K key, V oldValue, SerializedCacheValue<V> soldValue, V newValue, SerializedCacheValue<V> snewValue)
/* */ {
/* 47 */ this.r = r;
/* 48 */ this.op = op;
/* 49 */ this.arg = arg;
/* 50 */ this.key = key;
/* 51 */ this.oldValue = oldValue;
/* 52 */ this.soldValue = soldValue;
/* 53 */ this.newValue = newValue;
/* 54 */ this.snewValue = snewValue;
/* */ }
/* */
/* */
/* */
/* */
/* */ public Region<K, V> getRegion()
/* */ {
/* 62 */ return this.r;
/* */ }
/* */
/* */
/* */
/* */ public Operation getOperation()
/* */ {
/* 69 */ return this.op;
/* */ }
/* */
/* */
/* */
/* */
/* */ public Object getCallbackArgument()
/* */ {
/* 77 */ return this.arg;
/* */ }
/* */
/* */
/* */ public boolean isCallbackArgumentAvailable()
/* */ {
/* 83 */ return false;
/* */ }
/* */
/* */
/* */ public boolean isOriginRemote()
/* */ {
/* 89 */ return false;
/* */ }
/* */
/* */
/* */ public DistributedMember getDistributedMember()
/* */ {
/* 95 */ return null;
/* */ }
/* */
/* */
/* */ public boolean isExpiration()
/* */ {
/* 101 */ return false;
/* */ }
/* */
/* */
/* */ public boolean isDistributed()
/* */ {
/* 107 */ return false;
/* */ }
/* */
/* */
/* */
/* */ public K getKey()
/* */ {
/* 114 */ return (K)this.key;
/* */ }
/* */
/* */ public void setKey(K k)
/* */ {
/* 119 */ this.key = k;
/* */ }
/* */
/* */
/* */
/* */ public V getOldValue()
/* */ {
/* 126 */ return (V)this.oldValue;
/* */ }
/* */
/* */
/* */
/* */ public SerializedCacheValue<V> getSerializedOldValue()
/* */ {
/* 133 */ return this.soldValue;
/* */ }
/* */
/* */
/* */
/* */ public V getNewValue()
/* */ {
/* 140 */ return (V)this.newValue;
/* */ }
/* */
/* */
/* */
/* */
/* */ public SerializedCacheValue<V> getSerializedNewValue()
/* */ {
/* 148 */ return this.snewValue;
/* */ }
/* */
/* */
/* */ public boolean isLocalLoad()
/* */ {
/* 154 */ return false;
/* */ }
/* */
/* */
/* */ public boolean isNetLoad()
/* */ {
/* 160 */ return false;
/* */ }
/* */
/* */
/* */ public boolean isLoad()
/* */ {
/* 166 */ return false;
/* */ }
/* */
/* */
/* */ public boolean isNetSearch()
/* */ {
/* 172 */ return false;
/* */ }
/* */
/* */
/* */ public TransactionId getTransactionId()
/* */ {
/* 178 */ return null;
/* */ }
/* */
/* */
/* */ public boolean isBridgeEvent()
/* */ {
/* 184 */ return false;
/* */ }
/* */
/* */
/* */ public boolean hasClientOrigin()
/* */ {
/* 190 */ return false;
/* */ }
/* */
/* */
/* */ public boolean isOldValueAvailable()
/* */ {
/* 196 */ return false;
/* */ }
/* */
/* */
/* */
/* */
/* */ public String toString()
/* */ {
/* 204 */ return "AsyncEvent [r=" + this.r + ", op=" + this.op + ", arg=" + this.arg + ", key=" + this.key + ", oldValue=" + this.oldValue + ", soldValue=" + this.soldValue + ", newValue=" + this.newValue + ", snewValue=" + this.snewValue + "]";
/* */ }
/* */ }
/* Location: C:\Users\jliu315\repository\com\jnj\adf\adf-core\0.3.04\adf-core-0.3.04.jar!\com\jnj\adf\grid\events\SimpleEntryEvent.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/
|
UTF-8
|
Java
| 5,473 |
java
|
SimpleEntryEvent.java
|
Java
|
[
{
"context": "\n/* */ }\n\n\n/* Location: C:\\Users\\jliu315\\repository\\com\\jnj\\adf\\adf-core\\0.3.04\\adf-core-0",
"end": 5295,
"score": 0.9890448451042175,
"start": 5288,
"tag": "USERNAME",
"value": "jliu315"
}
] | null |
[] |
/* */ package com.jnj.adf.dataservice.adfcoreignite.grid.events;
/* */
/* */ import com.gemstone.gemfire.cache.EntryEvent;
/* */ import com.gemstone.gemfire.cache.Operation;
/* */ import com.gemstone.gemfire.cache.Region;
/* */ import com.gemstone.gemfire.cache.SerializedCacheValue;
/* */ import com.gemstone.gemfire.cache.TransactionId;
/* */ import com.gemstone.gemfire.distributed.DistributedMember;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class SimpleEntryEvent<K, V>
/* */ implements EntryEvent<K, V>
/* */ {
/* */ private Region<K, V> r;
/* */ private Operation op;
/* */ private Object arg;
/* */ private K key;
/* */ private V oldValue;
/* */ private SerializedCacheValue<V> soldValue;
/* */ private V newValue;
/* */ private SerializedCacheValue<V> snewValue;
/* */
/* */ public SimpleEntryEvent(EntryEvent<K, V> src)
/* */ {
/* 31 */ this.r = src.getRegion();
/* 32 */ this.op = src.getOperation();
/* 33 */ this.arg = src.getCallbackArgument();
/* 34 */ this.key = src.getKey();
/* 35 */ this.oldValue = src.getOldValue();
/* 36 */ this.soldValue = src.getSerializedOldValue();
/* 37 */ this.newValue = src.getNewValue();
/* 38 */ this.snewValue = src.getSerializedNewValue();
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */ public SimpleEntryEvent(Region<K, V> r, Operation op, Object arg, K key, V oldValue, SerializedCacheValue<V> soldValue, V newValue, SerializedCacheValue<V> snewValue)
/* */ {
/* 47 */ this.r = r;
/* 48 */ this.op = op;
/* 49 */ this.arg = arg;
/* 50 */ this.key = key;
/* 51 */ this.oldValue = oldValue;
/* 52 */ this.soldValue = soldValue;
/* 53 */ this.newValue = newValue;
/* 54 */ this.snewValue = snewValue;
/* */ }
/* */
/* */
/* */
/* */
/* */ public Region<K, V> getRegion()
/* */ {
/* 62 */ return this.r;
/* */ }
/* */
/* */
/* */
/* */ public Operation getOperation()
/* */ {
/* 69 */ return this.op;
/* */ }
/* */
/* */
/* */
/* */
/* */ public Object getCallbackArgument()
/* */ {
/* 77 */ return this.arg;
/* */ }
/* */
/* */
/* */ public boolean isCallbackArgumentAvailable()
/* */ {
/* 83 */ return false;
/* */ }
/* */
/* */
/* */ public boolean isOriginRemote()
/* */ {
/* 89 */ return false;
/* */ }
/* */
/* */
/* */ public DistributedMember getDistributedMember()
/* */ {
/* 95 */ return null;
/* */ }
/* */
/* */
/* */ public boolean isExpiration()
/* */ {
/* 101 */ return false;
/* */ }
/* */
/* */
/* */ public boolean isDistributed()
/* */ {
/* 107 */ return false;
/* */ }
/* */
/* */
/* */
/* */ public K getKey()
/* */ {
/* 114 */ return (K)this.key;
/* */ }
/* */
/* */ public void setKey(K k)
/* */ {
/* 119 */ this.key = k;
/* */ }
/* */
/* */
/* */
/* */ public V getOldValue()
/* */ {
/* 126 */ return (V)this.oldValue;
/* */ }
/* */
/* */
/* */
/* */ public SerializedCacheValue<V> getSerializedOldValue()
/* */ {
/* 133 */ return this.soldValue;
/* */ }
/* */
/* */
/* */
/* */ public V getNewValue()
/* */ {
/* 140 */ return (V)this.newValue;
/* */ }
/* */
/* */
/* */
/* */
/* */ public SerializedCacheValue<V> getSerializedNewValue()
/* */ {
/* 148 */ return this.snewValue;
/* */ }
/* */
/* */
/* */ public boolean isLocalLoad()
/* */ {
/* 154 */ return false;
/* */ }
/* */
/* */
/* */ public boolean isNetLoad()
/* */ {
/* 160 */ return false;
/* */ }
/* */
/* */
/* */ public boolean isLoad()
/* */ {
/* 166 */ return false;
/* */ }
/* */
/* */
/* */ public boolean isNetSearch()
/* */ {
/* 172 */ return false;
/* */ }
/* */
/* */
/* */ public TransactionId getTransactionId()
/* */ {
/* 178 */ return null;
/* */ }
/* */
/* */
/* */ public boolean isBridgeEvent()
/* */ {
/* 184 */ return false;
/* */ }
/* */
/* */
/* */ public boolean hasClientOrigin()
/* */ {
/* 190 */ return false;
/* */ }
/* */
/* */
/* */ public boolean isOldValueAvailable()
/* */ {
/* 196 */ return false;
/* */ }
/* */
/* */
/* */
/* */
/* */ public String toString()
/* */ {
/* 204 */ return "AsyncEvent [r=" + this.r + ", op=" + this.op + ", arg=" + this.arg + ", key=" + this.key + ", oldValue=" + this.oldValue + ", soldValue=" + this.soldValue + ", newValue=" + this.newValue + ", snewValue=" + this.snewValue + "]";
/* */ }
/* */ }
/* Location: C:\Users\jliu315\repository\com\jnj\adf\adf-core\0.3.04\adf-core-0.3.04.jar!\com\jnj\adf\grid\events\SimpleEntryEvent.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/
| 5,473 | 0.420793 | 0.400146 | 212 | 24.820755 | 25.941988 | 249 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.349057 | false | false |
14
|
11da5b53250dae17c8c79b09cd48a7a123d1bfa3
| 8,400,956,065,589 |
537c3b2c18873e4eda12900d2ed58437f3bd47be
|
/crypto/src/test/java/com/platon/crypto/TransactionEncoderTest.java
|
29aa179ab54d50175222f42ec9a4d192d2f039eb
|
[
"Apache-2.0"
] |
permissive
|
PlatONnetwork/client-sdk-java
|
https://github.com/PlatONnetwork/client-sdk-java
|
dd181e747025005b05eb562b81bdc5da310aedb8
|
6fc336b86474a6cab8973c97f93469eb36096fb2
|
refs/heads/master
| 2023-06-26T05:41:15.109000 | 2023-04-18T08:22:21 | 2023-04-18T08:22:21 | 162,657,716 | 173 | 27 |
NOASSERTION
| false | 2023-06-12T08:55:25 | 2018-12-21T02:54:57 | 2023-04-18T08:39:44 | 2023-06-12T08:18:45 | 5,716 | 159 | 22 | 0 |
Java
| false | false |
package com.platon.crypto;
import com.platon.parameters.NetworkParameters;
import com.platon.rlp.solidity.RlpString;
import com.platon.rlp.solidity.RlpType;
import com.platon.utils.Numeric;
import org.junit.Test;
import java.math.BigInteger;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
public class TransactionEncoderTest {
@Test
public void testEtherTransactionAsRlpValues() {
List<RlpType> rlpStrings = TransactionEncoder.asRlpValues(createEtherTransaction(),
new Sign.SignatureData((byte) 0, new byte[32], new byte[32]));
assertThat(rlpStrings.size(), is(9));
assertThat(rlpStrings.get(3), equalTo(RlpString.create(new BigInteger("33c98f20dd73d7bb1d533c4aa3371f2b30c6ebde", 16))));
}
@Test
public void testContractAsRlpValues() {
List<RlpType> rlpStrings = TransactionEncoder.asRlpValues(
createContractTransaction(), null);
assertThat(rlpStrings.size(), is(6));
assertThat(rlpStrings.get(3), is(RlpString.create("")));
}
@Test
public void testEip155Encode() {
assertThat(TransactionEncoder.encode(createEip155RawTransaction(), NetworkParameters.getChainId()),
is(Numeric.hexStringToByteArray("0xef098504a817c8008252089433c98f20dd73d7bb1d533c4aa3371f2b30c6ebde880de0b6b3a7640000808303113a8080")));
}
@Test
public void testEip155Transaction() {
// https://github.com/ethereum/EIPs/issues/155
Credentials credentials = Credentials.create("0x4646464646464646464646464646464646464646464646464646464646464646");
assertThat(TransactionEncoder.signMessage(createEip155RawTransaction(), NetworkParameters.getChainId(), credentials),
is(Numeric.hexStringToByteArray("0xf86f098504a817c8008252089433c98f20dd73d7bb1d533c4aa3371f2b30c6ebde880de0b6b3a76400008083062297a0045a8bbf804cc2c6a59f5f6acb544bc60efee31648581d00ebe58dfad67bb10aa01653665e957167922c95385d64590c1c56c7d225ef2ee214add692103a659514")));
}
private static RawTransaction createEtherTransaction() {
return RawTransaction.createEtherTransaction(
BigInteger.ZERO, BigInteger.ONE, BigInteger.TEN, "atp1x0yc7gxaw0tmk82n8392xdcl9vcvd677g57j0q",
BigInteger.valueOf(Long.MAX_VALUE));
}
static RawTransaction createContractTransaction() {
return RawTransaction.createContractTransaction(
BigInteger.ZERO, BigInteger.ONE, BigInteger.TEN, BigInteger.valueOf(Long.MAX_VALUE),
"01234566789");
}
private static RawTransaction createEip155RawTransaction() {
return RawTransaction.createEtherTransaction(
BigInteger.valueOf(9), BigInteger.valueOf(20000000000L),
BigInteger.valueOf(21000), "atp1x0yc7gxaw0tmk82n8392xdcl9vcvd677g57j0q",
BigInteger.valueOf(1000000000000000000L));
}
}
|
UTF-8
|
Java
| 3,001 |
java
|
TransactionEncoderTest.java
|
Java
|
[
{
"context": "p155Transaction() {\n // https://github.com/ethereum/EIPs/issues/155\n Credentials credentials =",
"end": 1556,
"score": 0.9909138679504395,
"start": 1548,
"tag": "USERNAME",
"value": "ethereum"
},
{
"context": " Credentials credentials = Credentials.create(\"0x4646464646464646464646464646464646464646464646464646464646464646\");\n assertThat(TransactionEncoder.signMess",
"end": 1693,
"score": 0.9631319642066956,
"start": 1627,
"tag": "KEY",
"value": "0x4646464646464646464646464646464646464646464646464646464646464646"
}
] | null |
[] |
package com.platon.crypto;
import com.platon.parameters.NetworkParameters;
import com.platon.rlp.solidity.RlpString;
import com.platon.rlp.solidity.RlpType;
import com.platon.utils.Numeric;
import org.junit.Test;
import java.math.BigInteger;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
public class TransactionEncoderTest {
@Test
public void testEtherTransactionAsRlpValues() {
List<RlpType> rlpStrings = TransactionEncoder.asRlpValues(createEtherTransaction(),
new Sign.SignatureData((byte) 0, new byte[32], new byte[32]));
assertThat(rlpStrings.size(), is(9));
assertThat(rlpStrings.get(3), equalTo(RlpString.create(new BigInteger("33c98f20dd73d7bb1d533c4aa3371f2b30c6ebde", 16))));
}
@Test
public void testContractAsRlpValues() {
List<RlpType> rlpStrings = TransactionEncoder.asRlpValues(
createContractTransaction(), null);
assertThat(rlpStrings.size(), is(6));
assertThat(rlpStrings.get(3), is(RlpString.create("")));
}
@Test
public void testEip155Encode() {
assertThat(TransactionEncoder.encode(createEip155RawTransaction(), NetworkParameters.getChainId()),
is(Numeric.hexStringToByteArray("0xef098504a817c8008252089433c98f20dd73d7bb1d533c4aa3371f2b30c6ebde880de0b6b3a7640000808303113a8080")));
}
@Test
public void testEip155Transaction() {
// https://github.com/ethereum/EIPs/issues/155
Credentials credentials = Credentials.create("0x4646464646464646464646464646464646464646464646464646464646464646");
assertThat(TransactionEncoder.signMessage(createEip155RawTransaction(), NetworkParameters.getChainId(), credentials),
is(Numeric.hexStringToByteArray("0xf86f098504a817c8008252089433c98f20dd73d7bb1d533c4aa3371f2b30c6ebde880de0b6b3a76400008083062297a0045a8bbf804cc2c6a59f5f6acb544bc60efee31648581d00ebe58dfad67bb10aa01653665e957167922c95385d64590c1c56c7d225ef2ee214add692103a659514")));
}
private static RawTransaction createEtherTransaction() {
return RawTransaction.createEtherTransaction(
BigInteger.ZERO, BigInteger.ONE, BigInteger.TEN, "atp1x0yc7gxaw0tmk82n8392xdcl9vcvd677g57j0q",
BigInteger.valueOf(Long.MAX_VALUE));
}
static RawTransaction createContractTransaction() {
return RawTransaction.createContractTransaction(
BigInteger.ZERO, BigInteger.ONE, BigInteger.TEN, BigInteger.valueOf(Long.MAX_VALUE),
"01234566789");
}
private static RawTransaction createEip155RawTransaction() {
return RawTransaction.createEtherTransaction(
BigInteger.valueOf(9), BigInteger.valueOf(20000000000L),
BigInteger.valueOf(21000), "atp1x0yc7gxaw0tmk82n8392xdcl9vcvd677g57j0q",
BigInteger.valueOf(1000000000000000000L));
}
}
| 3,001 | 0.743752 | 0.604132 | 66 | 44.469696 | 47.545265 | 282 | false | false | 0 | 0 | 0 | 0 | 228 | 0.130623 | 0.742424 | false | false |
14
|
c14adff2becc78e54bbd967eecd167d30f307624
| 29,283,087,059,321 |
dc1dbb7e5a4b95bf44170d2f51fd08b3814f2ac9
|
/data_defect4j/preprossed_method_corpus/Time/2/org/joda/time/convert/ConverterSet_select_47.java
|
ed120a5a1f5eeb35bd8d3e152c369ee8ed633710
|
[] |
no_license
|
hvdthong/NetML
|
https://github.com/hvdthong/NetML
|
dca6cf4d34c5799b400d718e0a6cd2e0b167297d
|
9bb103da21327912e5a29cbf9be9ff4d058731a5
|
refs/heads/master
| 2021-06-30T15:03:52.618000 | 2020-10-07T01:58:48 | 2020-10-07T01:58:48 | 150,383,588 | 1 | 1 | null | true | 2018-09-26T07:08:45 | 2018-09-26T07:08:44 | 2018-03-01T05:04:19 | 2018-01-15T07:59:20 | 172,367 | 0 | 0 | 0 | null | false | null |
org joda time convert
set convert exact convert quickli
select threadsaf essenti immut
author brian neill o'neil
convert set converterset
return closest match convert type
found
param type type select
illeg state except illegalstateexcept multipl convert match type
equal
convert select class type illeg state except illegalstateexcept
check hashtabl
entri entri select entri iselectentri
length entri length
index type type hash code hashcod length
entri
loop depend slot
entri index
type ityp type
convert iconvert
index length
index
found hashtabl actual work
convert convert select slow selectslow type
entri type convert
save entri futur select threadsaf
synchron hashtabl
cach destroi exist entri
occur high amount concurr
time cach updat occur cach
fill entri
updat copi slot select entri iselectentri
updat multipl thread slot
consum
entri entri entri clone
add entri
entri index
verifi slot exist
length
entri
found slot swap hashtabl
select entri iselectentri entri
convert
doubl capac hash
length newlength length
entri entri newentri entri length newlength
length
entri
type type ityp
index type type hash code hashcod length newlength
entri newentri index
index length newlength
index
entri newentri index
swap hashtabl
select entri iselectentri entri newentri
convert
|
UTF-8
|
Java
| 1,553 |
java
|
ConverterSet_select_47.java
|
Java
|
[
{
"context": "ert quickli\nselect threadsaf essenti immut\n\nauthor brian neill o'neil\n\n\nconvert set converterset\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nreturn c",
"end": 130,
"score": 0.9997990131378174,
"start": 112,
"tag": "NAME",
"value": "brian neill o'neil"
}
] | null |
[] |
org joda time convert
set convert exact convert quickli
select threadsaf essenti immut
author <NAME>
convert set converterset
return closest match convert type
found
param type type select
illeg state except illegalstateexcept multipl convert match type
equal
convert select class type illeg state except illegalstateexcept
check hashtabl
entri entri select entri iselectentri
length entri length
index type type hash code hashcod length
entri
loop depend slot
entri index
type ityp type
convert iconvert
index length
index
found hashtabl actual work
convert convert select slow selectslow type
entri type convert
save entri futur select threadsaf
synchron hashtabl
cach destroi exist entri
occur high amount concurr
time cach updat occur cach
fill entri
updat copi slot select entri iselectentri
updat multipl thread slot
consum
entri entri entri clone
add entri
entri index
verifi slot exist
length
entri
found slot swap hashtabl
select entri iselectentri entri
convert
doubl capac hash
length newlength length
entri entri newentri entri length newlength
length
entri
type type ityp
index type type hash code hashcod length newlength
entri newentri index
index length newlength
index
entri newentri index
swap hashtabl
select entri iselectentri entri newentri
convert
| 1,541 | 0.703155 | 0.703155 | 96 | 12.760417 | 15.127063 | 64 | false | false | 0 | 0 | 0 | 0 | 234 | 0.150676 | 0 | false | false |
14
|
92096c53bbe4a9b3a7689a12dea207b776a77624
| 6,528,350,355,764 |
f0c9ab897da97b1acbe5e991ebefd2e9117f448e
|
/lab12_sol/src/main/java/com/bemach/labguide/SecurityQuestionService.java
|
d43300c700738f2f941e9f60d0914ef24fb5c0d8
|
[] |
no_license
|
drtran/csd-solutions-eclipse
|
https://github.com/drtran/csd-solutions-eclipse
|
a9031793df4cb4f30799e3dcbe60c20a08c710ff
|
d44fd60be6758a5b8f237674c90c0b64a998a225
|
refs/heads/master
| 2016-09-05T15:21:32.332000 | 2015-05-08T05:55:38 | 2015-05-08T05:55:38 | 35,066,184 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.bemach.labguide;
import java.util.List;
/**
* Created by ktran on 4/30/2015.
*/
public interface SecurityQuestionService {
public List<SecurityQuestion> getSecurityQuestionList();
public List<SecurityQA> getUserSecurityQA(String userId, String answerIndicator);
public boolean modifyUserSecurityQuestions(String userId, String questionIds[], String answers[]);
}
|
UTF-8
|
Java
| 391 |
java
|
SecurityQuestionService.java
|
Java
|
[
{
"context": "bguide;\n\nimport java.util.List;\n\n/**\n * Created by ktran on 4/30/2015.\n */\npublic interface SecurityQuesti",
"end": 77,
"score": 0.9996553659439087,
"start": 72,
"tag": "USERNAME",
"value": "ktran"
}
] | null |
[] |
package com.bemach.labguide;
import java.util.List;
/**
* Created by ktran on 4/30/2015.
*/
public interface SecurityQuestionService {
public List<SecurityQuestion> getSecurityQuestionList();
public List<SecurityQA> getUserSecurityQA(String userId, String answerIndicator);
public boolean modifyUserSecurityQuestions(String userId, String questionIds[], String answers[]);
}
| 391 | 0.777494 | 0.759591 | 12 | 31.583334 | 33.415211 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false |
14
|
69db5fa181d7fc5a2e00c636522ea091b47e6a3c
| 22,986,665,017,621 |
5dc699290c6deb67907a20929d14e0c5310bebbc
|
/app/src/main/java/com/minlu/office_system/fragment/form/LeaveApplyFragment.java
|
272077f47c2b419928b8300027cb011e621e5539
|
[] |
no_license
|
sfgjys/Office_System
|
https://github.com/sfgjys/Office_System
|
6f5272e701424712163c5bced0d7844f02a5378e
|
37c64bce6a70b2a8522ba9a94ab5547fbb4c683b
|
refs/heads/master
| 2021-01-18T06:21:14.622000 | 2017-05-31T01:58:39 | 2017-05-31T01:58:39 | 84,282,610 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.minlu.office_system.fragment.form;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import com.minlu.baselibrary.base.ContentPage;
import com.minlu.baselibrary.util.SharedPreferencesUtil;
import com.minlu.baselibrary.util.StringUtils;
import com.minlu.baselibrary.util.TimeTool;
import com.minlu.baselibrary.util.ViewsUitls;
import com.minlu.office_system.IpFiled;
import com.minlu.office_system.PassBackStringData;
import com.minlu.office_system.R;
import com.minlu.office_system.StringsFiled;
import com.minlu.office_system.activity.FormActivity;
import com.minlu.office_system.customview.EditTextItem;
import com.minlu.office_system.customview.EditTextTimeSelector;
import com.minlu.office_system.fragment.dialog.PromptDialog;
import com.minlu.office_system.fragment.form.formPremise.FormFragment;
import com.minlu.office_system.http.OkHttpMethod;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import okhttp3.Response;
public class LeaveApplyFragment extends FormFragment {
private List<String> mLeaveType;
private EditTextItem mLeaveTypeEdit;
private EditTextItem mLeaveDayNumber;
private EditTextTimeSelector mStartTime;
private EditTextTimeSelector mEndTime;
private EditTextItem mLeaveTitle;
private EditTextItem mLeaveRemark;
private String mResidueYearLeaveText;
private String mAddUpLeaveDaysText;
private EditTextItem mSelectHour;
private List<String> mSelectHourData;
private String mResult;
private String mOrd;
private String mAssignee;
private String mAutoOrg;
private String mTaskId;
private String mTaskName;
private String mOrderId;
@Override
protected void onSubClassOnCreateView() {
loadDataAndRefresh();
}
@Override
protected View onCreateSuccessView(Bundle savedInstanceState) {
// 因为本fragment是通过R.id.sv_replace_form控件replace开启的,但是R.id.sv_replace_form控件是居中属性,所以再次我们要使得居中属性去除
FormActivity formActivity = (FormActivity) getContext();
if (formActivity != null) {
formActivity.setScrollViewNoGravity();
}
View inflate = ViewsUitls.inflate(R.layout.form_leave_apply);
initView(inflate);
return inflate;
}
private void initView(View inflate) {
EditTextItem mAddUpLeaveDays = (EditTextItem) inflate.findViewById(R.id.form_leave_apply_add_up_leave_day_number);
mAddUpLeaveDays.setEditText(mAddUpLeaveDaysText);
EditTextItem mResidueLeaveYears = (EditTextItem) inflate.findViewById(R.id.form_leave_apply_residue_leave_year_number);
mResidueLeaveYears.setEditText(mResidueYearLeaveText);
mLeaveTitle = (EditTextItem) inflate.findViewById(R.id.form_leave_apply_title);
mLeaveRemark = (EditTextItem) inflate.findViewById(R.id.form_leave_apply_remark);
ViewsUitls.setWidthFromTargetView(mLeaveTitle.getCustomEditTextLeft(), mLeaveRemark.getCustomEditTextLeft());
// 自动填写
mLeaveDayNumber = (EditTextItem) inflate.findViewById(R.id.form_leave_apply_leave_day_number);
// 类型列表展示
mLeaveTypeEdit = (EditTextItem) inflate.findViewById(R.id.form_leave_apply_type);
EditText typeCustomEditTextRight = mLeaveTypeEdit.getCustomEditTextRight();
setWhichViewShowListPopupWindow(false, typeCustomEditTextRight, mLeaveType, new ShowListPopupItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mLeaveTypeEdit.setEditText(mLeaveType.get(position));
}
@Override
public void onAnchorViewClick(View v) {
setBackGroundDarkColor(0.6f);
}
@Override
public void onListPopupDismiss() {
setBackGroundDarkColor(1.0f);
}
}, getActivity());
// 小时选择
mSelectHour = (EditTextItem) inflate.findViewById(R.id.form_leave_apply_leave_day_number_select_hour);
mSelectHour.getCustomEditTextRight().setText("0 小时");
setWhichViewShowListPopupWindow(false, mSelectHour.getCustomEditTextRight(), mSelectHourData, new ShowListPopupItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mSelectHour.setEditText(mSelectHourData.get(position));
}
@Override
public void onAnchorViewClick(View v) {
setBackGroundDarkColor(0.6f);
}
@Override
public void onListPopupDismiss() {
setBackGroundDarkColor(1.0f);
}
}, getActivity());
// 时间选择对话框展示
mStartTime = (EditTextTimeSelector) inflate.findViewById(R.id.form_leave_apply_start_time);
mStartTime.getmTimeOfDay().setVisibility(View.INVISIBLE);
mStartTime.setNowDayOfYearAndTimeOfDay();
startUseEditTextOnClickShowTimePicker(mStartTime);// 给mStartTime设置点击弹出时间选择对话框
mStartTime.setOnSetTextListener(new EditTextTimeSelector.OnSetTextListener() {
@Override
public void onSetText() {
setLeaveDayNumberText();
}
});// 设置 当mStartTime修改了文本输入框内的文本时的 监听事件
mEndTime = (EditTextTimeSelector) inflate.findViewById(R.id.form_leave_apply_end_time);
mEndTime.getmTimeOfDay().setVisibility(View.INVISIBLE);
mEndTime.setNowDayOfYearAndTimeOfDay();
startUseEditTextOnClickShowTimePicker(mEndTime);
mEndTime.setOnSetTextListener(new EditTextTimeSelector.OnSetTextListener() {
@Override
public void onSetText() {
setLeaveDayNumberText();
}
});
setLeaveDayNumberText();// 第一此显示界面对的时候就需要设置文本了
}
/*给开始时间和结束时间之间的 请假天数 的输入文本框设置具体的文本*/
private void setLeaveDayNumberText() {
if (mStartTime != null && mEndTime != null) {
// TODO 计算请假天数的时候,需要注意时间格式
float[] timeDifferenceValue = TimeTool.getBaseStringOfTimeDifferenceValue(mStartTime.getDayOrTimeText(), mEndTime.getDayOrTimeText(), "yyyy-MM-dd HH:mm");
mLeaveDayNumber.setEditText((int) timeDifferenceValue[0] + " 天 ");// + timeDifferenceValue[1] + " 小时 , 共 " + (int) timeDifferenceValue[2] + " 天"
}
}
@Override
protected ContentPage.ResultState onLoad() {
mSelectHourData = new ArrayList<>();
mSelectHourData.add("0 小时");
mSelectHourData.add("1 小时");
mSelectHourData.add("2 小时");
mSelectHourData.add("3 小时");
mSelectHourData.add("4 小时");
mSelectHourData.add("5 小时");
mSelectHourData.add("6 小时");
mSelectHourData.add("7 小时");
mSelectHourData.add("8 小时");
HashMap<String, String> leaveApplyPremise = new HashMap<>();
leaveApplyPremise.put("processId", StringsFiled.Leave_ProcessId);
leaveApplyPremise.put("taskName", "qjsh");
Response response = OkHttpMethod.synPostRequest(IpFiled.LEAVE_APPLY_PREMISE, leaveApplyPremise);
if (response != null && response.isSuccessful()) {
try {
String resultList = response.body().string();
if (StringUtils.interentIsNormal(resultList)) {
JSONObject jsonObject = new JSONObject(resultList);
if (jsonObject.has("year")) {
analyticalData(jsonObject);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return chat(mLeaveType);
}
private void analyticalData(JSONObject jsonObject) {
// 用来显示的
mResidueYearLeaveText = jsonObject.optInt("year") + "";
mAddUpLeaveDaysText = jsonObject.optInt("allday") + "";
// 用来请求下一步操作人
mAssignee = jsonObject.optString("assignee");
mOrd = jsonObject.optInt("ord") + "";
mAutoOrg = jsonObject.optString("autoOrg");
// 用于正式提交
mResult = jsonObject.optString("result");
mTaskId = jsonObject.optString("taskId");
mTaskName = jsonObject.optString("taskName");
mOrderId = jsonObject.optString("orderId");
mLeaveType = new ArrayList<>();
mLeaveType.add("事假");
mLeaveType.add("婚假");
mLeaveType.add("产假");
mLeaveType.add("陪产假");
mLeaveType.add("丧假");
mLeaveType.add("年假");
mLeaveType.add("病假");
mLeaveType.add("其他");
}
@Override
public void disAgreeOnClick(View v) {
}
@Override
public void agreeOnClick(View v) {
}
@Override
public void submitOnClick(View v) {
PromptDialog promptDialog = new PromptDialog(new PromptDialog.OnSureButtonClick() {
@Override
public void onSureClick(DialogInterface dialog, int id) {
getNextPersonData(mAssignee, mOrd, mAutoOrg, null, "LeaveApplySubmit_Have_Next", "LeaveApplySubmit_No_Next", "本界面是请假申请的第一步,则必定有下一步操作人",
new PassBackStringData() {
@Override
public void passBackStringData(String passBackData) {
officialLeaveApply(passBackData, 0);
}
});
}
}, "是否将请假申请进行提交处理 !");
promptDialog.show(getActivity().getSupportFragmentManager(), "LeaveApplySubmit");
}
private void officialLeaveApply(String userList, int method) {
startLoading();
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("processId", StringsFiled.Leave_ProcessId);
hashMap.put("orderId", mOrderId);
hashMap.put("taskId", mTaskId);
hashMap.put("taskName", mTaskName);
hashMap.put("method", "" + method);
hashMap.put("userName", SharedPreferencesUtil.getString(ViewsUitls.getContext(), StringsFiled.LOGIN_USER, ""));
hashMap.put("assignee", mAssignee);
hashMap.put("userList", userList);
// 以下为表单上的填写数据
hashMap.put("title", mLeaveTitle.getCustomEditTextRight().getText().toString());
hashMap.put("qtype", mLeaveTypeEdit.getCustomEditTextRight().getText().toString());
hashMap.put("stime", mStartTime.getmDayOfYear().getText().toString());
hashMap.put("etime", mEndTime.getmDayOfYear().getText().toString());
String leaveDayNumber = mLeaveDayNumber.getCustomEditTextRight().getText().toString().split(" ")[0] + "." + mSelectHour.getCustomEditTextRight().getText().toString().split(" ")[0];
hashMap.put("allleave", leaveDayNumber);
hashMap.put("bz", mLeaveRemark.getCustomEditTextRight().getText().toString());
hashMap.put("result", mResult);
startUltimatelySubmit(IpFiled.LEAVE_APPLY_SUBMIT, hashMap, "success", "服务器正忙,请稍后", "请假申请提交成功");
}
}
|
UTF-8
|
Java
| 11,636 |
java
|
LeaveApplyFragment.java
|
Java
|
[
{
"context": "ssId);\n leaveApplyPremise.put(\"taskName\", \"qjsh\");\n Response response = OkHttpMethod.synPo",
"end": 7125,
"score": 0.5689865946769714,
"start": 7121,
"tag": "USERNAME",
"value": "qjsh"
}
] | null |
[] |
package com.minlu.office_system.fragment.form;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import com.minlu.baselibrary.base.ContentPage;
import com.minlu.baselibrary.util.SharedPreferencesUtil;
import com.minlu.baselibrary.util.StringUtils;
import com.minlu.baselibrary.util.TimeTool;
import com.minlu.baselibrary.util.ViewsUitls;
import com.minlu.office_system.IpFiled;
import com.minlu.office_system.PassBackStringData;
import com.minlu.office_system.R;
import com.minlu.office_system.StringsFiled;
import com.minlu.office_system.activity.FormActivity;
import com.minlu.office_system.customview.EditTextItem;
import com.minlu.office_system.customview.EditTextTimeSelector;
import com.minlu.office_system.fragment.dialog.PromptDialog;
import com.minlu.office_system.fragment.form.formPremise.FormFragment;
import com.minlu.office_system.http.OkHttpMethod;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import okhttp3.Response;
public class LeaveApplyFragment extends FormFragment {
private List<String> mLeaveType;
private EditTextItem mLeaveTypeEdit;
private EditTextItem mLeaveDayNumber;
private EditTextTimeSelector mStartTime;
private EditTextTimeSelector mEndTime;
private EditTextItem mLeaveTitle;
private EditTextItem mLeaveRemark;
private String mResidueYearLeaveText;
private String mAddUpLeaveDaysText;
private EditTextItem mSelectHour;
private List<String> mSelectHourData;
private String mResult;
private String mOrd;
private String mAssignee;
private String mAutoOrg;
private String mTaskId;
private String mTaskName;
private String mOrderId;
@Override
protected void onSubClassOnCreateView() {
loadDataAndRefresh();
}
@Override
protected View onCreateSuccessView(Bundle savedInstanceState) {
// 因为本fragment是通过R.id.sv_replace_form控件replace开启的,但是R.id.sv_replace_form控件是居中属性,所以再次我们要使得居中属性去除
FormActivity formActivity = (FormActivity) getContext();
if (formActivity != null) {
formActivity.setScrollViewNoGravity();
}
View inflate = ViewsUitls.inflate(R.layout.form_leave_apply);
initView(inflate);
return inflate;
}
private void initView(View inflate) {
EditTextItem mAddUpLeaveDays = (EditTextItem) inflate.findViewById(R.id.form_leave_apply_add_up_leave_day_number);
mAddUpLeaveDays.setEditText(mAddUpLeaveDaysText);
EditTextItem mResidueLeaveYears = (EditTextItem) inflate.findViewById(R.id.form_leave_apply_residue_leave_year_number);
mResidueLeaveYears.setEditText(mResidueYearLeaveText);
mLeaveTitle = (EditTextItem) inflate.findViewById(R.id.form_leave_apply_title);
mLeaveRemark = (EditTextItem) inflate.findViewById(R.id.form_leave_apply_remark);
ViewsUitls.setWidthFromTargetView(mLeaveTitle.getCustomEditTextLeft(), mLeaveRemark.getCustomEditTextLeft());
// 自动填写
mLeaveDayNumber = (EditTextItem) inflate.findViewById(R.id.form_leave_apply_leave_day_number);
// 类型列表展示
mLeaveTypeEdit = (EditTextItem) inflate.findViewById(R.id.form_leave_apply_type);
EditText typeCustomEditTextRight = mLeaveTypeEdit.getCustomEditTextRight();
setWhichViewShowListPopupWindow(false, typeCustomEditTextRight, mLeaveType, new ShowListPopupItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mLeaveTypeEdit.setEditText(mLeaveType.get(position));
}
@Override
public void onAnchorViewClick(View v) {
setBackGroundDarkColor(0.6f);
}
@Override
public void onListPopupDismiss() {
setBackGroundDarkColor(1.0f);
}
}, getActivity());
// 小时选择
mSelectHour = (EditTextItem) inflate.findViewById(R.id.form_leave_apply_leave_day_number_select_hour);
mSelectHour.getCustomEditTextRight().setText("0 小时");
setWhichViewShowListPopupWindow(false, mSelectHour.getCustomEditTextRight(), mSelectHourData, new ShowListPopupItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mSelectHour.setEditText(mSelectHourData.get(position));
}
@Override
public void onAnchorViewClick(View v) {
setBackGroundDarkColor(0.6f);
}
@Override
public void onListPopupDismiss() {
setBackGroundDarkColor(1.0f);
}
}, getActivity());
// 时间选择对话框展示
mStartTime = (EditTextTimeSelector) inflate.findViewById(R.id.form_leave_apply_start_time);
mStartTime.getmTimeOfDay().setVisibility(View.INVISIBLE);
mStartTime.setNowDayOfYearAndTimeOfDay();
startUseEditTextOnClickShowTimePicker(mStartTime);// 给mStartTime设置点击弹出时间选择对话框
mStartTime.setOnSetTextListener(new EditTextTimeSelector.OnSetTextListener() {
@Override
public void onSetText() {
setLeaveDayNumberText();
}
});// 设置 当mStartTime修改了文本输入框内的文本时的 监听事件
mEndTime = (EditTextTimeSelector) inflate.findViewById(R.id.form_leave_apply_end_time);
mEndTime.getmTimeOfDay().setVisibility(View.INVISIBLE);
mEndTime.setNowDayOfYearAndTimeOfDay();
startUseEditTextOnClickShowTimePicker(mEndTime);
mEndTime.setOnSetTextListener(new EditTextTimeSelector.OnSetTextListener() {
@Override
public void onSetText() {
setLeaveDayNumberText();
}
});
setLeaveDayNumberText();// 第一此显示界面对的时候就需要设置文本了
}
/*给开始时间和结束时间之间的 请假天数 的输入文本框设置具体的文本*/
private void setLeaveDayNumberText() {
if (mStartTime != null && mEndTime != null) {
// TODO 计算请假天数的时候,需要注意时间格式
float[] timeDifferenceValue = TimeTool.getBaseStringOfTimeDifferenceValue(mStartTime.getDayOrTimeText(), mEndTime.getDayOrTimeText(), "yyyy-MM-dd HH:mm");
mLeaveDayNumber.setEditText((int) timeDifferenceValue[0] + " 天 ");// + timeDifferenceValue[1] + " 小时 , 共 " + (int) timeDifferenceValue[2] + " 天"
}
}
@Override
protected ContentPage.ResultState onLoad() {
mSelectHourData = new ArrayList<>();
mSelectHourData.add("0 小时");
mSelectHourData.add("1 小时");
mSelectHourData.add("2 小时");
mSelectHourData.add("3 小时");
mSelectHourData.add("4 小时");
mSelectHourData.add("5 小时");
mSelectHourData.add("6 小时");
mSelectHourData.add("7 小时");
mSelectHourData.add("8 小时");
HashMap<String, String> leaveApplyPremise = new HashMap<>();
leaveApplyPremise.put("processId", StringsFiled.Leave_ProcessId);
leaveApplyPremise.put("taskName", "qjsh");
Response response = OkHttpMethod.synPostRequest(IpFiled.LEAVE_APPLY_PREMISE, leaveApplyPremise);
if (response != null && response.isSuccessful()) {
try {
String resultList = response.body().string();
if (StringUtils.interentIsNormal(resultList)) {
JSONObject jsonObject = new JSONObject(resultList);
if (jsonObject.has("year")) {
analyticalData(jsonObject);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return chat(mLeaveType);
}
private void analyticalData(JSONObject jsonObject) {
// 用来显示的
mResidueYearLeaveText = jsonObject.optInt("year") + "";
mAddUpLeaveDaysText = jsonObject.optInt("allday") + "";
// 用来请求下一步操作人
mAssignee = jsonObject.optString("assignee");
mOrd = jsonObject.optInt("ord") + "";
mAutoOrg = jsonObject.optString("autoOrg");
// 用于正式提交
mResult = jsonObject.optString("result");
mTaskId = jsonObject.optString("taskId");
mTaskName = jsonObject.optString("taskName");
mOrderId = jsonObject.optString("orderId");
mLeaveType = new ArrayList<>();
mLeaveType.add("事假");
mLeaveType.add("婚假");
mLeaveType.add("产假");
mLeaveType.add("陪产假");
mLeaveType.add("丧假");
mLeaveType.add("年假");
mLeaveType.add("病假");
mLeaveType.add("其他");
}
@Override
public void disAgreeOnClick(View v) {
}
@Override
public void agreeOnClick(View v) {
}
@Override
public void submitOnClick(View v) {
PromptDialog promptDialog = new PromptDialog(new PromptDialog.OnSureButtonClick() {
@Override
public void onSureClick(DialogInterface dialog, int id) {
getNextPersonData(mAssignee, mOrd, mAutoOrg, null, "LeaveApplySubmit_Have_Next", "LeaveApplySubmit_No_Next", "本界面是请假申请的第一步,则必定有下一步操作人",
new PassBackStringData() {
@Override
public void passBackStringData(String passBackData) {
officialLeaveApply(passBackData, 0);
}
});
}
}, "是否将请假申请进行提交处理 !");
promptDialog.show(getActivity().getSupportFragmentManager(), "LeaveApplySubmit");
}
private void officialLeaveApply(String userList, int method) {
startLoading();
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("processId", StringsFiled.Leave_ProcessId);
hashMap.put("orderId", mOrderId);
hashMap.put("taskId", mTaskId);
hashMap.put("taskName", mTaskName);
hashMap.put("method", "" + method);
hashMap.put("userName", SharedPreferencesUtil.getString(ViewsUitls.getContext(), StringsFiled.LOGIN_USER, ""));
hashMap.put("assignee", mAssignee);
hashMap.put("userList", userList);
// 以下为表单上的填写数据
hashMap.put("title", mLeaveTitle.getCustomEditTextRight().getText().toString());
hashMap.put("qtype", mLeaveTypeEdit.getCustomEditTextRight().getText().toString());
hashMap.put("stime", mStartTime.getmDayOfYear().getText().toString());
hashMap.put("etime", mEndTime.getmDayOfYear().getText().toString());
String leaveDayNumber = mLeaveDayNumber.getCustomEditTextRight().getText().toString().split(" ")[0] + "." + mSelectHour.getCustomEditTextRight().getText().toString().split(" ")[0];
hashMap.put("allleave", leaveDayNumber);
hashMap.put("bz", mLeaveRemark.getCustomEditTextRight().getText().toString());
hashMap.put("result", mResult);
startUltimatelySubmit(IpFiled.LEAVE_APPLY_SUBMIT, hashMap, "success", "服务器正忙,请稍后", "请假申请提交成功");
}
}
| 11,636 | 0.658803 | 0.656544 | 276 | 39.086956 | 33.119453 | 188 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.73913 | false | false |
14
|
3a24a8c0d87ec8e431bae3ae9e70cb114033a9a6
| 31,662,498,930,955 |
61fcb283678ba74d4e4916eba7b9c90ecc9c2dc2
|
/src/exception/CertificationFailException.java
|
81969992f97596a0741d05bb9a143d5331d680f4
|
[] |
no_license
|
TrentaIcedCoffee/DBot
|
https://github.com/TrentaIcedCoffee/DBot
|
8fb283e2420782eab38365ad2bd2507c9a147867
|
303bb578daa3f729310aa4094e7acd045d6db448
|
refs/heads/master
| 2021-07-23T15:42:48.468000 | 2017-11-02T22:42:00 | 2017-11-02T22:42:00 | 106,324,209 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package exception;
@SuppressWarnings("serial")
public class CertificationFailException extends Exception {
public CertificationFailException() {
super();
}
public CertificationFailException(String message) {
super(message);
}
public CertificationFailException(String message, Throwable throwable) {
super(message, throwable);
}
public CertificationFailException(Throwable throwable) {
super(throwable);
}
}
|
UTF-8
|
Java
| 447 |
java
|
CertificationFailException.java
|
Java
|
[] | null |
[] |
package exception;
@SuppressWarnings("serial")
public class CertificationFailException extends Exception {
public CertificationFailException() {
super();
}
public CertificationFailException(String message) {
super(message);
}
public CertificationFailException(String message, Throwable throwable) {
super(message, throwable);
}
public CertificationFailException(Throwable throwable) {
super(throwable);
}
}
| 447 | 0.744966 | 0.744966 | 20 | 20.450001 | 22.857111 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.25 | false | false |
14
|
1360b671d2192623513eb994114f0d5221a04245
| 31,662,498,930,212 |
6806da8f6416b0e517b0b9019d04b01cea9c6b65
|
/Demo/src/main/java/book/thinking/interfaces/music4/Music4.java
|
d4a5fa5f56636107c74bc38df2fc9dc7408cdaaf
|
[] |
no_license
|
GaryLi80/practice-java
|
https://github.com/GaryLi80/practice-java
|
7f4a8e917b205a6897e256d9b6651539e56b490e
|
813f808bd80c1c2672a4576f563621baeb1991f6
|
refs/heads/master
| 2019-01-07T02:02:22.978000 | 2018-07-01T06:25:02 | 2018-07-01T06:25:02 | 74,984,420 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package book.thinking.interfaces.music4;
/**
* Created by Gary_Li on 2018/1/13.
*/
abstract class Instrument {
private int i;
public abstract void play();
public String what() {
return "Instrument";
}
public abstract void adjuest();
}
|
UTF-8
|
Java
| 268 |
java
|
Music4.java
|
Java
|
[
{
"context": "ook.thinking.interfaces.music4;\n\n/**\n * Created by Gary_Li on 2018/1/13.\n */\n\nabstract class Instrument {\n ",
"end": 67,
"score": 0.9582724571228027,
"start": 60,
"tag": "NAME",
"value": "Gary_Li"
}
] | null |
[] |
package book.thinking.interfaces.music4;
/**
* Created by Gary_Li on 2018/1/13.
*/
abstract class Instrument {
private int i;
public abstract void play();
public String what() {
return "Instrument";
}
public abstract void adjuest();
}
| 268 | 0.641791 | 0.61194 | 14 | 18.071428 | 14.781573 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false |
14
|
ed33ffc261a416de382c5dc0f2c4dbac00bf6f73
| 19,104,014,555,808 |
413714d9fc5068782fb223ef0f5a81bb94f96cda
|
/SantaGram/SantaGram_4.2.src/android/support/v7/widget/ActionBarOverlayLayout.java
|
0703ca640c49c4e6bf3617d0bd2ccfc9ba4d7a76
|
[] |
no_license
|
chaws/sanshack
|
https://github.com/chaws/sanshack
|
334c7046c01d2763f759d5636164125cc0097b27
|
de00adb4d60b3715046dbd708d602250680617ce
|
refs/heads/master
| 2021-01-19T20:11:58.671000 | 2016-12-29T22:02:15 | 2016-12-29T22:05:52 | 77,642,339 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package android.support.v7.widget;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.res.Configuration;
import android.content.res.Resources.Theme;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION;
import android.support.v4.j.af;
import android.support.v4.j.av;
import android.support.v4.j.az;
import android.support.v4.j.ba;
import android.support.v4.j.y;
import android.support.v4.j.z;
import android.support.v4.widget.u;
import android.support.v7.b.a.a;
import android.support.v7.b.a.f;
import android.support.v7.view.menu.l.a;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.Window.Callback;
public class ActionBarOverlayLayout
extends ViewGroup
implements y, ad
{
static final int[] a = { a.a.actionBarSize, 16842841 };
private final Runnable A = new Runnable()
{
public void run()
{
ActionBarOverlayLayout.a(ActionBarOverlayLayout.this);
ActionBarOverlayLayout.a(ActionBarOverlayLayout.this, af.q(ActionBarOverlayLayout.c(ActionBarOverlayLayout.this)).c(-ActionBarOverlayLayout.c(ActionBarOverlayLayout.this).getHeight()).a(ActionBarOverlayLayout.b(ActionBarOverlayLayout.this)));
}
};
private final z B;
private int b;
private int c = 0;
private ContentFrameLayout d;
private ActionBarContainer e;
private ae f;
private Drawable g;
private boolean h;
private boolean i;
private boolean j;
private boolean k;
private boolean l;
private int m;
private int n;
private final Rect o = new Rect();
private final Rect p = new Rect();
private final Rect q = new Rect();
private final Rect r = new Rect();
private final Rect s = new Rect();
private final Rect t = new Rect();
private a u;
private final int v = 600;
private u w;
private av x;
private final az y = new ba()
{
public void b(View paramAnonymousView)
{
ActionBarOverlayLayout.a(ActionBarOverlayLayout.this, null);
ActionBarOverlayLayout.a(ActionBarOverlayLayout.this, false);
}
public void c(View paramAnonymousView)
{
ActionBarOverlayLayout.a(ActionBarOverlayLayout.this, null);
ActionBarOverlayLayout.a(ActionBarOverlayLayout.this, false);
}
};
private final Runnable z = new Runnable()
{
public void run()
{
ActionBarOverlayLayout.a(ActionBarOverlayLayout.this);
ActionBarOverlayLayout.a(ActionBarOverlayLayout.this, af.q(ActionBarOverlayLayout.c(ActionBarOverlayLayout.this)).c(0.0F).a(ActionBarOverlayLayout.b(ActionBarOverlayLayout.this)));
}
};
public ActionBarOverlayLayout(Context paramContext)
{
this(paramContext, null);
}
public ActionBarOverlayLayout(Context paramContext, AttributeSet paramAttributeSet)
{
super(paramContext, paramAttributeSet);
a(paramContext);
this.B = new z(this);
}
private ae a(View paramView)
{
if ((paramView instanceof ae)) {
return (ae)paramView;
}
if ((paramView instanceof Toolbar)) {
return ((Toolbar)paramView).getWrapper();
}
throw new IllegalStateException("Can't make a decor toolbar out of " + paramView.getClass().getSimpleName());
}
private void a(Context paramContext)
{
boolean bool2 = true;
TypedArray localTypedArray = getContext().getTheme().obtainStyledAttributes(a);
this.b = localTypedArray.getDimensionPixelSize(0, 0);
this.g = localTypedArray.getDrawable(1);
if (this.g == null)
{
bool1 = true;
setWillNotDraw(bool1);
localTypedArray.recycle();
if (paramContext.getApplicationInfo().targetSdkVersion >= 19) {
break label88;
}
}
label88:
for (boolean bool1 = bool2;; bool1 = false)
{
this.h = bool1;
this.w = u.a(paramContext);
return;
bool1 = false;
break;
}
}
private boolean a(float paramFloat1, float paramFloat2)
{
boolean bool = false;
this.w.a(0, 0, 0, (int)paramFloat2, 0, 0, Integer.MIN_VALUE, Integer.MAX_VALUE);
if (this.w.e() > this.e.getHeight()) {
bool = true;
}
return bool;
}
private boolean a(View paramView, Rect paramRect, boolean paramBoolean1, boolean paramBoolean2, boolean paramBoolean3, boolean paramBoolean4)
{
boolean bool2 = false;
paramView = (b)paramView.getLayoutParams();
boolean bool1 = bool2;
if (paramBoolean1)
{
bool1 = bool2;
if (paramView.leftMargin != paramRect.left)
{
paramView.leftMargin = paramRect.left;
bool1 = true;
}
}
paramBoolean1 = bool1;
if (paramBoolean2)
{
paramBoolean1 = bool1;
if (paramView.topMargin != paramRect.top)
{
paramView.topMargin = paramRect.top;
paramBoolean1 = true;
}
}
paramBoolean2 = paramBoolean1;
if (paramBoolean4)
{
paramBoolean2 = paramBoolean1;
if (paramView.rightMargin != paramRect.right)
{
paramView.rightMargin = paramRect.right;
paramBoolean2 = true;
}
}
if ((paramBoolean3) && (paramView.bottomMargin != paramRect.bottom))
{
paramView.bottomMargin = paramRect.bottom;
return true;
}
return paramBoolean2;
}
private void k()
{
removeCallbacks(this.z);
removeCallbacks(this.A);
if (this.x != null) {
this.x.b();
}
}
private void l()
{
k();
postDelayed(this.z, 600L);
}
private void m()
{
k();
postDelayed(this.A, 600L);
}
private void n()
{
k();
this.z.run();
}
private void o()
{
k();
this.A.run();
}
public b a(AttributeSet paramAttributeSet)
{
return new b(getContext(), paramAttributeSet);
}
public void a(int paramInt)
{
c();
switch (paramInt)
{
default:
return;
case 2:
this.f.f();
return;
case 5:
this.f.g();
return;
}
setOverlayMode(true);
}
public void a(Menu paramMenu, l.a parama)
{
c();
this.f.a(paramMenu, parama);
}
public boolean a()
{
return this.i;
}
protected b b()
{
return new b(-1, -1);
}
void c()
{
if (this.d == null)
{
this.d = ((ContentFrameLayout)findViewById(a.f.action_bar_activity_content));
this.e = ((ActionBarContainer)findViewById(a.f.action_bar_container));
this.f = a(findViewById(a.f.action_bar));
}
}
protected boolean checkLayoutParams(ViewGroup.LayoutParams paramLayoutParams)
{
return paramLayoutParams instanceof b;
}
public boolean d()
{
c();
return this.f.h();
}
public void draw(Canvas paramCanvas)
{
super.draw(paramCanvas);
if ((this.g != null) && (!this.h)) {
if (this.e.getVisibility() != 0) {
break label82;
}
}
label82:
for (int i1 = (int)(this.e.getBottom() + af.n(this.e) + 0.5F);; i1 = 0)
{
this.g.setBounds(0, i1, getWidth(), this.g.getIntrinsicHeight() + i1);
this.g.draw(paramCanvas);
return;
}
}
public boolean e()
{
c();
return this.f.i();
}
public boolean f()
{
c();
return this.f.j();
}
protected boolean fitSystemWindows(Rect paramRect)
{
c();
if ((af.r(this) & 0x100) != 0) {}
boolean bool = a(this.e, paramRect, true, true, false, true);
this.r.set(paramRect);
bf.a(this, this.r, this.o);
if (!this.p.equals(this.o))
{
this.p.set(this.o);
bool = true;
}
if (bool) {
requestLayout();
}
return true;
}
public boolean g()
{
c();
return this.f.k();
}
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams paramLayoutParams)
{
return new b(paramLayoutParams);
}
public int getActionBarHideOffset()
{
if (this.e != null) {
return -(int)af.n(this.e);
}
return 0;
}
public int getNestedScrollAxes()
{
return this.B.a();
}
public CharSequence getTitle()
{
c();
return this.f.e();
}
public boolean h()
{
c();
return this.f.l();
}
public void i()
{
c();
this.f.m();
}
public void j()
{
c();
this.f.n();
}
protected void onConfigurationChanged(Configuration paramConfiguration)
{
if (Build.VERSION.SDK_INT >= 8) {
super.onConfigurationChanged(paramConfiguration);
}
a(getContext());
af.s(this);
}
protected void onDetachedFromWindow()
{
super.onDetachedFromWindow();
k();
}
protected void onLayout(boolean paramBoolean, int paramInt1, int paramInt2, int paramInt3, int paramInt4)
{
paramInt2 = getChildCount();
paramInt3 = getPaddingLeft();
getPaddingRight();
paramInt4 = getPaddingTop();
getPaddingBottom();
paramInt1 = 0;
while (paramInt1 < paramInt2)
{
View localView = getChildAt(paramInt1);
if (localView.getVisibility() != 8)
{
b localb = (b)localView.getLayoutParams();
int i1 = localView.getMeasuredWidth();
int i2 = localView.getMeasuredHeight();
int i3 = localb.leftMargin + paramInt3;
int i4 = localb.topMargin + paramInt4;
localView.layout(i3, i4, i1 + i3, i2 + i4);
}
paramInt1 += 1;
}
}
protected void onMeasure(int paramInt1, int paramInt2)
{
c();
measureChildWithMargins(this.e, paramInt1, 0, paramInt2, 0);
Object localObject = (b)this.e.getLayoutParams();
int i6 = Math.max(0, this.e.getMeasuredWidth() + ((b)localObject).leftMargin + ((b)localObject).rightMargin);
int i1 = this.e.getMeasuredHeight();
int i2 = ((b)localObject).topMargin;
int i5 = Math.max(0, ((b)localObject).bottomMargin + (i1 + i2));
int i4 = bf.a(0, af.j(this.e));
int i3;
if ((af.r(this) & 0x100) != 0)
{
i2 = 1;
if (i2 == 0) {
break label440;
}
i3 = this.b;
i1 = i3;
if (this.j)
{
i1 = i3;
if (this.e.getTabContainer() != null) {
i1 = i3 + this.b;
}
}
}
for (;;)
{
label153:
this.q.set(this.o);
this.s.set(this.r);
if ((!this.i) && (i2 == 0))
{
localObject = this.q;
((Rect)localObject).top = (i1 + ((Rect)localObject).top);
localObject = this.q;
}
for (((Rect)localObject).bottom += 0;; ((Rect)localObject).bottom += 0)
{
a(this.d, this.q, true, true, true, true);
if (!this.t.equals(this.s))
{
this.t.set(this.s);
this.d.a(this.s);
}
measureChildWithMargins(this.d, paramInt1, 0, paramInt2, 0);
localObject = (b)this.d.getLayoutParams();
i1 = Math.max(i6, this.d.getMeasuredWidth() + ((b)localObject).leftMargin + ((b)localObject).rightMargin);
i2 = this.d.getMeasuredHeight();
i3 = ((b)localObject).topMargin;
i2 = Math.max(i5, ((b)localObject).bottomMargin + (i2 + i3));
i3 = bf.a(i4, af.j(this.d));
i4 = getPaddingLeft();
i5 = getPaddingRight();
i2 = Math.max(i2 + (getPaddingTop() + getPaddingBottom()), getSuggestedMinimumHeight());
setMeasuredDimension(af.a(Math.max(i1 + (i4 + i5), getSuggestedMinimumWidth()), paramInt1, i3), af.a(i2, paramInt2, i3 << 16));
return;
i2 = 0;
break;
label440:
if (this.e.getVisibility() == 8) {
break label498;
}
i1 = this.e.getMeasuredHeight();
break label153;
localObject = this.s;
((Rect)localObject).top = (i1 + ((Rect)localObject).top);
localObject = this.s;
}
label498:
i1 = 0;
}
}
public boolean onNestedFling(View paramView, float paramFloat1, float paramFloat2, boolean paramBoolean)
{
if ((!this.k) || (!paramBoolean)) {
return false;
}
if (a(paramFloat1, paramFloat2)) {
o();
}
for (;;)
{
this.l = true;
return true;
n();
}
}
public boolean onNestedPreFling(View paramView, float paramFloat1, float paramFloat2)
{
return false;
}
public void onNestedPreScroll(View paramView, int paramInt1, int paramInt2, int[] paramArrayOfInt) {}
public void onNestedScroll(View paramView, int paramInt1, int paramInt2, int paramInt3, int paramInt4)
{
this.m += paramInt2;
setActionBarHideOffset(this.m);
}
public void onNestedScrollAccepted(View paramView1, View paramView2, int paramInt)
{
this.B.a(paramView1, paramView2, paramInt);
this.m = getActionBarHideOffset();
k();
if (this.u != null) {
this.u.o();
}
}
public boolean onStartNestedScroll(View paramView1, View paramView2, int paramInt)
{
if (((paramInt & 0x2) == 0) || (this.e.getVisibility() != 0)) {
return false;
}
return this.k;
}
public void onStopNestedScroll(View paramView)
{
if ((this.k) && (!this.l))
{
if (this.m > this.e.getHeight()) {
break label49;
}
l();
}
for (;;)
{
if (this.u != null) {
this.u.p();
}
return;
label49:
m();
}
}
public void onWindowSystemUiVisibilityChanged(int paramInt)
{
boolean bool = true;
if (Build.VERSION.SDK_INT >= 16) {
super.onWindowSystemUiVisibilityChanged(paramInt);
}
c();
int i3 = this.n;
this.n = paramInt;
int i1;
int i2;
if ((paramInt & 0x4) == 0)
{
i1 = 1;
if ((paramInt & 0x100) == 0) {
break label121;
}
i2 = 1;
label50:
if (this.u != null)
{
a locala = this.u;
if (i2 != 0) {
break label127;
}
label67:
locala.g(bool);
if ((i1 == 0) && (i2 != 0)) {
break label133;
}
this.u.m();
}
}
for (;;)
{
if ((((i3 ^ paramInt) & 0x100) != 0) && (this.u != null)) {
af.s(this);
}
return;
i1 = 0;
break;
label121:
i2 = 0;
break label50;
label127:
bool = false;
break label67;
label133:
this.u.n();
}
}
protected void onWindowVisibilityChanged(int paramInt)
{
super.onWindowVisibilityChanged(paramInt);
this.c = paramInt;
if (this.u != null) {
this.u.b(paramInt);
}
}
public void setActionBarHideOffset(int paramInt)
{
k();
paramInt = Math.max(0, Math.min(paramInt, this.e.getHeight()));
af.b(this.e, -paramInt);
}
public void setActionBarVisibilityCallback(a parama)
{
this.u = parama;
if (getWindowToken() != null)
{
this.u.b(this.c);
if (this.n != 0)
{
onWindowSystemUiVisibilityChanged(this.n);
af.s(this);
}
}
}
public void setHasNonEmbeddedTabs(boolean paramBoolean)
{
this.j = paramBoolean;
}
public void setHideOnContentScrollEnabled(boolean paramBoolean)
{
if (paramBoolean != this.k)
{
this.k = paramBoolean;
if (!paramBoolean)
{
k();
setActionBarHideOffset(0);
}
}
}
public void setIcon(int paramInt)
{
c();
this.f.a(paramInt);
}
public void setIcon(Drawable paramDrawable)
{
c();
this.f.a(paramDrawable);
}
public void setLogo(int paramInt)
{
c();
this.f.b(paramInt);
}
public void setOverlayMode(boolean paramBoolean)
{
this.i = paramBoolean;
if ((paramBoolean) && (getContext().getApplicationInfo().targetSdkVersion < 19)) {}
for (paramBoolean = true;; paramBoolean = false)
{
this.h = paramBoolean;
return;
}
}
public void setShowingForActionMode(boolean paramBoolean) {}
public void setUiOptions(int paramInt) {}
public void setWindowCallback(Window.Callback paramCallback)
{
c();
this.f.a(paramCallback);
}
public void setWindowTitle(CharSequence paramCharSequence)
{
c();
this.f.a(paramCharSequence);
}
public boolean shouldDelayChildPressedState()
{
return false;
}
public static abstract interface a
{
public abstract void b(int paramInt);
public abstract void g(boolean paramBoolean);
public abstract void m();
public abstract void n();
public abstract void o();
public abstract void p();
}
public static class b
extends ViewGroup.MarginLayoutParams
{
public b(int paramInt1, int paramInt2)
{
super(paramInt2);
}
public b(Context paramContext, AttributeSet paramAttributeSet)
{
super(paramAttributeSet);
}
public b(ViewGroup.LayoutParams paramLayoutParams)
{
super();
}
}
}
/* Location: /home/cdo/tmp/sanshack/SantaGram_4.2-dex2jar.jar!/android/support/v7/widget/ActionBarOverlayLayout.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
|
UTF-8
|
Java
| 17,189 |
java
|
ActionBarOverlayLayout.java
|
Java
|
[] | null |
[] |
package android.support.v7.widget;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.res.Configuration;
import android.content.res.Resources.Theme;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION;
import android.support.v4.j.af;
import android.support.v4.j.av;
import android.support.v4.j.az;
import android.support.v4.j.ba;
import android.support.v4.j.y;
import android.support.v4.j.z;
import android.support.v4.widget.u;
import android.support.v7.b.a.a;
import android.support.v7.b.a.f;
import android.support.v7.view.menu.l.a;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.Window.Callback;
public class ActionBarOverlayLayout
extends ViewGroup
implements y, ad
{
static final int[] a = { a.a.actionBarSize, 16842841 };
private final Runnable A = new Runnable()
{
public void run()
{
ActionBarOverlayLayout.a(ActionBarOverlayLayout.this);
ActionBarOverlayLayout.a(ActionBarOverlayLayout.this, af.q(ActionBarOverlayLayout.c(ActionBarOverlayLayout.this)).c(-ActionBarOverlayLayout.c(ActionBarOverlayLayout.this).getHeight()).a(ActionBarOverlayLayout.b(ActionBarOverlayLayout.this)));
}
};
private final z B;
private int b;
private int c = 0;
private ContentFrameLayout d;
private ActionBarContainer e;
private ae f;
private Drawable g;
private boolean h;
private boolean i;
private boolean j;
private boolean k;
private boolean l;
private int m;
private int n;
private final Rect o = new Rect();
private final Rect p = new Rect();
private final Rect q = new Rect();
private final Rect r = new Rect();
private final Rect s = new Rect();
private final Rect t = new Rect();
private a u;
private final int v = 600;
private u w;
private av x;
private final az y = new ba()
{
public void b(View paramAnonymousView)
{
ActionBarOverlayLayout.a(ActionBarOverlayLayout.this, null);
ActionBarOverlayLayout.a(ActionBarOverlayLayout.this, false);
}
public void c(View paramAnonymousView)
{
ActionBarOverlayLayout.a(ActionBarOverlayLayout.this, null);
ActionBarOverlayLayout.a(ActionBarOverlayLayout.this, false);
}
};
private final Runnable z = new Runnable()
{
public void run()
{
ActionBarOverlayLayout.a(ActionBarOverlayLayout.this);
ActionBarOverlayLayout.a(ActionBarOverlayLayout.this, af.q(ActionBarOverlayLayout.c(ActionBarOverlayLayout.this)).c(0.0F).a(ActionBarOverlayLayout.b(ActionBarOverlayLayout.this)));
}
};
public ActionBarOverlayLayout(Context paramContext)
{
this(paramContext, null);
}
public ActionBarOverlayLayout(Context paramContext, AttributeSet paramAttributeSet)
{
super(paramContext, paramAttributeSet);
a(paramContext);
this.B = new z(this);
}
private ae a(View paramView)
{
if ((paramView instanceof ae)) {
return (ae)paramView;
}
if ((paramView instanceof Toolbar)) {
return ((Toolbar)paramView).getWrapper();
}
throw new IllegalStateException("Can't make a decor toolbar out of " + paramView.getClass().getSimpleName());
}
private void a(Context paramContext)
{
boolean bool2 = true;
TypedArray localTypedArray = getContext().getTheme().obtainStyledAttributes(a);
this.b = localTypedArray.getDimensionPixelSize(0, 0);
this.g = localTypedArray.getDrawable(1);
if (this.g == null)
{
bool1 = true;
setWillNotDraw(bool1);
localTypedArray.recycle();
if (paramContext.getApplicationInfo().targetSdkVersion >= 19) {
break label88;
}
}
label88:
for (boolean bool1 = bool2;; bool1 = false)
{
this.h = bool1;
this.w = u.a(paramContext);
return;
bool1 = false;
break;
}
}
private boolean a(float paramFloat1, float paramFloat2)
{
boolean bool = false;
this.w.a(0, 0, 0, (int)paramFloat2, 0, 0, Integer.MIN_VALUE, Integer.MAX_VALUE);
if (this.w.e() > this.e.getHeight()) {
bool = true;
}
return bool;
}
private boolean a(View paramView, Rect paramRect, boolean paramBoolean1, boolean paramBoolean2, boolean paramBoolean3, boolean paramBoolean4)
{
boolean bool2 = false;
paramView = (b)paramView.getLayoutParams();
boolean bool1 = bool2;
if (paramBoolean1)
{
bool1 = bool2;
if (paramView.leftMargin != paramRect.left)
{
paramView.leftMargin = paramRect.left;
bool1 = true;
}
}
paramBoolean1 = bool1;
if (paramBoolean2)
{
paramBoolean1 = bool1;
if (paramView.topMargin != paramRect.top)
{
paramView.topMargin = paramRect.top;
paramBoolean1 = true;
}
}
paramBoolean2 = paramBoolean1;
if (paramBoolean4)
{
paramBoolean2 = paramBoolean1;
if (paramView.rightMargin != paramRect.right)
{
paramView.rightMargin = paramRect.right;
paramBoolean2 = true;
}
}
if ((paramBoolean3) && (paramView.bottomMargin != paramRect.bottom))
{
paramView.bottomMargin = paramRect.bottom;
return true;
}
return paramBoolean2;
}
private void k()
{
removeCallbacks(this.z);
removeCallbacks(this.A);
if (this.x != null) {
this.x.b();
}
}
private void l()
{
k();
postDelayed(this.z, 600L);
}
private void m()
{
k();
postDelayed(this.A, 600L);
}
private void n()
{
k();
this.z.run();
}
private void o()
{
k();
this.A.run();
}
public b a(AttributeSet paramAttributeSet)
{
return new b(getContext(), paramAttributeSet);
}
public void a(int paramInt)
{
c();
switch (paramInt)
{
default:
return;
case 2:
this.f.f();
return;
case 5:
this.f.g();
return;
}
setOverlayMode(true);
}
public void a(Menu paramMenu, l.a parama)
{
c();
this.f.a(paramMenu, parama);
}
public boolean a()
{
return this.i;
}
protected b b()
{
return new b(-1, -1);
}
void c()
{
if (this.d == null)
{
this.d = ((ContentFrameLayout)findViewById(a.f.action_bar_activity_content));
this.e = ((ActionBarContainer)findViewById(a.f.action_bar_container));
this.f = a(findViewById(a.f.action_bar));
}
}
protected boolean checkLayoutParams(ViewGroup.LayoutParams paramLayoutParams)
{
return paramLayoutParams instanceof b;
}
public boolean d()
{
c();
return this.f.h();
}
public void draw(Canvas paramCanvas)
{
super.draw(paramCanvas);
if ((this.g != null) && (!this.h)) {
if (this.e.getVisibility() != 0) {
break label82;
}
}
label82:
for (int i1 = (int)(this.e.getBottom() + af.n(this.e) + 0.5F);; i1 = 0)
{
this.g.setBounds(0, i1, getWidth(), this.g.getIntrinsicHeight() + i1);
this.g.draw(paramCanvas);
return;
}
}
public boolean e()
{
c();
return this.f.i();
}
public boolean f()
{
c();
return this.f.j();
}
protected boolean fitSystemWindows(Rect paramRect)
{
c();
if ((af.r(this) & 0x100) != 0) {}
boolean bool = a(this.e, paramRect, true, true, false, true);
this.r.set(paramRect);
bf.a(this, this.r, this.o);
if (!this.p.equals(this.o))
{
this.p.set(this.o);
bool = true;
}
if (bool) {
requestLayout();
}
return true;
}
public boolean g()
{
c();
return this.f.k();
}
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams paramLayoutParams)
{
return new b(paramLayoutParams);
}
public int getActionBarHideOffset()
{
if (this.e != null) {
return -(int)af.n(this.e);
}
return 0;
}
public int getNestedScrollAxes()
{
return this.B.a();
}
public CharSequence getTitle()
{
c();
return this.f.e();
}
public boolean h()
{
c();
return this.f.l();
}
public void i()
{
c();
this.f.m();
}
public void j()
{
c();
this.f.n();
}
protected void onConfigurationChanged(Configuration paramConfiguration)
{
if (Build.VERSION.SDK_INT >= 8) {
super.onConfigurationChanged(paramConfiguration);
}
a(getContext());
af.s(this);
}
protected void onDetachedFromWindow()
{
super.onDetachedFromWindow();
k();
}
protected void onLayout(boolean paramBoolean, int paramInt1, int paramInt2, int paramInt3, int paramInt4)
{
paramInt2 = getChildCount();
paramInt3 = getPaddingLeft();
getPaddingRight();
paramInt4 = getPaddingTop();
getPaddingBottom();
paramInt1 = 0;
while (paramInt1 < paramInt2)
{
View localView = getChildAt(paramInt1);
if (localView.getVisibility() != 8)
{
b localb = (b)localView.getLayoutParams();
int i1 = localView.getMeasuredWidth();
int i2 = localView.getMeasuredHeight();
int i3 = localb.leftMargin + paramInt3;
int i4 = localb.topMargin + paramInt4;
localView.layout(i3, i4, i1 + i3, i2 + i4);
}
paramInt1 += 1;
}
}
protected void onMeasure(int paramInt1, int paramInt2)
{
c();
measureChildWithMargins(this.e, paramInt1, 0, paramInt2, 0);
Object localObject = (b)this.e.getLayoutParams();
int i6 = Math.max(0, this.e.getMeasuredWidth() + ((b)localObject).leftMargin + ((b)localObject).rightMargin);
int i1 = this.e.getMeasuredHeight();
int i2 = ((b)localObject).topMargin;
int i5 = Math.max(0, ((b)localObject).bottomMargin + (i1 + i2));
int i4 = bf.a(0, af.j(this.e));
int i3;
if ((af.r(this) & 0x100) != 0)
{
i2 = 1;
if (i2 == 0) {
break label440;
}
i3 = this.b;
i1 = i3;
if (this.j)
{
i1 = i3;
if (this.e.getTabContainer() != null) {
i1 = i3 + this.b;
}
}
}
for (;;)
{
label153:
this.q.set(this.o);
this.s.set(this.r);
if ((!this.i) && (i2 == 0))
{
localObject = this.q;
((Rect)localObject).top = (i1 + ((Rect)localObject).top);
localObject = this.q;
}
for (((Rect)localObject).bottom += 0;; ((Rect)localObject).bottom += 0)
{
a(this.d, this.q, true, true, true, true);
if (!this.t.equals(this.s))
{
this.t.set(this.s);
this.d.a(this.s);
}
measureChildWithMargins(this.d, paramInt1, 0, paramInt2, 0);
localObject = (b)this.d.getLayoutParams();
i1 = Math.max(i6, this.d.getMeasuredWidth() + ((b)localObject).leftMargin + ((b)localObject).rightMargin);
i2 = this.d.getMeasuredHeight();
i3 = ((b)localObject).topMargin;
i2 = Math.max(i5, ((b)localObject).bottomMargin + (i2 + i3));
i3 = bf.a(i4, af.j(this.d));
i4 = getPaddingLeft();
i5 = getPaddingRight();
i2 = Math.max(i2 + (getPaddingTop() + getPaddingBottom()), getSuggestedMinimumHeight());
setMeasuredDimension(af.a(Math.max(i1 + (i4 + i5), getSuggestedMinimumWidth()), paramInt1, i3), af.a(i2, paramInt2, i3 << 16));
return;
i2 = 0;
break;
label440:
if (this.e.getVisibility() == 8) {
break label498;
}
i1 = this.e.getMeasuredHeight();
break label153;
localObject = this.s;
((Rect)localObject).top = (i1 + ((Rect)localObject).top);
localObject = this.s;
}
label498:
i1 = 0;
}
}
public boolean onNestedFling(View paramView, float paramFloat1, float paramFloat2, boolean paramBoolean)
{
if ((!this.k) || (!paramBoolean)) {
return false;
}
if (a(paramFloat1, paramFloat2)) {
o();
}
for (;;)
{
this.l = true;
return true;
n();
}
}
public boolean onNestedPreFling(View paramView, float paramFloat1, float paramFloat2)
{
return false;
}
public void onNestedPreScroll(View paramView, int paramInt1, int paramInt2, int[] paramArrayOfInt) {}
public void onNestedScroll(View paramView, int paramInt1, int paramInt2, int paramInt3, int paramInt4)
{
this.m += paramInt2;
setActionBarHideOffset(this.m);
}
public void onNestedScrollAccepted(View paramView1, View paramView2, int paramInt)
{
this.B.a(paramView1, paramView2, paramInt);
this.m = getActionBarHideOffset();
k();
if (this.u != null) {
this.u.o();
}
}
public boolean onStartNestedScroll(View paramView1, View paramView2, int paramInt)
{
if (((paramInt & 0x2) == 0) || (this.e.getVisibility() != 0)) {
return false;
}
return this.k;
}
public void onStopNestedScroll(View paramView)
{
if ((this.k) && (!this.l))
{
if (this.m > this.e.getHeight()) {
break label49;
}
l();
}
for (;;)
{
if (this.u != null) {
this.u.p();
}
return;
label49:
m();
}
}
public void onWindowSystemUiVisibilityChanged(int paramInt)
{
boolean bool = true;
if (Build.VERSION.SDK_INT >= 16) {
super.onWindowSystemUiVisibilityChanged(paramInt);
}
c();
int i3 = this.n;
this.n = paramInt;
int i1;
int i2;
if ((paramInt & 0x4) == 0)
{
i1 = 1;
if ((paramInt & 0x100) == 0) {
break label121;
}
i2 = 1;
label50:
if (this.u != null)
{
a locala = this.u;
if (i2 != 0) {
break label127;
}
label67:
locala.g(bool);
if ((i1 == 0) && (i2 != 0)) {
break label133;
}
this.u.m();
}
}
for (;;)
{
if ((((i3 ^ paramInt) & 0x100) != 0) && (this.u != null)) {
af.s(this);
}
return;
i1 = 0;
break;
label121:
i2 = 0;
break label50;
label127:
bool = false;
break label67;
label133:
this.u.n();
}
}
protected void onWindowVisibilityChanged(int paramInt)
{
super.onWindowVisibilityChanged(paramInt);
this.c = paramInt;
if (this.u != null) {
this.u.b(paramInt);
}
}
public void setActionBarHideOffset(int paramInt)
{
k();
paramInt = Math.max(0, Math.min(paramInt, this.e.getHeight()));
af.b(this.e, -paramInt);
}
public void setActionBarVisibilityCallback(a parama)
{
this.u = parama;
if (getWindowToken() != null)
{
this.u.b(this.c);
if (this.n != 0)
{
onWindowSystemUiVisibilityChanged(this.n);
af.s(this);
}
}
}
public void setHasNonEmbeddedTabs(boolean paramBoolean)
{
this.j = paramBoolean;
}
public void setHideOnContentScrollEnabled(boolean paramBoolean)
{
if (paramBoolean != this.k)
{
this.k = paramBoolean;
if (!paramBoolean)
{
k();
setActionBarHideOffset(0);
}
}
}
public void setIcon(int paramInt)
{
c();
this.f.a(paramInt);
}
public void setIcon(Drawable paramDrawable)
{
c();
this.f.a(paramDrawable);
}
public void setLogo(int paramInt)
{
c();
this.f.b(paramInt);
}
public void setOverlayMode(boolean paramBoolean)
{
this.i = paramBoolean;
if ((paramBoolean) && (getContext().getApplicationInfo().targetSdkVersion < 19)) {}
for (paramBoolean = true;; paramBoolean = false)
{
this.h = paramBoolean;
return;
}
}
public void setShowingForActionMode(boolean paramBoolean) {}
public void setUiOptions(int paramInt) {}
public void setWindowCallback(Window.Callback paramCallback)
{
c();
this.f.a(paramCallback);
}
public void setWindowTitle(CharSequence paramCharSequence)
{
c();
this.f.a(paramCharSequence);
}
public boolean shouldDelayChildPressedState()
{
return false;
}
public static abstract interface a
{
public abstract void b(int paramInt);
public abstract void g(boolean paramBoolean);
public abstract void m();
public abstract void n();
public abstract void o();
public abstract void p();
}
public static class b
extends ViewGroup.MarginLayoutParams
{
public b(int paramInt1, int paramInt2)
{
super(paramInt2);
}
public b(Context paramContext, AttributeSet paramAttributeSet)
{
super(paramAttributeSet);
}
public b(ViewGroup.LayoutParams paramLayoutParams)
{
super();
}
}
}
/* Location: /home/cdo/tmp/sanshack/SantaGram_4.2-dex2jar.jar!/android/support/v7/widget/ActionBarOverlayLayout.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| 17,189 | 0.600791 | 0.581709 | 748 | 21.981283 | 24.415295 | 248 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.569519 | false | false |
14
|
803bdd67d4e4bcad00063ee278fa93e124023b72
| 22,617,297,811,284 |
04763f9846f0c230ef2a1f38ef1796d6bfca536a
|
/Algorithm.java
|
2a0a29142ec50961099f205944125a446d1870d2
|
[] |
no_license
|
HiromuOhtsuka/GE
|
https://github.com/HiromuOhtsuka/GE
|
79c66d6f5bc82cb84f96d025d5a5181a6b81b9fd
|
15800fbac3600b5acb7c117c40552b4462e5fe67
|
refs/heads/master
| 2015-09-26T02:02:15.759000 | 2015-09-09T14:40:51 | 2015-09-09T14:40:51 | 41,856,690 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Map;
import java.util.TreeMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Stack;
import java.util.Queue;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Arrays;
public final class Algorithm {
private int graphSize;
private Map< Integer, List< Edge > > G;
private Map< Integer, Vertex > idv;
private Edge[] E;
private final class Pair implements Comparable< Pair > {
Integer first, second;
Pair(Integer first, Integer second){
this.first = first; this.second = second;
}
@Override
public int compareTo(Pair p){
int ret = this.first.compareTo(p.first);
if(ret == 0){
return this.second.compareTo(p.second);
}
return ret;
}
}
private final class UnionFind {
private int size;
private int[] parent, rank;
UnionFind(int size){
this.size = size;
this.parent = new int[this.size];
this.rank = new int[this.size];
init();
}
public void init(){
for(int i = 0; i < size; i++){
rank[i] = 0;
parent[i] = i;
}
}
public void unite(int u, int v){
int up = root(u), vp = root(v);
if(up == vp){
return;
}
if(rank[up] < rank[vp]){
parent[up] = vp;
}
else{
parent[vp] = up;
if(rank[up] == rank[vp]){
rank[up]++;
}
}
}
public boolean same(int u, int v){
return root(u) == root(v);
}
private int root(int u){
if(parent[u] == u){
return u;
}
return parent[u] = root(parent[u]);
}
}
public Algorithm(Graph g){
this.graphSize = g.getSize();
this.E = g.getE();
this.G = toAdjacencyList(g);
this.idv = idToVertex(g);
}
public void dfs(Vertex start, Vertex end){
if(start == null || end == null){
return;
}
idv.get(start.getId()).check(false);
idv.get(end.getId()).check(false);
final Stack< Integer > stack = new Stack< Integer >();
int count = 0;
stack.push(start.getId());
while(!stack.isEmpty()){
int id = stack.pop();
Vertex v = idv.get(id);
if(v.equals(end)){
v.check(true);
v.setValue(count++);
break;
}
if(v.isChecked()){ continue; }
v.check(true);
v.setValue(count++);
for(int i = 0; i < G.get(id).size(); i++){
int to = G.get(id).get(i).getTo();
G.get(id).get(i).check(true);
stack.push(to);
}
}
}
public void bfs(Vertex start, Vertex end){
if(start == null || end == null){
return;
}
idv.get(start.getId()).check(false);
idv.get(end.getId()).check(false);
final Queue< Integer > que = new LinkedList< Integer >();
int count = 0;
que.offer(start.getId());
while(!que.isEmpty()){
int id = que.poll();
Vertex v = idv.get(id);
if(v.equals(end)){
v.check(true);
v.setValue(count++);
break;
}
if(v.isChecked()){ continue; }
v.check(true);
v.setValue(count++);
for(int i = 0; i < G.get(id).size(); i++){
int to = G.get(id).get(i).getTo();
G.get(id).get(i).check(true);
que.offer(to);
}
}
}
public void dijkstra(Vertex start, Vertex end){
if(start == null || end == null){
return;
}
for(int i = 0; i < idv.size(); i++){
idv.get(i).setValue(Integer.MAX_VALUE);
}
final Queue< Pair > prique =
new PriorityQueue< Pair >();
idv.get(start.getId()).setValue(0);
prique.offer(new Pair(0, start.getId()));
while(!prique.isEmpty()){
Pair p = prique.poll();
int d = p.first, id = p.second;
for(int i = 0; i < G.get(id).size(); i++){
int cost = d + G.get(id).get(i).getCost(),
to = G.get(id).get(i).getTo();
if(cost < idv.get(to).getValue()){
idv.get(to).setValue(cost);
prique.offer(new Pair(cost, to));
}
}
}
}
public void kruskal(){
Arrays.sort(E);
UnionFind uf = new UnionFind(graphSize);
for(int i = 0; i < E.length; i++){
Edge e = E[i];
int from = e.getFrom(), to = e.getTo();
if(!uf.same(from, to)){
e.check(true);
idv.get(from).check(true);
idv.get(to).check(true);
uf.unite(from, to);
}
}
}
private Map< Integer, List< Edge > > toAdjacencyList(Graph g){
final Map< Integer, List< Edge > > ret =
new TreeMap< Integer, List< Edge > >();
final Edge[] E = g.getE();
for(int i = 0; i < E.length; i++){
if(E[i] instanceof UndirectedEdge){
int from = E[i].getFrom(),
to = E[i].getTo(), cost = E[i].getCost();
Edge rev = new UndirectedEdge(to, from, cost); // 逆向き
if(!ret.containsKey(from)){
List< Edge > list = new ArrayList< Edge >();
list.add(E[i]);
ret.put(from, list);
}
else{
ret.get(from).add(E[i]);
}
if(!ret.containsKey(to)){
List< Edge > list = new ArrayList< Edge >();
list.add(rev);
ret.put(to, list);
}
else{
ret.get(to).add(rev);
}
}
// else if(E[i] instanceof DirectedEdge){}
}
return ret;
}
private Map< Integer, Vertex > idToVertex(Graph g){
final Map< Integer, Vertex > ret = new TreeMap< Integer, Vertex>();
final Vertex[] V = g.getV();
for(int i = 0; i < V.length; i++){
int id = V[i].getId();
ret.put(id, V[i]);
}
return ret;
}
}
|
UTF-8
|
Java
| 5,640 |
java
|
Algorithm.java
|
Java
|
[] | null |
[] |
import java.util.Map;
import java.util.TreeMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Stack;
import java.util.Queue;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Arrays;
public final class Algorithm {
private int graphSize;
private Map< Integer, List< Edge > > G;
private Map< Integer, Vertex > idv;
private Edge[] E;
private final class Pair implements Comparable< Pair > {
Integer first, second;
Pair(Integer first, Integer second){
this.first = first; this.second = second;
}
@Override
public int compareTo(Pair p){
int ret = this.first.compareTo(p.first);
if(ret == 0){
return this.second.compareTo(p.second);
}
return ret;
}
}
private final class UnionFind {
private int size;
private int[] parent, rank;
UnionFind(int size){
this.size = size;
this.parent = new int[this.size];
this.rank = new int[this.size];
init();
}
public void init(){
for(int i = 0; i < size; i++){
rank[i] = 0;
parent[i] = i;
}
}
public void unite(int u, int v){
int up = root(u), vp = root(v);
if(up == vp){
return;
}
if(rank[up] < rank[vp]){
parent[up] = vp;
}
else{
parent[vp] = up;
if(rank[up] == rank[vp]){
rank[up]++;
}
}
}
public boolean same(int u, int v){
return root(u) == root(v);
}
private int root(int u){
if(parent[u] == u){
return u;
}
return parent[u] = root(parent[u]);
}
}
public Algorithm(Graph g){
this.graphSize = g.getSize();
this.E = g.getE();
this.G = toAdjacencyList(g);
this.idv = idToVertex(g);
}
public void dfs(Vertex start, Vertex end){
if(start == null || end == null){
return;
}
idv.get(start.getId()).check(false);
idv.get(end.getId()).check(false);
final Stack< Integer > stack = new Stack< Integer >();
int count = 0;
stack.push(start.getId());
while(!stack.isEmpty()){
int id = stack.pop();
Vertex v = idv.get(id);
if(v.equals(end)){
v.check(true);
v.setValue(count++);
break;
}
if(v.isChecked()){ continue; }
v.check(true);
v.setValue(count++);
for(int i = 0; i < G.get(id).size(); i++){
int to = G.get(id).get(i).getTo();
G.get(id).get(i).check(true);
stack.push(to);
}
}
}
public void bfs(Vertex start, Vertex end){
if(start == null || end == null){
return;
}
idv.get(start.getId()).check(false);
idv.get(end.getId()).check(false);
final Queue< Integer > que = new LinkedList< Integer >();
int count = 0;
que.offer(start.getId());
while(!que.isEmpty()){
int id = que.poll();
Vertex v = idv.get(id);
if(v.equals(end)){
v.check(true);
v.setValue(count++);
break;
}
if(v.isChecked()){ continue; }
v.check(true);
v.setValue(count++);
for(int i = 0; i < G.get(id).size(); i++){
int to = G.get(id).get(i).getTo();
G.get(id).get(i).check(true);
que.offer(to);
}
}
}
public void dijkstra(Vertex start, Vertex end){
if(start == null || end == null){
return;
}
for(int i = 0; i < idv.size(); i++){
idv.get(i).setValue(Integer.MAX_VALUE);
}
final Queue< Pair > prique =
new PriorityQueue< Pair >();
idv.get(start.getId()).setValue(0);
prique.offer(new Pair(0, start.getId()));
while(!prique.isEmpty()){
Pair p = prique.poll();
int d = p.first, id = p.second;
for(int i = 0; i < G.get(id).size(); i++){
int cost = d + G.get(id).get(i).getCost(),
to = G.get(id).get(i).getTo();
if(cost < idv.get(to).getValue()){
idv.get(to).setValue(cost);
prique.offer(new Pair(cost, to));
}
}
}
}
public void kruskal(){
Arrays.sort(E);
UnionFind uf = new UnionFind(graphSize);
for(int i = 0; i < E.length; i++){
Edge e = E[i];
int from = e.getFrom(), to = e.getTo();
if(!uf.same(from, to)){
e.check(true);
idv.get(from).check(true);
idv.get(to).check(true);
uf.unite(from, to);
}
}
}
private Map< Integer, List< Edge > > toAdjacencyList(Graph g){
final Map< Integer, List< Edge > > ret =
new TreeMap< Integer, List< Edge > >();
final Edge[] E = g.getE();
for(int i = 0; i < E.length; i++){
if(E[i] instanceof UndirectedEdge){
int from = E[i].getFrom(),
to = E[i].getTo(), cost = E[i].getCost();
Edge rev = new UndirectedEdge(to, from, cost); // 逆向き
if(!ret.containsKey(from)){
List< Edge > list = new ArrayList< Edge >();
list.add(E[i]);
ret.put(from, list);
}
else{
ret.get(from).add(E[i]);
}
if(!ret.containsKey(to)){
List< Edge > list = new ArrayList< Edge >();
list.add(rev);
ret.put(to, list);
}
else{
ret.get(to).add(rev);
}
}
// else if(E[i] instanceof DirectedEdge){}
}
return ret;
}
private Map< Integer, Vertex > idToVertex(Graph g){
final Map< Integer, Vertex > ret = new TreeMap< Integer, Vertex>();
final Vertex[] V = g.getV();
for(int i = 0; i < V.length; i++){
int id = V[i].getId();
ret.put(id, V[i]);
}
return ret;
}
}
| 5,640 | 0.516507 | 0.514022 | 226 | 23.929203 | 16.234846 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.716814 | false | false |
14
|
16263ddeb6ca04163df2de945d9d0c2aedf79107
| 21,852,793,635,421 |
d0b7846f22848926a7b3ee158304b9d8054ae6f1
|
/ShoppingList/app/src/main/java/com/example/shoppinglist/ItemList.java
|
0fd85554363cd62f7ada7650d8703563440dc496
|
[] |
no_license
|
bennaa/mobile_and_wearable_computing
|
https://github.com/bennaa/mobile_and_wearable_computing
|
34a08e8da4b01902ad8bbffe79b891d722fac7c6
|
c01df3dc11d583bc8389c4b69babd807769a26c2
|
refs/heads/master
| 2020-08-04T08:51:16.008000 | 2019-12-18T14:28:33 | 2019-12-18T14:28:33 | 212,078,914 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.shoppinglist;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ItemList extends AppCompatActivity {
public static final String EXTRA_NAME = "com.example.shoppinglist.extra.ITEMS";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list);
}
public void addItem(View view) {
Button b = findViewById(view.getId());
String text = b.getText().toString();
Intent intent = new Intent();
intent.putExtra(EXTRA_NAME, text);
setResult(RESULT_OK, intent);
finish();
}
}
|
UTF-8
|
Java
| 785 |
java
|
ItemList.java
|
Java
|
[] | null |
[] |
package com.example.shoppinglist;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ItemList extends AppCompatActivity {
public static final String EXTRA_NAME = "com.example.shoppinglist.extra.ITEMS";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list);
}
public void addItem(View view) {
Button b = findViewById(view.getId());
String text = b.getText().toString();
Intent intent = new Intent();
intent.putExtra(EXTRA_NAME, text);
setResult(RESULT_OK, intent);
finish();
}
}
| 785 | 0.699363 | 0.699363 | 28 | 27.035715 | 21.831305 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.607143 | false | false |
14
|
a3927ef6be85ea1e35b1d7f8ae71100cb071ca2d
| 26,723,286,542,388 |
b75c0f81771549dcd86ff6d28d1871cb16f8f150
|
/android/src/fishjord/wifisurvey/activities/PreferencesActivity.java
|
7e124879b6d7abcf786bf974f5d15e4d7e2ce1a6
|
[] |
no_license
|
fishjord/wifi_survey
|
https://github.com/fishjord/wifi_survey
|
e6ad50bb4cd46e6fca9996c30bafb5b2913982e8
|
cc6911ff04ecebfac425e76adbf3b1b3cec36f1a
|
refs/heads/master
| 2021-01-19T08:20:09.979000 | 2013-11-27T03:17:53 | 2013-11-27T03:17:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package fishjord.wifisurvey.activities;
import fishjord.wifisurvey.R;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
public class PreferencesActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
}
}
|
UTF-8
|
Java
| 459 |
java
|
PreferencesActivity.java
|
Java
|
[] | null |
[] |
package fishjord.wifisurvey.activities;
import fishjord.wifisurvey.R;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
public class PreferencesActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
}
}
| 459 | 0.808279 | 0.808279 | 17 | 26 | 26.718576 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.941176 | false | false |
14
|
4e6ce9b09b6f4137d09abfd7958091c800e91bfa
| 32,667,521,278,072 |
814fa8a45ac33f8b6ff59396d72798671baa7405
|
/Ventana1.java
|
d9b558313ef9d2c60a8b792ee04b45b44c326ebf
|
[] |
no_license
|
Elias34/Scholar
|
https://github.com/Elias34/Scholar
|
87d07557ce8c737379cce33297439dd583465ea2
|
f01b43eb180df6f456393355ac2f2c1d3f1dedba
|
refs/heads/master
| 2020-07-12T02:46:27.448000 | 2019-11-15T19:23:52 | 2019-11-15T19:23:52 | 204,696,688 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ventana1;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Ventana1 extends JFrame {
public Ventana1(){
this.setSize(500,500); //Estabeclemos el tamaño de la ventana1
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
Container cp = getContentPane();
cp.setLayout (new FlowLayout());
JLabel etiqueta = new JLabel ("Nombre:");
JTextField texto = new JTextField(25);
cp.add(etiqueta);
cp.add(texto);
JLabel etiqueta2 = new JLabel ("Apellido");
JTextField texto2 = new JTextField(25);
cp.add(etiqueta2);
cp.add(texto2);
JLabel etiqueta3 = new JLabel ("Fecha_de_nacimiento:");
JTextField texto3 = new JTextField(20);
cp.add(etiqueta3);
cp.add(texto3);
JLabel etiqueta4 = new JLabel ("Direccion");
JTextField texto4 = new JTextField (25);
cp.add(etiqueta4);
cp.add(texto4);
JLabel etiqueta5 = new JLabel ("Telefono");
JTextField texto5 = new JTextField(28);
cp.add(etiqueta5);
cp.add(texto5);
JLabel etiqueta6 = new JLabel ("Email");
JTextField texto6 = new JTextField(28);
cp.add(etiqueta6);
cp.add(texto6);
JLabel etiqueta7 = new JLabel ("Genero");
JTextField texto7= new JTextField(25);
cp.add(etiqueta7);
cp.add(texto7);
JButton boton = new JButton("Guardar");
JButton boton2 = new JButton("Salir");
cp.add(boton);
cp.add(boton2);
}
}
|
UTF-8
|
Java
| 1,847 |
java
|
Ventana1.java
|
Java
|
[] | null |
[] |
package ventana1;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Ventana1 extends JFrame {
public Ventana1(){
this.setSize(500,500); //Estabeclemos el tamaño de la ventana1
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
Container cp = getContentPane();
cp.setLayout (new FlowLayout());
JLabel etiqueta = new JLabel ("Nombre:");
JTextField texto = new JTextField(25);
cp.add(etiqueta);
cp.add(texto);
JLabel etiqueta2 = new JLabel ("Apellido");
JTextField texto2 = new JTextField(25);
cp.add(etiqueta2);
cp.add(texto2);
JLabel etiqueta3 = new JLabel ("Fecha_de_nacimiento:");
JTextField texto3 = new JTextField(20);
cp.add(etiqueta3);
cp.add(texto3);
JLabel etiqueta4 = new JLabel ("Direccion");
JTextField texto4 = new JTextField (25);
cp.add(etiqueta4);
cp.add(texto4);
JLabel etiqueta5 = new JLabel ("Telefono");
JTextField texto5 = new JTextField(28);
cp.add(etiqueta5);
cp.add(texto5);
JLabel etiqueta6 = new JLabel ("Email");
JTextField texto6 = new JTextField(28);
cp.add(etiqueta6);
cp.add(texto6);
JLabel etiqueta7 = new JLabel ("Genero");
JTextField texto7= new JTextField(25);
cp.add(etiqueta7);
cp.add(texto7);
JButton boton = new JButton("Guardar");
JButton boton2 = new JButton("Salir");
cp.add(boton);
cp.add(boton2);
}
}
| 1,847 | 0.570423 | 0.543337 | 72 | 24.625 | 17.543152 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false |
14
|
9923076cee9ee39cb4d884ccf030c774e7398f37
| 32,667,521,279,432 |
a61179a1c91ec5e6a66a29fcd0018ca64c331460
|
/week-01/day-3/Java-exercises/src/DrawDiamond.java
|
2b4ffb8eda9d741815f7e30fdea4485d65e2d8ad
|
[] |
no_license
|
green-fox-academy/daratniov
|
https://github.com/green-fox-academy/daratniov
|
a30f5d7fe49ccb58bad278056a39ecafe12fdeeb
|
548ed323bd8c53351ac2bdd866cee8fa02070d55
|
refs/heads/master
| 2021-02-15T07:38:35.778000 | 2020-05-13T22:52:34 | 2020-05-13T22:52:34 | 244,878,104 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Scanner;
public class DrawDiamond {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Give me an integer: ");
int number = input.nextInt();
for (int i = 0; i <= number; i++) {
for (int j = 1; j <= Math.abs(number / 2 + 1 - i); j++) {
System.out.print(" ");
}
for (int j = 1; j <= number - 2 * Math.abs(number / 2 + 1 - i); j++) {
System.out.print("*");
}
for (int j = 1; j <= Math.abs(number / 2 + 1 - i); j++) {
System.out.print(" ");
}
System.out.println();
}
}
}
// Write a program that reads a number from the standard input, then draws a
// diamond like this:
//
//
// *
// ***
// *****
// *******
// *****
// ***
// *
//
// The diamond should have as many lines as the number was
|
UTF-8
|
Java
| 948 |
java
|
DrawDiamond.java
|
Java
|
[] | null |
[] |
import java.util.Scanner;
public class DrawDiamond {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Give me an integer: ");
int number = input.nextInt();
for (int i = 0; i <= number; i++) {
for (int j = 1; j <= Math.abs(number / 2 + 1 - i); j++) {
System.out.print(" ");
}
for (int j = 1; j <= number - 2 * Math.abs(number / 2 + 1 - i); j++) {
System.out.print("*");
}
for (int j = 1; j <= Math.abs(number / 2 + 1 - i); j++) {
System.out.print(" ");
}
System.out.println();
}
}
}
// Write a program that reads a number from the standard input, then draws a
// diamond like this:
//
//
// *
// ***
// *****
// *******
// *****
// ***
// *
//
// The diamond should have as many lines as the number was
| 948 | 0.456751 | 0.445148 | 35 | 26.085714 | 23.791201 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.485714 | false | false |
14
|
a4d10b3f14e99b0869575ae37b7169cd9cd17f99
| 22,960,895,205,303 |
234a96e0f32cb500306ffd10e0dbaa03b86afd7d
|
/IAX24J-ANDROID/src/iax/client/protocol/user/command/UserCommandFacade.java
|
2b30bceb99764ae40bd61e2bfda9369762212340
|
[] |
no_license
|
adamantfromabakan/iax24j-android
|
https://github.com/adamantfromabakan/iax24j-android
|
23ffe6b35f5e6a8a888dbeac9c564140ee24eabc
|
5266d9fc2f874058fb012aadf9b60428af74ed09
|
refs/heads/master
| 2020-06-04T02:06:47.877000 | 2013-11-26T16:20:06 | 2013-11-26T16:20:06 | 10,304,875 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package iax.client.protocol.user.command;
import iax.client.protocol.peer.Peer;
public class UserCommandFacade {
/**
* Method that indicates that user has answered an incoming call.
* @param peer Current peer.
* @param callingNumber the calling number of the call that is going to be accepted
*/
public static void answerCall(Peer peer, String callingNumber) {
(new AnswerCall(peer, callingNumber)).execute();
}
/**
* Method to hang up a call.
* @param peer Current peer.
* @param calledNumber The number of the hung call.
*/
public static void hangupCall(Peer peer, String calledNumber) {
(new HangupCall(peer, calledNumber)).execute();
}
/**
* Method to hold a call.
* @param peer Current peer.
* @param calledNumber The number of the muted call.
*/
public static void holdCall(Peer peer, String calledNumber) {
(new HoldCall(peer, calledNumber)).execute();
}
/**
* Method to start a new call.
* @param peer Current peer.
* @param calledNumber Number to call to.
*/
public static void newCall(Peer peer, String calledNumber) {
System.out.println("UserCommandFacade.newCall");
(new NewCall(peer, calledNumber)).execute();
}
/**
* Exit from the system
* @param peer Current peer.
*/
public static void exit(Peer peer) {
(new Exit(peer)).execute();
}
/**
* Method to mute a call.
* @param peer Current peer.
* @param calledNumber The number of the muted call.
*/
public static void muteCall(Peer peer, String calledNumber) {
(new MuteCall(peer, calledNumber)).execute();
}
/**
* Method to unhold a call.
* @param peer Current peer.
* @param calledNumber The number of the muted call.
*/
public static void unHoldCall(Peer peer, String calledNumber) {
(new UnHoldCall(peer, calledNumber)).execute();
}
/**
* Method to unmute a call.
* @param peer Current peer.
* @param calledNumber The number of the muted call.
*/
public static void unMuteCall(Peer peer, String calledNumber) {
(new UnMuteCall(peer, calledNumber)).execute();
}
/**
* Method to send a DTMF tone.
* @param peer Current peer.
* @param calledNumber The number of the muted call.
*/
public static void sendDTMF(Peer peer, String calledNumber, char tone) {
(new SendDTMF(peer, calledNumber, tone)).execute();
}
/**
* Method to transfer a call.
* @param peer Current peer.
* @param srcNumber the source number of the transfer
* @param dstNumber the destination number of the transfer
*/
public static void transferCall(Peer peer, String srcNumber, String dstNumber) {
(new TransferCall(peer, srcNumber, dstNumber)).execute();
}
}
|
UTF-8
|
Java
| 3,032 |
java
|
UserCommandFacade.java
|
Java
|
[] | null |
[] |
package iax.client.protocol.user.command;
import iax.client.protocol.peer.Peer;
public class UserCommandFacade {
/**
* Method that indicates that user has answered an incoming call.
* @param peer Current peer.
* @param callingNumber the calling number of the call that is going to be accepted
*/
public static void answerCall(Peer peer, String callingNumber) {
(new AnswerCall(peer, callingNumber)).execute();
}
/**
* Method to hang up a call.
* @param peer Current peer.
* @param calledNumber The number of the hung call.
*/
public static void hangupCall(Peer peer, String calledNumber) {
(new HangupCall(peer, calledNumber)).execute();
}
/**
* Method to hold a call.
* @param peer Current peer.
* @param calledNumber The number of the muted call.
*/
public static void holdCall(Peer peer, String calledNumber) {
(new HoldCall(peer, calledNumber)).execute();
}
/**
* Method to start a new call.
* @param peer Current peer.
* @param calledNumber Number to call to.
*/
public static void newCall(Peer peer, String calledNumber) {
System.out.println("UserCommandFacade.newCall");
(new NewCall(peer, calledNumber)).execute();
}
/**
* Exit from the system
* @param peer Current peer.
*/
public static void exit(Peer peer) {
(new Exit(peer)).execute();
}
/**
* Method to mute a call.
* @param peer Current peer.
* @param calledNumber The number of the muted call.
*/
public static void muteCall(Peer peer, String calledNumber) {
(new MuteCall(peer, calledNumber)).execute();
}
/**
* Method to unhold a call.
* @param peer Current peer.
* @param calledNumber The number of the muted call.
*/
public static void unHoldCall(Peer peer, String calledNumber) {
(new UnHoldCall(peer, calledNumber)).execute();
}
/**
* Method to unmute a call.
* @param peer Current peer.
* @param calledNumber The number of the muted call.
*/
public static void unMuteCall(Peer peer, String calledNumber) {
(new UnMuteCall(peer, calledNumber)).execute();
}
/**
* Method to send a DTMF tone.
* @param peer Current peer.
* @param calledNumber The number of the muted call.
*/
public static void sendDTMF(Peer peer, String calledNumber, char tone) {
(new SendDTMF(peer, calledNumber, tone)).execute();
}
/**
* Method to transfer a call.
* @param peer Current peer.
* @param srcNumber the source number of the transfer
* @param dstNumber the destination number of the transfer
*/
public static void transferCall(Peer peer, String srcNumber, String dstNumber) {
(new TransferCall(peer, srcNumber, dstNumber)).execute();
}
}
| 3,032 | 0.606201 | 0.606201 | 97 | 29.257732 | 24.636858 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.371134 | false | false |
14
|
43dd02fb126ebac00c0ed662774e159858034d4d
| 24,696,061,981,480 |
a2f56ff0a21d4b4cdeda177758b418f5017f7e79
|
/src/com/hello915/rongclient/User.java
|
3a3fa899b76a03a7e87637e9a901ef4d51fb3d2f
|
[] |
no_license
|
HuShenghai/RongYunClient
|
https://github.com/HuShenghai/RongYunClient
|
0b335cf457624561925216396325447f7d6af8df
|
dfc4fb19f9d6d4ab242e07d0168ac485f751c647
|
refs/heads/master
| 2016-08-06T14:03:38.821000 | 2014-11-05T10:07:25 | 2014-11-05T10:07:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hello915.rongclient;
public class User {
private String username;
private String userid;
private String password;
private String token;
private String deviceid;
private String portrait;
public User(String name,String id,String pwd,String token,String dev,String port){
this.userid = id;
this.username = name;
this.password = pwd;
this.deviceid = dev;
this.token = token;
this.portrait = port;
}
public void setUserName(String userName){
this.username = userName;
}
public String getUserName(){
return this.username;
}
public void setUserId(String userId){
this.userid = userId;
}
public String getUserId(){
return this.userid;
}
public void setPassword(String pwd){
this.password = pwd;
}
public String getPassword(){
return this.password;
}
public void setDeviceId(String deviceId){
this.deviceid = deviceId;
}
public String getDeviceId(){
return this.deviceid;
}
public void setPortrait(String portrait){
this.portrait = portrait;
}
public String getPortrait(){
return this.portrait;
}
public void setToken(String token){
this.token = token;
}
public String getToken(){
return this.token;
}
}
|
UTF-8
|
Java
| 1,200 |
java
|
User.java
|
Java
|
[
{
"context": "tring port){\n\t\tthis.userid = id;\n\t\tthis.username = name;\n\t\tthis.password = pwd;\n\t\tthis.deviceid = dev;\n\t\t",
"end": 333,
"score": 0.9803568124771118,
"start": 329,
"tag": "USERNAME",
"value": "name"
},
{
"context": "id = id;\n\t\tthis.username = name;\n\t\tthis.password = pwd;\n\t\tthis.deviceid = dev;\n\t\tthis.token = token;\n\t\tt",
"end": 356,
"score": 0.9968104958534241,
"start": 353,
"tag": "PASSWORD",
"value": "pwd"
},
{
"context": "id setUserName(String userName){\n\t\tthis.username = userName;\n\t}\n\t\n\tpublic String getUserName(){\n\t\treturn this",
"end": 499,
"score": 0.9850887656211853,
"start": 491,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "ic void setPassword(String pwd){\n\t\tthis.password = pwd;\n\t}\n\t\n\tpublic String getPassword(){\n\t\treturn this.",
"end": 747,
"score": 0.7858834266662598,
"start": 744,
"tag": "PASSWORD",
"value": "pwd"
}
] | null |
[] |
package com.hello915.rongclient;
public class User {
private String username;
private String userid;
private String password;
private String token;
private String deviceid;
private String portrait;
public User(String name,String id,String pwd,String token,String dev,String port){
this.userid = id;
this.username = name;
this.password = pwd;
this.deviceid = dev;
this.token = token;
this.portrait = port;
}
public void setUserName(String userName){
this.username = userName;
}
public String getUserName(){
return this.username;
}
public void setUserId(String userId){
this.userid = userId;
}
public String getUserId(){
return this.userid;
}
public void setPassword(String pwd){
this.password = pwd;
}
public String getPassword(){
return this.password;
}
public void setDeviceId(String deviceId){
this.deviceid = deviceId;
}
public String getDeviceId(){
return this.deviceid;
}
public void setPortrait(String portrait){
this.portrait = portrait;
}
public String getPortrait(){
return this.portrait;
}
public void setToken(String token){
this.token = token;
}
public String getToken(){
return this.token;
}
}
| 1,200 | 0.7125 | 0.71 | 66 | 17.181818 | 15.552364 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.666667 | false | false |
14
|
34ffa5764e68a3433cdffa05106494e4b17d4ad8
| 128,849,052,827 |
de57de088a9cee6017d1a85a5e710ba0f565cb53
|
/src/main/java/tester.java
|
5f517b26ad523279bdb4b97db423c210ddfeaf9e
|
[] |
no_license
|
Jermaine34343/MobileDevice
|
https://github.com/Jermaine34343/MobileDevice
|
260c2c1ef83a6d438d1a879f75c42d6517b52cf2
|
4e55970a20e4a161d9dfdbad9d2e54e475798424
|
refs/heads/master
| 2020-03-08T06:51:53.790000 | 2018-04-03T23:50:23 | 2018-04-03T23:50:23 | 127,981,211 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class tester {
public static void main(String[] args) {
double[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
double sum = 0;
for(int i=0; i<numbers.length; i++){
sum = sum + numbers[i];
}
/* arr.length returns the number of elements
* present in the array
*/
double average = sum / numbers.length;
/* This is used for displaying the formatted output
* if you give %.4f then the output would have 4 digits
* after decimal point.
*/
System.out.format("The average is: %.3f", average);
}
}
|
UTF-8
|
Java
| 626 |
java
|
tester.java
|
Java
|
[] | null |
[] |
public class tester {
public static void main(String[] args) {
double[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
double sum = 0;
for(int i=0; i<numbers.length; i++){
sum = sum + numbers[i];
}
/* arr.length returns the number of elements
* present in the array
*/
double average = sum / numbers.length;
/* This is used for displaying the formatted output
* if you give %.4f then the output would have 4 digits
* after decimal point.
*/
System.out.format("The average is: %.3f", average);
}
}
| 626 | 0.531949 | 0.50639 | 23 | 26.26087 | 22.56241 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.73913 | false | false |
14
|
67349abe7aac583a3ff3c5a181412c6e4265fcdd
| 9,534,827,436,560 |
8daebe986ff13dd0103e56c4a2682d3c7e106bc5
|
/src/main/java/microBenchmark/MultiThreadJavaLR.java
|
09b2b21cfd5b72bee334dc1e2bf16f8471e5d9b7
|
[] |
no_license
|
zx247549135/DecaApplication
|
https://github.com/zx247549135/DecaApplication
|
1e64c94926e8d0e3dac0b69d3f9f29ca38f6e9b7
|
fbb05f386085a888b796a8b88a37a74ff09490e5
|
refs/heads/master
| 2020-12-06T20:19:11.852000 | 2016-10-09T09:12:41 | 2016-10-09T09:12:41 | 67,464,062 | 1 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package microBenchmark;
import java.util.concurrent.*;
/**
* Created by zx on 16-4-10.
*/
public class MultiThreadJavaLR extends LR {
private int partitions = 8;
private int cores = 2;
ExecutorService executor;
MultiThreadJavaLR(int paritions, int cores){
this.partitions = paritions;
this.cores = cores;
}
class RunThread implements Callable{
int partitionId;
RunThread(int partitionId){
this.partitionId = partitionId;
}
@Override
public Object call() {
double[] gradient = new double[D];
DataPoint[] block = cache[partitionId];
for (int i = 0; i < block.length; i++) {
double[] subgradient = new double[D];
DataPoint p = block[i];
if (p == null)
break;
double dot = dot(w, p.x);
double tmp = (1 / (1 + Math.exp(-p.y * dot)) - 1) * p.y;
for (int j = 0; j < D; j++) {
gradient[j] += tmp * p.x[j];
}
}
return gradient;
}
public double dot(double[] a, double[] b) {
double x = 0;
for (int i = 0; i < D; i++) {
x += a[i] * b[i];
}
return x;
}
}
private DataPoint[][] cache;
private static double[] w;
public void textFile(int dimension, int nums) {
this.D = dimension;
this.N = nums;
w = new double[D];
for (int i = 0; i < D; i++) {
w[i] = 2 * random.nextDouble() - 1;
}
// System.out.print("Initial w: ");
// System.out.println(Arrays.toString(w));
cache = new DataPoint[partitions][N / partitions + 1];
int partitionId = 0;
int cacheIndex = 0;
for (int i = 0; i < N; i++) {
int y;
if (i % 2 == 0)
y = 0;
else
y = 1;
double[] x = new double[D];
for (int j = 0; j < D; j++) {
x[j] = random.nextGaussian() + y * R;
}
if(partitionId >= partitions) {
partitionId -= partitions;
cacheIndex += 1;
}
cache[partitionId][cacheIndex] = new DataPoint(x, y);
partitionId += 1;
}
}
public void compute(int iterations){
executor = Executors.newFixedThreadPool(cores);
for(int iter = 0; iter < iterations; iter ++) {
Future[] futures = new Future[partitions];
try {
for(int i = 0; i < partitions; i ++){
Callable callable = new RunThread(i);
futures[i] = executor.submit(callable);
}
double[] gradient = new double[D];
for (int i = 0; i < partitions; i++) {
double[] subgradient = (double[]) futures[i].get(100, TimeUnit.MINUTES);
for (int j = 0; j < D; j++) {
gradient[j] += subgradient[j];
}
}
for (int j = 0; j < D; j++) {
w[j] -= gradient[j];
}
} catch (Exception e) {
System.out.println("compute error: " + e);
}
}
// System.out.print("Final w: ");
// System.out.println(Arrays.toString(w));
}
public void shutdown(){
executor.shutdown();
}
}
|
UTF-8
|
Java
| 3,550 |
java
|
MultiThreadJavaLR.java
|
Java
|
[
{
"context": "\nimport java.util.concurrent.*;\n\n/**\n * Created by zx on 16-4-10.\n */\npublic class MultiThreadJavaLR ex",
"end": 77,
"score": 0.9963025450706482,
"start": 75,
"tag": "USERNAME",
"value": "zx"
}
] | null |
[] |
package microBenchmark;
import java.util.concurrent.*;
/**
* Created by zx on 16-4-10.
*/
public class MultiThreadJavaLR extends LR {
private int partitions = 8;
private int cores = 2;
ExecutorService executor;
MultiThreadJavaLR(int paritions, int cores){
this.partitions = paritions;
this.cores = cores;
}
class RunThread implements Callable{
int partitionId;
RunThread(int partitionId){
this.partitionId = partitionId;
}
@Override
public Object call() {
double[] gradient = new double[D];
DataPoint[] block = cache[partitionId];
for (int i = 0; i < block.length; i++) {
double[] subgradient = new double[D];
DataPoint p = block[i];
if (p == null)
break;
double dot = dot(w, p.x);
double tmp = (1 / (1 + Math.exp(-p.y * dot)) - 1) * p.y;
for (int j = 0; j < D; j++) {
gradient[j] += tmp * p.x[j];
}
}
return gradient;
}
public double dot(double[] a, double[] b) {
double x = 0;
for (int i = 0; i < D; i++) {
x += a[i] * b[i];
}
return x;
}
}
private DataPoint[][] cache;
private static double[] w;
public void textFile(int dimension, int nums) {
this.D = dimension;
this.N = nums;
w = new double[D];
for (int i = 0; i < D; i++) {
w[i] = 2 * random.nextDouble() - 1;
}
// System.out.print("Initial w: ");
// System.out.println(Arrays.toString(w));
cache = new DataPoint[partitions][N / partitions + 1];
int partitionId = 0;
int cacheIndex = 0;
for (int i = 0; i < N; i++) {
int y;
if (i % 2 == 0)
y = 0;
else
y = 1;
double[] x = new double[D];
for (int j = 0; j < D; j++) {
x[j] = random.nextGaussian() + y * R;
}
if(partitionId >= partitions) {
partitionId -= partitions;
cacheIndex += 1;
}
cache[partitionId][cacheIndex] = new DataPoint(x, y);
partitionId += 1;
}
}
public void compute(int iterations){
executor = Executors.newFixedThreadPool(cores);
for(int iter = 0; iter < iterations; iter ++) {
Future[] futures = new Future[partitions];
try {
for(int i = 0; i < partitions; i ++){
Callable callable = new RunThread(i);
futures[i] = executor.submit(callable);
}
double[] gradient = new double[D];
for (int i = 0; i < partitions; i++) {
double[] subgradient = (double[]) futures[i].get(100, TimeUnit.MINUTES);
for (int j = 0; j < D; j++) {
gradient[j] += subgradient[j];
}
}
for (int j = 0; j < D; j++) {
w[j] -= gradient[j];
}
} catch (Exception e) {
System.out.println("compute error: " + e);
}
}
// System.out.print("Final w: ");
// System.out.println(Arrays.toString(w));
}
public void shutdown(){
executor.shutdown();
}
}
| 3,550 | 0.440845 | 0.430704 | 121 | 28.347107 | 19.748714 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.669421 | false | false |
14
|
146161fd37bfab1810d57a6d493b9885220052d0
| 33,389,075,792,308 |
ae652ef9816665ffa9e5991452f29f50311425b0
|
/hell-ml/src/main/java/ps/hell/ml/forest/classification/decisionTree/C45.java
|
ea3b5f8924422bf2a84b1bbbb7665b455e9cfa9f
|
[] |
no_license
|
qqgirllianxin/hell
|
https://github.com/qqgirllianxin/hell
|
97620a7657d48136113a789d97178bff9427875f
|
20080083b9efd160348471552b2cfb8661871db3
|
refs/heads/master
| 2021-01-13T14:13:09.394000 | 2016-09-30T12:26:26 | 2016-09-30T12:26:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ps.hell.ml.forest.classification.decisionTree;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map.Entry;
import ps.hell.math.base.MathBase;
import ps.hell.math.base.MathBase.MathTable;
import ps.hell.base.struct.TableTree;
import ps.hell.base.struct.TableTree.Node;
/**
* C45为id3的进化版本
* 主要使用的是 gini指数 以及
* 最小误差剪枝方法
* (代价复杂性剪枝,悲观误差剪枝)
* @author Administrator
*
*/
public class C45 {
/**
* 0.95对应的卡方值
*/
public double[] CHI=new double[]
{0.004,0.103,0.352,0.711,1.145,1.635,2.167,2.733,3.325,3.94,4.575,5.226,5.892,6.571,7.261,7.962};
/**
* 输入原数据
*/
public String[][] inputData=null;
/**
* 将信息转化为整数
*/
public int[][] inputDataInt=null;
/**
* 对应string 对应的int
*/
public ArrayList<HashMap<String,Integer>> inputDataStringToInt=new ArrayList<HashMap<String,Integer>>();
/**
* 对应的int地string
*/
public ArrayList<HashMap<Integer,String>> inputDataIntToString=new ArrayList<HashMap<Integer,String>>();
/**
* 输出原数据
*/
public String[] outputData=null;
/**
* 对应那个的int
*/
public int[] outputDataInt=null;
/**
* 对应string 对应的int
*/
public HashMap<String,Integer> outDataStringToInt=new HashMap<String,Integer>();
/**
* 对应的int地string
*/
public HashMap<Integer,String> outDataIntToString=new HashMap<Integer,String>();
/**
* 输入数据+输出的输入string对应的int形式
*/
public ArrayList<HashMap<String,Integer>> dataMap=new ArrayList<HashMap<String,Integer>>();
public TableTree fTree=new TableTree();
public C45(String[][] inputData,String[] outputData)
{
this.inputData=new String[inputData.length][];
for(int i=0;i<inputData.length;i++)
{
this.inputData[i]=inputData[i].clone();
}
this.outputData=outputData.clone();
this.inputDataInt=new int[inputData.length][inputData[0].length];
this.outputDataInt=new int[outputData.length];
changeToInt();
}
/**
* 将信息转化为int格式
*/
public void changeToInt()
{
for(int j=0;j<inputData[0].length;j++)
{
int count=0;
HashMap<String,Integer> map=new HashMap<String,Integer>();
HashMap<Integer,String> map2=new HashMap<Integer,String>();
for(int i=0;i<inputData.length;i++)
{
if(map.containsKey(inputData[i][j]))
{
inputDataInt[i][j]=map.get(inputData[i][j]);
}else{
map.put(inputData[i][j],count);
map2.put(count,inputData[i][j]);
count++;
}
}
this.inputDataStringToInt.add(map);
this.inputDataIntToString.add(map2);
}
int count=0;
for(int i=0;i<outputData.length;i++)
{
if(outDataStringToInt.containsKey(outputData[i]))
{
outputDataInt[i]=outDataStringToInt.get(outputData[i]);
}else{
this.outDataStringToInt.put(outputData[i],count);
this.outDataIntToString.put(count,outputData[i]);
count++;
}
}
//初始化输出数据
changeStringToInt(inputData, inputDataInt, outputData, outputDataInt, dataMap);
}
/**
* c45执行程序
*/
public void exec()
{
//判断维度选择
execSonLeaf(this.inputDataInt,this.inputData,this.outputDataInt,this.outputData,1,1,fTree.root,dataMap);
}
/**
* c45向下搜索方法
* @param inputDataToInt
* @param inputDataString
* @param deep 深度
* @param node null为根节点无 否则 向下添加子节点
* @param dataMap 为动态调整的结构 而跟节点上的dataMap不变
*/
public void execSonLeaf(int[][] inputDataToInt,String[][] inputDataString,int[] outputDataToInt,String[] outputDataString,int deep,
double errorFather,Node node,ArrayList<HashMap<String,Integer>> dataMap)
{
System.out.println("deep:"+deep);
//获取相关概率
ArrayList<double[]> inputP=new ArrayList<double[]>();
int outputlength=dataMap.get(dataMap.size()-1).size();
double[] outputP=new double[outputlength];
ArrayList<double[]> condtionP=new ArrayList<double[]>();
//获取最小gini的位置
int minIndex=getMinGiniIndex(inputDataToInt,outputDataToInt);
if(minIndex==-1)
{
System.out.println("无法向下延伸:"+"深度:"+deep);
return;
}else
{
System.out.println("已到叶子节点:"+"深度:"+deep);
}
int[] maxIndexValue=MathBase.getCol(inputDataToInt,minIndex);
//从 inputDataToInt 中剔除 maxIndex列数据
int[][] inputDataTempToInt=MathBase.moveCol(inputDataToInt, minIndex);
System.out.println("inputDataToInt:"+inputDataToInt[0].length);
System.out.println("inputDataTempToInt:"+inputDataTempToInt[0].length);
//获取以maxIndex列分类的 子二维数组
ArrayList<int[]> outputTemp=new ArrayList<int[]>();//存储分组后的outputDataToInt
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
//分组后的输入String[][]
ArrayList<String[][]> inputDataStringTemp=new ArrayList<String[][]>();
//分组后的输出String[][]
ArrayList<String[]> outputDataStringTemp=new ArrayList<String[]>();
//需要将inputDataString剔除对应的列
String[][] inputDataString2=MathBase.moveCol(inputDataString,minIndex);
ArrayList<int[][]> groupInputData=MathBase.getGroupSon(inputDataStringTemp,
inputDataTempToInt, inputDataString2, maxIndexValue, outputDataToInt, outputDataString, outputDataStringTemp, outputTemp, map);
//ArrayList<int[][]> groupInputData=MathMethod.getGroupSon(inputDataToInt,maxIndexValue,outputDataToInt,outputTemp,map);
//对每个子集作向下查找
int zq=0;
//移除调掉对应的信息
// dataMap.remove(maxIndex);
deep++;
for(int[][] sonInputDataToInt:groupInputData)
{
//重新计算 dataMap
ArrayList<HashMap<String,Integer>> dataMapTemp=new ArrayList<HashMap<String,Integer>>();
changeStringToInt(inputDataStringTemp.get(zq),sonInputDataToInt,outputDataStringTemp.get(zq),outputTemp.get(zq),dataMapTemp);
//重新计算误差
int index=-1;
//添加到fTree中
for(Entry<Integer, Integer> ll: map.entrySet())
{
if(ll.getValue()==zq)
{
index=ll.getValue();
}
}
//不写其他方法
//并设置概率 及数量
int ln=MathBase.getMode(outputTemp.get(zq));
String lnString=Integer.toString(ln);
MathTable table2=MathBase.getTable(outputTemp.get(zq), null);
for(int i=0;i<table2.nameRow.length;i++)
{
if(table2.nameRow[i].equals(lnString))
{
ln=table2.num[i][0];
}
}
zq++;
//继续调用子节点
Leaf leaf=new Leaf(dataMapTemp.get(minIndex).get(index),sonInputDataToInt.length*1.0/inputDataToInt.length,
sonInputDataToInt.length,1-(ln*1.0)/table2.num.length,dataMapTemp.get(dataMapTemp.size()-1).get(ln));
Node sonNode=fTree.add(node,leaf,deep);
System.out.println("sonInputDataToInt:"+sonInputDataToInt[0].length);
execSonLeaf(sonInputDataToInt,inputDataStringTemp.get(zq-1),
outputTemp.get(zq-1),outputDataStringTemp.get(zq-1),deep,0,sonNode,dataMapTemp);
}
}
/**
* 将 字符串类型的统一转化为int类型
*/
public void changeStringToInt(String[][] inputDataA,int[][] inputDataToIntA,
String[] outputDataA,int[] outputDataToIntA,
ArrayList<HashMap<String,Integer>> dataMap)
{
//输入变量的类型统计
for(int i=0;i<inputDataA[0].length;i++)
{
HashMap<String,Integer> temp=new HashMap<String,Integer>();
int index=-1;
for(int j=0;j<inputDataA.length;j++)
{
if(temp.containsKey(inputDataA[j][i]))
{
//输入变量类型修改
inputDataToIntA[j][i]=temp.get(inputDataA[j][i]);
}else{
index++;
temp.put(inputDataA[j][i],index);
inputDataToIntA[j][i]=index;
}
}
dataMap.add(temp);
}
//输出变量修改
HashMap<String,Integer> temp=new HashMap<String,Integer>();
int index=-1;
for(int j=0;j<outputDataA.length;j++)
{
if(temp.containsKey(outputDataA[j]))
{
//输入变量类型修改
outputDataToIntA[j]=temp.get(outputDataA[j]);
}else{
index++;
temp.put(outputDataA[j],index);
outputDataToIntA[j]=index;
}
}
dataMap.add(temp);
}
/**
* 将 字符串类型的统一转化为int类型 group组方法
* 将对应的int[][] 修改为对应的值
*/
public void changeStringToIntT(String[][] inputDataA,int[][] inputDataToIntA,
String[] outputDataA,int[] outputDataToIntA,
ArrayList<HashMap<String,Integer>> dataMap)
{
//输入变量的类型统计
for(int i=0;i<inputDataToIntA[0].length;i++)
{
HashMap<String,Integer> temp=new HashMap<String,Integer>();
int index=-1;
for(int j=0;j<inputDataA.length;j++)
{
if(temp.containsKey(inputDataA[j][i]))
{
//输入变量类型修改
inputDataToIntA[j][i]=temp.get(inputDataA[j][i]);
}else{
index++;
temp.put(inputDataA[j][i],index);
inputDataToIntA[j][i]=index;
}
}
dataMap.add(temp);
}
//输出变量修改
HashMap<String,Integer> temp=new HashMap<String,Integer>();
int index=-1;
for(int j=0;j<outputDataA.length;j++)
{
if(temp.containsKey(outputDataA[j]))
{
//输入变量类型修改
outputDataToIntA[j]=temp.get(outputDataA[j]);
}else{
index++;
temp.put(outputDataA[j],index);
outputDataToIntA[j]=index;
}
}
dataMap.add(temp);
}
/**
* 从输入和输出中获取 最小gini系数的index列
* @param in
* @param out
* @return
*/
public int getMinGiniIndex(int[][] in,int[] out)
{
ArrayList<LinkedList<Integer>> outputGroup=getOutputGroup(out);
double min=Double.MAX_VALUE;
int index=-1;
//类对应的最小gini的输入列的分类数
int inCount=0;
double val=0.0;
//对每一列获取gini系数并获取其中最小的点
for(int i=0;i<in[0].length;i++)
{
int cou=0;
val=getGiniValue(in,out,outputGroup,i,cou);
if(min>val)
{
min=val;
index=i;
inCount=cou;
}
}
//判断是否终结
boolean flag =isEnd(in,out,outputGroup,index,inCount);
if(flag)
{
//可以分裂
return index;
}else
{
//终止分裂
return -1;
}
}
public ArrayList<LinkedList<Integer>> getOutputGroup(int[] out)
{
ArrayList<LinkedList<Integer>> result=new ArrayList<LinkedList<Integer>>();
HashMap<Integer,Integer> value=new HashMap<Integer,Integer>();
int count=0;
LinkedList<Integer> re=new LinkedList<Integer>();
for(int i=0;i<out.length;i++)
{
if(value.containsKey(out[i]))
{
result.get(value.get(out[i])).add(i);
}else
{
value.put(out[i],count);
if(count==0)
{
}else{
re=new LinkedList<Integer>();
}
re.add(i);
result.add(re);
count++;
}
}
return result;
}
/**
* 获取制定列的gini值
* @param in
* @param out
* @param ok 为根据out分隔出来 值相同的index组合
* @param index
* @param inCount 为in对应的index中有多少个分类
* @return
*/
public double getGiniValue(int[][] in,int[] out,ArrayList<LinkedList<Integer>> ok,int index,int inCount)
{
double result=0.0;
for(int i=0;i<ok.size();i++)
{
//计算没一组的分组情况
int[] count=new int[ok.get(i).size()];
int co=0;
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(Integer indexGroup:ok.get(i))
{
if(map.containsKey(in[indexGroup][index]))
{
count[map.get(in[indexGroup][index])]++;
}else
{
map.put(in[indexGroup][index],co);
count[co]++;
co++;
}
}
inCount=map.size();
//计算值
double gini=0.0;
for(int j=0;j<count.length;j++)
{
if(count[j]==0)
{
break;
}else
{
gini+=Math.pow(count[j]*1D, 2D);
}
}
//gini=1-[(4/5)^2+(1/5)^2]
gini=1-gini;
//gini_gain=sum(p(a)*gini(a))
result+=ok.get(i).size()*1D/out.length*gini;
}
return result;
}
/**
* 判断是否终止
* 使用卡方检验
* @param in
* @param out
* @param outGroup 一output为不同分类划分
* @param minIndex 最小giniindex
* @param inCount 输入的minIndex中有多少个分类
* @return
*/
public boolean isEnd(int[][] in,int[] out,ArrayList<LinkedList<Integer>> outGroup,int minIndex,int inCount)
{
//判断获取的最小gini系数的列是否达到终止条件
if(outGroup.size()==0 ||inCount==0)
{
return false;
}
double[][] result=new double[outGroup.size()][inCount];
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
int coun=0;
for(int i=0;i<outGroup.size();i++)
{
for(Integer group:outGroup.get(i))
{
if(map.containsKey(in[group][minIndex]))
{
result[i][map.get(in[group][minIndex])]++;
}else
{
map.put(in[group][minIndex],coun);
result[i][coun]++;
coun++;
}
}
}
double x2fang=cal_chi(result);
//列-行数对应的自由度上的卡方值
if(x2fang<CHI[result[0].length-result.length])
{
//则为独立 不需要分裂了
return false;
}
return true;
}
/**
* 咖方值计算
* @param arr
* @return
*/
public double cal_chi(double[][] arr){
double[] rowsum=new double[arr.length];
double[] colsum=new double[arr[0].length];
double totalsum=0.0;
for(int i=0;i<arr.length;++i){
for(int j=0;j<arr[0].length;++j){
totalsum+=arr[i][j];
rowsum[i]+=arr[i][j];
colsum[j]+=arr[i][j];
}
}
double rect=0.0;
for(int i=0;i<arr.length;++i){
for(int j=0;j<arr[0].length;++j){
double excep=1.0*rowsum[i]*colsum[j]/totalsum;
if(excep!=0)
rect+=Math.pow(arr[i][j]-excep,2.0)/excep;
}
}
return rect;
}
/**
* 节点的实体对象
* @author Administrator
*/
public class Leaf<T extends Comparable>
{
//类名字
public T name=null;
//对应概率
public double p=0.0;
//对应数量
public int num=0;
//对应错误率
public double errorP=0.0;
//对应的y
public T yName=null;
public Leaf(T name,double p,int num,double errorP,T yName)
{
this.name=name;
this.p=p;
this.num=num;
this.errorP=errorP;
this.yName=yName;
}
//不用
public int compareTo(Leaf leaf)
{
if(this.name.compareTo(leaf.name)==0)
{
return 0;
}else if(this.name.compareTo(leaf.name)>0){
return 1;
}
return -1;
}
}
public static void main(String[] args) {
String[] name=new String[]
{
"名称","体温","表面覆盖","胎生","产蛋","能飞","水生","有腿","冬眠","类标记"
};
String[][] inputData=new String[][]
{{"人","恒温","毛发","是","否","否","否","是","否"},
{"巨蟒","冷血","鳞片","否","是","否","否","否","是"},
{"鲑鱼","冷血","鳞片","否","是","否","是","否","否"},
{"鲸","恒温","毛发","是","否","否","是","否","否"},
{"蛙","冷血","无","否","是","否","有时","是","是"},
{"巨蜥","冷血","鳞片","否","是","否","否","是","否"},
{"蝙蝠","恒温","毛发","是","否","是","否","是","否"},
{"猫","恒温","皮","是","否","否","否","是","否"},
{"豹纹鲨","冷血","鳞片","是","否","否","是","否","否"},
{"海龟","冷血","鳞片","否","是","否","有时","是","否"},
{"豪猪","恒温","刚毛","是","否","否","否","是","是"},
{"鳗","冷血","鳞片","否","是","否","是","否","否"},
{"蝾螈","冷血","无","否","是","否","有时","是","是"}};
String[] outputData=new String[]{"哺乳类","爬行类","鱼类","哺乳类","两栖类","爬行类",
"哺乳类","哺乳类","鱼类","爬行类","哺乳类","鱼类","两栖类"};
C45 c45=new C45(inputData,outputData);
c45.exec();
}
}
|
UTF-8
|
Java
| 15,668 |
java
|
C45.java
|
Java
|
[
{
"context": "ni指数 以及\n * 最小误差剪枝方法\n * (代价复杂性剪枝,悲观误差剪枝)\n * @author Administrator\n *\n */\npublic class C45 {\n\t/**\n\t * 0.95对应的卡方值\n\t *",
"end": 427,
"score": 0.9063886404037476,
"start": 414,
"tag": "USERNAME",
"value": "Administrator"
},
{
"context": "\n\t return rect;\n\t}\n\t/**\n\t * 节点的实体对象\n\t * @author Administrator\n\t */\n\tpublic class Leaf<T extends Comparable>\n\t{\n",
"end": 12484,
"score": 0.7150468826293945,
"start": 12471,
"tag": "USERNAME",
"value": "Administrator"
}
] | null |
[] |
package ps.hell.ml.forest.classification.decisionTree;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map.Entry;
import ps.hell.math.base.MathBase;
import ps.hell.math.base.MathBase.MathTable;
import ps.hell.base.struct.TableTree;
import ps.hell.base.struct.TableTree.Node;
/**
* C45为id3的进化版本
* 主要使用的是 gini指数 以及
* 最小误差剪枝方法
* (代价复杂性剪枝,悲观误差剪枝)
* @author Administrator
*
*/
public class C45 {
/**
* 0.95对应的卡方值
*/
public double[] CHI=new double[]
{0.004,0.103,0.352,0.711,1.145,1.635,2.167,2.733,3.325,3.94,4.575,5.226,5.892,6.571,7.261,7.962};
/**
* 输入原数据
*/
public String[][] inputData=null;
/**
* 将信息转化为整数
*/
public int[][] inputDataInt=null;
/**
* 对应string 对应的int
*/
public ArrayList<HashMap<String,Integer>> inputDataStringToInt=new ArrayList<HashMap<String,Integer>>();
/**
* 对应的int地string
*/
public ArrayList<HashMap<Integer,String>> inputDataIntToString=new ArrayList<HashMap<Integer,String>>();
/**
* 输出原数据
*/
public String[] outputData=null;
/**
* 对应那个的int
*/
public int[] outputDataInt=null;
/**
* 对应string 对应的int
*/
public HashMap<String,Integer> outDataStringToInt=new HashMap<String,Integer>();
/**
* 对应的int地string
*/
public HashMap<Integer,String> outDataIntToString=new HashMap<Integer,String>();
/**
* 输入数据+输出的输入string对应的int形式
*/
public ArrayList<HashMap<String,Integer>> dataMap=new ArrayList<HashMap<String,Integer>>();
public TableTree fTree=new TableTree();
public C45(String[][] inputData,String[] outputData)
{
this.inputData=new String[inputData.length][];
for(int i=0;i<inputData.length;i++)
{
this.inputData[i]=inputData[i].clone();
}
this.outputData=outputData.clone();
this.inputDataInt=new int[inputData.length][inputData[0].length];
this.outputDataInt=new int[outputData.length];
changeToInt();
}
/**
* 将信息转化为int格式
*/
public void changeToInt()
{
for(int j=0;j<inputData[0].length;j++)
{
int count=0;
HashMap<String,Integer> map=new HashMap<String,Integer>();
HashMap<Integer,String> map2=new HashMap<Integer,String>();
for(int i=0;i<inputData.length;i++)
{
if(map.containsKey(inputData[i][j]))
{
inputDataInt[i][j]=map.get(inputData[i][j]);
}else{
map.put(inputData[i][j],count);
map2.put(count,inputData[i][j]);
count++;
}
}
this.inputDataStringToInt.add(map);
this.inputDataIntToString.add(map2);
}
int count=0;
for(int i=0;i<outputData.length;i++)
{
if(outDataStringToInt.containsKey(outputData[i]))
{
outputDataInt[i]=outDataStringToInt.get(outputData[i]);
}else{
this.outDataStringToInt.put(outputData[i],count);
this.outDataIntToString.put(count,outputData[i]);
count++;
}
}
//初始化输出数据
changeStringToInt(inputData, inputDataInt, outputData, outputDataInt, dataMap);
}
/**
* c45执行程序
*/
public void exec()
{
//判断维度选择
execSonLeaf(this.inputDataInt,this.inputData,this.outputDataInt,this.outputData,1,1,fTree.root,dataMap);
}
/**
* c45向下搜索方法
* @param inputDataToInt
* @param inputDataString
* @param deep 深度
* @param node null为根节点无 否则 向下添加子节点
* @param dataMap 为动态调整的结构 而跟节点上的dataMap不变
*/
public void execSonLeaf(int[][] inputDataToInt,String[][] inputDataString,int[] outputDataToInt,String[] outputDataString,int deep,
double errorFather,Node node,ArrayList<HashMap<String,Integer>> dataMap)
{
System.out.println("deep:"+deep);
//获取相关概率
ArrayList<double[]> inputP=new ArrayList<double[]>();
int outputlength=dataMap.get(dataMap.size()-1).size();
double[] outputP=new double[outputlength];
ArrayList<double[]> condtionP=new ArrayList<double[]>();
//获取最小gini的位置
int minIndex=getMinGiniIndex(inputDataToInt,outputDataToInt);
if(minIndex==-1)
{
System.out.println("无法向下延伸:"+"深度:"+deep);
return;
}else
{
System.out.println("已到叶子节点:"+"深度:"+deep);
}
int[] maxIndexValue=MathBase.getCol(inputDataToInt,minIndex);
//从 inputDataToInt 中剔除 maxIndex列数据
int[][] inputDataTempToInt=MathBase.moveCol(inputDataToInt, minIndex);
System.out.println("inputDataToInt:"+inputDataToInt[0].length);
System.out.println("inputDataTempToInt:"+inputDataTempToInt[0].length);
//获取以maxIndex列分类的 子二维数组
ArrayList<int[]> outputTemp=new ArrayList<int[]>();//存储分组后的outputDataToInt
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
//分组后的输入String[][]
ArrayList<String[][]> inputDataStringTemp=new ArrayList<String[][]>();
//分组后的输出String[][]
ArrayList<String[]> outputDataStringTemp=new ArrayList<String[]>();
//需要将inputDataString剔除对应的列
String[][] inputDataString2=MathBase.moveCol(inputDataString,minIndex);
ArrayList<int[][]> groupInputData=MathBase.getGroupSon(inputDataStringTemp,
inputDataTempToInt, inputDataString2, maxIndexValue, outputDataToInt, outputDataString, outputDataStringTemp, outputTemp, map);
//ArrayList<int[][]> groupInputData=MathMethod.getGroupSon(inputDataToInt,maxIndexValue,outputDataToInt,outputTemp,map);
//对每个子集作向下查找
int zq=0;
//移除调掉对应的信息
// dataMap.remove(maxIndex);
deep++;
for(int[][] sonInputDataToInt:groupInputData)
{
//重新计算 dataMap
ArrayList<HashMap<String,Integer>> dataMapTemp=new ArrayList<HashMap<String,Integer>>();
changeStringToInt(inputDataStringTemp.get(zq),sonInputDataToInt,outputDataStringTemp.get(zq),outputTemp.get(zq),dataMapTemp);
//重新计算误差
int index=-1;
//添加到fTree中
for(Entry<Integer, Integer> ll: map.entrySet())
{
if(ll.getValue()==zq)
{
index=ll.getValue();
}
}
//不写其他方法
//并设置概率 及数量
int ln=MathBase.getMode(outputTemp.get(zq));
String lnString=Integer.toString(ln);
MathTable table2=MathBase.getTable(outputTemp.get(zq), null);
for(int i=0;i<table2.nameRow.length;i++)
{
if(table2.nameRow[i].equals(lnString))
{
ln=table2.num[i][0];
}
}
zq++;
//继续调用子节点
Leaf leaf=new Leaf(dataMapTemp.get(minIndex).get(index),sonInputDataToInt.length*1.0/inputDataToInt.length,
sonInputDataToInt.length,1-(ln*1.0)/table2.num.length,dataMapTemp.get(dataMapTemp.size()-1).get(ln));
Node sonNode=fTree.add(node,leaf,deep);
System.out.println("sonInputDataToInt:"+sonInputDataToInt[0].length);
execSonLeaf(sonInputDataToInt,inputDataStringTemp.get(zq-1),
outputTemp.get(zq-1),outputDataStringTemp.get(zq-1),deep,0,sonNode,dataMapTemp);
}
}
/**
* 将 字符串类型的统一转化为int类型
*/
public void changeStringToInt(String[][] inputDataA,int[][] inputDataToIntA,
String[] outputDataA,int[] outputDataToIntA,
ArrayList<HashMap<String,Integer>> dataMap)
{
//输入变量的类型统计
for(int i=0;i<inputDataA[0].length;i++)
{
HashMap<String,Integer> temp=new HashMap<String,Integer>();
int index=-1;
for(int j=0;j<inputDataA.length;j++)
{
if(temp.containsKey(inputDataA[j][i]))
{
//输入变量类型修改
inputDataToIntA[j][i]=temp.get(inputDataA[j][i]);
}else{
index++;
temp.put(inputDataA[j][i],index);
inputDataToIntA[j][i]=index;
}
}
dataMap.add(temp);
}
//输出变量修改
HashMap<String,Integer> temp=new HashMap<String,Integer>();
int index=-1;
for(int j=0;j<outputDataA.length;j++)
{
if(temp.containsKey(outputDataA[j]))
{
//输入变量类型修改
outputDataToIntA[j]=temp.get(outputDataA[j]);
}else{
index++;
temp.put(outputDataA[j],index);
outputDataToIntA[j]=index;
}
}
dataMap.add(temp);
}
/**
* 将 字符串类型的统一转化为int类型 group组方法
* 将对应的int[][] 修改为对应的值
*/
public void changeStringToIntT(String[][] inputDataA,int[][] inputDataToIntA,
String[] outputDataA,int[] outputDataToIntA,
ArrayList<HashMap<String,Integer>> dataMap)
{
//输入变量的类型统计
for(int i=0;i<inputDataToIntA[0].length;i++)
{
HashMap<String,Integer> temp=new HashMap<String,Integer>();
int index=-1;
for(int j=0;j<inputDataA.length;j++)
{
if(temp.containsKey(inputDataA[j][i]))
{
//输入变量类型修改
inputDataToIntA[j][i]=temp.get(inputDataA[j][i]);
}else{
index++;
temp.put(inputDataA[j][i],index);
inputDataToIntA[j][i]=index;
}
}
dataMap.add(temp);
}
//输出变量修改
HashMap<String,Integer> temp=new HashMap<String,Integer>();
int index=-1;
for(int j=0;j<outputDataA.length;j++)
{
if(temp.containsKey(outputDataA[j]))
{
//输入变量类型修改
outputDataToIntA[j]=temp.get(outputDataA[j]);
}else{
index++;
temp.put(outputDataA[j],index);
outputDataToIntA[j]=index;
}
}
dataMap.add(temp);
}
/**
* 从输入和输出中获取 最小gini系数的index列
* @param in
* @param out
* @return
*/
public int getMinGiniIndex(int[][] in,int[] out)
{
ArrayList<LinkedList<Integer>> outputGroup=getOutputGroup(out);
double min=Double.MAX_VALUE;
int index=-1;
//类对应的最小gini的输入列的分类数
int inCount=0;
double val=0.0;
//对每一列获取gini系数并获取其中最小的点
for(int i=0;i<in[0].length;i++)
{
int cou=0;
val=getGiniValue(in,out,outputGroup,i,cou);
if(min>val)
{
min=val;
index=i;
inCount=cou;
}
}
//判断是否终结
boolean flag =isEnd(in,out,outputGroup,index,inCount);
if(flag)
{
//可以分裂
return index;
}else
{
//终止分裂
return -1;
}
}
public ArrayList<LinkedList<Integer>> getOutputGroup(int[] out)
{
ArrayList<LinkedList<Integer>> result=new ArrayList<LinkedList<Integer>>();
HashMap<Integer,Integer> value=new HashMap<Integer,Integer>();
int count=0;
LinkedList<Integer> re=new LinkedList<Integer>();
for(int i=0;i<out.length;i++)
{
if(value.containsKey(out[i]))
{
result.get(value.get(out[i])).add(i);
}else
{
value.put(out[i],count);
if(count==0)
{
}else{
re=new LinkedList<Integer>();
}
re.add(i);
result.add(re);
count++;
}
}
return result;
}
/**
* 获取制定列的gini值
* @param in
* @param out
* @param ok 为根据out分隔出来 值相同的index组合
* @param index
* @param inCount 为in对应的index中有多少个分类
* @return
*/
public double getGiniValue(int[][] in,int[] out,ArrayList<LinkedList<Integer>> ok,int index,int inCount)
{
double result=0.0;
for(int i=0;i<ok.size();i++)
{
//计算没一组的分组情况
int[] count=new int[ok.get(i).size()];
int co=0;
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(Integer indexGroup:ok.get(i))
{
if(map.containsKey(in[indexGroup][index]))
{
count[map.get(in[indexGroup][index])]++;
}else
{
map.put(in[indexGroup][index],co);
count[co]++;
co++;
}
}
inCount=map.size();
//计算值
double gini=0.0;
for(int j=0;j<count.length;j++)
{
if(count[j]==0)
{
break;
}else
{
gini+=Math.pow(count[j]*1D, 2D);
}
}
//gini=1-[(4/5)^2+(1/5)^2]
gini=1-gini;
//gini_gain=sum(p(a)*gini(a))
result+=ok.get(i).size()*1D/out.length*gini;
}
return result;
}
/**
* 判断是否终止
* 使用卡方检验
* @param in
* @param out
* @param outGroup 一output为不同分类划分
* @param minIndex 最小giniindex
* @param inCount 输入的minIndex中有多少个分类
* @return
*/
public boolean isEnd(int[][] in,int[] out,ArrayList<LinkedList<Integer>> outGroup,int minIndex,int inCount)
{
//判断获取的最小gini系数的列是否达到终止条件
if(outGroup.size()==0 ||inCount==0)
{
return false;
}
double[][] result=new double[outGroup.size()][inCount];
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
int coun=0;
for(int i=0;i<outGroup.size();i++)
{
for(Integer group:outGroup.get(i))
{
if(map.containsKey(in[group][minIndex]))
{
result[i][map.get(in[group][minIndex])]++;
}else
{
map.put(in[group][minIndex],coun);
result[i][coun]++;
coun++;
}
}
}
double x2fang=cal_chi(result);
//列-行数对应的自由度上的卡方值
if(x2fang<CHI[result[0].length-result.length])
{
//则为独立 不需要分裂了
return false;
}
return true;
}
/**
* 咖方值计算
* @param arr
* @return
*/
public double cal_chi(double[][] arr){
double[] rowsum=new double[arr.length];
double[] colsum=new double[arr[0].length];
double totalsum=0.0;
for(int i=0;i<arr.length;++i){
for(int j=0;j<arr[0].length;++j){
totalsum+=arr[i][j];
rowsum[i]+=arr[i][j];
colsum[j]+=arr[i][j];
}
}
double rect=0.0;
for(int i=0;i<arr.length;++i){
for(int j=0;j<arr[0].length;++j){
double excep=1.0*rowsum[i]*colsum[j]/totalsum;
if(excep!=0)
rect+=Math.pow(arr[i][j]-excep,2.0)/excep;
}
}
return rect;
}
/**
* 节点的实体对象
* @author Administrator
*/
public class Leaf<T extends Comparable>
{
//类名字
public T name=null;
//对应概率
public double p=0.0;
//对应数量
public int num=0;
//对应错误率
public double errorP=0.0;
//对应的y
public T yName=null;
public Leaf(T name,double p,int num,double errorP,T yName)
{
this.name=name;
this.p=p;
this.num=num;
this.errorP=errorP;
this.yName=yName;
}
//不用
public int compareTo(Leaf leaf)
{
if(this.name.compareTo(leaf.name)==0)
{
return 0;
}else if(this.name.compareTo(leaf.name)>0){
return 1;
}
return -1;
}
}
public static void main(String[] args) {
String[] name=new String[]
{
"名称","体温","表面覆盖","胎生","产蛋","能飞","水生","有腿","冬眠","类标记"
};
String[][] inputData=new String[][]
{{"人","恒温","毛发","是","否","否","否","是","否"},
{"巨蟒","冷血","鳞片","否","是","否","否","否","是"},
{"鲑鱼","冷血","鳞片","否","是","否","是","否","否"},
{"鲸","恒温","毛发","是","否","否","是","否","否"},
{"蛙","冷血","无","否","是","否","有时","是","是"},
{"巨蜥","冷血","鳞片","否","是","否","否","是","否"},
{"蝙蝠","恒温","毛发","是","否","是","否","是","否"},
{"猫","恒温","皮","是","否","否","否","是","否"},
{"豹纹鲨","冷血","鳞片","是","否","否","是","否","否"},
{"海龟","冷血","鳞片","否","是","否","有时","是","否"},
{"豪猪","恒温","刚毛","是","否","否","否","是","是"},
{"鳗","冷血","鳞片","否","是","否","是","否","否"},
{"蝾螈","冷血","无","否","是","否","有时","是","是"}};
String[] outputData=new String[]{"哺乳类","爬行类","鱼类","哺乳类","两栖类","爬行类",
"哺乳类","哺乳类","鱼类","爬行类","哺乳类","鱼类","两栖类"};
C45 c45=new C45(inputData,outputData);
c45.exec();
}
}
| 15,668 | 0.630986 | 0.616804 | 559 | 24.101967 | 24.328226 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.21288 | false | false |
14
|
9cd7a977c059846f70e435ca46391769d042f05e
| 32,289,564,181,273 |
6c4674a7c55e08149fc603de9b6c24408c72b9ff
|
/src/Main.java
|
d2bdd81d35d1aee16f168279ffc30c1450433e1a
|
[] |
no_license
|
timsong-cu/assembler
|
https://github.com/timsong-cu/assembler
|
f5f0d4b29dd1fa6b229d35d7eb4140d80b585b03
|
7b02e19b134a00545a348b26bac87f59eb0fc874
|
refs/heads/master
| 2020-05-29T13:19:58.832000 | 2011-03-12T21:15:53 | 2011-03-12T21:15:53 | 1,407,445 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Driver class allows the user to input the reference file, as well as the insertion sequence files.
* @author Rebecca A. Sealfon, Ruijie Song, Manish Vasani
*
*/
public class Main {
/**
* Main method accepts file command line arguments.
* @param args[0] the file containing the original reference genome
* @param args[1] the relevant information about the insertions
* @param args[2,...] the files containing the insertion sequences
*/
public static void main(String[] args) throws Exception {
if (args.length < 2) System.out.println("Usage: java Main primaryReference insertionInfoFile <insertionFiles>");
else {
ReferenceSequenceManager references = new ReferenceSequenceManager(args);
references.loadInsertionInfo();
references.makeChimera();
}
}
}
|
UTF-8
|
Java
| 790 |
java
|
Main.java
|
Java
|
[
{
"context": "s well as the insertion sequence files.\n * @author Rebecca A. Sealfon, Ruijie Song, Manish Vasani\n *\n */\npublic class M",
"end": 135,
"score": 0.9998687505722046,
"start": 117,
"tag": "NAME",
"value": "Rebecca A. Sealfon"
},
{
"context": "ion sequence files.\n * @author Rebecca A. Sealfon, Ruijie Song, Manish Vasani\n *\n */\npublic class Main {\n\n\t/**\n\t",
"end": 148,
"score": 0.9998693466186523,
"start": 137,
"tag": "NAME",
"value": "Ruijie Song"
},
{
"context": "files.\n * @author Rebecca A. Sealfon, Ruijie Song, Manish Vasani\n *\n */\npublic class Main {\n\n\t/**\n\t * Main method ",
"end": 163,
"score": 0.999871551990509,
"start": 150,
"tag": "NAME",
"value": "Manish Vasani"
}
] | null |
[] |
/**
* Driver class allows the user to input the reference file, as well as the insertion sequence files.
* @author <NAME>, <NAME>, <NAME>
*
*/
public class Main {
/**
* Main method accepts file command line arguments.
* @param args[0] the file containing the original reference genome
* @param args[1] the relevant information about the insertions
* @param args[2,...] the files containing the insertion sequences
*/
public static void main(String[] args) throws Exception {
if (args.length < 2) System.out.println("Usage: java Main primaryReference insertionInfoFile <insertionFiles>");
else {
ReferenceSequenceManager references = new ReferenceSequenceManager(args);
references.loadInsertionInfo();
references.makeChimera();
}
}
}
| 766 | 0.736709 | 0.731646 | 22 | 34.909092 | 35.111393 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.409091 | false | false |
14
|
91fb17c78b3666d7b0bc48b5e5f249903729be38
| 4,612,794,935,387 |
e533421826d1cd008858f80267e6eba4dae81c6c
|
/app/src/main/java/com/jacob/windmill/ARActivity.java
|
177269da0be298ea18d26f357b9d015decb58809
|
[] |
no_license
|
Windmill-hq/ARExperience
|
https://github.com/Windmill-hq/ARExperience
|
55dfc140361745ea0f24fd76798bbec66d41541e
|
7c6e25ca8a9b5911589ef7e559c2783c8bf71411
|
refs/heads/master
| 2020-05-22T07:40:29.940000 | 2019-06-23T22:18:38 | 2019-06-23T22:18:38 | 186,269,783 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jacob.windmill;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import com.jacob.windmill.custom.ARSceneListener;
import com.jacob.windmill.custom.LifecycleAwareARView;
import com.jacob.windmill.custom.Utils;
import com.viro.core.ARAnchor;
import com.viro.core.ARNode;
import com.viro.core.ARScene;
import com.viro.core.Vector;
import com.viro.core.ViroViewARCore;
public class ARActivity extends AppCompatActivity implements ViroViewARCore.StartupListener {
public static final String TAG = "EXPERIMENT";
private static final String PORTAL_MODEL = "file:///android_asset/portal_wood_frame.vrx";
private static final String CANYON_SOUND = "file:///android_asset/canyon_wind.mp3";
private static final String PORTAL_BKG_ASSET = "canyon.jpg";
private LifecycleAwareARView mARView;
private boolean planesFound = false;
private ARPortal beachPortal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mARView = new LifecycleAwareARView(this, this);
beachPortal = new ARPortal(PORTAL_MODEL, CANYON_SOUND, PORTAL_BKG_ASSET, mARView.getViroContext(), getResources());
setContentView(mARView);
getLifecycle().addObserver(mARView);
getLifecycle().addObserver(beachPortal);
}
@Override
public void onSuccess() {
buildScene();
}
@Override
public void onFailure(ViroViewARCore.StartupError error, String errorMessage) {
Log.e(TAG, "Error initializing AR [" + errorMessage + "]");
}
private void buildScene() {
View.inflate(this, R.layout.viro_view_hud, mARView);
ARScene scene = createScene();
mARView.setScene(scene);
mARView.getScene().getRootNode().addLight(Utils.createLight());
beachPortal.show(mARView.getScene(), new Vector(0, 0, -2));
}
private ARScene createScene() {
ARScene scene = new ARScene();
scene.displayPointCloud(true);
scene.setListener((ARSceneListener) this::handleAnchor);
return scene;
}
private void handleAnchor(ARAnchor arAnchor, ARNode arNode) {
if (arAnchor.getType() == ARAnchor.Type.PLANE) {
Log.w(ARActivity.TAG, "PLANE detected");
hideUIHint();
}
}
private void hideUIHint() {
if (!planesFound) {
planesFound = true;
View hintView = findViewById(R.id.hint_view);
hintView.animate().alpha(0.0f).setDuration(500);
}
}
@Override
protected void onDestroy() {
getLifecycle().removeObserver(mARView);
getLifecycle().removeObserver(beachPortal);
super.onDestroy();
}
}
|
UTF-8
|
Java
| 2,795 |
java
|
ARActivity.java
|
Java
|
[] | null |
[] |
package com.jacob.windmill;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import com.jacob.windmill.custom.ARSceneListener;
import com.jacob.windmill.custom.LifecycleAwareARView;
import com.jacob.windmill.custom.Utils;
import com.viro.core.ARAnchor;
import com.viro.core.ARNode;
import com.viro.core.ARScene;
import com.viro.core.Vector;
import com.viro.core.ViroViewARCore;
public class ARActivity extends AppCompatActivity implements ViroViewARCore.StartupListener {
public static final String TAG = "EXPERIMENT";
private static final String PORTAL_MODEL = "file:///android_asset/portal_wood_frame.vrx";
private static final String CANYON_SOUND = "file:///android_asset/canyon_wind.mp3";
private static final String PORTAL_BKG_ASSET = "canyon.jpg";
private LifecycleAwareARView mARView;
private boolean planesFound = false;
private ARPortal beachPortal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mARView = new LifecycleAwareARView(this, this);
beachPortal = new ARPortal(PORTAL_MODEL, CANYON_SOUND, PORTAL_BKG_ASSET, mARView.getViroContext(), getResources());
setContentView(mARView);
getLifecycle().addObserver(mARView);
getLifecycle().addObserver(beachPortal);
}
@Override
public void onSuccess() {
buildScene();
}
@Override
public void onFailure(ViroViewARCore.StartupError error, String errorMessage) {
Log.e(TAG, "Error initializing AR [" + errorMessage + "]");
}
private void buildScene() {
View.inflate(this, R.layout.viro_view_hud, mARView);
ARScene scene = createScene();
mARView.setScene(scene);
mARView.getScene().getRootNode().addLight(Utils.createLight());
beachPortal.show(mARView.getScene(), new Vector(0, 0, -2));
}
private ARScene createScene() {
ARScene scene = new ARScene();
scene.displayPointCloud(true);
scene.setListener((ARSceneListener) this::handleAnchor);
return scene;
}
private void handleAnchor(ARAnchor arAnchor, ARNode arNode) {
if (arAnchor.getType() == ARAnchor.Type.PLANE) {
Log.w(ARActivity.TAG, "PLANE detected");
hideUIHint();
}
}
private void hideUIHint() {
if (!planesFound) {
planesFound = true;
View hintView = findViewById(R.id.hint_view);
hintView.animate().alpha(0.0f).setDuration(500);
}
}
@Override
protected void onDestroy() {
getLifecycle().removeObserver(mARView);
getLifecycle().removeObserver(beachPortal);
super.onDestroy();
}
}
| 2,795 | 0.680859 | 0.677281 | 83 | 32.650604 | 26.357794 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.710843 | false | false |
14
|
7827560b0dafcd6e671157fe60da4313a49be671
| 3,427,383,906,750 |
22da7f17f99a92b8dfd2086eec41c3488d7bed6d
|
/com/google/appinventor/components/runtime/Pedometer.java
|
b0c744a6006fd099ae8ff5b25808dda1ea9c5bf9
|
[] |
no_license
|
balajithegreat/payroll_android
|
https://github.com/balajithegreat/payroll_android
|
80b1becffd6f2b2a3be56fa01b3528d9967cce25
|
f612c6f857064b109f4912e80ab9c82b1dfe8dbc
|
refs/heads/master
| 2020-05-17T06:06:10.909000 | 2015-04-24T02:19:55 | 2015-04-24T02:19:55 | 34,059,116 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.google.appinventor.components.runtime;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.PropertyCategory;
import com.google.appinventor.components.annotations.SimpleEvent;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.annotations.UsesPermissions;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.runtime.AndroidNonvisibleComponent;
import com.google.appinventor.components.runtime.Component;
import com.google.appinventor.components.runtime.ComponentContainer;
import com.google.appinventor.components.runtime.Deleteable;
import com.google.appinventor.components.runtime.EventDispatcher;
import java.lang.reflect.Array;
@DesignerComponent(
category = ComponentCategory.INTERNAL,
description = "Component that can count steps.",
iconName = "images/pedometer.png",
nonVisible = true,
version = 1
)
@SimpleObject
@UsesPermissions(
permissionNames = "android.permission.ACCESS_FINE_LOCATION"
)
public class Pedometer extends AndroidNonvisibleComponent implements Component, LocationListener, SensorEventListener, Deleteable {
private static final int DIMENSIONS = 3;
private static final int INTERVAL_VARIATION = 250;
private static final int MIN_SATELLITES = 4;
private static final int NUM_INTERVALS = 2;
private static final float PEAK_VALLEY_RANGE = 4.0F;
private static final String PREFS_NAME = "PedometerPrefs";
private static final float STRIDE_LENGTH = 0.73F;
private static final String TAG = "Pedometer";
private static final int WIN_SIZE = 20;
private boolean calibrateSteps;
private final Context context;
private Location currentLocation;
private float distWhenGPSLost;
private long elapsedTimestamp;
private boolean firstGpsReading;
private boolean foundNonStep;
private boolean[] foundValley;
private boolean gpsAvailable;
private float gpsDistance;
private long gpsStepTime;
private int intervalPos = 0;
private int lastNumSteps = 0;
private float[] lastValley = new float[3];
private float[][] lastValues;
private final LocationManager locationManager;
private Location locationWhenGPSLost;
private int numStepsRaw = 0;
private int numStepsWithFilter = 0;
private int[] peak = new int[3];
private boolean pedometerPaused;
private float[] prevDiff;
private Location prevLocation;
private long prevStopClockTime;
private final SensorManager sensorManager;
private boolean startPeaking;
private long startTime;
private boolean statusMoving;
private long[] stepInterval;
private long stepTimestamp;
private int stopDetectionTimeout = 2000;
private float strideLength;
private float totalDistance;
private boolean useGps;
private int[] valley = new int[3];
private int winPos = 0;
public Pedometer(ComponentContainer var1) {
super(var1.$form());
this.lastValues = (float[][])Array.newInstance(Float.TYPE, new int[]{20, 3});
this.prevDiff = new float[3];
this.strideLength = 0.73F;
this.totalDistance = 0.0F;
this.distWhenGPSLost = 0.0F;
this.gpsDistance = 0.0F;
this.stepInterval = new long[2];
this.stepTimestamp = 0L;
this.elapsedTimestamp = 0L;
this.startTime = 0L;
this.prevStopClockTime = 0L;
this.gpsStepTime = 0L;
this.foundValley = new boolean[3];
this.startPeaking = false;
this.foundNonStep = true;
this.gpsAvailable = false;
this.calibrateSteps = true;
this.pedometerPaused = true;
this.useGps = true;
this.statusMoving = false;
this.firstGpsReading = true;
this.context = var1.$context();
this.winPos = 0;
this.startPeaking = false;
this.numStepsWithFilter = 0;
this.numStepsRaw = 0;
this.firstGpsReading = true;
this.gpsDistance = 0.0F;
for(int var2 = 0; var2 < 3; ++var2) {
this.foundValley[var2] = true;
this.lastValley[var2] = 0.0F;
}
this.sensorManager = (SensorManager)this.context.getSystemService("sensor");
this.locationManager = (LocationManager)this.context.getSystemService("location");
this.locationManager.requestLocationUpdates("gps", 0L, 0.0F, this);
SharedPreferences var3 = this.context.getSharedPreferences("PedometerPrefs", 0);
this.strideLength = var3.getFloat("Pedometer.stridelength", 0.73F);
this.totalDistance = var3.getFloat("Pedometer.distance", 0.0F);
this.numStepsRaw = var3.getInt("Pedometer.prevStepCount", 0);
this.prevStopClockTime = var3.getLong("Pedometer.clockTime", 0L);
this.numStepsWithFilter = this.numStepsRaw;
this.startTime = System.currentTimeMillis();
Log.d("Pedometer", "Pedometer Created");
}
private boolean areStepsEquallySpaced() {
float var1 = 0.0F;
int var5 = 0;
long[] var3 = this.stepInterval;
int var7 = var3.length;
int var4;
int var6;
for(var4 = 0; var4 < var7; var5 = var6) {
long var8 = var3[var4];
float var2 = var1;
var6 = var5;
if(var8 > 0L) {
var6 = var5 + 1;
var2 = var1 + (float)var8;
}
++var4;
var1 = var2;
}
var1 /= (float)var5;
var3 = this.stepInterval;
var5 = var3.length;
for(var4 = 0; var4 < var5; ++var4) {
if(Math.abs((float)var3[var4] - var1) > 250.0F) {
return false;
}
}
return true;
}
private void getPeak() {
int var3 = (this.winPos + 10) % 20;
int var1 = 0;
while(var1 < 3) {
this.peak[var1] = var3;
int var2 = 0;
while(true) {
if(var2 < 20) {
if(var2 == var3 || this.lastValues[var2][var1] < this.lastValues[var3][var1]) {
++var2;
continue;
}
this.peak[var1] = -1;
}
++var1;
break;
}
}
}
private void getValley() {
int var3 = (this.winPos + 10) % 20;
int var1 = 0;
while(var1 < 3) {
this.valley[var1] = var3;
int var2 = 0;
while(true) {
if(var2 < 20) {
if(var2 == var3 || this.lastValues[var2][var1] > this.lastValues[var3][var1]) {
++var2;
continue;
}
this.valley[var1] = -1;
}
++var1;
break;
}
}
}
private void setGpsAvailable(boolean var1) {
if(!this.gpsAvailable && var1) {
this.gpsAvailable = true;
this.GPSAvailable();
} else if(this.gpsAvailable && !var1) {
this.gpsAvailable = false;
this.GPSLost();
return;
}
}
@DesignerProperty(
defaultValue = "true",
editorType = "boolean"
)
@SimpleProperty(
category = PropertyCategory.BEHAVIOR
)
public void CalibrateStrideLength(boolean var1) {
if(!this.gpsAvailable && var1) {
this.CalibrationFailed();
} else {
if(var1) {
this.useGps = true;
}
this.calibrateSteps = var1;
}
}
@SimpleProperty
public boolean CalibrateStrideLength() {
return this.calibrateSteps;
}
@SimpleEvent
public void CalibrationFailed() {
EventDispatcher.dispatchEvent(this, "CalibrationFailed", new Object[0]);
}
@SimpleProperty(
category = PropertyCategory.BEHAVIOR
)
public float Distance() {
return this.totalDistance;
}
@SimpleProperty(
category = PropertyCategory.BEHAVIOR
)
public long ElapsedTime() {
return this.pedometerPaused?this.prevStopClockTime:this.prevStopClockTime + (System.currentTimeMillis() - this.startTime);
}
@SimpleEvent
public void GPSAvailable() {
EventDispatcher.dispatchEvent(this, "GPSAvailable", new Object[0]);
}
@SimpleEvent
public void GPSLost() {
EventDispatcher.dispatchEvent(this, "GPSLost", new Object[0]);
}
@SimpleProperty(
category = PropertyCategory.BEHAVIOR
)
public boolean Moving() {
return this.statusMoving;
}
@SimpleFunction
public void Pause() {
if(!this.pedometerPaused) {
this.pedometerPaused = true;
this.statusMoving = false;
this.sensorManager.unregisterListener(this);
Log.d("Pedometer", "Unregistered listener on pause");
this.prevStopClockTime += System.currentTimeMillis() - this.startTime;
}
}
@SimpleFunction
public void Reset() {
this.numStepsWithFilter = 0;
this.numStepsRaw = 0;
this.totalDistance = 0.0F;
this.calibrateSteps = false;
this.prevStopClockTime = 0L;
this.startTime = System.currentTimeMillis();
}
@SimpleFunction
public void Resume() {
this.Start();
}
@SimpleFunction(
description = "Saves the pedometer state to the phone"
)
public void Save() {
Editor var1 = this.context.getSharedPreferences("PedometerPrefs", 0).edit();
var1.putFloat("Pedometer.stridelength", this.strideLength);
var1.putFloat("Pedometer.distance", this.totalDistance);
var1.putInt("Pedometer.prevStepCount", this.numStepsRaw);
if(this.pedometerPaused) {
var1.putLong("Pedometer.clockTime", this.prevStopClockTime);
} else {
var1.putLong("Pedometer.clockTime", this.prevStopClockTime + (System.currentTimeMillis() - this.startTime));
}
var1.putLong("Pedometer.closeTime", System.currentTimeMillis());
var1.commit();
Log.d("Pedometer", "Pedometer state saved.");
}
@SimpleEvent(
description = "This event is run when a raw step is detected"
)
public void SimpleStep(int var1, float var2) {
EventDispatcher.dispatchEvent(this, "SimpleStep", new Object[]{Integer.valueOf(var1), Float.valueOf(var2)});
}
@SimpleFunction
public void Start() {
if(this.pedometerPaused) {
this.pedometerPaused = false;
this.sensorManager.registerListener(this, (Sensor)this.sensorManager.getSensorList(1).get(0), 0);
this.startTime = System.currentTimeMillis();
}
}
@SimpleEvent
public void StartedMoving() {
EventDispatcher.dispatchEvent(this, "StartedMoving", new Object[0]);
}
@SimpleFunction
public void Stop() {
this.Pause();
this.locationManager.removeUpdates(this);
this.useGps = false;
this.calibrateSteps = false;
this.setGpsAvailable(false);
}
@SimpleProperty
public int StopDetectionTimeout() {
return this.stopDetectionTimeout;
}
@DesignerProperty(
defaultValue = "2000",
editorType = "non_negative_integer"
)
@SimpleProperty(
category = PropertyCategory.BEHAVIOR
)
public void StopDetectionTimeout(int var1) {
this.stopDetectionTimeout = var1;
}
@SimpleEvent
public void StoppedMoving() {
EventDispatcher.dispatchEvent(this, "StoppedMoving", new Object[0]);
}
@SimpleProperty
public float StrideLength() {
return this.strideLength;
}
@DesignerProperty(
defaultValue = "0.73",
editorType = "non_negative_float"
)
@SimpleProperty(
category = PropertyCategory.BEHAVIOR
)
public void StrideLength(float var1) {
this.CalibrateStrideLength(false);
this.strideLength = var1;
}
@DesignerProperty(
defaultValue = "true",
editorType = "boolean"
)
@SimpleProperty(
category = PropertyCategory.BEHAVIOR
)
public void UseGPS(boolean var1) {
if(!var1 && this.useGps) {
this.locationManager.removeUpdates(this);
} else if(var1 && !this.useGps) {
this.locationManager.requestLocationUpdates("gps", 0L, 0.0F, this);
}
this.useGps = var1;
}
@SimpleProperty
public boolean UseGPS() {
return this.useGps;
}
@SimpleEvent(
description = "This event is run when a walking step is detected"
)
public void WalkStep(int var1, float var2) {
EventDispatcher.dispatchEvent(this, "WalkStep", new Object[]{Integer.valueOf(var1), Float.valueOf(var2)});
}
public void onAccuracyChanged(Sensor var1, int var2) {
Log.d("Pedometer", "Accelerometer accuracy changed.");
}
public void onDelete() {
this.sensorManager.unregisterListener(this);
this.locationManager.removeUpdates(this);
}
public void onLocationChanged(Location var1) {
if(this.statusMoving && !this.pedometerPaused && this.useGps) {
float var2 = 0.0F;
this.currentLocation = var1;
if(this.currentLocation.getAccuracy() > 10.0F) {
this.setGpsAvailable(false);
} else {
this.setGpsAvailable(true);
float var3;
if(this.prevLocation != null) {
var3 = this.currentLocation.distanceTo(this.prevLocation);
var2 = var3;
if((double)var3 > 0.1D) {
var2 = var3;
if(var3 < 10.0F) {
this.totalDistance += var3;
this.prevLocation = this.currentLocation;
var2 = var3;
}
}
} else {
if(this.locationWhenGPSLost != null) {
var3 = this.currentLocation.distanceTo(this.locationWhenGPSLost);
this.totalDistance = this.distWhenGPSLost + (this.totalDistance - this.distWhenGPSLost + var3) / 2.0F;
}
this.gpsStepTime = System.currentTimeMillis();
this.prevLocation = this.currentLocation;
}
if(this.calibrateSteps) {
if(!this.firstGpsReading) {
this.gpsDistance += var2;
int var4 = this.numStepsRaw;
int var5 = this.lastNumSteps;
this.strideLength = this.gpsDistance / (float)(var4 - var5);
} else {
this.firstGpsReading = false;
this.lastNumSteps = this.numStepsRaw;
}
} else {
this.firstGpsReading = true;
this.gpsDistance = 0.0F;
}
}
}
}
public void onProviderDisabled(String var1) {
this.distWhenGPSLost = this.totalDistance;
this.locationWhenGPSLost = this.currentLocation;
this.firstGpsReading = true;
this.prevLocation = null;
this.setGpsAvailable(false);
}
public void onProviderEnabled(String var1) {
this.setGpsAvailable(true);
}
public void onSensorChanged(SensorEvent var1) {
if(var1.sensor.getType() == 1) {
float[] var6 = var1.values;
if(this.startPeaking) {
this.getPeak();
this.getValley();
}
byte var2;
if(this.prevDiff[0] > this.prevDiff[1]) {
var2 = 0;
} else {
var2 = 1;
}
byte var3 = var2;
if(this.prevDiff[2] > this.prevDiff[var2]) {
var3 = 2;
}
int var7;
for(var7 = 0; var7 < 3; ++var7) {
if(this.startPeaking && this.peak[var7] >= 0) {
if(this.foundValley[var7] && this.lastValues[this.peak[var7]][var7] - this.lastValley[var7] > 4.0F) {
if(var3 == var7) {
long var4 = System.currentTimeMillis();
this.stepInterval[this.intervalPos] = var4 - this.stepTimestamp;
this.intervalPos = (this.intervalPos + 1) % 2;
this.stepTimestamp = var4;
if(this.areStepsEquallySpaced()) {
if(this.foundNonStep) {
this.numStepsWithFilter += 2;
if(!this.gpsAvailable) {
this.totalDistance += this.strideLength * 2.0F;
}
this.foundNonStep = false;
}
++this.numStepsWithFilter;
this.WalkStep(this.numStepsWithFilter, this.totalDistance);
if(!this.gpsAvailable) {
this.totalDistance += this.strideLength;
}
} else {
this.foundNonStep = true;
}
++this.numStepsRaw;
this.SimpleStep(this.numStepsRaw, this.totalDistance);
if(!this.statusMoving) {
this.statusMoving = true;
this.StartedMoving();
}
}
this.foundValley[var7] = false;
this.prevDiff[var7] = this.lastValues[this.peak[var7]][var7] - this.lastValley[var7];
} else {
this.prevDiff[var7] = 0.0F;
}
}
if(this.startPeaking && this.valley[var7] >= 0) {
this.foundValley[var7] = true;
this.lastValley[var7] = this.lastValues[this.valley[var7]][var7];
}
this.lastValues[this.winPos][var7] = var6[var7];
}
this.elapsedTimestamp = System.currentTimeMillis();
if(this.elapsedTimestamp - this.stepTimestamp > (long)this.stopDetectionTimeout) {
if(this.statusMoving) {
this.statusMoving = false;
this.StoppedMoving();
}
this.stepTimestamp = this.elapsedTimestamp;
}
if(this.winPos - 1 < 0) {
var7 = 19;
} else {
var7 = this.winPos - 1;
}
for(int var8 = 0; var8 < 3; ++var8) {
if(this.lastValues[var7][var8] == this.lastValues[this.winPos][var8]) {
var6 = this.lastValues[this.winPos];
var6[var8] = (float)((double)var6[var8] + 0.001D);
}
}
if(this.winPos == 19 && !this.startPeaking) {
this.startPeaking = true;
}
this.winPos = (this.winPos + 1) % 20;
}
}
public void onStatusChanged(String var1, int var2, Bundle var3) {
}
}
|
UTF-8
|
Java
| 19,104 |
java
|
Pedometer.java
|
Java
|
[] | null |
[] |
package com.google.appinventor.components.runtime;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.PropertyCategory;
import com.google.appinventor.components.annotations.SimpleEvent;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.annotations.UsesPermissions;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.runtime.AndroidNonvisibleComponent;
import com.google.appinventor.components.runtime.Component;
import com.google.appinventor.components.runtime.ComponentContainer;
import com.google.appinventor.components.runtime.Deleteable;
import com.google.appinventor.components.runtime.EventDispatcher;
import java.lang.reflect.Array;
@DesignerComponent(
category = ComponentCategory.INTERNAL,
description = "Component that can count steps.",
iconName = "images/pedometer.png",
nonVisible = true,
version = 1
)
@SimpleObject
@UsesPermissions(
permissionNames = "android.permission.ACCESS_FINE_LOCATION"
)
public class Pedometer extends AndroidNonvisibleComponent implements Component, LocationListener, SensorEventListener, Deleteable {
private static final int DIMENSIONS = 3;
private static final int INTERVAL_VARIATION = 250;
private static final int MIN_SATELLITES = 4;
private static final int NUM_INTERVALS = 2;
private static final float PEAK_VALLEY_RANGE = 4.0F;
private static final String PREFS_NAME = "PedometerPrefs";
private static final float STRIDE_LENGTH = 0.73F;
private static final String TAG = "Pedometer";
private static final int WIN_SIZE = 20;
private boolean calibrateSteps;
private final Context context;
private Location currentLocation;
private float distWhenGPSLost;
private long elapsedTimestamp;
private boolean firstGpsReading;
private boolean foundNonStep;
private boolean[] foundValley;
private boolean gpsAvailable;
private float gpsDistance;
private long gpsStepTime;
private int intervalPos = 0;
private int lastNumSteps = 0;
private float[] lastValley = new float[3];
private float[][] lastValues;
private final LocationManager locationManager;
private Location locationWhenGPSLost;
private int numStepsRaw = 0;
private int numStepsWithFilter = 0;
private int[] peak = new int[3];
private boolean pedometerPaused;
private float[] prevDiff;
private Location prevLocation;
private long prevStopClockTime;
private final SensorManager sensorManager;
private boolean startPeaking;
private long startTime;
private boolean statusMoving;
private long[] stepInterval;
private long stepTimestamp;
private int stopDetectionTimeout = 2000;
private float strideLength;
private float totalDistance;
private boolean useGps;
private int[] valley = new int[3];
private int winPos = 0;
public Pedometer(ComponentContainer var1) {
super(var1.$form());
this.lastValues = (float[][])Array.newInstance(Float.TYPE, new int[]{20, 3});
this.prevDiff = new float[3];
this.strideLength = 0.73F;
this.totalDistance = 0.0F;
this.distWhenGPSLost = 0.0F;
this.gpsDistance = 0.0F;
this.stepInterval = new long[2];
this.stepTimestamp = 0L;
this.elapsedTimestamp = 0L;
this.startTime = 0L;
this.prevStopClockTime = 0L;
this.gpsStepTime = 0L;
this.foundValley = new boolean[3];
this.startPeaking = false;
this.foundNonStep = true;
this.gpsAvailable = false;
this.calibrateSteps = true;
this.pedometerPaused = true;
this.useGps = true;
this.statusMoving = false;
this.firstGpsReading = true;
this.context = var1.$context();
this.winPos = 0;
this.startPeaking = false;
this.numStepsWithFilter = 0;
this.numStepsRaw = 0;
this.firstGpsReading = true;
this.gpsDistance = 0.0F;
for(int var2 = 0; var2 < 3; ++var2) {
this.foundValley[var2] = true;
this.lastValley[var2] = 0.0F;
}
this.sensorManager = (SensorManager)this.context.getSystemService("sensor");
this.locationManager = (LocationManager)this.context.getSystemService("location");
this.locationManager.requestLocationUpdates("gps", 0L, 0.0F, this);
SharedPreferences var3 = this.context.getSharedPreferences("PedometerPrefs", 0);
this.strideLength = var3.getFloat("Pedometer.stridelength", 0.73F);
this.totalDistance = var3.getFloat("Pedometer.distance", 0.0F);
this.numStepsRaw = var3.getInt("Pedometer.prevStepCount", 0);
this.prevStopClockTime = var3.getLong("Pedometer.clockTime", 0L);
this.numStepsWithFilter = this.numStepsRaw;
this.startTime = System.currentTimeMillis();
Log.d("Pedometer", "Pedometer Created");
}
private boolean areStepsEquallySpaced() {
float var1 = 0.0F;
int var5 = 0;
long[] var3 = this.stepInterval;
int var7 = var3.length;
int var4;
int var6;
for(var4 = 0; var4 < var7; var5 = var6) {
long var8 = var3[var4];
float var2 = var1;
var6 = var5;
if(var8 > 0L) {
var6 = var5 + 1;
var2 = var1 + (float)var8;
}
++var4;
var1 = var2;
}
var1 /= (float)var5;
var3 = this.stepInterval;
var5 = var3.length;
for(var4 = 0; var4 < var5; ++var4) {
if(Math.abs((float)var3[var4] - var1) > 250.0F) {
return false;
}
}
return true;
}
private void getPeak() {
int var3 = (this.winPos + 10) % 20;
int var1 = 0;
while(var1 < 3) {
this.peak[var1] = var3;
int var2 = 0;
while(true) {
if(var2 < 20) {
if(var2 == var3 || this.lastValues[var2][var1] < this.lastValues[var3][var1]) {
++var2;
continue;
}
this.peak[var1] = -1;
}
++var1;
break;
}
}
}
private void getValley() {
int var3 = (this.winPos + 10) % 20;
int var1 = 0;
while(var1 < 3) {
this.valley[var1] = var3;
int var2 = 0;
while(true) {
if(var2 < 20) {
if(var2 == var3 || this.lastValues[var2][var1] > this.lastValues[var3][var1]) {
++var2;
continue;
}
this.valley[var1] = -1;
}
++var1;
break;
}
}
}
private void setGpsAvailable(boolean var1) {
if(!this.gpsAvailable && var1) {
this.gpsAvailable = true;
this.GPSAvailable();
} else if(this.gpsAvailable && !var1) {
this.gpsAvailable = false;
this.GPSLost();
return;
}
}
@DesignerProperty(
defaultValue = "true",
editorType = "boolean"
)
@SimpleProperty(
category = PropertyCategory.BEHAVIOR
)
public void CalibrateStrideLength(boolean var1) {
if(!this.gpsAvailable && var1) {
this.CalibrationFailed();
} else {
if(var1) {
this.useGps = true;
}
this.calibrateSteps = var1;
}
}
@SimpleProperty
public boolean CalibrateStrideLength() {
return this.calibrateSteps;
}
@SimpleEvent
public void CalibrationFailed() {
EventDispatcher.dispatchEvent(this, "CalibrationFailed", new Object[0]);
}
@SimpleProperty(
category = PropertyCategory.BEHAVIOR
)
public float Distance() {
return this.totalDistance;
}
@SimpleProperty(
category = PropertyCategory.BEHAVIOR
)
public long ElapsedTime() {
return this.pedometerPaused?this.prevStopClockTime:this.prevStopClockTime + (System.currentTimeMillis() - this.startTime);
}
@SimpleEvent
public void GPSAvailable() {
EventDispatcher.dispatchEvent(this, "GPSAvailable", new Object[0]);
}
@SimpleEvent
public void GPSLost() {
EventDispatcher.dispatchEvent(this, "GPSLost", new Object[0]);
}
@SimpleProperty(
category = PropertyCategory.BEHAVIOR
)
public boolean Moving() {
return this.statusMoving;
}
@SimpleFunction
public void Pause() {
if(!this.pedometerPaused) {
this.pedometerPaused = true;
this.statusMoving = false;
this.sensorManager.unregisterListener(this);
Log.d("Pedometer", "Unregistered listener on pause");
this.prevStopClockTime += System.currentTimeMillis() - this.startTime;
}
}
@SimpleFunction
public void Reset() {
this.numStepsWithFilter = 0;
this.numStepsRaw = 0;
this.totalDistance = 0.0F;
this.calibrateSteps = false;
this.prevStopClockTime = 0L;
this.startTime = System.currentTimeMillis();
}
@SimpleFunction
public void Resume() {
this.Start();
}
@SimpleFunction(
description = "Saves the pedometer state to the phone"
)
public void Save() {
Editor var1 = this.context.getSharedPreferences("PedometerPrefs", 0).edit();
var1.putFloat("Pedometer.stridelength", this.strideLength);
var1.putFloat("Pedometer.distance", this.totalDistance);
var1.putInt("Pedometer.prevStepCount", this.numStepsRaw);
if(this.pedometerPaused) {
var1.putLong("Pedometer.clockTime", this.prevStopClockTime);
} else {
var1.putLong("Pedometer.clockTime", this.prevStopClockTime + (System.currentTimeMillis() - this.startTime));
}
var1.putLong("Pedometer.closeTime", System.currentTimeMillis());
var1.commit();
Log.d("Pedometer", "Pedometer state saved.");
}
@SimpleEvent(
description = "This event is run when a raw step is detected"
)
public void SimpleStep(int var1, float var2) {
EventDispatcher.dispatchEvent(this, "SimpleStep", new Object[]{Integer.valueOf(var1), Float.valueOf(var2)});
}
@SimpleFunction
public void Start() {
if(this.pedometerPaused) {
this.pedometerPaused = false;
this.sensorManager.registerListener(this, (Sensor)this.sensorManager.getSensorList(1).get(0), 0);
this.startTime = System.currentTimeMillis();
}
}
@SimpleEvent
public void StartedMoving() {
EventDispatcher.dispatchEvent(this, "StartedMoving", new Object[0]);
}
@SimpleFunction
public void Stop() {
this.Pause();
this.locationManager.removeUpdates(this);
this.useGps = false;
this.calibrateSteps = false;
this.setGpsAvailable(false);
}
@SimpleProperty
public int StopDetectionTimeout() {
return this.stopDetectionTimeout;
}
@DesignerProperty(
defaultValue = "2000",
editorType = "non_negative_integer"
)
@SimpleProperty(
category = PropertyCategory.BEHAVIOR
)
public void StopDetectionTimeout(int var1) {
this.stopDetectionTimeout = var1;
}
@SimpleEvent
public void StoppedMoving() {
EventDispatcher.dispatchEvent(this, "StoppedMoving", new Object[0]);
}
@SimpleProperty
public float StrideLength() {
return this.strideLength;
}
@DesignerProperty(
defaultValue = "0.73",
editorType = "non_negative_float"
)
@SimpleProperty(
category = PropertyCategory.BEHAVIOR
)
public void StrideLength(float var1) {
this.CalibrateStrideLength(false);
this.strideLength = var1;
}
@DesignerProperty(
defaultValue = "true",
editorType = "boolean"
)
@SimpleProperty(
category = PropertyCategory.BEHAVIOR
)
public void UseGPS(boolean var1) {
if(!var1 && this.useGps) {
this.locationManager.removeUpdates(this);
} else if(var1 && !this.useGps) {
this.locationManager.requestLocationUpdates("gps", 0L, 0.0F, this);
}
this.useGps = var1;
}
@SimpleProperty
public boolean UseGPS() {
return this.useGps;
}
@SimpleEvent(
description = "This event is run when a walking step is detected"
)
public void WalkStep(int var1, float var2) {
EventDispatcher.dispatchEvent(this, "WalkStep", new Object[]{Integer.valueOf(var1), Float.valueOf(var2)});
}
public void onAccuracyChanged(Sensor var1, int var2) {
Log.d("Pedometer", "Accelerometer accuracy changed.");
}
public void onDelete() {
this.sensorManager.unregisterListener(this);
this.locationManager.removeUpdates(this);
}
public void onLocationChanged(Location var1) {
if(this.statusMoving && !this.pedometerPaused && this.useGps) {
float var2 = 0.0F;
this.currentLocation = var1;
if(this.currentLocation.getAccuracy() > 10.0F) {
this.setGpsAvailable(false);
} else {
this.setGpsAvailable(true);
float var3;
if(this.prevLocation != null) {
var3 = this.currentLocation.distanceTo(this.prevLocation);
var2 = var3;
if((double)var3 > 0.1D) {
var2 = var3;
if(var3 < 10.0F) {
this.totalDistance += var3;
this.prevLocation = this.currentLocation;
var2 = var3;
}
}
} else {
if(this.locationWhenGPSLost != null) {
var3 = this.currentLocation.distanceTo(this.locationWhenGPSLost);
this.totalDistance = this.distWhenGPSLost + (this.totalDistance - this.distWhenGPSLost + var3) / 2.0F;
}
this.gpsStepTime = System.currentTimeMillis();
this.prevLocation = this.currentLocation;
}
if(this.calibrateSteps) {
if(!this.firstGpsReading) {
this.gpsDistance += var2;
int var4 = this.numStepsRaw;
int var5 = this.lastNumSteps;
this.strideLength = this.gpsDistance / (float)(var4 - var5);
} else {
this.firstGpsReading = false;
this.lastNumSteps = this.numStepsRaw;
}
} else {
this.firstGpsReading = true;
this.gpsDistance = 0.0F;
}
}
}
}
public void onProviderDisabled(String var1) {
this.distWhenGPSLost = this.totalDistance;
this.locationWhenGPSLost = this.currentLocation;
this.firstGpsReading = true;
this.prevLocation = null;
this.setGpsAvailable(false);
}
public void onProviderEnabled(String var1) {
this.setGpsAvailable(true);
}
public void onSensorChanged(SensorEvent var1) {
if(var1.sensor.getType() == 1) {
float[] var6 = var1.values;
if(this.startPeaking) {
this.getPeak();
this.getValley();
}
byte var2;
if(this.prevDiff[0] > this.prevDiff[1]) {
var2 = 0;
} else {
var2 = 1;
}
byte var3 = var2;
if(this.prevDiff[2] > this.prevDiff[var2]) {
var3 = 2;
}
int var7;
for(var7 = 0; var7 < 3; ++var7) {
if(this.startPeaking && this.peak[var7] >= 0) {
if(this.foundValley[var7] && this.lastValues[this.peak[var7]][var7] - this.lastValley[var7] > 4.0F) {
if(var3 == var7) {
long var4 = System.currentTimeMillis();
this.stepInterval[this.intervalPos] = var4 - this.stepTimestamp;
this.intervalPos = (this.intervalPos + 1) % 2;
this.stepTimestamp = var4;
if(this.areStepsEquallySpaced()) {
if(this.foundNonStep) {
this.numStepsWithFilter += 2;
if(!this.gpsAvailable) {
this.totalDistance += this.strideLength * 2.0F;
}
this.foundNonStep = false;
}
++this.numStepsWithFilter;
this.WalkStep(this.numStepsWithFilter, this.totalDistance);
if(!this.gpsAvailable) {
this.totalDistance += this.strideLength;
}
} else {
this.foundNonStep = true;
}
++this.numStepsRaw;
this.SimpleStep(this.numStepsRaw, this.totalDistance);
if(!this.statusMoving) {
this.statusMoving = true;
this.StartedMoving();
}
}
this.foundValley[var7] = false;
this.prevDiff[var7] = this.lastValues[this.peak[var7]][var7] - this.lastValley[var7];
} else {
this.prevDiff[var7] = 0.0F;
}
}
if(this.startPeaking && this.valley[var7] >= 0) {
this.foundValley[var7] = true;
this.lastValley[var7] = this.lastValues[this.valley[var7]][var7];
}
this.lastValues[this.winPos][var7] = var6[var7];
}
this.elapsedTimestamp = System.currentTimeMillis();
if(this.elapsedTimestamp - this.stepTimestamp > (long)this.stopDetectionTimeout) {
if(this.statusMoving) {
this.statusMoving = false;
this.StoppedMoving();
}
this.stepTimestamp = this.elapsedTimestamp;
}
if(this.winPos - 1 < 0) {
var7 = 19;
} else {
var7 = this.winPos - 1;
}
for(int var8 = 0; var8 < 3; ++var8) {
if(this.lastValues[var7][var8] == this.lastValues[this.winPos][var8]) {
var6 = this.lastValues[this.winPos];
var6[var8] = (float)((double)var6[var8] + 0.001D);
}
}
if(this.winPos == 19 && !this.startPeaking) {
this.startPeaking = true;
}
this.winPos = (this.winPos + 1) % 20;
}
}
public void onStatusChanged(String var1, int var2, Bundle var3) {
}
}
| 19,104 | 0.603434 | 0.584223 | 613 | 30.164764 | 24.127258 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.577488 | false | false |
14
|
863d23c4ae7cea32fcb502fee1e8fcce8d4481df
| 12,687,333,451,372 |
03401c3dfbfa1db65b09d2213db34bae2e98938d
|
/src/main/java/com/ditra/travelagency/core/user/UserServices.java
|
120c95711f962374cd8e23f508aa20e8ea066c65
|
[] |
no_license
|
Ons-ok/travelagency
|
https://github.com/Ons-ok/travelagency
|
67bf4ae1cba74ba7a5e383337e9fb721208d1490
|
0b994f94a64ba5bb84e2840e1f9454f6a62c0755
|
refs/heads/master
| 2020-09-14T12:18:49.196000 | 2020-01-27T11:24:08 | 2020-01-27T11:24:08 | 223,126,524 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ditra.travelagency.core.user;
import com.ditra.travelagency.core.user.models.SignInRequestModel;
import com.ditra.travelagency.core.user.models.SignInResponseModel;
import com.ditra.travelagency.utils.ErrorResponseModes;
import com.ditra.travelagency.utils.JwtUtils;
import com.ditra.travelagency.utils.ValidationResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class UserServices implements UserDetailsService {
@Autowired
UserRepositroy userRepositroy;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
JwtUtils jwtUtils;
public ResponseEntity<?> creatUser (User user)
{
if (user.getName()==null)
return new ResponseEntity<>(new ErrorResponseModes("User name Required"), HttpStatus.BAD_REQUEST);
if (user.getName().length() < 3)
return new ResponseEntity<>(new ErrorResponseModes("Wrong User name " ),HttpStatus.BAD_REQUEST);
if (user.getAge()==null)
return new ResponseEntity<>(new ErrorResponseModes("User age Required"),HttpStatus.BAD_REQUEST);
if (user.getAge() <= 0)
return new ResponseEntity<>(new ErrorResponseModes("Wrong User age " ),HttpStatus.BAD_REQUEST);
String password1= passwordEncoder().encode(user.getPassword());
user.setPassword(password1);
User databaseuser = userRepositroy.save(user);
return new ResponseEntity<>(databaseuser, HttpStatus.OK);
}
public List<User> GetAllUser (){
List<User> userList= userRepositroy.findAll();
return userList;
}
public ResponseEntity<?> GetUser ( int id){
Optional<User> userOptional= userRepositroy.findById(id);
if (!userOptional.isPresent()){
ErrorResponseModes errorResponseModes= new ErrorResponseModes("Wrong user Id");
return new ResponseEntity<>(errorResponseModes, HttpStatus.BAD_REQUEST);
}
User user = userOptional.get();
return new ResponseEntity<>(user , HttpStatus.OK);
}
public ResponseEntity<?> updateUser(int id , User updatedUser ){
Optional<User> userOptional= userRepositroy.findById(id);
if (!userOptional.isPresent()){
ErrorResponseModes errorResponseModes= new ErrorResponseModes("Wrong user Id");
return new ResponseEntity<>(errorResponseModes, HttpStatus.BAD_REQUEST);
}
User databaseUser = userOptional.get();
if (updatedUser.getName() != null)
{
if (updatedUser.getName().length() < 3)
return new ResponseEntity<>(new ErrorResponseModes("wrong name"), HttpStatus.BAD_REQUEST);
databaseUser.setName(updatedUser.getName());
}
if (updatedUser.getAge()!=null)
{
if (updatedUser.getAge() < 0)
return new ResponseEntity<>(new ErrorResponseModes("wrong age"), HttpStatus.BAD_REQUEST);
databaseUser.setAge(updatedUser.getAge());
}
userRepositroy.save(databaseUser);
return new ResponseEntity<>(databaseUser, HttpStatus.OK);
}
public ResponseEntity<?> DeleteUser (int id){
Optional<User> userOptional= userRepositroy.findById(id);
if (!userOptional.isPresent()) {
ErrorResponseModes errorResponseModes = new ErrorResponseModes("Wrong user Id");
return new ResponseEntity<>(errorResponseModes, HttpStatus.BAD_REQUEST);
}
userRepositroy.deleteById(id);
ValidationResponse validationResponse = new ValidationResponse("User successfully deleted ");
return new ResponseEntity<>(validationResponse, HttpStatus.OK);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<User> userOptional=userRepositroy.findByUsername(username);
if (!userOptional.isPresent())
return null;
String password=userOptional.get().getPassword();
return new org.springframework.security.core.userdetails.User(username, password, AuthorityUtils.NO_AUTHORITIES);
}
@Bean
PasswordEncoder passwordEncoder (){
return new BCryptPasswordEncoder();
}
public ResponseEntity<?> signin(SignInRequestModel signInRequestModel) {
String username=signInRequestModel.getUsername();
String password=signInRequestModel.getPassword();
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(username,password)
);
String token = jwtUtils.genratedtoken(username);
return new ResponseEntity<>(new SignInResponseModel(token), HttpStatus.OK);
}
}
|
UTF-8
|
Java
| 5,568 |
java
|
UserServices.java
|
Java
|
[] | null |
[] |
package com.ditra.travelagency.core.user;
import com.ditra.travelagency.core.user.models.SignInRequestModel;
import com.ditra.travelagency.core.user.models.SignInResponseModel;
import com.ditra.travelagency.utils.ErrorResponseModes;
import com.ditra.travelagency.utils.JwtUtils;
import com.ditra.travelagency.utils.ValidationResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class UserServices implements UserDetailsService {
@Autowired
UserRepositroy userRepositroy;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
JwtUtils jwtUtils;
public ResponseEntity<?> creatUser (User user)
{
if (user.getName()==null)
return new ResponseEntity<>(new ErrorResponseModes("User name Required"), HttpStatus.BAD_REQUEST);
if (user.getName().length() < 3)
return new ResponseEntity<>(new ErrorResponseModes("Wrong User name " ),HttpStatus.BAD_REQUEST);
if (user.getAge()==null)
return new ResponseEntity<>(new ErrorResponseModes("User age Required"),HttpStatus.BAD_REQUEST);
if (user.getAge() <= 0)
return new ResponseEntity<>(new ErrorResponseModes("Wrong User age " ),HttpStatus.BAD_REQUEST);
String password1= passwordEncoder().encode(user.getPassword());
user.setPassword(password1);
User databaseuser = userRepositroy.save(user);
return new ResponseEntity<>(databaseuser, HttpStatus.OK);
}
public List<User> GetAllUser (){
List<User> userList= userRepositroy.findAll();
return userList;
}
public ResponseEntity<?> GetUser ( int id){
Optional<User> userOptional= userRepositroy.findById(id);
if (!userOptional.isPresent()){
ErrorResponseModes errorResponseModes= new ErrorResponseModes("Wrong user Id");
return new ResponseEntity<>(errorResponseModes, HttpStatus.BAD_REQUEST);
}
User user = userOptional.get();
return new ResponseEntity<>(user , HttpStatus.OK);
}
public ResponseEntity<?> updateUser(int id , User updatedUser ){
Optional<User> userOptional= userRepositroy.findById(id);
if (!userOptional.isPresent()){
ErrorResponseModes errorResponseModes= new ErrorResponseModes("Wrong user Id");
return new ResponseEntity<>(errorResponseModes, HttpStatus.BAD_REQUEST);
}
User databaseUser = userOptional.get();
if (updatedUser.getName() != null)
{
if (updatedUser.getName().length() < 3)
return new ResponseEntity<>(new ErrorResponseModes("wrong name"), HttpStatus.BAD_REQUEST);
databaseUser.setName(updatedUser.getName());
}
if (updatedUser.getAge()!=null)
{
if (updatedUser.getAge() < 0)
return new ResponseEntity<>(new ErrorResponseModes("wrong age"), HttpStatus.BAD_REQUEST);
databaseUser.setAge(updatedUser.getAge());
}
userRepositroy.save(databaseUser);
return new ResponseEntity<>(databaseUser, HttpStatus.OK);
}
public ResponseEntity<?> DeleteUser (int id){
Optional<User> userOptional= userRepositroy.findById(id);
if (!userOptional.isPresent()) {
ErrorResponseModes errorResponseModes = new ErrorResponseModes("Wrong user Id");
return new ResponseEntity<>(errorResponseModes, HttpStatus.BAD_REQUEST);
}
userRepositroy.deleteById(id);
ValidationResponse validationResponse = new ValidationResponse("User successfully deleted ");
return new ResponseEntity<>(validationResponse, HttpStatus.OK);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<User> userOptional=userRepositroy.findByUsername(username);
if (!userOptional.isPresent())
return null;
String password=userOptional.get().getPassword();
return new org.springframework.security.core.userdetails.User(username, password, AuthorityUtils.NO_AUTHORITIES);
}
@Bean
PasswordEncoder passwordEncoder (){
return new BCryptPasswordEncoder();
}
public ResponseEntity<?> signin(SignInRequestModel signInRequestModel) {
String username=signInRequestModel.getUsername();
String password=signInRequestModel.getPassword();
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(username,password)
);
String token = jwtUtils.genratedtoken(username);
return new ResponseEntity<>(new SignInResponseModel(token), HttpStatus.OK);
}
}
| 5,568 | 0.713901 | 0.712823 | 151 | 35.874172 | 33.377094 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.549669 | false | false |
14
|
cdfb8261f9f3c18cdbfc4b00a3fb04ece8673b91
| 18,021,682,829,758 |
5bc6a266ce941474ac555a81e2c2f4b70ff84e68
|
/smcenter.agent/src/main/java/com/irdstudio/smcenter/core/batch/dao/BatBatchInfoConfigDao.java
|
de582d019656839b251d4a311b659ba8d0f6c824
|
[] |
no_license
|
Fuzm/smcenter
|
https://github.com/Fuzm/smcenter
|
182e1bbaa98f4669846fec18e6877f3970241927
|
0b84e08355096871088ca472db79181265607a2c
|
refs/heads/master
| 2022-07-26T12:28:58.324000 | 2021-01-15T01:04:14 | 2021-01-15T01:04:14 | 188,767,425 | 0 | 0 | null | false | 2022-07-11T21:04:47 | 2019-05-27T03:51:36 | 2021-01-15T01:04:18 | 2022-07-11T21:04:44 | 4,747 | 0 | 0 | 7 |
Java
| false | false |
package com.irdstudio.smcenter.core.batch.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* 数据表操作类-[表名: 01.批次信息配置(BAT_BATCH_INFO_CONFIG)]
* 通过JDBC实现基本的数据表操作(CRUD)
* @author 代码自动生成
* @version 1.0
* @date 2014-04-21
*/
public class BatBatchInfoConfigDao {
/* 连接对象 */
Connection conn = null;
public BatBatchInfoConfigDao(Connection conn){
this.conn = conn;
}
/**
* 根据主键查询单条记录
* @param
* @return
* @throws SQLException
*/
public BatBatchInfoConfig queryWithKeys(String batchId)
throws SQLException {
BatBatchInfoConfig dc = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn
.prepareStatement("SELECT * FROM bat_batch_info_config WHERE batch_id=?");
ps.setString(1,batchId);
rs = ps.executeQuery();
if (rs.next()) {
dc = new BatBatchInfoConfig();
dc.setBatchId(rs.getString("batch_id"));
dc.setBatchName(rs.getString("batch_name"));
dc.setSubsCode(rs.getString("subs_code"));
dc.setLaunchType(rs.getString("launch_type"));
dc.setBatchCronValue(rs.getString("batch_cron_value"));
dc.setAgentId(rs.getString("agent_id"));
dc.setValidDate(rs.getString("valid_date"));
dc.setEquallyTaskAmount(rs.getInt("equally_task_amount"));
dc.setIsRunAgain(rs.getString("is_run_again"));
dc.setRemark(rs.getString("remark"));
}
} catch (SQLException e) {
throw new SQLException("queryBatBatchInfoConfigWithKeys is Wrong!"
+ e.getMessage());
} finally {
close(rs, null, ps);
}
return dc;
}
/**
* 根据查询条件查询多条或单条记录
* @param szCondition
* @return
* @throws SQLException
*/
public List<BatBatchInfoConfig> queryWithCond(String szCondition,String szOrderBy)
throws SQLException {
List<BatBatchInfoConfig> dcList = new ArrayList<BatBatchInfoConfig>();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement("SELECT * FROM BAT_BATCH_INFO_CONFIG "
+ szCondition + " " + szOrderBy);
rs = ps.executeQuery();
while (rs.next()) {
BatBatchInfoConfig dc = new BatBatchInfoConfig();
dc.setBatchId(rs.getString("batch_id"));
dc.setBatchName(rs.getString("batch_name"));
dc.setSubsCode(rs.getString("subs_code"));
dc.setLaunchType(rs.getString("launch_type"));
dc.setBatchCronValue(rs.getString("batch_cron_value"));
dc.setAgentId(rs.getString("agent_id"));
dc.setValidDate(rs.getString("valid_date"));
dc.setEquallyTaskAmount(rs.getInt("equally_task_amount"));
dc.setIsRunAgain(rs.getString("is_run_again"));
dc.setRemark(rs.getString("remark"));
dcList.add(dc);
}
} catch (SQLException e) {
throw new SQLException("queryBatBatchInfoConfigWithCond is Wrong!"
+ e.getMessage());
} finally {
close(rs, null, ps);
}
return dcList;
}
/**
* 关闭资源
* @param theRs
* @param theStmt
* @param thePs
*/
protected void close(ResultSet theRs, Statement theStmt,
PreparedStatement thePs) {
try {
if (theRs != null)
theRs.close();
if (theStmt != null)
theStmt.close();
if (thePs != null)
thePs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 3,426 |
java
|
BatBatchInfoConfigDao.java
|
Java
|
[] | null |
[] |
package com.irdstudio.smcenter.core.batch.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* 数据表操作类-[表名: 01.批次信息配置(BAT_BATCH_INFO_CONFIG)]
* 通过JDBC实现基本的数据表操作(CRUD)
* @author 代码自动生成
* @version 1.0
* @date 2014-04-21
*/
public class BatBatchInfoConfigDao {
/* 连接对象 */
Connection conn = null;
public BatBatchInfoConfigDao(Connection conn){
this.conn = conn;
}
/**
* 根据主键查询单条记录
* @param
* @return
* @throws SQLException
*/
public BatBatchInfoConfig queryWithKeys(String batchId)
throws SQLException {
BatBatchInfoConfig dc = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn
.prepareStatement("SELECT * FROM bat_batch_info_config WHERE batch_id=?");
ps.setString(1,batchId);
rs = ps.executeQuery();
if (rs.next()) {
dc = new BatBatchInfoConfig();
dc.setBatchId(rs.getString("batch_id"));
dc.setBatchName(rs.getString("batch_name"));
dc.setSubsCode(rs.getString("subs_code"));
dc.setLaunchType(rs.getString("launch_type"));
dc.setBatchCronValue(rs.getString("batch_cron_value"));
dc.setAgentId(rs.getString("agent_id"));
dc.setValidDate(rs.getString("valid_date"));
dc.setEquallyTaskAmount(rs.getInt("equally_task_amount"));
dc.setIsRunAgain(rs.getString("is_run_again"));
dc.setRemark(rs.getString("remark"));
}
} catch (SQLException e) {
throw new SQLException("queryBatBatchInfoConfigWithKeys is Wrong!"
+ e.getMessage());
} finally {
close(rs, null, ps);
}
return dc;
}
/**
* 根据查询条件查询多条或单条记录
* @param szCondition
* @return
* @throws SQLException
*/
public List<BatBatchInfoConfig> queryWithCond(String szCondition,String szOrderBy)
throws SQLException {
List<BatBatchInfoConfig> dcList = new ArrayList<BatBatchInfoConfig>();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement("SELECT * FROM BAT_BATCH_INFO_CONFIG "
+ szCondition + " " + szOrderBy);
rs = ps.executeQuery();
while (rs.next()) {
BatBatchInfoConfig dc = new BatBatchInfoConfig();
dc.setBatchId(rs.getString("batch_id"));
dc.setBatchName(rs.getString("batch_name"));
dc.setSubsCode(rs.getString("subs_code"));
dc.setLaunchType(rs.getString("launch_type"));
dc.setBatchCronValue(rs.getString("batch_cron_value"));
dc.setAgentId(rs.getString("agent_id"));
dc.setValidDate(rs.getString("valid_date"));
dc.setEquallyTaskAmount(rs.getInt("equally_task_amount"));
dc.setIsRunAgain(rs.getString("is_run_again"));
dc.setRemark(rs.getString("remark"));
dcList.add(dc);
}
} catch (SQLException e) {
throw new SQLException("queryBatBatchInfoConfigWithCond is Wrong!"
+ e.getMessage());
} finally {
close(rs, null, ps);
}
return dcList;
}
/**
* 关闭资源
* @param theRs
* @param theStmt
* @param thePs
*/
protected void close(ResultSet theRs, Statement theStmt,
PreparedStatement thePs) {
try {
if (theRs != null)
theRs.close();
if (theStmt != null)
theStmt.close();
if (thePs != null)
thePs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| 3,426 | 0.678398 | 0.674454 | 123 | 25.796747 | 19.931982 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.560976 | false | false |
14
|
1670e95013ec2cbac14a07d3d8e45fe509ddb522
| 11,321,533,854,308 |
7129d0516e50774a24900ebb0229f4064e728014
|
/OOP6/src/SWLeibwaechterSoftware.java
|
38aae06139287f6aa4878aa99ec39567214c086d
|
[] |
no_license
|
flowlo/oop
|
https://github.com/flowlo/oop
|
3383c0d5171f2c8eecaf413b79466434fd1683bf
|
69a2009a4f6cd018975fec4a07547420d703b25c
|
refs/heads/master
| 2020-06-28T22:40:59.863000 | 2016-11-30T18:53:28 | 2016-11-30T18:53:28 | 74,465,606 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Repraesentiert die Software eines Leibwaechters
*
* Zusicherungen:
* * Sicherheitsstufe muss 4 sein
*
* @author Dominik
*
*/
public class SWLeibwaechterSoftware extends SWSoftware {
/**
* Konstruktor
*
* @param securityLevel
* die Sicherheitsstufe der Software
*/
public SWLeibwaechterSoftware(SWSecurityLevel securityLevel) {
super(securityLevel);
}
@Override
public void installedOnLeibwaechter(ANAndroide androide) {
System.out.println("OK - Passende Software fuer diesen Typ");
}
}
|
UTF-8
|
Java
| 561 |
java
|
SWLeibwaechterSoftware.java
|
Java
|
[
{
"context": " * * Sicherheitsstufe muss 4 sein\r\n * \r\n * @author Dominik\r\n * \r\n */\r\npublic class SWLeibwaechterSoftware ex",
"end": 139,
"score": 0.9995050430297852,
"start": 132,
"tag": "NAME",
"value": "Dominik"
}
] | null |
[] |
/**
* Repraesentiert die Software eines Leibwaechters
*
* Zusicherungen:
* * Sicherheitsstufe muss 4 sein
*
* @author Dominik
*
*/
public class SWLeibwaechterSoftware extends SWSoftware {
/**
* Konstruktor
*
* @param securityLevel
* die Sicherheitsstufe der Software
*/
public SWLeibwaechterSoftware(SWSecurityLevel securityLevel) {
super(securityLevel);
}
@Override
public void installedOnLeibwaechter(ANAndroide androide) {
System.out.println("OK - Passende Software fuer diesen Typ");
}
}
| 561 | 0.682709 | 0.680927 | 25 | 20.440001 | 22.043737 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.68 | false | false |
14
|
bce001b1d2a4d56f5b301eb2443321a31e37642b
| 31,018,253,862,045 |
25863e1f55a84848922af8cdec469159b5c4282d
|
/src/main/java/persistence/DAO.java
|
26029ffbe0a186e1f060dbb56f063e7126db2862
|
[] |
no_license
|
maffan/nodes
|
https://github.com/maffan/nodes
|
82ec0797fb83f7ed3d151844a77ddefccdb6ca28
|
c5c9a06dca47288b2f4df197db9d9150304f63cb
|
refs/heads/master
| 2021-01-10T07:46:37.049000 | 2016-03-13T20:13:11 | 2016-03-13T20:13:11 | 52,424,542 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package persistence;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
/**
*
* @author Marcus
* @param <T> Type
* @param <K> Primary Key
*/
public abstract class DAO<T, K> {
private final Class<T> typeClass;
protected abstract EntityManager getEntityManager();
protected DAO(Class<T> typeClass) {
this.typeClass = typeClass;
}
public void create(T t) {
this.getEntityManager().persist(t);
}
public void delete(K id) {
T t = getEntityManager().getReference(typeClass, id);
getEntityManager().remove(t);
}
public void update(T t) {
getEntityManager().merge(t);
}
public T find(K id) {
return getEntityManager().find(typeClass, id);
}
public List<T> findAll() {
return get(true, -1, -1);
}
public List<T> findRange(int first, int n) {
return get(false, first, n);
}
private List<T> get(boolean all, int first, int n) {
EntityManager em = getEntityManager();
List<T> found = new ArrayList<>();
TypedQuery<T> q = em.createQuery("select t from " + typeClass.getSimpleName() + " t", typeClass);
if (!all) {
q.setFirstResult(first);
q.setMaxResults(n);
}
found.addAll(q.getResultList());
return found;
}
public int count() {
EntityManager em = getEntityManager();
Long n = em.createQuery("select count(t) from " + typeClass.getSimpleName() + " t", Long.class)
.getSingleResult();
return n.intValue();
}
}
|
UTF-8
|
Java
| 1,840 |
java
|
DAO.java
|
Java
|
[
{
"context": "t javax.persistence.TypedQuery;\n\n/**\n *\n * @author Marcus\n * @param <T> Type\n * @param <K> Primary Key\n */\n",
"end": 360,
"score": 0.9997031688690186,
"start": 354,
"tag": "NAME",
"value": "Marcus"
}
] | null |
[] |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package persistence;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
/**
*
* @author Marcus
* @param <T> Type
* @param <K> Primary Key
*/
public abstract class DAO<T, K> {
private final Class<T> typeClass;
protected abstract EntityManager getEntityManager();
protected DAO(Class<T> typeClass) {
this.typeClass = typeClass;
}
public void create(T t) {
this.getEntityManager().persist(t);
}
public void delete(K id) {
T t = getEntityManager().getReference(typeClass, id);
getEntityManager().remove(t);
}
public void update(T t) {
getEntityManager().merge(t);
}
public T find(K id) {
return getEntityManager().find(typeClass, id);
}
public List<T> findAll() {
return get(true, -1, -1);
}
public List<T> findRange(int first, int n) {
return get(false, first, n);
}
private List<T> get(boolean all, int first, int n) {
EntityManager em = getEntityManager();
List<T> found = new ArrayList<>();
TypedQuery<T> q = em.createQuery("select t from " + typeClass.getSimpleName() + " t", typeClass);
if (!all) {
q.setFirstResult(first);
q.setMaxResults(n);
}
found.addAll(q.getResultList());
return found;
}
public int count() {
EntityManager em = getEntityManager();
Long n = em.createQuery("select count(t) from " + typeClass.getSimpleName() + " t", Long.class)
.getSingleResult();
return n.intValue();
}
}
| 1,840 | 0.6125 | 0.611413 | 72 | 24.541666 | 23.480452 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false |
14
|
50b92ea574cb8d1445f9afcc2db41aea863819d3
| 10,565,619,554,335 |
163b8e5eac0a7e5a88a3ad9eb008f72ececdff46
|
/src/design/javaBasics/generics/IntegerTest.java
|
3078e6de6d7eea846cd8602cb8d30ef4bec75d35
|
[] |
no_license
|
harshaprabha/coding-practice
|
https://github.com/harshaprabha/coding-practice
|
a0a3c27c41e1679cf760272f9788714bf561e125
|
80b5dd04fa52d5519ed2c299d0ff099962c28c27
|
refs/heads/master
| 2021-06-13T14:02:24.766000 | 2021-04-20T08:44:48 | 2021-04-20T08:44:48 | 183,869,305 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package javaBasics.generics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class IntegerTest {
public static void main(String[] args) {
Integer a = new Integer(1);
//Integer b= new Integer(1);
Integer b = null;
int bb = 0;
// System.out.println(b < bb);
List<Integer> ll = new ArrayList<>();
ll.add(1);
IntegerTest obj = new IntegerTest();
obj.printValues(Arrays.asList(1, 2, ""));
obj.printValues(Arrays.asList(1, 2, 3, 4, 5));
obj.printValues(Arrays.asList("harsha", "prabha"));
obj.printValues(ll);
List<String> list = new ArrayList();
list.add("hahah");
//list.add(1);
//int value= (int)list.get(0);
// System.out.println(value);
}
<T> void printValues(List<T> values) {
for (T t : values) {
System.out.println(t);
}
}
}
|
UTF-8
|
Java
| 863 |
java
|
IntegerTest.java
|
Java
|
[
{
"context": " 2, 3, 4, 5));\n obj.printValues(Arrays.asList(\"harsha\", \"prabha\"));\n obj.printValues(ll);\n\n List<",
"end": 555,
"score": 0.9984478950500488,
"start": 549,
"tag": "NAME",
"value": "harsha"
},
{
"context": "5));\n obj.printValues(Arrays.asList(\"harsha\", \"prabha\"));\n obj.printValues(ll);\n\n List<String> li",
"end": 565,
"score": 0.9966092705726624,
"start": 559,
"tag": "NAME",
"value": "prabha"
}
] | null |
[] |
package javaBasics.generics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class IntegerTest {
public static void main(String[] args) {
Integer a = new Integer(1);
//Integer b= new Integer(1);
Integer b = null;
int bb = 0;
// System.out.println(b < bb);
List<Integer> ll = new ArrayList<>();
ll.add(1);
IntegerTest obj = new IntegerTest();
obj.printValues(Arrays.asList(1, 2, ""));
obj.printValues(Arrays.asList(1, 2, 3, 4, 5));
obj.printValues(Arrays.asList("harsha", "prabha"));
obj.printValues(ll);
List<String> list = new ArrayList();
list.add("hahah");
//list.add(1);
//int value= (int)list.get(0);
// System.out.println(value);
}
<T> void printValues(List<T> values) {
for (T t : values) {
System.out.println(t);
}
}
}
| 863 | 0.609502 | 0.594438 | 41 | 20.04878 | 16.820358 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.707317 | false | false |
14
|
36e25216336628a0592574f68e2067c97b95bf6a
| 6,176,163,035,546 |
5a7dbbce8a7d3a28bbed377788f9f5772939be8d
|
/Week12/gymnocercusJade-foundation-normal-exam/WeeklyFeedbackEvaluator/Main.java
|
e888c8ad128cd2360ff3a7ef6b2172d88af8dcd2
|
[] |
no_license
|
Radek2rady/List-repos
|
https://github.com/Radek2rady/List-repos
|
9e8f815c79dc2da7d8898b616dca39b82efb2db8
|
27050a22c94d46e75040eb4093e0f2356b4bbd72
|
refs/heads/main
| 2023-05-15T01:12:31.947000 | 2021-06-07T07:21:59 | 2021-06-07T07:21:59 | 374,569,044 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package gymnocercusJadeFoundationNormalExamWeeklyFeedbackEvaluator;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
// Path myPath = Paths.get("responses.txt");
Scanner input = new Scanner(new File("src/gymnocercusJadeFoundationNormalExamWeeklyFeedbackEvaluator/responses.txt"));
int[][] a = new int[0][];
// matrixFromFile(Scanner input);
System.out.println(matReview(a));
}
public static void matrixFromFile(Scanner input) throws FileNotFoundException {
int rows = 0;
int columns = 0;
while (input.hasNextLine()) {
++rows;
Scanner colReader = new Scanner(input.nextLine());
while (colReader.hasNextInt()) {
++columns;
}
}
int[][] a = new int[rows][columns];
input.close();
input = new Scanner(new File("src/gymnocercusJadeFoundationNormalExamWeeklyFeedbackEvaluator/responses.txt"));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns; ++j) {
if (input.hasNextInt()) {
a[i][j] = input.nextInt();
}
}
}
}
public static double matReview(int[][] a) {
// matrixFromFile(a);
double mathRating = 0;
double sum = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
sum += a[0][j];
}
}
return mathRating = sum / a[0].length;
}
}
|
UTF-8
|
Java
| 1,714 |
java
|
Main.java
|
Java
|
[] | null |
[] |
package gymnocercusJadeFoundationNormalExamWeeklyFeedbackEvaluator;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
// Path myPath = Paths.get("responses.txt");
Scanner input = new Scanner(new File("src/gymnocercusJadeFoundationNormalExamWeeklyFeedbackEvaluator/responses.txt"));
int[][] a = new int[0][];
// matrixFromFile(Scanner input);
System.out.println(matReview(a));
}
public static void matrixFromFile(Scanner input) throws FileNotFoundException {
int rows = 0;
int columns = 0;
while (input.hasNextLine()) {
++rows;
Scanner colReader = new Scanner(input.nextLine());
while (colReader.hasNextInt()) {
++columns;
}
}
int[][] a = new int[rows][columns];
input.close();
input = new Scanner(new File("src/gymnocercusJadeFoundationNormalExamWeeklyFeedbackEvaluator/responses.txt"));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns; ++j) {
if (input.hasNextInt()) {
a[i][j] = input.nextInt();
}
}
}
}
public static double matReview(int[][] a) {
// matrixFromFile(a);
double mathRating = 0;
double sum = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
sum += a[0][j];
}
}
return mathRating = sum / a[0].length;
}
}
| 1,714 | 0.558926 | 0.551925 | 54 | 30.74074 | 26.948637 | 126 | false | false | 0 | 0 | 0 | 0 | 72 | 0.084014 | 0.611111 | false | false |
14
|
e38cac359353e24e87155dca72e95b497295417b
| 15,315,853,440,061 |
56edfe5c0ce81946601126d6013760cfd9c92c95
|
/src/main/java/ezksd/Trie.java
|
c897e04133929f8a5362a031a53fc21fe7884978
|
[] |
no_license
|
ezksd/leetcode-solutions
|
https://github.com/ezksd/leetcode-solutions
|
cb78e63b3104cdbe481b90c117d66215653332ac
|
101081569abbec23345c2b8cb71163ac1ed42a6a
|
refs/heads/master
| 2020-06-04T01:03:04.757000 | 2019-06-16T09:00:17 | 2019-06-16T09:00:17 | 191,805,460 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ezksd;
import java.util.HashMap;
public class Trie {
}
|
UTF-8
|
Java
| 65 |
java
|
Trie.java
|
Java
|
[] | null |
[] |
package ezksd;
import java.util.HashMap;
public class Trie {
}
| 65 | 0.738462 | 0.738462 | 6 | 9.833333 | 10.023583 | 25 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
14
|
956d0fc623c9731215db6ec9d6cb36aaaaa24e33
| 9,586,367,063,331 |
64fda175e69a2196178b7b43f6fbf71e07ce11bd
|
/app/src/main/java/com/example/meetsoft/activity/ActivityContactBook.java
|
324ee2d15413a17e825648fbae6e2165b27f9426
|
[] |
no_license
|
RyanTech/MeetSoft
|
https://github.com/RyanTech/MeetSoft
|
ef946a809f64026a0b42df3441f66db7067e64ec
|
8fbb6483630527daedd660bbf517b40c66a0bb02
|
refs/heads/master
| 2017-12-05T10:14:09.793000 | 2015-06-18T12:28:16 | 2015-06-18T12:28:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.meetsoft.activity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.example.meetsoft.R;
import com.example.meetsoft.util.CONST;
import com.example.meetsoft.util.UmengEvent;
import com.meet.android.client.bean.ContackBookList;
import com.meet.android.client.core.MeetException;
import com.meet.android.client.core.PhoneMsgClient;
import com.umeng.analytics.MobclickAgent;
public class ActivityContactBook extends BaseActivity {
public final String ACT_contactDetails = CONST.ACTION_contactDetails;
private final String PRM_aid = "aid";
private final String PRM_name = "name";
private final String PRM_phone = "phone";
private final int PAGESIZE = 30;
private EditText edt_search;
private ListView lst_contacts;
private ContactBookAdapter adp_contacts;
private List<Map<String, Object>> data;
private boolean hasLastItem = false;
@Override
protected int getViewId() {
return R.layout.activity_contactbook;
}
@Override
protected String getPageTitle() {
return "通讯录";
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView();
createNavMenu();
// 2014-7-1 hzp增加,增加油门接口
MobclickAgent.onEvent(ActivityContactBook.this,
UmengEvent.UMENG_EVENTID_tongxunlu);
// ***
cleanData();
if (!fetchData(0)) {
this.finish();
return;
}
edt_search = (EditText) findViewById(R.id.contactbook_edt_search);
edt_search.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start,
int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
cleanData();
String condition = s.toString();
if (condition.equals("")) {
if (!fetchData(0)) {
ActivityContactBook.this.finish();
return;
}
} else {
if (!fetchData(condition, 0)) {
ActivityContactBook.this.finish();
return;
}
}
adp_contacts.notifyDataSetChanged();
}
});
lst_contacts = (ListView) findViewById(R.id.contactbook_lst_contacts);
lst_contacts.setOnItemClickListener(new OnItemClickListener() {
@SuppressWarnings("unchecked")
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, Object> item = (HashMap<String, Object>) view
.getTag();
Intent intent = new Intent();
intent.setAction(ACT_contactDetails);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra(PRM_aid, (String) item.get(PRM_aid));
startActivity(intent);
}
});
lst_contacts.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView v, int state) {
}
@Override
public void onScroll(AbsListView v, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (visibleItemCount == 0)
return;
if (hasLastItem) {
return;
}
if (totalItemCount <= (firstVisibleItem + visibleItemCount * 2)) {
String condition = edt_search.getText().toString().trim();
if (condition.equals("")) {
if (!fetchData(totalItemCount)) {
ActivityContactBook.this.finish();
return;
}
} else {
if (!fetchData(condition, totalItemCount)) {
ActivityContactBook.this.finish();
return;
}
}
adp_contacts.notifyDataSetChanged();
}
}
});
adp_contacts = new ContactBookAdapter(this);
lst_contacts.setAdapter(adp_contacts);
}
private void cleanData() {
data = null;
hasLastItem = false;
}
private boolean fetchData(int startrow) {
try {
List<ContackBookList> contacts = PhoneMsgClient
.getContackBookList1027(getMeetid(), startrow, PAGESIZE);
if (contacts.size() < PAGESIZE)
hasLastItem = true;
else
hasLastItem = false;
if (data == null) {
data = new ArrayList<Map<String, Object>>();
}
Map<String, Object> map;
for (Iterator<ContackBookList> iter = contacts.iterator(); iter
.hasNext();) {
ContackBookList contact = iter.next();
map = new HashMap<String, Object>();
map.put(PRM_name, contact.getName());
map.put(PRM_aid, contact.getAid());
map.put(PRM_phone, contact.getPeopleid());
data.add(map);
}
return true;
} catch (MeetException e) {
e.printStackTrace();
return false;
}
}
private boolean fetchData(String condition, int startrow) {
try {
List<ContackBookList> contacts = PhoneMsgClient
.getContackBookListByName1029(getMeetid(), condition,
startrow, PAGESIZE);
if (contacts.size() < PAGESIZE)
hasLastItem = true;
else
hasLastItem = false;
if (data == null)
data = new ArrayList<Map<String, Object>>();
Map<String, Object> map;
for (Iterator<ContackBookList> iter = contacts.iterator(); iter
.hasNext();) {
ContackBookList contact = iter.next();
map = new HashMap<String, Object>();
map.put(PRM_name, contact.getName());
map.put(PRM_aid, contact.getAid());
map.put(PRM_phone, contact.getPeopleid());
data.add(map);
}
return true;
} catch (MeetException e) {
Log.e("Meetsoft", e.getMessage());
return false;
}
}
@Override
public void onDestroy() {
super.onDestroy();
cleanData();
}
private class ContactBookAdapter extends BaseAdapter {
private LayoutInflater inflater;
public ContactBookAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
if (data == null)
return 0;
return data.size();
}
@Override
public Object getItem(int position) {
if (data == null)
return null;
return data.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = inflater
.inflate(R.layout.activity_contactbookitem, null);
}
Map<String, Object> item = data.get(position);
view.setTag(item);
//
TextView txt_username = (TextView) view
.findViewById(R.id.contactitem_txt_username);
txt_username.setText((String) item.get(PRM_name));
return view;
}
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
MobclickAgent.onPause(this);
}
@Override
public void onResume() {
super.onResume();
MobclickAgent.onResume(this);
}
}
|
UTF-8
|
Java
| 7,185 |
java
|
ActivityContactBook.java
|
Java
|
[] | null |
[] |
package com.example.meetsoft.activity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.example.meetsoft.R;
import com.example.meetsoft.util.CONST;
import com.example.meetsoft.util.UmengEvent;
import com.meet.android.client.bean.ContackBookList;
import com.meet.android.client.core.MeetException;
import com.meet.android.client.core.PhoneMsgClient;
import com.umeng.analytics.MobclickAgent;
public class ActivityContactBook extends BaseActivity {
public final String ACT_contactDetails = CONST.ACTION_contactDetails;
private final String PRM_aid = "aid";
private final String PRM_name = "name";
private final String PRM_phone = "phone";
private final int PAGESIZE = 30;
private EditText edt_search;
private ListView lst_contacts;
private ContactBookAdapter adp_contacts;
private List<Map<String, Object>> data;
private boolean hasLastItem = false;
@Override
protected int getViewId() {
return R.layout.activity_contactbook;
}
@Override
protected String getPageTitle() {
return "通讯录";
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView();
createNavMenu();
// 2014-7-1 hzp增加,增加油门接口
MobclickAgent.onEvent(ActivityContactBook.this,
UmengEvent.UMENG_EVENTID_tongxunlu);
// ***
cleanData();
if (!fetchData(0)) {
this.finish();
return;
}
edt_search = (EditText) findViewById(R.id.contactbook_edt_search);
edt_search.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start,
int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
cleanData();
String condition = s.toString();
if (condition.equals("")) {
if (!fetchData(0)) {
ActivityContactBook.this.finish();
return;
}
} else {
if (!fetchData(condition, 0)) {
ActivityContactBook.this.finish();
return;
}
}
adp_contacts.notifyDataSetChanged();
}
});
lst_contacts = (ListView) findViewById(R.id.contactbook_lst_contacts);
lst_contacts.setOnItemClickListener(new OnItemClickListener() {
@SuppressWarnings("unchecked")
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, Object> item = (HashMap<String, Object>) view
.getTag();
Intent intent = new Intent();
intent.setAction(ACT_contactDetails);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra(PRM_aid, (String) item.get(PRM_aid));
startActivity(intent);
}
});
lst_contacts.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView v, int state) {
}
@Override
public void onScroll(AbsListView v, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (visibleItemCount == 0)
return;
if (hasLastItem) {
return;
}
if (totalItemCount <= (firstVisibleItem + visibleItemCount * 2)) {
String condition = edt_search.getText().toString().trim();
if (condition.equals("")) {
if (!fetchData(totalItemCount)) {
ActivityContactBook.this.finish();
return;
}
} else {
if (!fetchData(condition, totalItemCount)) {
ActivityContactBook.this.finish();
return;
}
}
adp_contacts.notifyDataSetChanged();
}
}
});
adp_contacts = new ContactBookAdapter(this);
lst_contacts.setAdapter(adp_contacts);
}
private void cleanData() {
data = null;
hasLastItem = false;
}
private boolean fetchData(int startrow) {
try {
List<ContackBookList> contacts = PhoneMsgClient
.getContackBookList1027(getMeetid(), startrow, PAGESIZE);
if (contacts.size() < PAGESIZE)
hasLastItem = true;
else
hasLastItem = false;
if (data == null) {
data = new ArrayList<Map<String, Object>>();
}
Map<String, Object> map;
for (Iterator<ContackBookList> iter = contacts.iterator(); iter
.hasNext();) {
ContackBookList contact = iter.next();
map = new HashMap<String, Object>();
map.put(PRM_name, contact.getName());
map.put(PRM_aid, contact.getAid());
map.put(PRM_phone, contact.getPeopleid());
data.add(map);
}
return true;
} catch (MeetException e) {
e.printStackTrace();
return false;
}
}
private boolean fetchData(String condition, int startrow) {
try {
List<ContackBookList> contacts = PhoneMsgClient
.getContackBookListByName1029(getMeetid(), condition,
startrow, PAGESIZE);
if (contacts.size() < PAGESIZE)
hasLastItem = true;
else
hasLastItem = false;
if (data == null)
data = new ArrayList<Map<String, Object>>();
Map<String, Object> map;
for (Iterator<ContackBookList> iter = contacts.iterator(); iter
.hasNext();) {
ContackBookList contact = iter.next();
map = new HashMap<String, Object>();
map.put(PRM_name, contact.getName());
map.put(PRM_aid, contact.getAid());
map.put(PRM_phone, contact.getPeopleid());
data.add(map);
}
return true;
} catch (MeetException e) {
Log.e("Meetsoft", e.getMessage());
return false;
}
}
@Override
public void onDestroy() {
super.onDestroy();
cleanData();
}
private class ContactBookAdapter extends BaseAdapter {
private LayoutInflater inflater;
public ContactBookAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
if (data == null)
return 0;
return data.size();
}
@Override
public Object getItem(int position) {
if (data == null)
return null;
return data.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = inflater
.inflate(R.layout.activity_contactbookitem, null);
}
Map<String, Object> item = data.get(position);
view.setTag(item);
//
TextView txt_username = (TextView) view
.findViewById(R.id.contactitem_txt_username);
txt_username.setText((String) item.get(PRM_name));
return view;
}
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
MobclickAgent.onPause(this);
}
@Override
public void onResume() {
super.onResume();
MobclickAgent.onResume(this);
}
}
| 7,185 | 0.693339 | 0.690127 | 279 | 24.666666 | 19.208719 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.97491 | false | false |
14
|
a2feafdf1e31d70bd4c68ad6cca38aaa000979c1
| 33,715,493,310,365 |
f989fb80c88780059b14ae49dd6a5d1f670fc994
|
/app/src/main/java/com/revolve44/fragments22/MainActivity.java
|
a9d39bd18110f68c4372f2f18dcc1c30024f17c5
|
[] |
no_license
|
Murad255/scalc
|
https://github.com/Murad255/scalc
|
4a6d55e144d4f8771b8e0de4ea86c5a3932e56f3
|
d059e481591891e15ed1b344c2e146274cbfdb59
|
refs/heads/master
| 2022-06-28T00:16:39.251000 | 2020-05-09T12:35:08 | 2020-05-09T12:35:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.revolve44.fragments22;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Display;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.gson.Gson;
import com.revolve44.fragments22.recyclerview.Model;
import com.revolve44.fragments22.recyclerview.MultiViewTypeAdapter;
import com.revolve44.fragments22.ui.HomeFragment;
import com.revolve44.fragments22.ui.CalcFragment;
import com.revolve44.fragments22.ui.SidekickFragment;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.ExecutionException;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/*
Внимание! при каждом запуске эмулятора ставь правильную дату на эмуляторе
ото бывает время восхода и заката не схадятся из за разницы дат и времени
*/
/*
TODO: The main functions of this class: communication with Weather API,
get main variables (cloud, temp coefficient, sunrise sunset time)
*/
public class MainActivity extends AppCompatActivity {
private View root;
final Fragment fragment1 = new HomeFragment();
final Fragment fragment2 = new CalcFragment();
final Fragment fragment3 = new SidekickFragment();
final FragmentManager fm = getSupportFragmentManager();
Fragment active = fragment1;
RelativeLayout SkyLayout;
//Example
//api.openweathermap.org/data/2.5/weather?q=moscow&appid=1b87fee17221ed7893aa488cff08bfa2
// http://api.openweathermap.org/data/2.5/find?lat=55.5&lon=37.5&cnt=10&appid=ac79fea59e9d15377b787a610a29b784
public static String BaseUrl = "https://api.openweathermap.org/";
public static String CITY = "Moscow";
public static String AppId = "4e78fa71de97f97aa376e42f2f1c99cf";
public static String MC = "&units=metric&appid=";
public TextView temperatureText;
public TextView windText;
public static String lat;
public static String lon;
public static String metric = "metric";
//Variables
public float NominalPower;//????????????????????????????????
public float CurrentPower;
public int CurrentPowerInt;
public float cloud;
public float windF;
public int windI;
public float temp;
public String desription;
public float pressure;
public float humidity;
public boolean tempScale;
public long unixSunrise;
public long unixSunset;
public String city;
public String country;
//public String
public boolean isDataAvailable = false;
public final LinkedHashMap<Long, Float> dataMap = new LinkedHashMap<>();
public LinkedHashMap<String, Float> corvette = new LinkedHashMap<>();
public String sunset;
public String sunrise;
public String hournowStr;
public TextView mainoutput;
public TextView saymayname;
public long TimeHashMap;
public float CurrentPowerHashMap;
Boolean HotCheck= false;
int SunPeriod = 0;
public String solarhoursString;
public long GMT = 0;
public long UTCtime;
public long UnixCurrentTime;
public String jsonString;
//Context context;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Lifecycle ->"," onCreate launch ");
SharedPreferences sharedPreferences = this.getSharedPreferences("MasterSave", MODE_PRIVATE);
if (!sharedPreferences.getBoolean("firstTime", false)) {
// <---- run your one time code here
Intent intent2 = new Intent(this, MapsActivity.class);
startActivity(intent2);
}
//setContentView(R.layout.activity_main);
mainoutput = findViewById(R.id.Forecast_number);
lat = getIntent().getStringExtra("FROM_MAPS1");
lon = getIntent().getStringExtra("FROM_MAPS2");
///////////////////////////////////////////////////////////////////////////////////////////
// Launch Pad //
///////////////////////////////////////////////////////////////////////////////////////////
// Log.d(" Launch method ", " loaddata() ");
// LoadData();
// Log.d(" Launch method ", " getcurrentdata() ");
// getCurrentData();
// Log.d(" Launch method ", " loaddata() ");
// TimeManipulations();
// Log.d(" Launch method ", " othermainupulations() ");
// //OtherManipulations();
// Log.d(" Launch method ", " savedata() ");
// SaveData();
RelativeLayout SkyLayout = (RelativeLayout) findViewById(R.id.SkyLayout);
// BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
// bottomNav.setOnNavigationItemSelectedListener(navListener);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.bottom_navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
//I added this if statement to keep the selected fragment when rotating the device
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
fm.beginTransaction().add(R.id.fragment_container, fragment3, "3").hide(fragment3).commit();
fm.beginTransaction().add(R.id.fragment_container, fragment2, "2").hide(fragment2).commit();
fm.beginTransaction().add(R.id.fragment_container,fragment1, "1").commit();
}
@Override
protected void onResume() {
super.onResume();
Log.d("Lifecycle ->"," onResume launch ");
LoadData();
}
@Override
protected void onPause() {
super.onPause();
Log.d("Lifecycle ->"," onPause launch ");
SaveData();
}
@Override
protected void onStop() {
super.onStop();
Log.d("Lifecycle ->"," onStop launch ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("Lifecycle ->"," onDestroy launch ");
}
@RequiresApi(api = Build.VERSION_CODES.N)
public void runforecast() {
//////////////////////////////////////////////
// Click from Fragment //
//////////////////////////////////////////////
LoadData();
getCurrentData();
TimeManipulations();
SaveData();
// OtherManipulations();
}
@RequiresApi(api = Build.VERSION_CODES.N)
void getCurrentData() {
// // Before all, we load coordinations and nominal power of station
SharedPreferences sharedPreferences = getSharedPreferences("MasterSave", MODE_PRIVATE);
lat = sharedPreferences.getString("lati",lat);
lon = sharedPreferences.getString("long",lon);
// NominalPower = sharedPreferences.getFloat("Nominal_Power", (float) NominalPower);
//city = sharedPreferences.getString("MyCity",city);
//NominalPower = 1000;
//CITY = "Mexico";
//NominalPower = 29000;
OkHttpClient.Builder okhttpClientBuilder = new OkHttpClient.Builder();//for create a LOGs
HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); //for create a LOGs
logging.setLevel(HttpLoggingInterceptor.Level.BODY); //for create a LOGs
okhttpClientBuilder.addInterceptor(logging); //for create a LOGs
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(okhttpClientBuilder.build()) //for create a LOGs
.build();
WeatherService service = retrofit.create(WeatherService.class);
//Call<WeatherResponse> call = service.getCurrentWeatherData(CITY, metric, AppId);
Call<WeatherResponse> call = service.getCurrentWeatherData(lat, lon, metric, AppId);
call.enqueue(new Callback<WeatherResponse>() {
@Override
public void onResponse(@NonNull Call<WeatherResponse> call, @NonNull Response<WeatherResponse> response) {
if (response.code() == 200) {
WeatherResponse weatherResponse = response.body();
assert weatherResponse != null;
isDataAvailable = true;
// Log.d("RETROFITTTTTTTT ", weatherResponse+" ");
//main variables
cloud = weatherResponse.clouds.all;
temp = weatherResponse.main.temp;
windF = weatherResponse.wind.speed;
country = weatherResponse.sys.country;
unixSunrise = weatherResponse. sys.sunrise;
unixSunset = weatherResponse.sys.sunset; // time of sunrise and sunset
city = weatherResponse.name; // i added two variable and this work, before i dont see this in Toast.
pressure = weatherResponse.main.pressure;
humidity = weatherResponse.main.humidity;
GMT = weatherResponse.timezone;
UnixCurrentTime = (long) weatherResponse.dt;
Log.d("From retrofit ", "Temp and press " + temp+ " "+ pressure);
// unixSunrise = weatherResponse.sunrise;
// unixSunset = weatherResponse.sunset; // time of sunrise and sunset
// try {
// desription = weatherResponse.weather.description;
// }catch (Exception e){
// Log.d("################DEPLOY", "descript dont work");
// }
if (cloud >-1 ){
CurrentPower = NominalPower - NominalPower*(cloud/100)*0.8f;
}else{
CurrentPower = 404;
}
}
}
@Override
public void onFailure(@NonNull Call<WeatherResponse> call, @NonNull Throwable t) {
Context context = getApplicationContext();
CharSequence text = "Check Internet connection. Fail in Response"+t.getMessage();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
Call<WeatherForecastResponse> forecastCall = service.getDailyData(lat, lon, metric, AppId);
forecastCall.enqueue(new Callback<WeatherForecastResponse>() {
@Override
public void onResponse(@NonNull Call<WeatherForecastResponse> forecastCall, @NonNull Response<WeatherForecastResponse> response) {
if (response.code() == 200) {
WeatherForecastResponse weatherResponse = response.body();
assert weatherResponse != null;
ArrayList<WeatherResponse> list = weatherResponse.list;
if (dataMap.size() == 0){
for(WeatherResponse wr: list){
// .put (Key, Clouds.all)
CurrentPowerHashMap = NominalPower - NominalPower * (wr.clouds.all / 100) * 0.8f;
TimeHashMap = (long) wr.dt * 1000;
//if (unixSunrise )
dataMap.put(TimeHashMap, CurrentPowerHashMap);
Log.d("Datamap ->", TimeHashMap+" "+ CurrentPowerHashMap);
// try {
// }catch (Exception e){
// Log.d("my Error", "in retrofit array");
// }
//list.dt -- is Time of data forecasted, unix, UTC
//Toast.makeText(getApplicationContext(), (CharSequence) dataMap, Toast.LENGTH_LONG).show();
}
}
}
}
@Override
public void onFailure(@NonNull Call<WeatherForecastResponse> forecastCall, @NonNull Throwable t) {
Context context = getApplicationContext();
CharSequence text = "Fail in Response"+t.getMessage();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
windI = Math.round(windF);
if (temp>30){
HotCheck = true;
}
//SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
//SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putString("MyCity",city);
// editor.apply();
Log.d("From retrofit ", "Sunrise and sunset " + unixSunrise+ " "+ unixSunset);
Log.d("From retrofit ", GMT +"GMT now ");
Log.d("From retrofit ", UnixCurrentTime +"current time ");
Log.d("$$$$$$$$$$", GMT +"Responce: " +city+country);
Log.d("$$$$$$$$$$", GMT +"Responce: " +city+country+ "Current power "+ CurrentPower + " cloud " + cloud);
Log.d("%%%%%%%%%%%%%%", " "+ dataMap);
//TimeManipulations();
}
public void TimeManipulations(){
////////////////////////////////////////////////////
// Time zone & unix sunrise/sunset //
// //
////////////////////////////////////////////////////
UTCtime = System.currentTimeMillis(); // Here i have been problem coz i multipled on 1000L UTC time:(
UnixCurrentTime = UTCtime;
unixSunrise = unixSunrise* 1000L;
unixSunset = unixSunset* 1000L;
String hours = String.valueOf((GMT/3600));
String blankGMT = "GMT";
String finalblank;
if (GMT>0){
finalblank= blankGMT+"+"+hours;
}else{
finalblank= blankGMT+hours;
}
TimeZone tz = TimeZone.getTimeZone(finalblank);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
sdf.setTimeZone(tz);
Date netDate = (new Date(unixSunrise));
sunrise = sdf.format(netDate);
Date netDate2 = (new Date(unixSunset));
sunset = sdf.format(netDate2);
SimpleDateFormat sd = new SimpleDateFormat("HH:mm");
sd.setTimeZone(tz);
Date netDate3 = (new Date(UnixCurrentTime));
hournowStr = (sd.format(netDate3));
int hournow = Integer.parseInt(hournowStr.substring(0, hournowStr.length() - 3));
int hourRise = Integer.parseInt(sunrise.substring(0, sunrise.length() - 3));
int hourSet = Integer.parseInt(sunset.substring(0, sunset.length() - 3));
Log.d("?????????????????", "UTC -> "+UTCtime +" \\// "+UnixCurrentTime+ " UnixVar ->" + " hour now -> " + hournow+" and hournow str -> "+ hournowStr+ " ... ... "+hourRise+" "+ hourSet +" gmt -> "+ finalblank);
int sector = (hourSet - hourRise)/5;
//set Sun Position
if (hournow >hourSet){
SunPeriod=0;
//Toast.makeText(this, "NIGHT", Toast.LENGTH_SHORT).show();
}else if (hournow >hourSet - sector){
//Toast.makeText(this, "sunset", Toast.LENGTH_SHORT).show();
SunPeriod=5;
}else if (hournow >hourSet - 2*sector){
//Toast.makeText(this, "135", Toast.LENGTH_SHORT).show();
SunPeriod=4;
}else if (hournow >hourSet - 3*sector){
//Toast.makeText(this, "90", Toast.LENGTH_SHORT).show();
SunPeriod=3;
}else if (hournow >hourSet - 4*sector){
//Toast.makeText(this, "45", Toast.LENGTH_SHORT).show();
SunPeriod=2;
}else if (hournow >hourRise){
//Toast.makeText(this, "sunrise", Toast.LENGTH_SHORT).show();
SunPeriod=1;
}else {
SunPeriod=0;
// Toast.makeText(this, "NIGHT", Toast.LENGTH_SHORT).show();
}
CurrentPowerInt = Math.round(CurrentPower);
if (SunPeriod==0){
CurrentPowerInt = 0;
}
solarhoursString = String.valueOf(hourSet-hourRise);
Log.d("##########", " "+sunrise+" "+sunset + " unix -> " +unixSunrise + " GMT is ->" + GMT +" TZ is -> "+ finalblank);
// SharedPreferences sharedPreferences = getSharedPreferences("MasterSave", MODE_PRIVATE);
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putLong("GMT",GMT);
//editor.putLong("GMT",UTCtime);
// LinkedHashMap<Long, Float> corvette = new LinkedHashMap<>();
// LinkedHashMap<Long, Float> dataMap = new LinkedHashMap<>();
// dataMap.put(1L,242487489f);
// dataMap.put(2L,242487189f);
// dataMap.put(3L,242487289f);
// dataMap.put(4L,242484789f);
int a = 0;
for(Map.Entry<Long, Float> entry : dataMap.entrySet()) {
long key = (entry.getKey());
float value = (entry.getValue());
SimpleDateFormat sd4 = new SimpleDateFormat("HH:mm");
sd4.setTimeZone(tz);
Date netDate4 = (new Date(key));
String ModernTime = (sd4.format(netDate4));
// SimpleDateFormat sd5 = new SimpleDateFormat("yyyy MM-dd HH:mm");
// sd4.setTimeZone(tz);
// Date netDate5 = (new Date(key));
// String ModernTime5 = (sd5.format(netDate5));
//
// Log.d(" loop, new format", " -> "+ ModernTime5+ " and value "+ value);
// int hournow = Integer.parseInt(hournowStr.substring(0, hournowStr.length() - 3));
// int hourRise = Integer.parseInt(sunrise.substring(0, sunrise.length() - 3));
// int hourSet = Integer.parseInt(sunset.substring(0, sunset.length() - 3));
//////////////
//long time = (key+GMT); //???????????
//String ModernTime = DateFormat.format("HH:mm", time).toString();
Log.d("Hashmap test loop -> ", "key : "+ key + " value : "+ value);
int transitTime = Integer.parseInt(ModernTime.substring(0, ModernTime.length() - 3));
if (transitTime>hourSet){
//0
corvette.put(ModernTime, value*0f);
}else if (transitTime>hourSet-sector){
//0.6
corvette.put(ModernTime, value*0.6f);
}else if (transitTime>hourSet-2*sector){
//0.8
corvette.put(ModernTime, value*0.8f);
}else if (transitTime>hourSet-3*sector){
//1
corvette.put(ModernTime, value);
}else if (transitTime>hourSet-4*sector){
//0.8
corvette.put(ModernTime, value*0.8f);
}else if (transitTime>hourSet-5*sector){
//0.6
corvette.put(ModernTime, value*0.6f);
}else{
//0
corvette.put(ModernTime, value*0f);
}
a++;
Log.d(" loop ", a+" times ");
}
//////////////////////////////////////////////////////////////////////////
// convert to gson and save //
//////////////////////////////////////////////////////////////////////////
SharedPreferences sharedPreferences = getSharedPreferences("MasterSave", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
jsonString = new Gson().toJson(corvette);
editor.putString("map", jsonString); // this hashmap
editor.apply(); // added apply and this works!
Log.d("Hash map corvette -> ", " "+ corvette + "json -> "+ jsonString);
}
public void SaveData(){
SharedPreferences sharedPreferences = getSharedPreferences("MasterSave", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("CurPow",CurrentPowerInt);
editor.putLong("GMT",GMT);
editor.putBoolean("tempScale",tempScale);
editor.putFloat("temp",temp);
editor.putFloat("pressure",pressure);
editor.putFloat("humidity",humidity);
editor.putString("sunrise",sunrise);
editor.putString("sunset",sunset);
//editor.putString("map", jsonString); // this hashmap
editor.putString("MyCity",city);
editor.apply();
Log.d("@@@@@@@@@@@@", "GMT: "+GMT);
Log.d("@@@@@@@@@@@@", "temp: "+temp);
Log.d("@@@@@@@@@@@@", "JSON: "+jsonString);
Log.d("@@@@@@@@@@@@", "CITY: "+city);
}
public void LoadData(){
// Before all, we load coordinations and nominal power of station
SharedPreferences sharedPreferences = getSharedPreferences("MasterSave",MODE_PRIVATE);
//Check Savings
Map<String, ?> allPrefs = sharedPreferences.getAll(); //your sharedPreference
Set<String> set = allPrefs.keySet();
for(String s : set){
Log.d("Shared Pref", s + "<" + allPrefs.get(s).getClass().getSimpleName() +"> = "
+ allPrefs.get(s).toString());
}
lat = sharedPreferences.getString("lati",lat);
lon = sharedPreferences.getString("long",lon);
city = sharedPreferences.getString("MyCity",city);
NominalPower = sharedPreferences.getFloat("Nominal_Power",(float)NominalPower);
sunrise = sharedPreferences.getString("sunrise",sunrise);
sunset = sharedPreferences.getString("sunset",sunset);
Log.d("************", "LAT LOT: "+lat+ " and " + lon);
Log.d("************", "GMT: "+GMT);
Log.d("************", "temp: "+temp);
Log.d("************", "JSON: "+jsonString);
Log.d("************", "CITY: "+city);
}
public int getWindSpeed() {
return windI;
}
public int getSunPeriod() {
return SunPeriod;
}
public String getSolarHours() {
return solarhoursString;
}
public String getSunrisetime() {
return sunrise;
}
public String getSunsetime() {
return sunset;
}
public int getCurrentPowerData() {
return CurrentPowerInt;
}
public String getСityData() {
return city;
}
public Boolean HotCheck(){ return HotCheck; }
public Boolean isDataAvailable(){ return isDataAvailable; }
//public LinkedHashMap<String, Float> getDataPointsData() { return dataMap; }
public Float getNominalPower() {return NominalPower;}
@RequiresApi(api = Build.VERSION_CODES.N)
//switcher of fragmnets, he help for switching without loss filled form in fragments
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
fm.beginTransaction().hide(active).show(fragment1).commit();
active = fragment1;
return true;
case R.id.nav_settings:
fm.beginTransaction().hide(active).show(fragment2).commit();
active = fragment2;
return true;
//beginTransaction().hide(fragment1).hide(fragment3).show(fragment2).commit()
case R.id.nav_sidekick:
fm.beginTransaction().hide(active).show(fragment3).commit();
active = fragment3;
return true;
}
return false;
}
};
public void seven(View view) {
startActivity(new Intent(MainActivity.this, MapsActivity.class));
}
public void toast0(View view) {
Toast.makeText(this, " It`s CURRENT POWER output of your solar panels, with accountant weather data ", Toast.LENGTH_SHORT).show();
}
public void toast1(View view) {
Toast.makeText(this, " Its time of sunrise ", Toast.LENGTH_SHORT).show();
}
public void toast2(View view) {
Toast.makeText(this, " Its sunshine duration ", Toast.LENGTH_SHORT).show();
}
public void toast3(View view) {
Toast.makeText(this, " Its time of sunset ", Toast.LENGTH_SHORT).show();
}
}
|
UTF-8
|
Java
| 25,774 |
java
|
MainActivity.java
|
Java
|
[] | null |
[] |
package com.revolve44.fragments22;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Display;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.gson.Gson;
import com.revolve44.fragments22.recyclerview.Model;
import com.revolve44.fragments22.recyclerview.MultiViewTypeAdapter;
import com.revolve44.fragments22.ui.HomeFragment;
import com.revolve44.fragments22.ui.CalcFragment;
import com.revolve44.fragments22.ui.SidekickFragment;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.ExecutionException;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/*
Внимание! при каждом запуске эмулятора ставь правильную дату на эмуляторе
ото бывает время восхода и заката не схадятся из за разницы дат и времени
*/
/*
TODO: The main functions of this class: communication with Weather API,
get main variables (cloud, temp coefficient, sunrise sunset time)
*/
public class MainActivity extends AppCompatActivity {
private View root;
final Fragment fragment1 = new HomeFragment();
final Fragment fragment2 = new CalcFragment();
final Fragment fragment3 = new SidekickFragment();
final FragmentManager fm = getSupportFragmentManager();
Fragment active = fragment1;
RelativeLayout SkyLayout;
//Example
//api.openweathermap.org/data/2.5/weather?q=moscow&appid=1b87fee17221ed7893aa488cff08bfa2
// http://api.openweathermap.org/data/2.5/find?lat=55.5&lon=37.5&cnt=10&appid=ac79fea59e9d15377b787a610a29b784
public static String BaseUrl = "https://api.openweathermap.org/";
public static String CITY = "Moscow";
public static String AppId = "4e78fa71de97f97aa376e42f2f1c99cf";
public static String MC = "&units=metric&appid=";
public TextView temperatureText;
public TextView windText;
public static String lat;
public static String lon;
public static String metric = "metric";
//Variables
public float NominalPower;//????????????????????????????????
public float CurrentPower;
public int CurrentPowerInt;
public float cloud;
public float windF;
public int windI;
public float temp;
public String desription;
public float pressure;
public float humidity;
public boolean tempScale;
public long unixSunrise;
public long unixSunset;
public String city;
public String country;
//public String
public boolean isDataAvailable = false;
public final LinkedHashMap<Long, Float> dataMap = new LinkedHashMap<>();
public LinkedHashMap<String, Float> corvette = new LinkedHashMap<>();
public String sunset;
public String sunrise;
public String hournowStr;
public TextView mainoutput;
public TextView saymayname;
public long TimeHashMap;
public float CurrentPowerHashMap;
Boolean HotCheck= false;
int SunPeriod = 0;
public String solarhoursString;
public long GMT = 0;
public long UTCtime;
public long UnixCurrentTime;
public String jsonString;
//Context context;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Lifecycle ->"," onCreate launch ");
SharedPreferences sharedPreferences = this.getSharedPreferences("MasterSave", MODE_PRIVATE);
if (!sharedPreferences.getBoolean("firstTime", false)) {
// <---- run your one time code here
Intent intent2 = new Intent(this, MapsActivity.class);
startActivity(intent2);
}
//setContentView(R.layout.activity_main);
mainoutput = findViewById(R.id.Forecast_number);
lat = getIntent().getStringExtra("FROM_MAPS1");
lon = getIntent().getStringExtra("FROM_MAPS2");
///////////////////////////////////////////////////////////////////////////////////////////
// Launch Pad //
///////////////////////////////////////////////////////////////////////////////////////////
// Log.d(" Launch method ", " loaddata() ");
// LoadData();
// Log.d(" Launch method ", " getcurrentdata() ");
// getCurrentData();
// Log.d(" Launch method ", " loaddata() ");
// TimeManipulations();
// Log.d(" Launch method ", " othermainupulations() ");
// //OtherManipulations();
// Log.d(" Launch method ", " savedata() ");
// SaveData();
RelativeLayout SkyLayout = (RelativeLayout) findViewById(R.id.SkyLayout);
// BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
// bottomNav.setOnNavigationItemSelectedListener(navListener);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.bottom_navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
//I added this if statement to keep the selected fragment when rotating the device
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
fm.beginTransaction().add(R.id.fragment_container, fragment3, "3").hide(fragment3).commit();
fm.beginTransaction().add(R.id.fragment_container, fragment2, "2").hide(fragment2).commit();
fm.beginTransaction().add(R.id.fragment_container,fragment1, "1").commit();
}
@Override
protected void onResume() {
super.onResume();
Log.d("Lifecycle ->"," onResume launch ");
LoadData();
}
@Override
protected void onPause() {
super.onPause();
Log.d("Lifecycle ->"," onPause launch ");
SaveData();
}
@Override
protected void onStop() {
super.onStop();
Log.d("Lifecycle ->"," onStop launch ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("Lifecycle ->"," onDestroy launch ");
}
@RequiresApi(api = Build.VERSION_CODES.N)
public void runforecast() {
//////////////////////////////////////////////
// Click from Fragment //
//////////////////////////////////////////////
LoadData();
getCurrentData();
TimeManipulations();
SaveData();
// OtherManipulations();
}
@RequiresApi(api = Build.VERSION_CODES.N)
void getCurrentData() {
// // Before all, we load coordinations and nominal power of station
SharedPreferences sharedPreferences = getSharedPreferences("MasterSave", MODE_PRIVATE);
lat = sharedPreferences.getString("lati",lat);
lon = sharedPreferences.getString("long",lon);
// NominalPower = sharedPreferences.getFloat("Nominal_Power", (float) NominalPower);
//city = sharedPreferences.getString("MyCity",city);
//NominalPower = 1000;
//CITY = "Mexico";
//NominalPower = 29000;
OkHttpClient.Builder okhttpClientBuilder = new OkHttpClient.Builder();//for create a LOGs
HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); //for create a LOGs
logging.setLevel(HttpLoggingInterceptor.Level.BODY); //for create a LOGs
okhttpClientBuilder.addInterceptor(logging); //for create a LOGs
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(okhttpClientBuilder.build()) //for create a LOGs
.build();
WeatherService service = retrofit.create(WeatherService.class);
//Call<WeatherResponse> call = service.getCurrentWeatherData(CITY, metric, AppId);
Call<WeatherResponse> call = service.getCurrentWeatherData(lat, lon, metric, AppId);
call.enqueue(new Callback<WeatherResponse>() {
@Override
public void onResponse(@NonNull Call<WeatherResponse> call, @NonNull Response<WeatherResponse> response) {
if (response.code() == 200) {
WeatherResponse weatherResponse = response.body();
assert weatherResponse != null;
isDataAvailable = true;
// Log.d("RETROFITTTTTTTT ", weatherResponse+" ");
//main variables
cloud = weatherResponse.clouds.all;
temp = weatherResponse.main.temp;
windF = weatherResponse.wind.speed;
country = weatherResponse.sys.country;
unixSunrise = weatherResponse. sys.sunrise;
unixSunset = weatherResponse.sys.sunset; // time of sunrise and sunset
city = weatherResponse.name; // i added two variable and this work, before i dont see this in Toast.
pressure = weatherResponse.main.pressure;
humidity = weatherResponse.main.humidity;
GMT = weatherResponse.timezone;
UnixCurrentTime = (long) weatherResponse.dt;
Log.d("From retrofit ", "Temp and press " + temp+ " "+ pressure);
// unixSunrise = weatherResponse.sunrise;
// unixSunset = weatherResponse.sunset; // time of sunrise and sunset
// try {
// desription = weatherResponse.weather.description;
// }catch (Exception e){
// Log.d("################DEPLOY", "descript dont work");
// }
if (cloud >-1 ){
CurrentPower = NominalPower - NominalPower*(cloud/100)*0.8f;
}else{
CurrentPower = 404;
}
}
}
@Override
public void onFailure(@NonNull Call<WeatherResponse> call, @NonNull Throwable t) {
Context context = getApplicationContext();
CharSequence text = "Check Internet connection. Fail in Response"+t.getMessage();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
Call<WeatherForecastResponse> forecastCall = service.getDailyData(lat, lon, metric, AppId);
forecastCall.enqueue(new Callback<WeatherForecastResponse>() {
@Override
public void onResponse(@NonNull Call<WeatherForecastResponse> forecastCall, @NonNull Response<WeatherForecastResponse> response) {
if (response.code() == 200) {
WeatherForecastResponse weatherResponse = response.body();
assert weatherResponse != null;
ArrayList<WeatherResponse> list = weatherResponse.list;
if (dataMap.size() == 0){
for(WeatherResponse wr: list){
// .put (Key, Clouds.all)
CurrentPowerHashMap = NominalPower - NominalPower * (wr.clouds.all / 100) * 0.8f;
TimeHashMap = (long) wr.dt * 1000;
//if (unixSunrise )
dataMap.put(TimeHashMap, CurrentPowerHashMap);
Log.d("Datamap ->", TimeHashMap+" "+ CurrentPowerHashMap);
// try {
// }catch (Exception e){
// Log.d("my Error", "in retrofit array");
// }
//list.dt -- is Time of data forecasted, unix, UTC
//Toast.makeText(getApplicationContext(), (CharSequence) dataMap, Toast.LENGTH_LONG).show();
}
}
}
}
@Override
public void onFailure(@NonNull Call<WeatherForecastResponse> forecastCall, @NonNull Throwable t) {
Context context = getApplicationContext();
CharSequence text = "Fail in Response"+t.getMessage();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
windI = Math.round(windF);
if (temp>30){
HotCheck = true;
}
//SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
//SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putString("MyCity",city);
// editor.apply();
Log.d("From retrofit ", "Sunrise and sunset " + unixSunrise+ " "+ unixSunset);
Log.d("From retrofit ", GMT +"GMT now ");
Log.d("From retrofit ", UnixCurrentTime +"current time ");
Log.d("$$$$$$$$$$", GMT +"Responce: " +city+country);
Log.d("$$$$$$$$$$", GMT +"Responce: " +city+country+ "Current power "+ CurrentPower + " cloud " + cloud);
Log.d("%%%%%%%%%%%%%%", " "+ dataMap);
//TimeManipulations();
}
public void TimeManipulations(){
////////////////////////////////////////////////////
// Time zone & unix sunrise/sunset //
// //
////////////////////////////////////////////////////
UTCtime = System.currentTimeMillis(); // Here i have been problem coz i multipled on 1000L UTC time:(
UnixCurrentTime = UTCtime;
unixSunrise = unixSunrise* 1000L;
unixSunset = unixSunset* 1000L;
String hours = String.valueOf((GMT/3600));
String blankGMT = "GMT";
String finalblank;
if (GMT>0){
finalblank= blankGMT+"+"+hours;
}else{
finalblank= blankGMT+hours;
}
TimeZone tz = TimeZone.getTimeZone(finalblank);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
sdf.setTimeZone(tz);
Date netDate = (new Date(unixSunrise));
sunrise = sdf.format(netDate);
Date netDate2 = (new Date(unixSunset));
sunset = sdf.format(netDate2);
SimpleDateFormat sd = new SimpleDateFormat("HH:mm");
sd.setTimeZone(tz);
Date netDate3 = (new Date(UnixCurrentTime));
hournowStr = (sd.format(netDate3));
int hournow = Integer.parseInt(hournowStr.substring(0, hournowStr.length() - 3));
int hourRise = Integer.parseInt(sunrise.substring(0, sunrise.length() - 3));
int hourSet = Integer.parseInt(sunset.substring(0, sunset.length() - 3));
Log.d("?????????????????", "UTC -> "+UTCtime +" \\// "+UnixCurrentTime+ " UnixVar ->" + " hour now -> " + hournow+" and hournow str -> "+ hournowStr+ " ... ... "+hourRise+" "+ hourSet +" gmt -> "+ finalblank);
int sector = (hourSet - hourRise)/5;
//set Sun Position
if (hournow >hourSet){
SunPeriod=0;
//Toast.makeText(this, "NIGHT", Toast.LENGTH_SHORT).show();
}else if (hournow >hourSet - sector){
//Toast.makeText(this, "sunset", Toast.LENGTH_SHORT).show();
SunPeriod=5;
}else if (hournow >hourSet - 2*sector){
//Toast.makeText(this, "135", Toast.LENGTH_SHORT).show();
SunPeriod=4;
}else if (hournow >hourSet - 3*sector){
//Toast.makeText(this, "90", Toast.LENGTH_SHORT).show();
SunPeriod=3;
}else if (hournow >hourSet - 4*sector){
//Toast.makeText(this, "45", Toast.LENGTH_SHORT).show();
SunPeriod=2;
}else if (hournow >hourRise){
//Toast.makeText(this, "sunrise", Toast.LENGTH_SHORT).show();
SunPeriod=1;
}else {
SunPeriod=0;
// Toast.makeText(this, "NIGHT", Toast.LENGTH_SHORT).show();
}
CurrentPowerInt = Math.round(CurrentPower);
if (SunPeriod==0){
CurrentPowerInt = 0;
}
solarhoursString = String.valueOf(hourSet-hourRise);
Log.d("##########", " "+sunrise+" "+sunset + " unix -> " +unixSunrise + " GMT is ->" + GMT +" TZ is -> "+ finalblank);
// SharedPreferences sharedPreferences = getSharedPreferences("MasterSave", MODE_PRIVATE);
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putLong("GMT",GMT);
//editor.putLong("GMT",UTCtime);
// LinkedHashMap<Long, Float> corvette = new LinkedHashMap<>();
// LinkedHashMap<Long, Float> dataMap = new LinkedHashMap<>();
// dataMap.put(1L,242487489f);
// dataMap.put(2L,242487189f);
// dataMap.put(3L,242487289f);
// dataMap.put(4L,242484789f);
int a = 0;
for(Map.Entry<Long, Float> entry : dataMap.entrySet()) {
long key = (entry.getKey());
float value = (entry.getValue());
SimpleDateFormat sd4 = new SimpleDateFormat("HH:mm");
sd4.setTimeZone(tz);
Date netDate4 = (new Date(key));
String ModernTime = (sd4.format(netDate4));
// SimpleDateFormat sd5 = new SimpleDateFormat("yyyy MM-dd HH:mm");
// sd4.setTimeZone(tz);
// Date netDate5 = (new Date(key));
// String ModernTime5 = (sd5.format(netDate5));
//
// Log.d(" loop, new format", " -> "+ ModernTime5+ " and value "+ value);
// int hournow = Integer.parseInt(hournowStr.substring(0, hournowStr.length() - 3));
// int hourRise = Integer.parseInt(sunrise.substring(0, sunrise.length() - 3));
// int hourSet = Integer.parseInt(sunset.substring(0, sunset.length() - 3));
//////////////
//long time = (key+GMT); //???????????
//String ModernTime = DateFormat.format("HH:mm", time).toString();
Log.d("Hashmap test loop -> ", "key : "+ key + " value : "+ value);
int transitTime = Integer.parseInt(ModernTime.substring(0, ModernTime.length() - 3));
if (transitTime>hourSet){
//0
corvette.put(ModernTime, value*0f);
}else if (transitTime>hourSet-sector){
//0.6
corvette.put(ModernTime, value*0.6f);
}else if (transitTime>hourSet-2*sector){
//0.8
corvette.put(ModernTime, value*0.8f);
}else if (transitTime>hourSet-3*sector){
//1
corvette.put(ModernTime, value);
}else if (transitTime>hourSet-4*sector){
//0.8
corvette.put(ModernTime, value*0.8f);
}else if (transitTime>hourSet-5*sector){
//0.6
corvette.put(ModernTime, value*0.6f);
}else{
//0
corvette.put(ModernTime, value*0f);
}
a++;
Log.d(" loop ", a+" times ");
}
//////////////////////////////////////////////////////////////////////////
// convert to gson and save //
//////////////////////////////////////////////////////////////////////////
SharedPreferences sharedPreferences = getSharedPreferences("MasterSave", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
jsonString = new Gson().toJson(corvette);
editor.putString("map", jsonString); // this hashmap
editor.apply(); // added apply and this works!
Log.d("Hash map corvette -> ", " "+ corvette + "json -> "+ jsonString);
}
public void SaveData(){
SharedPreferences sharedPreferences = getSharedPreferences("MasterSave", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("CurPow",CurrentPowerInt);
editor.putLong("GMT",GMT);
editor.putBoolean("tempScale",tempScale);
editor.putFloat("temp",temp);
editor.putFloat("pressure",pressure);
editor.putFloat("humidity",humidity);
editor.putString("sunrise",sunrise);
editor.putString("sunset",sunset);
//editor.putString("map", jsonString); // this hashmap
editor.putString("MyCity",city);
editor.apply();
Log.d("@@@@@@@@@@@@", "GMT: "+GMT);
Log.d("@@@@@@@@@@@@", "temp: "+temp);
Log.d("@@@@@@@@@@@@", "JSON: "+jsonString);
Log.d("@@@@@@@@@@@@", "CITY: "+city);
}
public void LoadData(){
// Before all, we load coordinations and nominal power of station
SharedPreferences sharedPreferences = getSharedPreferences("MasterSave",MODE_PRIVATE);
//Check Savings
Map<String, ?> allPrefs = sharedPreferences.getAll(); //your sharedPreference
Set<String> set = allPrefs.keySet();
for(String s : set){
Log.d("Shared Pref", s + "<" + allPrefs.get(s).getClass().getSimpleName() +"> = "
+ allPrefs.get(s).toString());
}
lat = sharedPreferences.getString("lati",lat);
lon = sharedPreferences.getString("long",lon);
city = sharedPreferences.getString("MyCity",city);
NominalPower = sharedPreferences.getFloat("Nominal_Power",(float)NominalPower);
sunrise = sharedPreferences.getString("sunrise",sunrise);
sunset = sharedPreferences.getString("sunset",sunset);
Log.d("************", "LAT LOT: "+lat+ " and " + lon);
Log.d("************", "GMT: "+GMT);
Log.d("************", "temp: "+temp);
Log.d("************", "JSON: "+jsonString);
Log.d("************", "CITY: "+city);
}
public int getWindSpeed() {
return windI;
}
public int getSunPeriod() {
return SunPeriod;
}
public String getSolarHours() {
return solarhoursString;
}
public String getSunrisetime() {
return sunrise;
}
public String getSunsetime() {
return sunset;
}
public int getCurrentPowerData() {
return CurrentPowerInt;
}
public String getСityData() {
return city;
}
public Boolean HotCheck(){ return HotCheck; }
public Boolean isDataAvailable(){ return isDataAvailable; }
//public LinkedHashMap<String, Float> getDataPointsData() { return dataMap; }
public Float getNominalPower() {return NominalPower;}
@RequiresApi(api = Build.VERSION_CODES.N)
//switcher of fragmnets, he help for switching without loss filled form in fragments
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
fm.beginTransaction().hide(active).show(fragment1).commit();
active = fragment1;
return true;
case R.id.nav_settings:
fm.beginTransaction().hide(active).show(fragment2).commit();
active = fragment2;
return true;
//beginTransaction().hide(fragment1).hide(fragment3).show(fragment2).commit()
case R.id.nav_sidekick:
fm.beginTransaction().hide(active).show(fragment3).commit();
active = fragment3;
return true;
}
return false;
}
};
public void seven(View view) {
startActivity(new Intent(MainActivity.this, MapsActivity.class));
}
public void toast0(View view) {
Toast.makeText(this, " It`s CURRENT POWER output of your solar panels, with accountant weather data ", Toast.LENGTH_SHORT).show();
}
public void toast1(View view) {
Toast.makeText(this, " Its time of sunrise ", Toast.LENGTH_SHORT).show();
}
public void toast2(View view) {
Toast.makeText(this, " Its sunshine duration ", Toast.LENGTH_SHORT).show();
}
public void toast3(View view) {
Toast.makeText(this, " Its time of sunset ", Toast.LENGTH_SHORT).show();
}
}
| 25,774 | 0.578441 | 0.566745 | 680 | 36.719116 | 30.835268 | 217 | false | false | 0 | 0 | 0 | 0 | 94 | 0.013099 | 0.758824 | false | false |
14
|
1f47f167fc640965f0886496f4ee7d16f8a1c387
| 21,294,447,886,598 |
77fe48285f70ba713125ac180c3daeb1a45168ee
|
/src/com/kjwork/util/test/TestBase64.java
|
f4fe8bd5f2aa074033558da30110718d943c0371
|
[] |
no_license
|
kjhermans/cryptofile
|
https://github.com/kjhermans/cryptofile
|
7dbcc3f1c7175009f00c2f22ba6236a1a5c1499a
|
5bd1acb1130a9b05b2a50572cb9323a24ba5e0d4
|
refs/heads/master
| 2021-01-10T19:34:14.309000 | 2015-09-13T19:43:13 | 2015-09-13T19:43:13 | 42,331,850 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kjwork.util.test;
import com.kjwork.util.Base64;
public class TestBase64 {
public static void main(String[] args) {
for (int i=0; i < 30; i++) {
int msglen = (int)(Math.random() * 100);
byte[] msg = new byte[ msglen ];
for (int j=0; j < msglen; j++) {
msg[ j ] = (byte)(Math.random() * 256);
}
test_message(msg);
System.err.println("");
}
}
private static void test_message(byte[] msg) {
String base64 = Base64.encode(msg);
System.err.println("Original message length is " + msg.length);
System.err.print(base64);
byte[] bin = Base64.decode(base64);
if (msg.length != bin.length) {
System.err.println(
"Messages are not the same length: " +
msg.length + " != " + bin.length
);
return;
}
for (int i=0; i < msg.length; i++) {
if (msg[ i ] != bin[ i ]) {
System.err.println("Message differ at byte " + i);
return;
}
}
System.err.println("Messages are identical.");
}
}
|
UTF-8
|
Java
| 964 |
java
|
TestBase64.java
|
Java
|
[] | null |
[] |
package com.kjwork.util.test;
import com.kjwork.util.Base64;
public class TestBase64 {
public static void main(String[] args) {
for (int i=0; i < 30; i++) {
int msglen = (int)(Math.random() * 100);
byte[] msg = new byte[ msglen ];
for (int j=0; j < msglen; j++) {
msg[ j ] = (byte)(Math.random() * 256);
}
test_message(msg);
System.err.println("");
}
}
private static void test_message(byte[] msg) {
String base64 = Base64.encode(msg);
System.err.println("Original message length is " + msg.length);
System.err.print(base64);
byte[] bin = Base64.decode(base64);
if (msg.length != bin.length) {
System.err.println(
"Messages are not the same length: " +
msg.length + " != " + bin.length
);
return;
}
for (int i=0; i < msg.length; i++) {
if (msg[ i ] != bin[ i ]) {
System.err.println("Message differ at byte " + i);
return;
}
}
System.err.println("Messages are identical.");
}
}
| 964 | 0.594398 | 0.568465 | 40 | 23.1 | 18.221964 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.575 | false | false |
14
|
087ed738d79893641ddb697baa1b9eb6780fd349
| 23,218,593,249,532 |
af7c8e493be053d600d21a6b7eaba55844e2269e
|
/Westwinglife/commonLibrary/src/main/java/common/selector/StringSelectorActivity.java
|
6e27bb07debb366a255cbc76b599b2e16723d670
|
[] |
no_license
|
wutianchi/Tudou-android
|
https://github.com/wutianchi/Tudou-android
|
fa8cb86d33ecef0ed3bdddcaf2069a55efb0bff1
|
d73db454eeb26ac7c85090778097add0bc7a9271
|
refs/heads/master
| 2021-01-09T06:04:15.980000 | 2017-02-04T04:42:35 | 2017-02-04T04:42:35 | 80,893,685 | 5 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package common.selector;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.gunlei.app.R;
import com.gunlei.app.ui.base.BaseTitleActivity;
import com.gunlei.app.ui.util.StringUtil;
import com.gunlei.app.ui.util.ViewFinderUtil;
/**
* 字符串单选Activity.
* Usage:
* startActivityForResult(StringSelectorActivity.createSelectorIntent(getActivity(),
new String[]{"Java", "PHP", "Android"}, "PHP", ListView.CHOICE_MODE_SINGLE, "语言", "请选择您最擅长的语言", "设定好友可以查看的最擅长语言"
), SELECT_LANGUAGE);
* Created by liuchangjiong on 15/5/31.
*/
public class StringSelectorActivity extends BaseTitleActivity {
private static final String TAG = StringSelectorActivity.class.getSimpleName();
public static final String ACTIVITY_TITLE = "ACTIVITY_TITLE";
public static final String ITEMS = "ITEMS";
public static final String SELECTED_STRING = "SELECTED_STRING";
public static final String SELECTED_INDEX = "SELECTED_INDEX";
public static final String SELECTION_MODE = "SELECTION_MODE";// Values of ListView.CHOICE_MODE_SINGLE
public static final String INITIAL_SELECTION = "INITIAL_SELECTION";// 初识选择
public static final String LIST_TITLE = "LIST_TITLE";// 列表区的标题
public static final String LIST_DESCRIPTION = "LIST_DESCRIPTION";// 列表区的详细说明
//@InjectView(R.id.sub_title)
TextView subTitle;
//@InjectView(R.id.item_list)
ListView listView;
//@InjectView(R.id.detail)
TextView detail;
private String selectedItem = "1";
private String[] items = new String[]{"2", "1", "3"};
private String initialSelection;
private int selectionMode;// 选择模式
// protected ListAdapter listAdapter = null;
/**
* 创建选择器动作。
*
* @param context 起始包
* @param items 项目列表,不能为空
* @param initialSelection 初始选择,可为空
* @param selectionMode 选择模式, 不置顶为单选
* @return 动作
* @see ListView#CHOICE_MODE_SINGLE
*/
public static Intent createSelectorIntent(Context context, String[] items, String initialSelection, int selectionMode, String title) {
return createSelectorIntent(context,items, initialSelection, selectionMode, title, null, null);
}
/**
* 创建选择器动作。
*
* @param context 起始包
* @param items 项目列表,不能为空
* @param initialSelection 初始选择,可为空
* @param selectionMode 选择模式, 不置顶为单选
* @return 动作
* @see ListView#CHOICE_MODE_SINGLE
*/
public static Intent createSelectorIntent(Context context, String[] items, String initialSelection,
int selectionMode, String title, String listTitle, String listDescription) {
Intent intent = new Intent(context, StringSelectorActivity.class);
intent.putExtra(INITIAL_SELECTION, initialSelection);
intent.putExtra(ITEMS, items);
intent.putExtra(SELECTION_MODE, selectionMode);
intent.putExtra(ACTIVITY_TITLE, title);
intent.putExtra(LIST_TITLE, listTitle);
intent.putExtra(LIST_DESCRIPTION, listDescription);
// Bundle bundle=new Bundle();
// bundle.putSerializable(ITEMS, items);
// bundle.putSerializable(INITIAL_SELECTION, initialSelection);
// bundle.putInt(SELECTION_MODE, selectionMode);
// intent.putExtras(bundle);
return intent;
}
// 读取传递来的参数
private void readIntentData() {
String[] _items = getIntent().getStringArrayExtra(ITEMS);
if (_items != null) {
items = _items;
}
String _initialSelection = getIntent().getStringExtra(INITIAL_SELECTION);
if (_initialSelection != null) {
initialSelection = _initialSelection;
}
int _selectionMode = getIntent().getIntExtra(SELECTION_MODE, ListView.CHOICE_MODE_SINGLE);
selectionMode = _selectionMode;
String _title = getIntent().getStringExtra(ACTIVITY_TITLE);
if (_title != null)
setTitleText(_title);
String _listTitle = getIntent().getStringExtra(LIST_TITLE);
if (_listTitle != null) {
subTitle.setText(_listTitle);
} else {
subTitle.setVisibility(View.INVISIBLE);
}
String _listDescription = getIntent().getStringExtra(LIST_DESCRIPTION);
if (_listDescription != null) {
detail.setText(_listDescription);
} else {
detail.setVisibility(View.INVISIBLE);
}
}
public void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10); // 可删除
listView.setLayoutParams(params);
}
@Override
protected void setContentView() {
setContentView(R.layout.activity_selector_string);
}
@Override
protected void initTitle() {
}
@Override
protected void initView() {
listView = ViewFinderUtil.findViewById(this, R.id.item_list);
subTitle = ViewFinderUtil.findViewById(this, R.id.sub_title);
detail = ViewFinderUtil.findViewById(this, R.id.detail);
readIntentData();
listView.setChoiceMode(selectionMode);
//
// listAdapter = new ListAdapter();
// listAdapter.selectedIndex = 1;
ArrayAdapter<String> directoryAdapter = new ArrayAdapter<String>(this, R.layout.selector_string_list_item, items);
// listView.setAdapter(listAdapter);
listView.setAdapter(directoryAdapter);
// listView.setSelector(R.drawable.list_selector);
// listView.setItemChecked(1, true);
// listView.setSelection(1);
setSelectedItem(initialSelection);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// CheckBox rdBtn = (CheckBox) ((RelativeLayout) view).getChildAt(0);
// rdBtn.setChecked(!rdBtn.isChecked());
// listAdapter.selectedIndex = position;
// CheckableRelativeLayout curView = (CheckableRelativeLayout)view;
// curView.toggle();
// ToastUtil.show(StringSelectorActivity.this, listView.getCheckedItemPosition() + " getCheckedItemPosition ");
ok();
}
});
// setListViewHeightBasedOnChildren(listView);
// listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
// @Override
// public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// if (position > 0 && items != null) {
// selectedItem = items[position];
// }
//
// ToastUtil.show(StringSelectorActivity.this, selectedItem);
// ok();
// }
//
// @Override
// public void onNothingSelected(AdapterView<?> parent) {
// selectedItem = null;
// ok();
// }
// });
}
public String getSelectedItem() {
if (listView.getCheckedItemPosition() >= 0) {
selectedItem = items[listView.getCheckedItemPosition()];
}
return selectedItem;
}
public void setSelectedItem(String selectedItem) {
this.selectedItem = selectedItem;
if (StringUtil.isEmpty(selectedItem)) {
listView.clearChoices();
} else if (items != null) {
for (int i = 0; i < items.length; i++) {
listView.setItemChecked(i, selectedItem.equals(items[i]));
}
}
}
public void ok() {
Log.d(TAG, "Upload clicked, finishing activity");
if (items == null) {
Log.d(TAG, "No selection");
finish();
}
Intent result = this.getIntent();
result.putExtra(SELECTED_STRING, getSelectedItem());
result.putExtra(SELECTED_INDEX, listView.getCheckedItemPosition());
setResult(Activity.RESULT_OK, result);
finish();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: add setContentView(...) invocation
// ButterKnife.inject(this);
}
/**
* customizing adapter.
*
* @author liuchangjiong
*/
/*
public class ListAdapter extends BaseAdapter {
public int selectedIndex;
public ListAdapter() {
}
public void updateList() {
notifyDataSetChanged();
}
@Override
public int getCount() {
return items == null? 0 : items.length;
}
@Override
public Object getItem(int position) {
return items == null? "": items[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
String str = items[position];
if (convertView == null)
convertView = getLayoutInflater().inflate(R.layout.selector_string_list_item, parent, false);
Viewholder holder = (Viewholder) convertView.getTag();
if (holder == null) {
holder = new Viewholder();
convertView.setTag(holder);
// holder.radioButton = ViewFinderUtil.findViewById(convertView, R.id.radioButton);
}
// holder.radioButton.setChecked(position == selectedIndex);
// holder.radioButton.setText(str);
// holder.radioButton.setSelected(str.equals(selectedItem));
return convertView;
}
}
*/
}
|
UTF-8
|
Java
| 10,936 |
java
|
StringSelectorActivity.java
|
Java
|
[
{
"context": "定好友可以查看的最擅长语言\"\n ), SELECT_LANGUAGE);\n * Created by liuchangjiong on 15/5/31.\n */\npublic class StringSelectorActivi",
"end": 857,
"score": 0.9996788501739502,
"start": 844,
"tag": "USERNAME",
"value": "liuchangjiong"
},
{
"context": "\n * customizing adapter.\n *\n * @author liuchangjiong\n */\n /*\n public class ListAdapter exten",
"end": 9234,
"score": 0.9366629123687744,
"start": 9221,
"tag": "USERNAME",
"value": "liuchangjiong"
}
] | null |
[] |
package common.selector;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.gunlei.app.R;
import com.gunlei.app.ui.base.BaseTitleActivity;
import com.gunlei.app.ui.util.StringUtil;
import com.gunlei.app.ui.util.ViewFinderUtil;
/**
* 字符串单选Activity.
* Usage:
* startActivityForResult(StringSelectorActivity.createSelectorIntent(getActivity(),
new String[]{"Java", "PHP", "Android"}, "PHP", ListView.CHOICE_MODE_SINGLE, "语言", "请选择您最擅长的语言", "设定好友可以查看的最擅长语言"
), SELECT_LANGUAGE);
* Created by liuchangjiong on 15/5/31.
*/
public class StringSelectorActivity extends BaseTitleActivity {
private static final String TAG = StringSelectorActivity.class.getSimpleName();
public static final String ACTIVITY_TITLE = "ACTIVITY_TITLE";
public static final String ITEMS = "ITEMS";
public static final String SELECTED_STRING = "SELECTED_STRING";
public static final String SELECTED_INDEX = "SELECTED_INDEX";
public static final String SELECTION_MODE = "SELECTION_MODE";// Values of ListView.CHOICE_MODE_SINGLE
public static final String INITIAL_SELECTION = "INITIAL_SELECTION";// 初识选择
public static final String LIST_TITLE = "LIST_TITLE";// 列表区的标题
public static final String LIST_DESCRIPTION = "LIST_DESCRIPTION";// 列表区的详细说明
//@InjectView(R.id.sub_title)
TextView subTitle;
//@InjectView(R.id.item_list)
ListView listView;
//@InjectView(R.id.detail)
TextView detail;
private String selectedItem = "1";
private String[] items = new String[]{"2", "1", "3"};
private String initialSelection;
private int selectionMode;// 选择模式
// protected ListAdapter listAdapter = null;
/**
* 创建选择器动作。
*
* @param context 起始包
* @param items 项目列表,不能为空
* @param initialSelection 初始选择,可为空
* @param selectionMode 选择模式, 不置顶为单选
* @return 动作
* @see ListView#CHOICE_MODE_SINGLE
*/
public static Intent createSelectorIntent(Context context, String[] items, String initialSelection, int selectionMode, String title) {
return createSelectorIntent(context,items, initialSelection, selectionMode, title, null, null);
}
/**
* 创建选择器动作。
*
* @param context 起始包
* @param items 项目列表,不能为空
* @param initialSelection 初始选择,可为空
* @param selectionMode 选择模式, 不置顶为单选
* @return 动作
* @see ListView#CHOICE_MODE_SINGLE
*/
public static Intent createSelectorIntent(Context context, String[] items, String initialSelection,
int selectionMode, String title, String listTitle, String listDescription) {
Intent intent = new Intent(context, StringSelectorActivity.class);
intent.putExtra(INITIAL_SELECTION, initialSelection);
intent.putExtra(ITEMS, items);
intent.putExtra(SELECTION_MODE, selectionMode);
intent.putExtra(ACTIVITY_TITLE, title);
intent.putExtra(LIST_TITLE, listTitle);
intent.putExtra(LIST_DESCRIPTION, listDescription);
// Bundle bundle=new Bundle();
// bundle.putSerializable(ITEMS, items);
// bundle.putSerializable(INITIAL_SELECTION, initialSelection);
// bundle.putInt(SELECTION_MODE, selectionMode);
// intent.putExtras(bundle);
return intent;
}
// 读取传递来的参数
private void readIntentData() {
String[] _items = getIntent().getStringArrayExtra(ITEMS);
if (_items != null) {
items = _items;
}
String _initialSelection = getIntent().getStringExtra(INITIAL_SELECTION);
if (_initialSelection != null) {
initialSelection = _initialSelection;
}
int _selectionMode = getIntent().getIntExtra(SELECTION_MODE, ListView.CHOICE_MODE_SINGLE);
selectionMode = _selectionMode;
String _title = getIntent().getStringExtra(ACTIVITY_TITLE);
if (_title != null)
setTitleText(_title);
String _listTitle = getIntent().getStringExtra(LIST_TITLE);
if (_listTitle != null) {
subTitle.setText(_listTitle);
} else {
subTitle.setVisibility(View.INVISIBLE);
}
String _listDescription = getIntent().getStringExtra(LIST_DESCRIPTION);
if (_listDescription != null) {
detail.setText(_listDescription);
} else {
detail.setVisibility(View.INVISIBLE);
}
}
public void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10); // 可删除
listView.setLayoutParams(params);
}
@Override
protected void setContentView() {
setContentView(R.layout.activity_selector_string);
}
@Override
protected void initTitle() {
}
@Override
protected void initView() {
listView = ViewFinderUtil.findViewById(this, R.id.item_list);
subTitle = ViewFinderUtil.findViewById(this, R.id.sub_title);
detail = ViewFinderUtil.findViewById(this, R.id.detail);
readIntentData();
listView.setChoiceMode(selectionMode);
//
// listAdapter = new ListAdapter();
// listAdapter.selectedIndex = 1;
ArrayAdapter<String> directoryAdapter = new ArrayAdapter<String>(this, R.layout.selector_string_list_item, items);
// listView.setAdapter(listAdapter);
listView.setAdapter(directoryAdapter);
// listView.setSelector(R.drawable.list_selector);
// listView.setItemChecked(1, true);
// listView.setSelection(1);
setSelectedItem(initialSelection);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// CheckBox rdBtn = (CheckBox) ((RelativeLayout) view).getChildAt(0);
// rdBtn.setChecked(!rdBtn.isChecked());
// listAdapter.selectedIndex = position;
// CheckableRelativeLayout curView = (CheckableRelativeLayout)view;
// curView.toggle();
// ToastUtil.show(StringSelectorActivity.this, listView.getCheckedItemPosition() + " getCheckedItemPosition ");
ok();
}
});
// setListViewHeightBasedOnChildren(listView);
// listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
// @Override
// public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// if (position > 0 && items != null) {
// selectedItem = items[position];
// }
//
// ToastUtil.show(StringSelectorActivity.this, selectedItem);
// ok();
// }
//
// @Override
// public void onNothingSelected(AdapterView<?> parent) {
// selectedItem = null;
// ok();
// }
// });
}
public String getSelectedItem() {
if (listView.getCheckedItemPosition() >= 0) {
selectedItem = items[listView.getCheckedItemPosition()];
}
return selectedItem;
}
public void setSelectedItem(String selectedItem) {
this.selectedItem = selectedItem;
if (StringUtil.isEmpty(selectedItem)) {
listView.clearChoices();
} else if (items != null) {
for (int i = 0; i < items.length; i++) {
listView.setItemChecked(i, selectedItem.equals(items[i]));
}
}
}
public void ok() {
Log.d(TAG, "Upload clicked, finishing activity");
if (items == null) {
Log.d(TAG, "No selection");
finish();
}
Intent result = this.getIntent();
result.putExtra(SELECTED_STRING, getSelectedItem());
result.putExtra(SELECTED_INDEX, listView.getCheckedItemPosition());
setResult(Activity.RESULT_OK, result);
finish();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: add setContentView(...) invocation
// ButterKnife.inject(this);
}
/**
* customizing adapter.
*
* @author liuchangjiong
*/
/*
public class ListAdapter extends BaseAdapter {
public int selectedIndex;
public ListAdapter() {
}
public void updateList() {
notifyDataSetChanged();
}
@Override
public int getCount() {
return items == null? 0 : items.length;
}
@Override
public Object getItem(int position) {
return items == null? "": items[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
String str = items[position];
if (convertView == null)
convertView = getLayoutInflater().inflate(R.layout.selector_string_list_item, parent, false);
Viewholder holder = (Viewholder) convertView.getTag();
if (holder == null) {
holder = new Viewholder();
convertView.setTag(holder);
// holder.radioButton = ViewFinderUtil.findViewById(convertView, R.id.radioButton);
}
// holder.radioButton.setChecked(position == selectedIndex);
// holder.radioButton.setText(str);
// holder.radioButton.setSelected(str.equals(selectedItem));
return convertView;
}
}
*/
}
| 10,936 | 0.618989 | 0.616172 | 317 | 32.589905 | 28.753313 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.659306 | false | false |
14
|
fd6c6e98fa5e3811fa25f649d082ed0ac3eb3033
| 14,190,571,949,722 |
47f6f546cadd8bc8de13cd9384224465f6fed757
|
/SpringMVCProject5/src/main/java/com/sist/manager/MovieManager.java
|
416db05473c23027192dafcb09c7495cc9c35113
|
[] |
no_license
|
ung6039/javaStudy
|
https://github.com/ung6039/javaStudy
|
63f79620925d91f2a6b7fbe529742162633d3527
|
0b33126f9355359cfd9d5708bd60db29a9dbf605
|
refs/heads/master
| 2022-05-02T12:19:30.872000 | 2020-05-26T00:59:36 | 2020-05-26T00:59:36 | 227,052,035 | 0 | 0 | null | false | 2022-07-07T19:42:26 | 2019-12-10T07:08:55 | 2020-10-08T04:41:51 | 2022-07-07T19:42:26 | 93,214 | 0 | 0 | 174 |
CSS
| false | false |
package com.sist.manager;
import java.util.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.sist.dao.MovieDAO;
import com.sist.dao.MovieVO;
public class MovieManager {
public List<String> movieLinkData(){
List<String> list = new ArrayList<String>();
String url =" ";
try{
for(int i =1; i<40; i++){
url ="https://movie.naver.com/movie/sdb/rank/rmovie.nhn?sel=pnt&date=20200513&page="+i;
Document doc = Jsoup.connect(url).get();
Elements link = doc.select("td.title div.tit5 a");
for(int j =0; j<link.size(); j++){
String strLink = link.get(j).attr("href");
list.add("https://movie.naver.com"+strLink);
}
}
}catch(Exception ex){
System.out.println(ex.getMessage());
ex.printStackTrace();
}
return list;
}
public void movieAllData(){
MovieDAO dao = new MovieDAO();
try{
List<String> list =movieLinkData();
int k =1;
for(String url : list){
try{
Document doc = Jsoup.connect(url).get();
Element title = doc.selectFirst("div.mv_info h3.h_movie a");
Element poster = doc.selectFirst("div.poster a img");
Element genre = doc.selectFirst("dl.info_spec span a");
Elements grade = doc.select("dl.info_spec p");
// Element grade = doc.select("dl.info_spec d").get(2);
Element director = doc.selectFirst("div.info_spec2 dl.step1 a");
Element actor = doc.selectFirst("div.info_spec2 dl.step2 a");
Element story = doc.selectFirst("div.story_area p.con_tx");
MovieVO vo = new MovieVO();
vo.setMno(Integer.parseInt(url.substring(url.lastIndexOf("=")+1)));
// String grade_t = grade.text().substring(grade.text().lastIndexOf("[국내]")+1);
// String actor_t = grade_t.substring(grade_t.lastIndexOf("개봉"));
String temp = " ";
System.out.println("1: "+grade.text().indexOf("["));
System.out.println("2: "+grade.lastIndexOf("["));
temp = grade.text().substring(grade.text().indexOf("["),grade.lastIndexOf("["));
System.out.println("mttt : "+temp);
System.out.println("===== 영화 정보 ======");
System.out.println("k= "+k);
System.out.println(title.text());
System.out.println(poster.attr("src"));
System.out.println(genre.text());
System.out.println(grade.text());
System.out.println(director.text());
System.out.println(actor.text());
System.out.println(story.text());
vo.setTitle(title.text());
vo.setPoster(poster.text());
vo.setGenre(genre.text());
vo.setGrade(grade.text());
vo.setDirector(director.text());
vo.setActor(actor.text());
vo.setStory(story.text());
k++;
// dao.movieInsert(vo);
}catch(Exception ex){
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
}catch(Exception ex){
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
public static void main(String[] args) {
MovieManager m = new MovieManager();
m.movieAllData();
}
}
|
UTF-8
|
Java
| 3,070 |
java
|
MovieManager.java
|
Java
|
[] | null |
[] |
package com.sist.manager;
import java.util.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.sist.dao.MovieDAO;
import com.sist.dao.MovieVO;
public class MovieManager {
public List<String> movieLinkData(){
List<String> list = new ArrayList<String>();
String url =" ";
try{
for(int i =1; i<40; i++){
url ="https://movie.naver.com/movie/sdb/rank/rmovie.nhn?sel=pnt&date=20200513&page="+i;
Document doc = Jsoup.connect(url).get();
Elements link = doc.select("td.title div.tit5 a");
for(int j =0; j<link.size(); j++){
String strLink = link.get(j).attr("href");
list.add("https://movie.naver.com"+strLink);
}
}
}catch(Exception ex){
System.out.println(ex.getMessage());
ex.printStackTrace();
}
return list;
}
public void movieAllData(){
MovieDAO dao = new MovieDAO();
try{
List<String> list =movieLinkData();
int k =1;
for(String url : list){
try{
Document doc = Jsoup.connect(url).get();
Element title = doc.selectFirst("div.mv_info h3.h_movie a");
Element poster = doc.selectFirst("div.poster a img");
Element genre = doc.selectFirst("dl.info_spec span a");
Elements grade = doc.select("dl.info_spec p");
// Element grade = doc.select("dl.info_spec d").get(2);
Element director = doc.selectFirst("div.info_spec2 dl.step1 a");
Element actor = doc.selectFirst("div.info_spec2 dl.step2 a");
Element story = doc.selectFirst("div.story_area p.con_tx");
MovieVO vo = new MovieVO();
vo.setMno(Integer.parseInt(url.substring(url.lastIndexOf("=")+1)));
// String grade_t = grade.text().substring(grade.text().lastIndexOf("[국내]")+1);
// String actor_t = grade_t.substring(grade_t.lastIndexOf("개봉"));
String temp = " ";
System.out.println("1: "+grade.text().indexOf("["));
System.out.println("2: "+grade.lastIndexOf("["));
temp = grade.text().substring(grade.text().indexOf("["),grade.lastIndexOf("["));
System.out.println("mttt : "+temp);
System.out.println("===== 영화 정보 ======");
System.out.println("k= "+k);
System.out.println(title.text());
System.out.println(poster.attr("src"));
System.out.println(genre.text());
System.out.println(grade.text());
System.out.println(director.text());
System.out.println(actor.text());
System.out.println(story.text());
vo.setTitle(title.text());
vo.setPoster(poster.text());
vo.setGenre(genre.text());
vo.setGrade(grade.text());
vo.setDirector(director.text());
vo.setActor(actor.text());
vo.setStory(story.text());
k++;
// dao.movieInsert(vo);
}catch(Exception ex){
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
}catch(Exception ex){
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
public static void main(String[] args) {
MovieManager m = new MovieManager();
m.movieAllData();
}
}
| 3,070 | 0.629666 | 0.621807 | 99 | 29.848484 | 21.819445 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.89899 | false | false |
14
|
d838fba81d6ccb8c27927b377c48dbedbfc1a43e
| 4,750,233,896,079 |
497ebda32a81cde80dd7534f024f6ad9a3964401
|
/src/main/java/softuniBlog/entity/Comment.java
|
f8fe4cd1a003ebb0cedebc599d46bfcfc838cae0
|
[] |
no_license
|
yanev3/proekt
|
https://github.com/yanev3/proekt
|
4ac9f91a0f1c5df68526793afe0b7943e9e5bfeb
|
db40fdf3d965fd8592518a0e3a09603142cf1162
|
refs/heads/master
| 2021-01-20T01:10:11.526000 | 2017-04-27T22:41:54 | 2017-04-27T22:41:54 | 89,226,408 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package softuniBlog.entity;
import javax.persistence.*;
@Entity
@Table(name="comments")
public class Comment{
private Integer id;
private String name;
private String comment;
private Article article;
public Comment() { }
public Comment(String name, String comment, Article article) {
this.name = name;
this.comment = comment;
this.article=article;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(columnDefinition = "text", nullable = false)
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
@ManyToOne()
@JoinColumn(nullable = false, name = "article_id")
public Article getArticle() {
return article;
}
public void setArticle(Article article) {
this.article = article;
}
}
|
UTF-8
|
Java
| 1,250 |
java
|
Comment.java
|
Java
|
[] | null |
[] |
package softuniBlog.entity;
import javax.persistence.*;
@Entity
@Table(name="comments")
public class Comment{
private Integer id;
private String name;
private String comment;
private Article article;
public Comment() { }
public Comment(String name, String comment, Article article) {
this.name = name;
this.comment = comment;
this.article=article;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(columnDefinition = "text", nullable = false)
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
@ManyToOne()
@JoinColumn(nullable = false, name = "article_id")
public Article getArticle() {
return article;
}
public void setArticle(Article article) {
this.article = article;
}
}
| 1,250 | 0.5768 | 0.5768 | 63 | 17.84127 | 16.968885 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
14
|
71d4aa2b3918746cbef8802bfbc7f97de2310696
| 13,718,125,546,610 |
d8e146521f3aa15ea4f2a06b64429815583af4b9
|
/_34.java
|
9a8d8bc438383550031ac8c9814fa18c9f00ac85
|
[] |
no_license
|
kuowilly885/leetcode
|
https://github.com/kuowilly885/leetcode
|
40d9bbcf87600f80e992511738b1071e51cf97bc
|
2de9a7052bcba9c34371530804943c97d84c9f48
|
refs/heads/master
| 2020-05-29T08:47:27.193000 | 2018-01-27T05:05:16 | 2018-01-27T05:05:16 | 69,141,431 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package test_crack;
class _34 {
public int[] searchRange(int[] a, int b) {
int bP;
if (a==null || a.length==0 || (bP=bs(a,0,a.length-1,b))==-1) return new int[] {-1,-1};
return new int[] {a[0]== b?0:bsG(a,0,bP,b,true),a[a.length-1]==b?a.length-1:bsG(a,bP,a.length-1,b,false)};
}
int bsG (int[] a, int s, int e, int t, boolean f) {
if (e>s) {
int m=(s+e)/2;
if (a[m]!=t && a[f?m+1:m-1]==t) return f?m+1:m-1;
else if (a[m]!=t && a[f?m+1:m-1]!=t) return f?bsG(a,m+1,e,t,true):bsG(a,s,m-1,t,false);
else if (a[m]==t)return f?bsG(a,s,m-1,t,true):bsG(a,m+1,e,t,false);
} else if (e==s && a[s]!=t && a[f?s+1:s-1]==t) return f?s+1:s-1;
return -1;
}
int bs (int[] a, int s, int e, int t) {
if (e>s) {
int m=(s+e)/2;
if (a[m]==t) return m;
else if (a[m]>t) return bs(a,s,m-1,t);
else return bs(a,m+1,e,t);
} else if (e==s && a[s]==t) return s;
return -1;
}
}
|
UTF-8
|
Java
| 937 |
java
|
_34.java
|
Java
|
[] | null |
[] |
package test_crack;
class _34 {
public int[] searchRange(int[] a, int b) {
int bP;
if (a==null || a.length==0 || (bP=bs(a,0,a.length-1,b))==-1) return new int[] {-1,-1};
return new int[] {a[0]== b?0:bsG(a,0,bP,b,true),a[a.length-1]==b?a.length-1:bsG(a,bP,a.length-1,b,false)};
}
int bsG (int[] a, int s, int e, int t, boolean f) {
if (e>s) {
int m=(s+e)/2;
if (a[m]!=t && a[f?m+1:m-1]==t) return f?m+1:m-1;
else if (a[m]!=t && a[f?m+1:m-1]!=t) return f?bsG(a,m+1,e,t,true):bsG(a,s,m-1,t,false);
else if (a[m]==t)return f?bsG(a,s,m-1,t,true):bsG(a,m+1,e,t,false);
} else if (e==s && a[s]!=t && a[f?s+1:s-1]==t) return f?s+1:s-1;
return -1;
}
int bs (int[] a, int s, int e, int t) {
if (e>s) {
int m=(s+e)/2;
if (a[m]==t) return m;
else if (a[m]>t) return bs(a,s,m-1,t);
else return bs(a,m+1,e,t);
} else if (e==s && a[s]==t) return s;
return -1;
}
}
| 937 | 0.495197 | 0.458911 | 30 | 29.233334 | 29.664438 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.766667 | false | false |
14
|
c49d21920b95fbdbbfb26621a4250f5251e13b9b
| 901,943,156,334 |
d013a0fdd944b8410412713765dd0f27b255176a
|
/Programmers_42578_위장.java
|
8be86b54c00da07cb0148a438109e8a1b338b9d2
|
[] |
no_license
|
jokebear/Java
|
https://github.com/jokebear/Java
|
95d48363b228affe64c72e3b7d565cc99a0a9bc7
|
04e493e994e0835da9052d93ec24d0bb55eeffbe
|
refs/heads/master
| 2021-07-10T22:11:15.308000 | 2021-03-09T10:41:52 | 2021-03-09T10:41:52 | 237,774,713 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.HashMap;
public class Programmers_42578_위장 {
// 1. 의상 종류와 개수를 각각 키 밸류로 하여 해시맵에 담는다.
// 2. 의상 (개수+1) 개를 종류별로 곱한다.
// 3. 아무것도 안입을 경우 1을 뺀다.
public static int solution(String[][] clothes) {
int answer = 1;
HashMap<String,Integer> map = new HashMap<>();
for(String[] cloth : clothes) {
if(map.containsKey(cloth[1]))
map.put(cloth[1], map.get(cloth[1])+1);
else
map.put(cloth[1], 1);
}
// map : {eyewear=1, headgear=2}
for (int val : map.values()) {
answer*=(val+1);
}
return answer-1;
}
public static void main(String[] args) {
// https://programmers.co.kr/learn/courses/30/lessons/42578
String[][] clothes = {{"yellow_hat", "headgear"}, {"blue_sunglasses", "eyewear"}, {"green_turban", "headgear"}};
System.out.println(solution(clothes));
}
}
|
UTF-8
|
Java
| 1,007 |
java
|
Programmers_42578_위장.java
|
Java
|
[] | null |
[] |
import java.util.HashMap;
public class Programmers_42578_위장 {
// 1. 의상 종류와 개수를 각각 키 밸류로 하여 해시맵에 담는다.
// 2. 의상 (개수+1) 개를 종류별로 곱한다.
// 3. 아무것도 안입을 경우 1을 뺀다.
public static int solution(String[][] clothes) {
int answer = 1;
HashMap<String,Integer> map = new HashMap<>();
for(String[] cloth : clothes) {
if(map.containsKey(cloth[1]))
map.put(cloth[1], map.get(cloth[1])+1);
else
map.put(cloth[1], 1);
}
// map : {eyewear=1, headgear=2}
for (int val : map.values()) {
answer*=(val+1);
}
return answer-1;
}
public static void main(String[] args) {
// https://programmers.co.kr/learn/courses/30/lessons/42578
String[][] clothes = {{"yellow_hat", "headgear"}, {"blue_sunglasses", "eyewear"}, {"green_turban", "headgear"}};
System.out.println(solution(clothes));
}
}
| 1,007 | 0.556781 | 0.52591 | 32 | 27.34375 | 23.853209 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.21875 | false | false |
14
|
6d1a00a3dd355b8a4aec2654094fadaf67cf0299
| 901,943,154,726 |
43bc5bf8ab2888cc5c3c52e4e4b55c29d232ba59
|
/app/src/main/java/com/example/steven/app1/MyBringBack.java
|
86859660e741198f177beadd16cf92e4762af045
|
[] |
no_license
|
steven1227/AndroidTraining
|
https://github.com/steven1227/AndroidTraining
|
4579e173e9ba81b9722f1d4b74bbfe7abca424ae
|
efe427da765fa794d168bbcecdc7b7f31d706a32
|
refs/heads/master
| 2016-09-05T15:33:40.524000 | 2015-05-25T10:08:40 | 2015-05-25T10:08:40 | 34,163,817 | 0 | 0 | null | false | 2015-04-24T00:15:56 | 2015-04-18T11:45:06 | 2015-04-21T21:50:49 | 2015-04-24T00:15:56 | 0 | 0 | 0 | 0 |
Java
| null | null |
package com.example.steven.app1;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.view.View;
/**
* Created by steven on 20-4-15.
*/
public class MyBringBack extends View {
private Bitmap gBall;
float changeY;
Typeface font;
public MyBringBack(Context context) {
super(context);
this.changeY=0;
this.gBall= BitmapFactory.decodeResource(getResources(),R.drawable.greenball);
this.font=Typeface.createFromAsset(context.getAssets(),"G-Unit.TTF");
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
Rect middleRect=new Rect();
middleRect.set(0,400,canvas.getWidth(),550);
Paint text= new Paint();
text.setARGB(50,55,23,23);
text.setTypeface(font);
text.setTextAlign(Paint.Align.CENTER);
text.setTextSize(50);
canvas.drawText("My first ball",canvas.getHeight()/2,canvas.getWidth()/2,text);
Paint ourblue=new Paint();
ourblue.setColor(Color.BLUE);
canvas.drawRect(middleRect,ourblue);
canvas.drawBitmap(this.gBall, canvas.getWidth()/2-this.gBall.getWidth()/2, changeY, null);
if( changeY<=canvas.getHeight())
changeY=changeY+5;
else
changeY=0;
invalidate();
}
}
|
UTF-8
|
Java
| 1,576 |
java
|
MyBringBack.java
|
Java
|
[
{
"context": "package com.example.steven.app1;\n\nimport android.content.Context;\nimport and",
"end": 26,
"score": 0.7190426588058472,
"start": 20,
"tag": "USERNAME",
"value": "steven"
},
{
"context": "face;\nimport android.view.View;\n\n/**\n * Created by steven on 20-4-15.\n */\npublic class MyBringBack extends ",
"end": 346,
"score": 0.9842098951339722,
"start": 340,
"tag": "USERNAME",
"value": "steven"
}
] | null |
[] |
package com.example.steven.app1;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.view.View;
/**
* Created by steven on 20-4-15.
*/
public class MyBringBack extends View {
private Bitmap gBall;
float changeY;
Typeface font;
public MyBringBack(Context context) {
super(context);
this.changeY=0;
this.gBall= BitmapFactory.decodeResource(getResources(),R.drawable.greenball);
this.font=Typeface.createFromAsset(context.getAssets(),"G-Unit.TTF");
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
Rect middleRect=new Rect();
middleRect.set(0,400,canvas.getWidth(),550);
Paint text= new Paint();
text.setARGB(50,55,23,23);
text.setTypeface(font);
text.setTextAlign(Paint.Align.CENTER);
text.setTextSize(50);
canvas.drawText("My first ball",canvas.getHeight()/2,canvas.getWidth()/2,text);
Paint ourblue=new Paint();
ourblue.setColor(Color.BLUE);
canvas.drawRect(middleRect,ourblue);
canvas.drawBitmap(this.gBall, canvas.getWidth()/2-this.gBall.getWidth()/2, changeY, null);
if( changeY<=canvas.getHeight())
changeY=changeY+5;
else
changeY=0;
invalidate();
}
}
| 1,576 | 0.66434 | 0.645305 | 61 | 24.836065 | 22.716486 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.803279 | false | false |
14
|
61cbfc8253c8f32a11508918ff62daf35728ec1b
| 8,504,035,269,002 |
01db0cf13fc5068aac521a916f83747e4cc406cb
|
/Java/src/collection/MapTest.java
|
c53b9e5c4009e23ca2fbbe08ab1e098b27b8596c
|
[] |
no_license
|
weijj/workspace
|
https://github.com/weijj/workspace
|
e686845aec8123662ebae862e4a31adafcb4fb64
|
eebef6c4a96b2e638615da81129a4a1a5a83b795
|
refs/heads/master
| 2016-09-10T17:35:11.983000 | 2014-07-13T12:23:59 | 2014-07-13T12:23:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package collection;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
public class MapTest {
public static void main(String[] args) {
String a = "wei", b = "wei";
if (!a.equals(b) && a.compareTo(b) == 0) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
|
UTF-8
|
Java
| 347 |
java
|
MapTest.java
|
Java
|
[] | null |
[] |
package collection;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
public class MapTest {
public static void main(String[] args) {
String a = "wei", b = "wei";
if (!a.equals(b) && a.compareTo(b) == 0) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
| 347 | 0.648415 | 0.645533 | 19 | 17.263159 | 14.425278 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.315789 | false | false |
14
|
709420e05cced2319756b59253b7ea280739a130
| 2,869,038,155,836 |
ef2e64ba7f0b2721da58f69f8c90f94d28ec2ab2
|
/L101/src/main/java/ru/otus/dz/helpers/DbHelper.java
|
a7c9c9807e301e2fe357b418a2518b0706c8edea
|
[] |
no_license
|
Arsn86/otus_java_2018_06_ns
|
https://github.com/Arsn86/otus_java_2018_06_ns
|
921147ff22301047aeb433057122569d62b6adfb
|
e3b1a66d707781a6cb7f18e49048355ff32b6256
|
refs/heads/master
| 2018-10-23T22:46:47.125000 | 2018-10-08T18:27:04 | 2018-10-08T18:27:04 | 140,257,819 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ru.otus.dz.helpers;
import ru.otus.dz.DataSet;
import java.sql.SQLException;
import java.util.List;
public interface DbHelper {
void createTables() throws SQLException;
void dropTables() throws SQLException;
void insert(String s) throws SQLException;
List<DataSet> select(String s, DataSet set) throws SQLException;
}
|
UTF-8
|
Java
| 345 |
java
|
DbHelper.java
|
Java
|
[] | null |
[] |
package ru.otus.dz.helpers;
import ru.otus.dz.DataSet;
import java.sql.SQLException;
import java.util.List;
public interface DbHelper {
void createTables() throws SQLException;
void dropTables() throws SQLException;
void insert(String s) throws SQLException;
List<DataSet> select(String s, DataSet set) throws SQLException;
}
| 345 | 0.75942 | 0.75942 | 13 | 25.538462 | 20.421013 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false |
14
|
ffaac427c8f07dcbb20cf42a1ba084fcc16b4de3
| 12,086,038,008,754 |
968ad617a9a23b4482d07fe7916c1471dd34f816
|
/f3Ftimer/src/main/java/com/marktreble/f3ftimer/dialog/RaceTimerFrag3.java
|
5fe6aae5aebca41452c83ed9bb85074c98a21c25
|
[
"MIT"
] |
permissive
|
marktreble/f3f-timer
|
https://github.com/marktreble/f3f-timer
|
3a939eccc49b1869f193287a5aa3f0399dc8fda3
|
88fd6c35f3e52959e8785e15c055b7eb657495c5
|
refs/heads/master
| 2023-03-09T14:55:24.640000 | 2023-02-28T21:47:12 | 2023-02-28T21:47:12 | 38,211,575 | 2 | 8 |
MIT
| false | 2018-03-12T13:16:27 | 2015-06-28T19:38:05 | 2018-03-12T13:06:19 | 2018-03-12T13:06:17 | 15,796 | 1 | 4 | 0 |
Java
| false | null |
/*
* ___________ ______ _______
* / ____/__ // ____/ /_ __(_)___ ___ ___ _____
* / /_ /_ </ /_ / / / / __ `__ \/ _ \/ ___/
* / __/ ___/ / __/ / / / / / / / / / __/ /
* /_/ /____/_/ /_/ /_/_/ /_/ /_/\___/_/
*
* Open Source F3F timer UI and scores database
*
*/
package com.marktreble.f3ftimer.dialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import androidx.preference.PreferenceManager;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.marktreble.f3ftimer.R;
import com.marktreble.f3ftimer.constants.Pref;
/* Model Launched */
public class RaceTimerFrag3 extends RaceTimerFrag {
private Handler mHandler = new Handler(Looper.getMainLooper());
private long mStart;
public RaceTimerFrag3() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
mStart = System.currentTimeMillis();
mHandler.postDelayed(updateClock, 10);
}
}
@Override
public void onDestroy() {
super.onDestroy();
mHandler.removeCallbacks(updateClock);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.race_timer_frag2, container, false);
Button ab = mView.findViewById(R.id.button_abort);
ab.setVisibility(View.VISIBLE);
ab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mHandler.removeCallbacks(updateClock);
RaceTimerActivity a = (RaceTimerActivity) getActivity();
a.sendCommand("abort");
a.sendCommand("begin_timeout");
a.getFragment(new RaceTimerFragAborted(getString(R.string.race_aborted)), 6); // Abort submenu (reflight or score 0)
}
});
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
String soft_buttons = sharedPref.getString(Pref.INPUT_SRC, getString(R.string.Demo));
if (soft_buttons.equals(getString(R.string.Demo))) {
Button baseA = mView.findViewById(R.id.base_A);
baseA.setVisibility(View.VISIBLE);
baseA.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
RaceTimerActivity a = (RaceTimerActivity) getActivity();
a.sendCommand("baseA");
}
});
Button baseB = mView.findViewById(R.id.base_B);
baseB.setVisibility(View.VISIBLE);
baseB.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
RaceTimerActivity a = (RaceTimerActivity) getActivity();
a.sendCommand("baseB");
}
});
}
super.setStatus(getString(R.string.model_launched));
super.setPilotName();
if (((RaceTimerActivity) getActivity()).mWindowState == RaceTimerActivity.WINDOW_STATE_MINIMIZED) {
setMinimized();
}
return mView;
}
private Runnable updateClock = new Runnable() {
public void run() {
long elapsed = System.currentTimeMillis() - mStart;
float seconds = (float) elapsed / 1000;
if (seconds > 30) seconds = 30;
TextView cd = mView.findViewById(R.id.time);
String str_time = String.format("%.2f", 30 - seconds);
cd.setText(str_time);
TextView min = mView.findViewById(R.id.mintime);
min.setText(str_time);
int s = (int) Math.floor(seconds);
RaceTimerActivity a = (RaceTimerActivity) getActivity();
if (s == 4) a.sendCommand("25");
if (s == 9) a.sendCommand("20");
if (s == 14) a.sendCommand("15");
if (s == 17) a.sendCommand("12");
if (s == 19) a.sendCommand("10");
if (s == 20) a.sendCommand("9");
if (s == 21) a.sendCommand("8");
if (s == 22) a.sendCommand("7");
if (s == 23) a.sendCommand("6");
if (s == 24) a.sendCommand("5");
if (s == 25) a.sendCommand("4");
if (s == 26) a.sendCommand("3");
if (s == 27) a.sendCommand("2");
if (s == 28) a.sendCommand("1");
if (s == 30) {
// Runout of climbout time
// Force the server to start the clock
a.sendCommand("0"); // Informs the driver that this was a late entry
next();
} else {
mHandler.postDelayed(updateClock, 10);
}
}
};
public void setOffCourse() {
super.setStatus(getString(R.string.off_course));
}
public void next() {
mHandler.removeCallbacks(updateClock);
RaceTimerActivity a = (RaceTimerActivity) getActivity();
a.getFragment(new RaceTimerFrag4(), 4);
}
public void startPressed() {
// Ignore
}
}
|
UTF-8
|
Java
| 5,522 |
java
|
RaceTimerFrag3.java
|
Java
|
[] | null |
[] |
/*
* ___________ ______ _______
* / ____/__ // ____/ /_ __(_)___ ___ ___ _____
* / /_ /_ </ /_ / / / / __ `__ \/ _ \/ ___/
* / __/ ___/ / __/ / / / / / / / / / __/ /
* /_/ /____/_/ /_/ /_/_/ /_/ /_/\___/_/
*
* Open Source F3F timer UI and scores database
*
*/
package com.marktreble.f3ftimer.dialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import androidx.preference.PreferenceManager;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.marktreble.f3ftimer.R;
import com.marktreble.f3ftimer.constants.Pref;
/* Model Launched */
public class RaceTimerFrag3 extends RaceTimerFrag {
private Handler mHandler = new Handler(Looper.getMainLooper());
private long mStart;
public RaceTimerFrag3() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
mStart = System.currentTimeMillis();
mHandler.postDelayed(updateClock, 10);
}
}
@Override
public void onDestroy() {
super.onDestroy();
mHandler.removeCallbacks(updateClock);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.race_timer_frag2, container, false);
Button ab = mView.findViewById(R.id.button_abort);
ab.setVisibility(View.VISIBLE);
ab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mHandler.removeCallbacks(updateClock);
RaceTimerActivity a = (RaceTimerActivity) getActivity();
a.sendCommand("abort");
a.sendCommand("begin_timeout");
a.getFragment(new RaceTimerFragAborted(getString(R.string.race_aborted)), 6); // Abort submenu (reflight or score 0)
}
});
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
String soft_buttons = sharedPref.getString(Pref.INPUT_SRC, getString(R.string.Demo));
if (soft_buttons.equals(getString(R.string.Demo))) {
Button baseA = mView.findViewById(R.id.base_A);
baseA.setVisibility(View.VISIBLE);
baseA.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
RaceTimerActivity a = (RaceTimerActivity) getActivity();
a.sendCommand("baseA");
}
});
Button baseB = mView.findViewById(R.id.base_B);
baseB.setVisibility(View.VISIBLE);
baseB.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
RaceTimerActivity a = (RaceTimerActivity) getActivity();
a.sendCommand("baseB");
}
});
}
super.setStatus(getString(R.string.model_launched));
super.setPilotName();
if (((RaceTimerActivity) getActivity()).mWindowState == RaceTimerActivity.WINDOW_STATE_MINIMIZED) {
setMinimized();
}
return mView;
}
private Runnable updateClock = new Runnable() {
public void run() {
long elapsed = System.currentTimeMillis() - mStart;
float seconds = (float) elapsed / 1000;
if (seconds > 30) seconds = 30;
TextView cd = mView.findViewById(R.id.time);
String str_time = String.format("%.2f", 30 - seconds);
cd.setText(str_time);
TextView min = mView.findViewById(R.id.mintime);
min.setText(str_time);
int s = (int) Math.floor(seconds);
RaceTimerActivity a = (RaceTimerActivity) getActivity();
if (s == 4) a.sendCommand("25");
if (s == 9) a.sendCommand("20");
if (s == 14) a.sendCommand("15");
if (s == 17) a.sendCommand("12");
if (s == 19) a.sendCommand("10");
if (s == 20) a.sendCommand("9");
if (s == 21) a.sendCommand("8");
if (s == 22) a.sendCommand("7");
if (s == 23) a.sendCommand("6");
if (s == 24) a.sendCommand("5");
if (s == 25) a.sendCommand("4");
if (s == 26) a.sendCommand("3");
if (s == 27) a.sendCommand("2");
if (s == 28) a.sendCommand("1");
if (s == 30) {
// Runout of climbout time
// Force the server to start the clock
a.sendCommand("0"); // Informs the driver that this was a late entry
next();
} else {
mHandler.postDelayed(updateClock, 10);
}
}
};
public void setOffCourse() {
super.setStatus(getString(R.string.off_course));
}
public void next() {
mHandler.removeCallbacks(updateClock);
RaceTimerActivity a = (RaceTimerActivity) getActivity();
a.getFragment(new RaceTimerFrag4(), 4);
}
public void startPressed() {
// Ignore
}
}
| 5,522 | 0.551974 | 0.538573 | 171 | 31.292398 | 25.919508 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.508772 | false | false |
14
|
20a01ea2a156ce34a6a2b700590f5a9bb4f6a297
| 36,730,560,324,411 |
3f495c669d7715d20977d983096404b9ede2d6a7
|
/basislibrary/src/main/java/com/gingold/basislibrary/view/LvRefresh/BasisLvRefreshHV.java
|
e7b292e8ce44b68868a8a81746c18bf2ecd12d9c
|
[] |
no_license
|
hayukleung/BasisDependency
|
https://github.com/hayukleung/BasisDependency
|
20268cb59c0bbdc50622acd5fa465827b2a57e6a
|
8d50fc79a2cfc4f4cbbb1748aa3d69e3c0436ccc
|
refs/heads/master
| 2023-03-11T22:57:09.153000 | 2021-03-02T07:22:12 | 2021-03-02T07:22:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.gingold.basislibrary.view.LvRefresh;
import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.gingold.basislibrary.R;
import com.gingold.basislibrary.view.CircleProgress.CircleProgressView;
/**
* 下拉刷新listView头布局
*/
public class BasisLvRefreshHV extends LinearLayout {
private LinearLayout mContainer;
private ImageView mArrowImageView;
private CircleProgressView mCircleProgressView;
private TextView mStatusTextView;
private int mState = STATE_NORMAL;
private Animation mRotateUpAnim;
private Animation mRotateDownAnim;
private final int ROTATE_ANIM_DURATION = 252;
public final static int STATE_NORMAL = 0;//默认状态(下拉刷新和刷新完成)
public final static int STATE_READY = 1;//松开刷新
public final static int STATE_REFRESHING = 2;//正在刷新
public BasisLvRefreshHV(Context context) {
super(context);
initView(context);
}
public BasisLvRefreshHV(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
private void initView(Context context) {
// 初始情况,设置下拉刷新view高度为0
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0);
mContainer = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.lv_refresh_header, null);
addView(mContainer, lp);
setGravity(Gravity.CENTER);//下拉时,布局默认显示center
mArrowImageView = (ImageView) findViewById(R.id.iv_lv_header_arrow);//箭头
mStatusTextView = (TextView) findViewById(R.id.tv_lv_header_status);//刷新状态
mCircleProgressView = (CircleProgressView) findViewById(R.id.cpv_lv_header);//进度条
//箭头旋转向上动画(默认向下)
mRotateUpAnim = new RotateAnimation(0.0f, -180.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
mRotateUpAnim.setDuration(ROTATE_ANIM_DURATION);
mRotateUpAnim.setFillAfter(true);
//箭头旋转向下状态
mRotateDownAnim = new RotateAnimation(-180.0f, 0.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
mRotateDownAnim.setDuration(ROTATE_ANIM_DURATION);
mRotateDownAnim.setFillAfter(true);
}
public void setState(int state) {
if (state == mState) return;
if (state == STATE_REFRESHING) { // 正在刷新
mArrowImageView.clearAnimation();
mArrowImageView.setVisibility(View.GONE);
mCircleProgressView.setVisibility(View.VISIBLE);
} else { // 其它
mArrowImageView.setVisibility(View.VISIBLE);
mCircleProgressView.setVisibility(View.GONE);
}
switch (state) {
case STATE_NORMAL://默认状态(下拉刷新和刷新完成)
if (mState == STATE_READY) {//当前是准备刷新状态, 将箭头旋转朝下
mArrowImageView.startAnimation(mRotateDownAnim);
}
if (mState == STATE_REFRESHING) {
mArrowImageView.clearAnimation();
}
mStatusTextView.setText("下拉刷新");
break;
case STATE_READY://松开刷新
if (mState != STATE_READY) {
mArrowImageView.clearAnimation();
mArrowImageView.startAnimation(mRotateUpAnim);
mStatusTextView.setText("松开刷新数据");
}
break;
case STATE_REFRESHING://正在刷新
mStatusTextView.setText("正在加载...");
break;
default:
}
mState = state;
}
public void setVisiableHeight(int height) {
if (height < 0)
height = 0;
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContainer
.getLayoutParams();
lp.height = height;
mContainer.setLayoutParams(lp);
}
public int getVisiableHeight() {
return mContainer.getLayoutParams().height;
}
}
|
UTF-8
|
Java
| 4,493 |
java
|
BasisLvRefreshHV.java
|
Java
|
[] | null |
[] |
package com.gingold.basislibrary.view.LvRefresh;
import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.gingold.basislibrary.R;
import com.gingold.basislibrary.view.CircleProgress.CircleProgressView;
/**
* 下拉刷新listView头布局
*/
public class BasisLvRefreshHV extends LinearLayout {
private LinearLayout mContainer;
private ImageView mArrowImageView;
private CircleProgressView mCircleProgressView;
private TextView mStatusTextView;
private int mState = STATE_NORMAL;
private Animation mRotateUpAnim;
private Animation mRotateDownAnim;
private final int ROTATE_ANIM_DURATION = 252;
public final static int STATE_NORMAL = 0;//默认状态(下拉刷新和刷新完成)
public final static int STATE_READY = 1;//松开刷新
public final static int STATE_REFRESHING = 2;//正在刷新
public BasisLvRefreshHV(Context context) {
super(context);
initView(context);
}
public BasisLvRefreshHV(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
private void initView(Context context) {
// 初始情况,设置下拉刷新view高度为0
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0);
mContainer = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.lv_refresh_header, null);
addView(mContainer, lp);
setGravity(Gravity.CENTER);//下拉时,布局默认显示center
mArrowImageView = (ImageView) findViewById(R.id.iv_lv_header_arrow);//箭头
mStatusTextView = (TextView) findViewById(R.id.tv_lv_header_status);//刷新状态
mCircleProgressView = (CircleProgressView) findViewById(R.id.cpv_lv_header);//进度条
//箭头旋转向上动画(默认向下)
mRotateUpAnim = new RotateAnimation(0.0f, -180.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
mRotateUpAnim.setDuration(ROTATE_ANIM_DURATION);
mRotateUpAnim.setFillAfter(true);
//箭头旋转向下状态
mRotateDownAnim = new RotateAnimation(-180.0f, 0.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
mRotateDownAnim.setDuration(ROTATE_ANIM_DURATION);
mRotateDownAnim.setFillAfter(true);
}
public void setState(int state) {
if (state == mState) return;
if (state == STATE_REFRESHING) { // 正在刷新
mArrowImageView.clearAnimation();
mArrowImageView.setVisibility(View.GONE);
mCircleProgressView.setVisibility(View.VISIBLE);
} else { // 其它
mArrowImageView.setVisibility(View.VISIBLE);
mCircleProgressView.setVisibility(View.GONE);
}
switch (state) {
case STATE_NORMAL://默认状态(下拉刷新和刷新完成)
if (mState == STATE_READY) {//当前是准备刷新状态, 将箭头旋转朝下
mArrowImageView.startAnimation(mRotateDownAnim);
}
if (mState == STATE_REFRESHING) {
mArrowImageView.clearAnimation();
}
mStatusTextView.setText("下拉刷新");
break;
case STATE_READY://松开刷新
if (mState != STATE_READY) {
mArrowImageView.clearAnimation();
mArrowImageView.startAnimation(mRotateUpAnim);
mStatusTextView.setText("松开刷新数据");
}
break;
case STATE_REFRESHING://正在刷新
mStatusTextView.setText("正在加载...");
break;
default:
}
mState = state;
}
public void setVisiableHeight(int height) {
if (height < 0)
height = 0;
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContainer
.getLayoutParams();
lp.height = height;
mContainer.setLayoutParams(lp);
}
public int getVisiableHeight() {
return mContainer.getLayoutParams().height;
}
}
| 4,493 | 0.643991 | 0.636881 | 122 | 33.581966 | 24.919491 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.655738 | false | false |
14
|
5d229ef5e80e70cb072a36a9c5e2d92b1f0120bf
| 14,156,212,248,755 |
8fc2c458de5c56db603f6dd97013c9fd4d0180c6
|
/source/it/cure/core/implem/timecontroller/tcmanage/TcTimelineChecker.java
|
47e166021b0d222955e2fb7f92e61f2f1c989084
|
[
"MIT"
] |
permissive
|
robo3945/Cure
|
https://github.com/robo3945/Cure
|
121049fe128e396871a79b84189a8b09b228949d
|
d4242bb8f1f909225dd474d369086eefcfb600c6
|
refs/heads/master
| 2021-01-10T04:24:39.050000 | 2016-03-13T05:40:57 | 2016-03-13T05:40:57 | 53,617,833 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*******************************************************************************
The MIT License (MIT)
Copyright (c) 2015,2016 Roberto Battistoni, Roberto Di Pietro, Flavio Lombardi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*******************************************************************************/
package it.cure.core.implem.timecontroller.tcmanage;
import it.cure.core.implem.Context;
import it.cure.core.implem.timecontroller.message.bean.AbstractMessage;
import it.cure.core.implem.timecontroller.message.bean.HeartBeatMessage;
import java.util.Map.Entry;
import java.util.TreeMap;
/**
* Time Controller Timeline checker: checking APIs
*
*/
class TcTimelineChecker {
private TcDataController tcDataController;
/**
* @param tcDataController
*
*/
public TcTimelineChecker(TcDataController tcDataController) {
this.tcDataController = tcDataController;
}
/*
/ **
* Set the last timestamp for the arrived message
*
* @param message
* /
protected void setTimestampForTimeout(IHeartBeat message)
{
if (message.isTimeoutHacked())
{
// TODO caso di timeout hacked
this.tcDataController.getGotMessagesTimestamp().put(message, Context.FAKETIME_FOR_TIMEOUTHACKED);
}
else
{
this.tcDataController.getGotMessagesTimestamp().put(message, new BasicTimeStampService().getTimeStamp());
}
}
*/
/**
* Check the timeline and set the error
*
* @param message
*/
protected void setFlagsForTimeline(HeartBeatMessage message)
{
// does not consider response time ordinal
if (message.getTimelineOrdinal()<0)
return;
// creates the structure to organize the messages for sender ID
int senderId = message.getSender().getId();
// I must check the existence of the senderId before, otherwise the Treemap will be reinitialized
if (this.tcDataController.getRecvForSenderList().get(senderId)== null)
this.tcDataController.getRecvForSenderList().put(senderId, new TreeMap<Integer, AbstractMessage>());
TreeMap<Integer, AbstractMessage> senderTreeMap = this.tcDataController.getRecvForSenderList().get(senderId);
// add the message to the correct queue
senderTreeMap.put(message.getTimelineOrdinal(), (AbstractMessage) message);
evalTimesNG(senderTreeMap, Context.TIMELINEWINDOWPACKSIZE);
//evalNTimes(senderTreeMap, Context.TIMELINEWINDOWPACKSIZE);
}
/**
* Evaluate the last three messages and remove them
*
* @param senderTreeMap
*/
protected void eval3Times(TreeMap<Integer, AbstractMessage> senderTreeMap)
{
if (senderTreeMap.values().size()>=3)
{
// the first one is the oldest
Entry<Integer, AbstractMessage> lastEntry;
lastEntry = senderTreeMap.pollLastEntry();
HeartBeatMessage third = (HeartBeatMessage) lastEntry.getValue();
lastEntry = senderTreeMap.pollLastEntry();
HeartBeatMessage second = (HeartBeatMessage) lastEntry.getValue();
lastEntry = senderTreeMap.pollLastEntry();
HeartBeatMessage first = (HeartBeatMessage) lastEntry.getValue();
// Check the middle message timestamp
if (first!=null && second!=null && third!=null)
{
if ((second.getTimestamp().getTimestampAsLong() >= first.getTimestamp().getTimestampAsLong() &&
second.getTimestamp().getTimestampAsLong() <= third.getTimestamp().getTimestampAsLong()) == false)
{
second.setTimelineError();
//System.out.println("Timeline error of: "+second.getSender().getDesc() + " - " +second.getReceiver().getDesc() + "-idSender:" + senderId);
}
}
}
}
protected void evalNTimes(TreeMap<Integer, AbstractMessage> senderTreeMap, int N)
{
if (senderTreeMap.values().size()>=N)
{
// the first one is the oldest
HeartBeatMessage[] arHB = new HeartBeatMessage[N];
for (int i=0;i<N;i++)
{
Entry<Integer, AbstractMessage> lastEntry = senderTreeMap.pollLastEntry();
arHB[i] = (HeartBeatMessage) lastEntry.getValue();
}
// verify the timeline sequence
for (int i=0;i<N-1;i++)
{
long first = arHB[i].getTimestamp().getTimestampAsLong();
long second = arHB[i+1].getTimestamp().getTimestampAsLong();
if (first<second)
{
arHB[i+1].setTimelineError();
//System.out.println("First: "+first + " - Second: "+second);
}
}
}
}
/**
* New Generation to evaluate Timeline correctness: it analyzes a Window of N packets and considers the last and the before ones, ever!
* (created 27/12/2012)
*
* @param senderTreeMap
* @param N
*/
protected void evalTimesNG(TreeMap<Integer, AbstractMessage> senderTreeMap, int N)
{
if (senderTreeMap.values().size()>N)
{
Entry<Integer, AbstractMessage> lastEntry = senderTreeMap.pollLastEntry();
for (int i=0;i<N-1;i++)
{
Entry<Integer, AbstractMessage> beforeLastEntry = senderTreeMap.pollLastEntry();
long last = ((HeartBeatMessage) lastEntry.getValue()).getTimestamp().getTimestampAsLong();
long beforeLast = ((HeartBeatMessage) beforeLastEntry.getValue()).getTimestamp().getTimestampAsLong();
if (last<beforeLast)
{
((HeartBeatMessage) beforeLastEntry.getValue()).setTimelineError();
}
lastEntry = beforeLastEntry;
}
}
}
/** Evaluate the last three messages and remove them
*
* @param senderTreeMap
*/
protected void evalLastTimes(TreeMap<Integer, AbstractMessage> senderTreeMap)
{
if (senderTreeMap.size()>=2)
{
// the first one is the oldest
Entry<Integer, AbstractMessage> lastEntry = senderTreeMap.pollLastEntry();
HeartBeatMessage last = (HeartBeatMessage) lastEntry.getValue();
HeartBeatMessage current = (HeartBeatMessage) senderTreeMap.lastEntry().getValue();
// Check the middle message timestamp
if (last!=null && current!=null)
{
if (last.getTimestamp().getTimestampAsLong() < current.getTimestamp().getTimestampAsLong())
{
last.setTimelineError();
//System.out.println("Timeline error of: "+last.getSender().getDesc() + " - " +last.getReceiver().getDesc());
}
}
}
}
}
|
UTF-8
|
Java
| 7,007 |
java
|
TcTimelineChecker.java
|
Java
|
[
{
"context": "**\n The MIT License (MIT)\n\nCopyright (c) 2015,2016 Roberto Battistoni, Roberto Di Pietro, Flavio Lombardi\n\nPermission i",
"end": 147,
"score": 0.9998510479927063,
"start": 129,
"tag": "NAME",
"value": "Roberto Battistoni"
},
{
"context": "(MIT)\n\nCopyright (c) 2015,2016 Roberto Battistoni, Roberto Di Pietro, Flavio Lombardi\n\nPermission is hereby granted, f",
"end": 166,
"score": 0.9998471140861511,
"start": 149,
"tag": "NAME",
"value": "Roberto Di Pietro"
},
{
"context": ") 2015,2016 Roberto Battistoni, Roberto Di Pietro, Flavio Lombardi\n\nPermission is hereby granted, free of charge, to",
"end": 183,
"score": 0.9998512864112854,
"start": 168,
"tag": "NAME",
"value": "Flavio Lombardi"
}
] | null |
[] |
/*******************************************************************************
The MIT License (MIT)
Copyright (c) 2015,2016 <NAME>, <NAME>, <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*******************************************************************************/
package it.cure.core.implem.timecontroller.tcmanage;
import it.cure.core.implem.Context;
import it.cure.core.implem.timecontroller.message.bean.AbstractMessage;
import it.cure.core.implem.timecontroller.message.bean.HeartBeatMessage;
import java.util.Map.Entry;
import java.util.TreeMap;
/**
* Time Controller Timeline checker: checking APIs
*
*/
class TcTimelineChecker {
private TcDataController tcDataController;
/**
* @param tcDataController
*
*/
public TcTimelineChecker(TcDataController tcDataController) {
this.tcDataController = tcDataController;
}
/*
/ **
* Set the last timestamp for the arrived message
*
* @param message
* /
protected void setTimestampForTimeout(IHeartBeat message)
{
if (message.isTimeoutHacked())
{
// TODO caso di timeout hacked
this.tcDataController.getGotMessagesTimestamp().put(message, Context.FAKETIME_FOR_TIMEOUTHACKED);
}
else
{
this.tcDataController.getGotMessagesTimestamp().put(message, new BasicTimeStampService().getTimeStamp());
}
}
*/
/**
* Check the timeline and set the error
*
* @param message
*/
protected void setFlagsForTimeline(HeartBeatMessage message)
{
// does not consider response time ordinal
if (message.getTimelineOrdinal()<0)
return;
// creates the structure to organize the messages for sender ID
int senderId = message.getSender().getId();
// I must check the existence of the senderId before, otherwise the Treemap will be reinitialized
if (this.tcDataController.getRecvForSenderList().get(senderId)== null)
this.tcDataController.getRecvForSenderList().put(senderId, new TreeMap<Integer, AbstractMessage>());
TreeMap<Integer, AbstractMessage> senderTreeMap = this.tcDataController.getRecvForSenderList().get(senderId);
// add the message to the correct queue
senderTreeMap.put(message.getTimelineOrdinal(), (AbstractMessage) message);
evalTimesNG(senderTreeMap, Context.TIMELINEWINDOWPACKSIZE);
//evalNTimes(senderTreeMap, Context.TIMELINEWINDOWPACKSIZE);
}
/**
* Evaluate the last three messages and remove them
*
* @param senderTreeMap
*/
protected void eval3Times(TreeMap<Integer, AbstractMessage> senderTreeMap)
{
if (senderTreeMap.values().size()>=3)
{
// the first one is the oldest
Entry<Integer, AbstractMessage> lastEntry;
lastEntry = senderTreeMap.pollLastEntry();
HeartBeatMessage third = (HeartBeatMessage) lastEntry.getValue();
lastEntry = senderTreeMap.pollLastEntry();
HeartBeatMessage second = (HeartBeatMessage) lastEntry.getValue();
lastEntry = senderTreeMap.pollLastEntry();
HeartBeatMessage first = (HeartBeatMessage) lastEntry.getValue();
// Check the middle message timestamp
if (first!=null && second!=null && third!=null)
{
if ((second.getTimestamp().getTimestampAsLong() >= first.getTimestamp().getTimestampAsLong() &&
second.getTimestamp().getTimestampAsLong() <= third.getTimestamp().getTimestampAsLong()) == false)
{
second.setTimelineError();
//System.out.println("Timeline error of: "+second.getSender().getDesc() + " - " +second.getReceiver().getDesc() + "-idSender:" + senderId);
}
}
}
}
protected void evalNTimes(TreeMap<Integer, AbstractMessage> senderTreeMap, int N)
{
if (senderTreeMap.values().size()>=N)
{
// the first one is the oldest
HeartBeatMessage[] arHB = new HeartBeatMessage[N];
for (int i=0;i<N;i++)
{
Entry<Integer, AbstractMessage> lastEntry = senderTreeMap.pollLastEntry();
arHB[i] = (HeartBeatMessage) lastEntry.getValue();
}
// verify the timeline sequence
for (int i=0;i<N-1;i++)
{
long first = arHB[i].getTimestamp().getTimestampAsLong();
long second = arHB[i+1].getTimestamp().getTimestampAsLong();
if (first<second)
{
arHB[i+1].setTimelineError();
//System.out.println("First: "+first + " - Second: "+second);
}
}
}
}
/**
* New Generation to evaluate Timeline correctness: it analyzes a Window of N packets and considers the last and the before ones, ever!
* (created 27/12/2012)
*
* @param senderTreeMap
* @param N
*/
protected void evalTimesNG(TreeMap<Integer, AbstractMessage> senderTreeMap, int N)
{
if (senderTreeMap.values().size()>N)
{
Entry<Integer, AbstractMessage> lastEntry = senderTreeMap.pollLastEntry();
for (int i=0;i<N-1;i++)
{
Entry<Integer, AbstractMessage> beforeLastEntry = senderTreeMap.pollLastEntry();
long last = ((HeartBeatMessage) lastEntry.getValue()).getTimestamp().getTimestampAsLong();
long beforeLast = ((HeartBeatMessage) beforeLastEntry.getValue()).getTimestamp().getTimestampAsLong();
if (last<beforeLast)
{
((HeartBeatMessage) beforeLastEntry.getValue()).setTimelineError();
}
lastEntry = beforeLastEntry;
}
}
}
/** Evaluate the last three messages and remove them
*
* @param senderTreeMap
*/
protected void evalLastTimes(TreeMap<Integer, AbstractMessage> senderTreeMap)
{
if (senderTreeMap.size()>=2)
{
// the first one is the oldest
Entry<Integer, AbstractMessage> lastEntry = senderTreeMap.pollLastEntry();
HeartBeatMessage last = (HeartBeatMessage) lastEntry.getValue();
HeartBeatMessage current = (HeartBeatMessage) senderTreeMap.lastEntry().getValue();
// Check the middle message timestamp
if (last!=null && current!=null)
{
if (last.getTimestamp().getTimestampAsLong() < current.getTimestamp().getTimestampAsLong())
{
last.setTimelineError();
//System.out.println("Timeline error of: "+last.getSender().getDesc() + " - " +last.getReceiver().getDesc());
}
}
}
}
}
| 6,975 | 0.702012 | 0.698159 | 216 | 31.439816 | 33.868156 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.347222 | false | false |
14
|
1fd55c5f855e5bbc03be2681818c356c46e56e00
| 15,453,292,371,313 |
938c11bf6098196528632cd09365d66884a508e8
|
/src/test/java/TestPairwise.java
|
de0ad68bca8f97598e2b193c5118fe7189f9e84a
|
[] |
no_license
|
Purik/sirius-sdk-java
|
https://github.com/Purik/sirius-sdk-java
|
fd659c5a3eb8a1f1bbcf66b0f4411aea348f474c
|
40c6cad318abdf06a65d6321c3789285ef071bd4
|
refs/heads/master
| 2023-08-22T21:52:45.805000 | 2021-10-01T11:41:09 | 2021-10-01T11:41:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import com.sirius.sdk.agent.CloudAgent;
import com.sirius.sdk.agent.pairwise.Pairwise;
import com.sirius.sdk.utils.Pair;
import helpers.ConfTest;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
public class TestPairwise {
ConfTest confTest;
@Before
public void configureTest() {
confTest = ConfTest.newInstance();
}
@Test
public void testPairwiseList() {
CloudAgent agent1 = confTest.agent1();
CloudAgent agent2 = confTest.agent2();
agent1.open();
agent2.open();
Pair<String,String> did1Verkey1 = agent1.getWallet().getDid().createAndStoreMyDid();
Pair<String,String> did2Verkey2 = agent2.getWallet().getDid().createAndStoreMyDid();
JSONObject metaObj = new JSONObject();
metaObj.put("test","test-value");
Pairwise pairwise = new Pairwise(new Pairwise.Me(did1Verkey1.first,did1Verkey1.second),
new Pairwise.Their(did2Verkey2.first,"Test-Pairwise","http://endpoint",did2Verkey2.second),metaObj);
List<Object> list1 = agent1.getWallet().getPairwise().listPairwise();
agent1.getPairwiseList().ensureExists(pairwise);
List<Object> list2 = agent1.getWallet().getPairwise().listPairwise();
Assert.assertTrue(list1.size()<list2.size());
boolean ok = agent1.getPairwiseList().isExists(did2Verkey2.first);
Assert.assertTrue(ok);
Pairwise pairwise2 = agent1.getPairwiseList().loadForVerkey(did2Verkey2.second);
Assert.assertEquals(pairwise.getMetadata().toString(),pairwise2.getMetadata().toString());
agent1.close();
agent2.close();
}
}
|
UTF-8
|
Java
| 1,723 |
java
|
TestPairwise.java
|
Java
|
[] | null |
[] |
import com.sirius.sdk.agent.CloudAgent;
import com.sirius.sdk.agent.pairwise.Pairwise;
import com.sirius.sdk.utils.Pair;
import helpers.ConfTest;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
public class TestPairwise {
ConfTest confTest;
@Before
public void configureTest() {
confTest = ConfTest.newInstance();
}
@Test
public void testPairwiseList() {
CloudAgent agent1 = confTest.agent1();
CloudAgent agent2 = confTest.agent2();
agent1.open();
agent2.open();
Pair<String,String> did1Verkey1 = agent1.getWallet().getDid().createAndStoreMyDid();
Pair<String,String> did2Verkey2 = agent2.getWallet().getDid().createAndStoreMyDid();
JSONObject metaObj = new JSONObject();
metaObj.put("test","test-value");
Pairwise pairwise = new Pairwise(new Pairwise.Me(did1Verkey1.first,did1Verkey1.second),
new Pairwise.Their(did2Verkey2.first,"Test-Pairwise","http://endpoint",did2Verkey2.second),metaObj);
List<Object> list1 = agent1.getWallet().getPairwise().listPairwise();
agent1.getPairwiseList().ensureExists(pairwise);
List<Object> list2 = agent1.getWallet().getPairwise().listPairwise();
Assert.assertTrue(list1.size()<list2.size());
boolean ok = agent1.getPairwiseList().isExists(did2Verkey2.first);
Assert.assertTrue(ok);
Pairwise pairwise2 = agent1.getPairwiseList().loadForVerkey(did2Verkey2.second);
Assert.assertEquals(pairwise.getMetadata().toString(),pairwise2.getMetadata().toString());
agent1.close();
agent2.close();
}
}
| 1,723 | 0.684852 | 0.663378 | 52 | 32.134617 | 31.444719 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.769231 | false | false |
14
|
3d57c9c2fd27bbe88f68529cd4df39a7b24cf0bb
| 60,129,568,201 |
7e77eb813974abdf99d83aefd3a6aaa52e1712db
|
/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/robot/RobotUtilities.java
|
6e396bbf8e43df4ed09b151d946c2983094e8ac8
|
[] |
no_license
|
ykarim/FTC-Piotech-VelocityVortex
|
https://github.com/ykarim/FTC-Piotech-VelocityVortex
|
96fae91728feeed9248af30217774bb4347041bc
|
3f314538bf5bf6bc181112c9e8f0b5d4cd102804
|
refs/heads/master
| 2021-01-22T05:28:04.232000 | 2017-03-06T21:32:34 | 2017-03-06T21:32:34 | 81,663,857 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.firstinspires.ftc.teamcode.robot;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.UltrasonicSensor;
import com.qualcomm.robotcore.util.ElapsedTime;
import org.firstinspires.ftc.teamcode.sensors.beacon.BeaconStatus;
import org.firstinspires.ftc.teamcode.sensors.utils.PID;
import org.firstinspires.ftc.teamcode.utils.Color;
import org.firstinspires.ftc.teamcode.utils.OpModeUtils;
import org.lasarobotics.vision.opmode.LinearVisionOpMode;
import static java.lang.Thread.sleep;
public class RobotUtilities {
private Robot robot = null;
public boolean continuousIntake = false;
public boolean continuousShoot = false;
private boolean lightLED = true;
private boolean secondUltraTest = false;
private double prevPos= 0;
private double previousTime = 0;
public RobotUtilities(Robot robot) {
this.robot = robot;
}
public void capBall() {
//TODO
}
/**
* Pushes beacon button once aligned with wall
* @param robot
*/
public void pushBeacon(Robot robot, Color desiredColor) {
RobotMovement robotMovement = new RobotMovement(robot);
robotMovement.orient(RobotMovement.Orientation.RIGHT);
if (BeaconStatus.getLeftColor() != desiredColor &&
BeaconStatus.getRightColor() != desiredColor) {
robotMovement.move(RobotMovement.Direction.NORTH, 4);
robotMovement.move(RobotMovement.Direction.SOUTH, 2);
}
}
public void toggleLightLED() {
if (lightLED) {
lightLED = false;
robot.lightSensor.enableLed(lightLED);
} else {
lightLED = true;
robot.lightSensor.enableLed(lightLED);
}
}
public void shootDoubleBall(LinearOpMode opMode, double timeout) {
long stop = System.currentTimeMillis() + Math.round(timeout * 1000);
shootBalls(true);
OpModeUtils.waitFor(opMode, RobotConstants.shotWaitPeriod);
if (System.currentTimeMillis() < stop) {
intakeBalls(true);
OpModeUtils.waitFor(opMode, RobotConstants.intakeWaitPeriod);
}
intakeBalls(false);
shootBalls(false);
}
public void shootDoubleBall(LinearVisionOpMode opMode, double timeout) {
long stop = System.currentTimeMillis() + Math.round(timeout * 1000);
shootBalls(true);
OpModeUtils.waitFor(opMode, RobotConstants.shotWaitPeriod);
if (System.currentTimeMillis() < stop) {
intakeBalls(true);
OpModeUtils.waitFor(opMode, RobotConstants.intakeWaitPeriod);
}
intakeBalls(false);
shootBalls(false);
}
public void intakeBalls(boolean condition) {
if (condition) {
robot.intake.setPower(-RobotConstants.intakeSpeed);
} else {
robot.intake.setPower(0);
}
}
public void shootBalls(boolean condition) {
if (condition) {
robot.shoot.setPower(-RobotConstants.shootSpeed);
} else {
robot.shoot.setPower(0);
}
}
public void continuousIntake() {
if (!continuousIntake) {
continuousIntake = true;
robot.intake.setPower(-RobotConstants.intakeSpeed);
} else {
continuousIntake = false;
robot.intake.setPower(0);
}
}
public void continuousShoot() {
if (!continuousShoot) {
continuousShoot = true;
robot.shoot.setPower(-RobotConstants.shootSpeed);
} else {
continuousShoot = false;
robot.shoot.setPower(0);
}
}
/**
* Aligns ODS by moving left or right given which side line is located on
* @param direction
*/
public void alignWithLine(RobotMovement.Direction direction, int timeoutSec) {
ElapsedTime time = new ElapsedTime();
time.reset();
if (!lightLED) {
toggleLightLED();
}
RobotMovement robotMovement = new RobotMovement(robot);
RobotConstants.moveSpeed = 0.4;
robotMovement.orient(RobotMovement.Orientation.RIGHT); //Sensors are currently on the right
robotMovement.move(direction);
while (robot.lightSensor.getLightDetected() < RobotConstants.perfectWhiteLineValue
&& time.seconds() < timeoutSec) {
if (robot.lightSensor.getLightDetected() > RobotConstants.whiteLineValue) {
RobotConstants.moveSpeed = 0.0;
break;
} else if (robot.lightSensor.getLightDetected() > 0.3) {
RobotConstants.moveSpeed = 0.2;
} else if (robot.lightSensor.getLightDetected() > 0.2) {
RobotConstants.moveSpeed = 0.3;
} else {
RobotConstants.moveSpeed = 0.4;
}
robotMovement.move(direction);
}
robotMovement.move(RobotMovement.Direction.NONE);
RobotConstants.moveSpeed = 1.0;
toggleLightLED();
// Add PID loop to slow down once reaching
}
//TODO: Change for Blue or Red
public boolean alignWithWallUsingGyro() {
RobotMovement robotMovement = new RobotMovement(robot);
if (robot.imu.getHeading() < RobotConstants.perfectGyroAngleMin) {
while (robot.imu.getHeading() < RobotConstants.perfectGyroAngleMin) {
robotMovement.rotate(RobotMovement.Direction.ROTATE_LEFT,
Math.abs(robot.imu.getHeading() - RobotConstants.perfectGyroAngleMin));
}
} else if (robot.imu.getHeading() > RobotConstants.perfectGyroAngleMax) {
while (robot.imu.getHeading() > RobotConstants.perfectGyroAngleMax) {
robotMovement.rotate(RobotMovement.Direction.ROTATE_RIGHT,
Math.abs(robot.imu.getHeading() - RobotConstants.perfectGyroAngleMax));
}
}
return false;
}
public double getGyroAngle() {
return (robot.imu.getHeading() - RobotConstants.homeHeadingAngle);
}
public double getShooterRate() {
double posC = robot.shoot.getCurrentPosition() - prevPos;
try {
sleep(100);
} catch (InterruptedException ie) {
}
double tChange = System.nanoTime() - previousTime;
previousTime = System.nanoTime();
tChange = tChange / 1e9;
prevPos = robot.shoot.getCurrentPosition();
return posC / tChange;
}
}
|
UTF-8
|
Java
| 6,547 |
java
|
RobotUtilities.java
|
Java
|
[] | null |
[] |
package org.firstinspires.ftc.teamcode.robot;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.UltrasonicSensor;
import com.qualcomm.robotcore.util.ElapsedTime;
import org.firstinspires.ftc.teamcode.sensors.beacon.BeaconStatus;
import org.firstinspires.ftc.teamcode.sensors.utils.PID;
import org.firstinspires.ftc.teamcode.utils.Color;
import org.firstinspires.ftc.teamcode.utils.OpModeUtils;
import org.lasarobotics.vision.opmode.LinearVisionOpMode;
import static java.lang.Thread.sleep;
public class RobotUtilities {
private Robot robot = null;
public boolean continuousIntake = false;
public boolean continuousShoot = false;
private boolean lightLED = true;
private boolean secondUltraTest = false;
private double prevPos= 0;
private double previousTime = 0;
public RobotUtilities(Robot robot) {
this.robot = robot;
}
public void capBall() {
//TODO
}
/**
* Pushes beacon button once aligned with wall
* @param robot
*/
public void pushBeacon(Robot robot, Color desiredColor) {
RobotMovement robotMovement = new RobotMovement(robot);
robotMovement.orient(RobotMovement.Orientation.RIGHT);
if (BeaconStatus.getLeftColor() != desiredColor &&
BeaconStatus.getRightColor() != desiredColor) {
robotMovement.move(RobotMovement.Direction.NORTH, 4);
robotMovement.move(RobotMovement.Direction.SOUTH, 2);
}
}
public void toggleLightLED() {
if (lightLED) {
lightLED = false;
robot.lightSensor.enableLed(lightLED);
} else {
lightLED = true;
robot.lightSensor.enableLed(lightLED);
}
}
public void shootDoubleBall(LinearOpMode opMode, double timeout) {
long stop = System.currentTimeMillis() + Math.round(timeout * 1000);
shootBalls(true);
OpModeUtils.waitFor(opMode, RobotConstants.shotWaitPeriod);
if (System.currentTimeMillis() < stop) {
intakeBalls(true);
OpModeUtils.waitFor(opMode, RobotConstants.intakeWaitPeriod);
}
intakeBalls(false);
shootBalls(false);
}
public void shootDoubleBall(LinearVisionOpMode opMode, double timeout) {
long stop = System.currentTimeMillis() + Math.round(timeout * 1000);
shootBalls(true);
OpModeUtils.waitFor(opMode, RobotConstants.shotWaitPeriod);
if (System.currentTimeMillis() < stop) {
intakeBalls(true);
OpModeUtils.waitFor(opMode, RobotConstants.intakeWaitPeriod);
}
intakeBalls(false);
shootBalls(false);
}
public void intakeBalls(boolean condition) {
if (condition) {
robot.intake.setPower(-RobotConstants.intakeSpeed);
} else {
robot.intake.setPower(0);
}
}
public void shootBalls(boolean condition) {
if (condition) {
robot.shoot.setPower(-RobotConstants.shootSpeed);
} else {
robot.shoot.setPower(0);
}
}
public void continuousIntake() {
if (!continuousIntake) {
continuousIntake = true;
robot.intake.setPower(-RobotConstants.intakeSpeed);
} else {
continuousIntake = false;
robot.intake.setPower(0);
}
}
public void continuousShoot() {
if (!continuousShoot) {
continuousShoot = true;
robot.shoot.setPower(-RobotConstants.shootSpeed);
} else {
continuousShoot = false;
robot.shoot.setPower(0);
}
}
/**
* Aligns ODS by moving left or right given which side line is located on
* @param direction
*/
public void alignWithLine(RobotMovement.Direction direction, int timeoutSec) {
ElapsedTime time = new ElapsedTime();
time.reset();
if (!lightLED) {
toggleLightLED();
}
RobotMovement robotMovement = new RobotMovement(robot);
RobotConstants.moveSpeed = 0.4;
robotMovement.orient(RobotMovement.Orientation.RIGHT); //Sensors are currently on the right
robotMovement.move(direction);
while (robot.lightSensor.getLightDetected() < RobotConstants.perfectWhiteLineValue
&& time.seconds() < timeoutSec) {
if (robot.lightSensor.getLightDetected() > RobotConstants.whiteLineValue) {
RobotConstants.moveSpeed = 0.0;
break;
} else if (robot.lightSensor.getLightDetected() > 0.3) {
RobotConstants.moveSpeed = 0.2;
} else if (robot.lightSensor.getLightDetected() > 0.2) {
RobotConstants.moveSpeed = 0.3;
} else {
RobotConstants.moveSpeed = 0.4;
}
robotMovement.move(direction);
}
robotMovement.move(RobotMovement.Direction.NONE);
RobotConstants.moveSpeed = 1.0;
toggleLightLED();
// Add PID loop to slow down once reaching
}
//TODO: Change for Blue or Red
public boolean alignWithWallUsingGyro() {
RobotMovement robotMovement = new RobotMovement(robot);
if (robot.imu.getHeading() < RobotConstants.perfectGyroAngleMin) {
while (robot.imu.getHeading() < RobotConstants.perfectGyroAngleMin) {
robotMovement.rotate(RobotMovement.Direction.ROTATE_LEFT,
Math.abs(robot.imu.getHeading() - RobotConstants.perfectGyroAngleMin));
}
} else if (robot.imu.getHeading() > RobotConstants.perfectGyroAngleMax) {
while (robot.imu.getHeading() > RobotConstants.perfectGyroAngleMax) {
robotMovement.rotate(RobotMovement.Direction.ROTATE_RIGHT,
Math.abs(robot.imu.getHeading() - RobotConstants.perfectGyroAngleMax));
}
}
return false;
}
public double getGyroAngle() {
return (robot.imu.getHeading() - RobotConstants.homeHeadingAngle);
}
public double getShooterRate() {
double posC = robot.shoot.getCurrentPosition() - prevPos;
try {
sleep(100);
} catch (InterruptedException ie) {
}
double tChange = System.nanoTime() - previousTime;
previousTime = System.nanoTime();
tChange = tChange / 1e9;
prevPos = robot.shoot.getCurrentPosition();
return posC / tChange;
}
}
| 6,547 | 0.626852 | 0.621201 | 203 | 31.251232 | 26.382202 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.453202 | false | false |
14
|
c554d353ea969be17d1a9a98aaf3e6d4eadc867c
| 60,129,570,789 |
2a3f19a4a2b91d9d715378aadb0b1557997ffafe
|
/sources/com/amap/api/mapcore/util/C0850g.java
|
e21ca5bbb43e9e6f10ae9f2a4ec09464357b9441
|
[] |
no_license
|
amelieko/McDonalds-java
|
https://github.com/amelieko/McDonalds-java
|
ce5062f863f7f1cbe2677938a67db940c379d0a9
|
2fe00d672caaa7b97c4ff3acdb0e1678669b0300
|
refs/heads/master
| 2022-01-09T22:10:40.360000 | 2019-04-21T14:47:20 | 2019-04-21T14:47:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.amap.api.mapcore.util;
/* compiled from: AMapDelegateImp */
/* renamed from: com.amap.api.mapcore.util.g */
class C0850g implements Runnable {
/* renamed from: a */
final /* synthetic */ AMapDelegateImp f2014a;
C0850g(AMapDelegateImp aMapDelegateImp) {
this.f2014a = aMapDelegateImp;
}
public void run() {
if (this.f2014a.f1594aj != null) {
this.f2014a.f1577aS = true;
if (this.f2014a.f1596al != null) {
this.f2014a.f1596al.setVisible(false);
}
}
}
}
|
UTF-8
|
Java
| 566 |
java
|
C0850g.java
|
Java
|
[] | null |
[] |
package com.amap.api.mapcore.util;
/* compiled from: AMapDelegateImp */
/* renamed from: com.amap.api.mapcore.util.g */
class C0850g implements Runnable {
/* renamed from: a */
final /* synthetic */ AMapDelegateImp f2014a;
C0850g(AMapDelegateImp aMapDelegateImp) {
this.f2014a = aMapDelegateImp;
}
public void run() {
if (this.f2014a.f1594aj != null) {
this.f2014a.f1577aS = true;
if (this.f2014a.f1596al != null) {
this.f2014a.f1596al.setVisible(false);
}
}
}
}
| 566 | 0.595406 | 0.510601 | 21 | 25.952381 | 18.66363 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.238095 | false | false |
14
|
1c1e2c98707f801aa8c6f800feb806bef619f445
| 36,395,552,875,239 |
9fa2d81dd1bb339c1244665bc599b68995bbe08b
|
/AutoTracker/src/com/silentcorp/autotracker/db/EventDB.java
|
e367b1cc7a47ab7da53b570252031d7423ab58ca
|
[] |
no_license
|
neandertal-nanospace/autotracker
|
https://github.com/neandertal-nanospace/autotracker
|
e56e8797492dec611bd212a35dcfb5aa647ca9c9
|
867c127a6378434ff638e148e2a387b2b5473522
|
refs/heads/master
| 2016-08-04T22:21:00.718000 | 2013-08-13T17:12:06 | 2013-08-13T17:12:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.silentcorp.autotracker.db;
import java.util.Iterator;
import java.util.Set;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import com.silentcorp.autotracker.beans.EventBean;
import com.silentcorp.autotracker.utils.DoubleNumber;
import com.silentcorp.autotracker.utils.EventType;
import com.silentcorp.autotracker.utils.Utils;
/**
* Event table database helper to contain functionality to access and modify the
* Event table.
*
* @author neandertal
*/
public class EventDB
{
// Table name
protected final static String TABLE_EVENT = "event";
// Columns
private final static String COL_ID = Utils.COL_ID;
private final static String COL_VEHICLE_REF = "vehicle_ref";
private final static String COL_EVENT_DATE = "event_date";
private final static String COL_EVENT_TYPE = "event_type";
private final static String COL_COST = "cost";
private final static String COL_ODOMETER = "odometer";
private final static String COL_NOTE = "note";
private final static String COL_FUEL = "fuel";
private final static String COL_QUANTITY = "quantity";
private final static String COL_PRICE = "price";
private final static String COL_DESCRIPRION = "description";
private final static String COL_PLACE = "place";
// @formatter:off
private final static String CREATE_TABLE =
"CREATE TABLE " + TABLE_EVENT + " ( " +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_VEHICLE_REF + " INTEGER, " +
COL_EVENT_DATE + " INTEGER NOT NULL, " +
COL_EVENT_TYPE + " TEXT NOT NULL, " +
COL_COST + " INTEGER NOT NULL, " +
COL_ODOMETER + " INTEGER, " +
COL_NOTE + " TEXT, " +
COL_FUEL + " TEXT, " +
COL_QUANTITY + " INTEGER, " +
COL_PRICE + " INTEGER, " +
COL_DESCRIPRION + " TEXT, " +
COL_PLACE + " TEXT )";
private final static String DROP_TABLE =
"DROP TABLE IF EXISTS " + TABLE_EVENT;
// Columns to be used for list entries
public final static String[] LIST_COLUMNS = new String[] {
COL_ID,
COL_VEHICLE_REF,
COL_EVENT_DATE,
COL_EVENT_TYPE,
COL_COST,
COL_FUEL,
COL_QUANTITY,
COL_PRICE,
COL_DESCRIPRION };
//Order by date - most recent on top
private static final String ORDER = COL_EVENT_DATE + " DESC";
// @formatter:on
/**
* Creates the event table
*
* @param db the DB
*/
public static void onCreate(SQLiteDatabase db)
{
Log.i(VehicleDB.class.getName(), "Creating table: " + CREATE_TABLE);
db.execSQL(CREATE_TABLE);
}
/**
* Drops and recreates the event table TODO not on production environment
*
* @param db the DB
* @param oldVersion old DB version
* @param newVersion new DB version
*/
public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.i(VehicleDB.class.getName(), "Upgrading DB from V:" + oldVersion + " to V:" + newVersion);
// Drop older table if existed
Log.i(VehicleDB.class.getName(), "Dropping old table: " + DROP_TABLE);
db.execSQL(DROP_TABLE);
// Create tables again
onCreate(db);
}
/**
* Get cursor loader for events list activity
*
* @param context
* @return
*/
public static Loader<Cursor> getCursorLoader(Context context)
{
CursorLoader cursorLoader = new CursorLoader(context, DBContentProvider.EVENTS_URI, EventDB.LIST_COLUMNS, null,
null, ORDER);
return cursorLoader;
}
/**
* Get cursor to filter Fuel, Maintenance, Repair, Payment events for list
* adapter
*
* @param contentResolver
* @param hideFE if true hide Fuel events
* @param hideME if true hide Maintenance events
* @param hideRE if true hide Repair events
* @param hidePE if true hide Payment events
* @return new Cursor
*/
public static Cursor getFilteredCursor(Context context, boolean hideFE, boolean hideME, boolean hideRE,
boolean hidePE)
{
// TODO better sql ?
StringBuilder whereQ = new StringBuilder();
boolean hasPrevious;
if (hideFE && hideME && hideRE && hidePE)
{
whereQ.append(COL_EVENT_TYPE);
whereQ.append(" IS NULL");
}
else
{
hasPrevious = false;
if (!hideFE)
{
whereQ.append(COL_EVENT_TYPE);
whereQ.append("='");
whereQ.append(EventType.FUEL_EVENT.toString());
whereQ.append("'");
hasPrevious = true;
}
if (!hideME)
{
if (hasPrevious)
{
whereQ.append(" OR ");
}
whereQ.append(COL_EVENT_TYPE);
whereQ.append("='");
whereQ.append(EventType.MAINTENANCE_EVENT.toString());
whereQ.append("'");
hasPrevious = true;
}
if (!hideRE)
{
if (hasPrevious)
{
whereQ.append(" OR ");
}
whereQ.append(COL_EVENT_TYPE);
whereQ.append("='");
whereQ.append(EventType.REPAIR_EVENT.toString());
whereQ.append("'");
hasPrevious = true;
}
if (!hidePE)
{
if (hasPrevious)
{
whereQ.append(" OR ");
}
whereQ.append(COL_EVENT_TYPE);
whereQ.append("='");
whereQ.append(EventType.PAYMENT_EVENT.toString());
whereQ.append("'");
hasPrevious = true;
}
}
// Get filtered cursor
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(DBContentProvider.EVENTS_URI, LIST_COLUMNS, whereQ.toString(), null,
ORDER);
return cursor;
}
/**
* Read an event from the DB given its ID
*
* @param contentResolver content resolver
* @param id event ID
* @param event object to fill, if NULL, new created and returned
* @return full event object
* @throws SQLException
*/
public static EventBean readEvent(Context context, long id, EventBean event) throws SQLException
{
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Uri.parse(DBContentProvider.EVENTS_URI + "/" + id);
// Read all columns for the record
Cursor cursor = contentResolver.query(uri, null, null, null, null);
if (cursor == null || cursor.getCount() == 0)
{
throw new SQLException("Unable to find event with ID: " + id + " Corrupt DB?");
}
// more then one event
if (cursor.getCount() > 1)
{
throw new SQLException("More then one event with ID: " + id + " Corrupt DB?");
}
cursor.moveToFirst();
if (event == null)
{
event = new EventBean();
}
event.setId(id);
event.setVehicleRef(Utils.readLong(cursor, COL_VEHICLE_REF, TABLE_EVENT));
event.setEventDate(Utils.readLong(cursor, COL_EVENT_DATE, TABLE_EVENT));
event.setEventType(EventType.parse(Utils.readString(cursor, COL_EVENT_TYPE, TABLE_EVENT)));
event.setCost(Utils.readDouble(cursor, COL_COST, TABLE_EVENT));
event.setOdometer(Utils.readWhole(cursor, COL_ODOMETER, TABLE_EVENT));
event.setNote(Utils.readString(cursor, COL_NOTE, TABLE_EVENT));
event.setFuel(Utils.readString(cursor, COL_FUEL, TABLE_EVENT));
event.setQuantity(Utils.readDouble(cursor, COL_QUANTITY, TABLE_EVENT));
event.setPrice(Utils.readDouble(cursor, COL_PRICE, TABLE_EVENT));
event.setDescription(Utils.readString(cursor, COL_DESCRIPRION, TABLE_EVENT));
event.setPlace(Utils.readString(cursor, COL_PLACE, TABLE_EVENT));
cursor.close();
return event;
}
/**
* Returns event bean's values as content value map
*
* @param event
* @return
*/
private static ContentValues getAsContentValues(EventBean event)
{
ContentValues values = new ContentValues();
values.put(COL_VEHICLE_REF, event.getVehicleRef());
values.put(COL_EVENT_DATE, event.getEventDate());
values.put(COL_EVENT_TYPE, event.getEventType().toString());
values.put(COL_COST, event.getCost().getDoubleInt());
values.put(COL_ODOMETER, event.getOdometer().getWholeInt());
values.put(COL_NOTE, event.getNote());
values.put(COL_FUEL, event.getFuel());
values.put(COL_QUANTITY, event.getQuantity().getDoubleInt());
values.put(COL_PRICE, event.getPrice().getDoubleInt());
values.put(COL_DESCRIPRION, event.getDescription());
values.put(COL_PLACE, event.getPlace());
return values;
}
/**
* Delete events TODO better sql query
*
* @param resolver
* @param ids
*/
public static void deleteEvents(Context context, Set<Long> ids)
{
StringBuilder sb = new StringBuilder();
String[] args = new String[ids.size()];
Iterator<Long> iter = ids.iterator();
int index = 0;
while (iter.hasNext())
{
Long id = iter.next();
args[index] = Long.toString(id);
index++;
sb.append(COL_ID);
sb.append(" = ?");
if (iter.hasNext())
{
sb.append(" OR ");
}
}
// delete records
ContentResolver contentResolver = context.getContentResolver();
contentResolver.delete(DBContentProvider.EVENTS_URI, sb.toString(), args);
}
/**
* Delete events which use these vehicles IDs TODO better sql query
*
* @param resolver
* @param ids
*/
public static void deleteEventsByVehicleIDs(Context context, Set<Long> vehicleIds)
{
StringBuilder sb = new StringBuilder();
String[] args = new String[vehicleIds.size()];
Iterator<Long> iter = vehicleIds.iterator();
int index = 0;
while (iter.hasNext())
{
Long id = iter.next();
args[index] = Long.toString(id);
index++;
sb.append(COL_VEHICLE_REF);
sb.append(" = ?");
if (iter.hasNext())
{
sb.append(" OR ");
}
}
// delete records
ContentResolver contentResolver = context.getContentResolver();
contentResolver.delete(DBContentProvider.EVENTS_URI, sb.toString(), args);
}
/**
* Create new event
*
* @param contentResolver
* @param event
*/
public static void createEvent(Context context, EventBean event)
{
ContentValues values = getAsContentValues(event);
ContentResolver contentResolver = context.getContentResolver();
contentResolver.insert(DBContentProvider.EVENTS_URI, values);
}
/**
* Update existing events
*
* @param contentResolver
* @param event
* @throws SQLException
*/
public static void updateEvent(Context context, EventBean event) throws SQLException
{
ContentValues values = getAsContentValues(event);
Uri uri = Uri.parse(DBContentProvider.EVENTS_URI + "/" + event.getId());
ContentResolver contentResolver = context.getContentResolver();
contentResolver.update(uri, values, null, null);
}
/**
* Return event type of the current record in the cursor
*
* @param c
* @return
*/
public static EventType getEventType(Cursor c)
{
String type = c.getString(c.getColumnIndex(COL_EVENT_TYPE));
return EventType.parse(type);
}
/**
* Return event date of the current record in the cursor
*
* @param c
* @return
*/
public static Long getEventDate(Cursor c)
{
Long eventDate = Utils.readLong(c, COL_EVENT_DATE, TABLE_EVENT);
return eventDate;
}
/**
* Construct header text
*
* @param c DB cursor
* @return header text
*/
public static String constructHeaderText(Cursor c, Context context)
{
// / event type
String sType = c.getString(c.getColumnIndex(COL_EVENT_TYPE));
EventType type = EventType.parse(sType);
if (EventType.FUEL_EVENT.equals(type))
{
String sFuel = c.getString(c.getColumnIndexOrThrow(COL_FUEL));
return Utils.getLocalizedFuelTypeLabel(sFuel, context);
}
else
{
return c.getString(c.getColumnIndexOrThrow(COL_DESCRIPRION));
}
}
/**
* Description of the event
*
* @param c DB cursor
* @return description text
*/
public static String constructDescriptionText(Cursor c, Context context)
{
// event type
String sType = c.getString(c.getColumnIndex(COL_EVENT_TYPE));
EventType type = EventType.parse(sType);
StringBuilder sb = new StringBuilder();
// Vehicle Name
Long vRef = Utils.readLong(c, COL_VEHICLE_REF, TABLE_EVENT);
String vName = VehicleDB.getVehicleName(context, vRef);
if (vName != null)
{
sb.append(vName);
}
if (EventType.FUEL_EVENT.equals(type))
{
String fuelType = null;
// Quantity
DoubleNumber quantity = Utils.readDouble(c, COL_QUANTITY, TABLE_EVENT);
if (!quantity.isNull())
{
fuelType = Utils.readString(c, COL_FUEL, TABLE_EVENT);
String sQuantity = Utils.formatQuantity(quantity, context, fuelType);
if (sb.length() > 0)
{
sb.append(", ");
}
sb.append(sQuantity);
}
// Price per unit
DoubleNumber price = Utils.readDouble(c, COL_PRICE, TABLE_EVENT);
if (!price.isNull())
{
if (fuelType == null)
{
fuelType = Utils.readString(c, COL_FUEL, TABLE_EVENT);
}
String sPrice = Utils.formatPricePerUnit(price, context, fuelType);
if (sb.length() > 0)
{
sb.append(", ");
}
sb.append(sPrice);
}
}
return sb.toString();
}
/**
* Value for the event = cost
*
* @param c DB cursor
* @return description text
*/
public static String constructValueText(Cursor c, Context context)
{
// cost
DoubleNumber cost = Utils.readDouble(c, COL_COST, TABLE_EVENT);
if (cost.isNull())
{
// Should never happen
return null;
}
return Utils.formatCost(cost, context);
}
}
|
UTF-8
|
Java
| 16,159 |
java
|
EventDB.java
|
Java
|
[
{
"context": "s and modify the\r\n * Event table.\r\n * \r\n * @author neandertal\r\n */\r\npublic class EventDB\r\n{\r\n // Table name\r",
"end": 812,
"score": 0.9995743632316589,
"start": 802,
"tag": "USERNAME",
"value": "neandertal"
}
] | null |
[] |
package com.silentcorp.autotracker.db;
import java.util.Iterator;
import java.util.Set;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import com.silentcorp.autotracker.beans.EventBean;
import com.silentcorp.autotracker.utils.DoubleNumber;
import com.silentcorp.autotracker.utils.EventType;
import com.silentcorp.autotracker.utils.Utils;
/**
* Event table database helper to contain functionality to access and modify the
* Event table.
*
* @author neandertal
*/
public class EventDB
{
// Table name
protected final static String TABLE_EVENT = "event";
// Columns
private final static String COL_ID = Utils.COL_ID;
private final static String COL_VEHICLE_REF = "vehicle_ref";
private final static String COL_EVENT_DATE = "event_date";
private final static String COL_EVENT_TYPE = "event_type";
private final static String COL_COST = "cost";
private final static String COL_ODOMETER = "odometer";
private final static String COL_NOTE = "note";
private final static String COL_FUEL = "fuel";
private final static String COL_QUANTITY = "quantity";
private final static String COL_PRICE = "price";
private final static String COL_DESCRIPRION = "description";
private final static String COL_PLACE = "place";
// @formatter:off
private final static String CREATE_TABLE =
"CREATE TABLE " + TABLE_EVENT + " ( " +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_VEHICLE_REF + " INTEGER, " +
COL_EVENT_DATE + " INTEGER NOT NULL, " +
COL_EVENT_TYPE + " TEXT NOT NULL, " +
COL_COST + " INTEGER NOT NULL, " +
COL_ODOMETER + " INTEGER, " +
COL_NOTE + " TEXT, " +
COL_FUEL + " TEXT, " +
COL_QUANTITY + " INTEGER, " +
COL_PRICE + " INTEGER, " +
COL_DESCRIPRION + " TEXT, " +
COL_PLACE + " TEXT )";
private final static String DROP_TABLE =
"DROP TABLE IF EXISTS " + TABLE_EVENT;
// Columns to be used for list entries
public final static String[] LIST_COLUMNS = new String[] {
COL_ID,
COL_VEHICLE_REF,
COL_EVENT_DATE,
COL_EVENT_TYPE,
COL_COST,
COL_FUEL,
COL_QUANTITY,
COL_PRICE,
COL_DESCRIPRION };
//Order by date - most recent on top
private static final String ORDER = COL_EVENT_DATE + " DESC";
// @formatter:on
/**
* Creates the event table
*
* @param db the DB
*/
public static void onCreate(SQLiteDatabase db)
{
Log.i(VehicleDB.class.getName(), "Creating table: " + CREATE_TABLE);
db.execSQL(CREATE_TABLE);
}
/**
* Drops and recreates the event table TODO not on production environment
*
* @param db the DB
* @param oldVersion old DB version
* @param newVersion new DB version
*/
public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.i(VehicleDB.class.getName(), "Upgrading DB from V:" + oldVersion + " to V:" + newVersion);
// Drop older table if existed
Log.i(VehicleDB.class.getName(), "Dropping old table: " + DROP_TABLE);
db.execSQL(DROP_TABLE);
// Create tables again
onCreate(db);
}
/**
* Get cursor loader for events list activity
*
* @param context
* @return
*/
public static Loader<Cursor> getCursorLoader(Context context)
{
CursorLoader cursorLoader = new CursorLoader(context, DBContentProvider.EVENTS_URI, EventDB.LIST_COLUMNS, null,
null, ORDER);
return cursorLoader;
}
/**
* Get cursor to filter Fuel, Maintenance, Repair, Payment events for list
* adapter
*
* @param contentResolver
* @param hideFE if true hide Fuel events
* @param hideME if true hide Maintenance events
* @param hideRE if true hide Repair events
* @param hidePE if true hide Payment events
* @return new Cursor
*/
public static Cursor getFilteredCursor(Context context, boolean hideFE, boolean hideME, boolean hideRE,
boolean hidePE)
{
// TODO better sql ?
StringBuilder whereQ = new StringBuilder();
boolean hasPrevious;
if (hideFE && hideME && hideRE && hidePE)
{
whereQ.append(COL_EVENT_TYPE);
whereQ.append(" IS NULL");
}
else
{
hasPrevious = false;
if (!hideFE)
{
whereQ.append(COL_EVENT_TYPE);
whereQ.append("='");
whereQ.append(EventType.FUEL_EVENT.toString());
whereQ.append("'");
hasPrevious = true;
}
if (!hideME)
{
if (hasPrevious)
{
whereQ.append(" OR ");
}
whereQ.append(COL_EVENT_TYPE);
whereQ.append("='");
whereQ.append(EventType.MAINTENANCE_EVENT.toString());
whereQ.append("'");
hasPrevious = true;
}
if (!hideRE)
{
if (hasPrevious)
{
whereQ.append(" OR ");
}
whereQ.append(COL_EVENT_TYPE);
whereQ.append("='");
whereQ.append(EventType.REPAIR_EVENT.toString());
whereQ.append("'");
hasPrevious = true;
}
if (!hidePE)
{
if (hasPrevious)
{
whereQ.append(" OR ");
}
whereQ.append(COL_EVENT_TYPE);
whereQ.append("='");
whereQ.append(EventType.PAYMENT_EVENT.toString());
whereQ.append("'");
hasPrevious = true;
}
}
// Get filtered cursor
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(DBContentProvider.EVENTS_URI, LIST_COLUMNS, whereQ.toString(), null,
ORDER);
return cursor;
}
/**
* Read an event from the DB given its ID
*
* @param contentResolver content resolver
* @param id event ID
* @param event object to fill, if NULL, new created and returned
* @return full event object
* @throws SQLException
*/
public static EventBean readEvent(Context context, long id, EventBean event) throws SQLException
{
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Uri.parse(DBContentProvider.EVENTS_URI + "/" + id);
// Read all columns for the record
Cursor cursor = contentResolver.query(uri, null, null, null, null);
if (cursor == null || cursor.getCount() == 0)
{
throw new SQLException("Unable to find event with ID: " + id + " Corrupt DB?");
}
// more then one event
if (cursor.getCount() > 1)
{
throw new SQLException("More then one event with ID: " + id + " Corrupt DB?");
}
cursor.moveToFirst();
if (event == null)
{
event = new EventBean();
}
event.setId(id);
event.setVehicleRef(Utils.readLong(cursor, COL_VEHICLE_REF, TABLE_EVENT));
event.setEventDate(Utils.readLong(cursor, COL_EVENT_DATE, TABLE_EVENT));
event.setEventType(EventType.parse(Utils.readString(cursor, COL_EVENT_TYPE, TABLE_EVENT)));
event.setCost(Utils.readDouble(cursor, COL_COST, TABLE_EVENT));
event.setOdometer(Utils.readWhole(cursor, COL_ODOMETER, TABLE_EVENT));
event.setNote(Utils.readString(cursor, COL_NOTE, TABLE_EVENT));
event.setFuel(Utils.readString(cursor, COL_FUEL, TABLE_EVENT));
event.setQuantity(Utils.readDouble(cursor, COL_QUANTITY, TABLE_EVENT));
event.setPrice(Utils.readDouble(cursor, COL_PRICE, TABLE_EVENT));
event.setDescription(Utils.readString(cursor, COL_DESCRIPRION, TABLE_EVENT));
event.setPlace(Utils.readString(cursor, COL_PLACE, TABLE_EVENT));
cursor.close();
return event;
}
/**
* Returns event bean's values as content value map
*
* @param event
* @return
*/
private static ContentValues getAsContentValues(EventBean event)
{
ContentValues values = new ContentValues();
values.put(COL_VEHICLE_REF, event.getVehicleRef());
values.put(COL_EVENT_DATE, event.getEventDate());
values.put(COL_EVENT_TYPE, event.getEventType().toString());
values.put(COL_COST, event.getCost().getDoubleInt());
values.put(COL_ODOMETER, event.getOdometer().getWholeInt());
values.put(COL_NOTE, event.getNote());
values.put(COL_FUEL, event.getFuel());
values.put(COL_QUANTITY, event.getQuantity().getDoubleInt());
values.put(COL_PRICE, event.getPrice().getDoubleInt());
values.put(COL_DESCRIPRION, event.getDescription());
values.put(COL_PLACE, event.getPlace());
return values;
}
/**
* Delete events TODO better sql query
*
* @param resolver
* @param ids
*/
public static void deleteEvents(Context context, Set<Long> ids)
{
StringBuilder sb = new StringBuilder();
String[] args = new String[ids.size()];
Iterator<Long> iter = ids.iterator();
int index = 0;
while (iter.hasNext())
{
Long id = iter.next();
args[index] = Long.toString(id);
index++;
sb.append(COL_ID);
sb.append(" = ?");
if (iter.hasNext())
{
sb.append(" OR ");
}
}
// delete records
ContentResolver contentResolver = context.getContentResolver();
contentResolver.delete(DBContentProvider.EVENTS_URI, sb.toString(), args);
}
/**
* Delete events which use these vehicles IDs TODO better sql query
*
* @param resolver
* @param ids
*/
public static void deleteEventsByVehicleIDs(Context context, Set<Long> vehicleIds)
{
StringBuilder sb = new StringBuilder();
String[] args = new String[vehicleIds.size()];
Iterator<Long> iter = vehicleIds.iterator();
int index = 0;
while (iter.hasNext())
{
Long id = iter.next();
args[index] = Long.toString(id);
index++;
sb.append(COL_VEHICLE_REF);
sb.append(" = ?");
if (iter.hasNext())
{
sb.append(" OR ");
}
}
// delete records
ContentResolver contentResolver = context.getContentResolver();
contentResolver.delete(DBContentProvider.EVENTS_URI, sb.toString(), args);
}
/**
* Create new event
*
* @param contentResolver
* @param event
*/
public static void createEvent(Context context, EventBean event)
{
ContentValues values = getAsContentValues(event);
ContentResolver contentResolver = context.getContentResolver();
contentResolver.insert(DBContentProvider.EVENTS_URI, values);
}
/**
* Update existing events
*
* @param contentResolver
* @param event
* @throws SQLException
*/
public static void updateEvent(Context context, EventBean event) throws SQLException
{
ContentValues values = getAsContentValues(event);
Uri uri = Uri.parse(DBContentProvider.EVENTS_URI + "/" + event.getId());
ContentResolver contentResolver = context.getContentResolver();
contentResolver.update(uri, values, null, null);
}
/**
* Return event type of the current record in the cursor
*
* @param c
* @return
*/
public static EventType getEventType(Cursor c)
{
String type = c.getString(c.getColumnIndex(COL_EVENT_TYPE));
return EventType.parse(type);
}
/**
* Return event date of the current record in the cursor
*
* @param c
* @return
*/
public static Long getEventDate(Cursor c)
{
Long eventDate = Utils.readLong(c, COL_EVENT_DATE, TABLE_EVENT);
return eventDate;
}
/**
* Construct header text
*
* @param c DB cursor
* @return header text
*/
public static String constructHeaderText(Cursor c, Context context)
{
// / event type
String sType = c.getString(c.getColumnIndex(COL_EVENT_TYPE));
EventType type = EventType.parse(sType);
if (EventType.FUEL_EVENT.equals(type))
{
String sFuel = c.getString(c.getColumnIndexOrThrow(COL_FUEL));
return Utils.getLocalizedFuelTypeLabel(sFuel, context);
}
else
{
return c.getString(c.getColumnIndexOrThrow(COL_DESCRIPRION));
}
}
/**
* Description of the event
*
* @param c DB cursor
* @return description text
*/
public static String constructDescriptionText(Cursor c, Context context)
{
// event type
String sType = c.getString(c.getColumnIndex(COL_EVENT_TYPE));
EventType type = EventType.parse(sType);
StringBuilder sb = new StringBuilder();
// Vehicle Name
Long vRef = Utils.readLong(c, COL_VEHICLE_REF, TABLE_EVENT);
String vName = VehicleDB.getVehicleName(context, vRef);
if (vName != null)
{
sb.append(vName);
}
if (EventType.FUEL_EVENT.equals(type))
{
String fuelType = null;
// Quantity
DoubleNumber quantity = Utils.readDouble(c, COL_QUANTITY, TABLE_EVENT);
if (!quantity.isNull())
{
fuelType = Utils.readString(c, COL_FUEL, TABLE_EVENT);
String sQuantity = Utils.formatQuantity(quantity, context, fuelType);
if (sb.length() > 0)
{
sb.append(", ");
}
sb.append(sQuantity);
}
// Price per unit
DoubleNumber price = Utils.readDouble(c, COL_PRICE, TABLE_EVENT);
if (!price.isNull())
{
if (fuelType == null)
{
fuelType = Utils.readString(c, COL_FUEL, TABLE_EVENT);
}
String sPrice = Utils.formatPricePerUnit(price, context, fuelType);
if (sb.length() > 0)
{
sb.append(", ");
}
sb.append(sPrice);
}
}
return sb.toString();
}
/**
* Value for the event = cost
*
* @param c DB cursor
* @return description text
*/
public static String constructValueText(Cursor c, Context context)
{
// cost
DoubleNumber cost = Utils.readDouble(c, COL_COST, TABLE_EVENT);
if (cost.isNull())
{
// Should never happen
return null;
}
return Utils.formatCost(cost, context);
}
}
| 16,159 | 0.552757 | 0.552262 | 497 | 30.513079 | 25.357967 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.581489 | false | false |
14
|
c0d39099f41f6fd45b8b8e70721c6ea9c79257a9
| 29,291,676,998,946 |
58b12199d5eb1fba131d08263cfc85bdf8e5db32
|
/ImageWriter.java
|
4e84667f914aeef7e5973c9144307fce46504880
|
[] |
no_license
|
RyanLBWoods/Bin_web_server
|
https://github.com/RyanLBWoods/Bin_web_server
|
5d0c8aad4cc10bde33f717ab36b6318ff2dc6e9d
|
2cf08f31594483c0b3e686521436e8375947d0db
|
refs/heads/master
| 2021-08-08T17:34:17.515000 | 2017-11-10T19:39:31 | 2017-11-10T19:39:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Class for writing binary image file.
*
* @author bl41
*
*/
public class ImageWriter {
/**
* Method to write binary content to new image file.
*
* @param filename
* Name of file to transfer
* @param bytes
* File content indicated in bytes
*/
public static void writeImage(String filename, byte[] bytes) {
// Get exact same name of file being transfered
String name = filename.substring(filename.lastIndexOf("/") + 1);
File file = new File(name);
try {
if (!file.exists()) {
file.createNewFile(); // Create file if it does not exist
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(bytes);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 1,203 |
java
|
ImageWriter.java
|
Java
|
[
{
"context": "lass for writing binary image file.\n * \n * @author bl41\n *\n */\npublic class ImageWriter {\n /**\n * ",
"end": 184,
"score": 0.9994680881500244,
"start": 180,
"tag": "USERNAME",
"value": "bl41"
}
] | null |
[] |
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Class for writing binary image file.
*
* @author bl41
*
*/
public class ImageWriter {
/**
* Method to write binary content to new image file.
*
* @param filename
* Name of file to transfer
* @param bytes
* File content indicated in bytes
*/
public static void writeImage(String filename, byte[] bytes) {
// Get exact same name of file being transfered
String name = filename.substring(filename.lastIndexOf("/") + 1);
File file = new File(name);
try {
if (!file.exists()) {
file.createNewFile(); // Create file if it does not exist
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(bytes);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 1,203 | 0.567747 | 0.565254 | 41 | 28.341463 | 20.388435 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.341463 | false | false |
14
|
31ab4adc0b7a5addab858292a28e1a0f58993e62
| 35,029,753,276,375 |
53c8115444d0087937afe7afdb544c3870b374db
|
/Herald-Admin-Service/src/main/java/com/pr/herald/controller/CategoryController.java
|
3f08c90889c1ae4687fb7e8a1a7457c12b891c37
|
[] |
no_license
|
pratsonii/Herald
|
https://github.com/pratsonii/Herald
|
6da1b42116e9988b6b4acdfb13c08d87add5cd52
|
0a2ea042dd4dfa91e81b69ca309cb78a076b33e9
|
refs/heads/master
| 2020-08-05T12:30:40.311000 | 2016-12-20T16:23:34 | 2016-12-20T16:23:34 | 66,715,059 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.pr.herald.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.pr.herald.base.BaseException;
import com.pr.herald.base.RespEntity;
import com.pr.herald.contants.Constants;
import com.pr.herald.dto.CategoryRequestDto;
import com.pr.herald.models.Categories;
import com.pr.herald.service.CategoryServ;
@RestController
@RequestMapping("/category")
public class CategoryController
{
@Autowired
CategoryServ category;
@RequestMapping(value = "/add", method = RequestMethod.POST)
public ResponseEntity addCategory(@RequestBody CategoryRequestDto dto) throws BaseException
{
category.addCategory(dto.convertToModels());
return new ResponseEntity<String>(Constants.addSuccess, HttpStatus.OK);
}
@RequestMapping(value = "/findAll", method = RequestMethod.GET)
public ResponseEntity<RespEntity<List<Categories>>> findAllCategory()
{
return new ResponseEntity<RespEntity<List<Categories>>>
((new RespEntity<List<Categories>>(category.findAllCategory(),"Success")), HttpStatus.OK
);
}
@RequestMapping(value = "/update", method = RequestMethod.PUT)
public ResponseEntity updateCategory(@RequestBody CategoryRequestDto dto)
{
category.updateCategory(dto.convertToModels());
return new ResponseEntity<String>(Constants.updatSuccess, HttpStatus.OK);
}
}
|
UTF-8
|
Java
| 1,739 |
java
|
CategoryController.java
|
Java
|
[] | null |
[] |
package com.pr.herald.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.pr.herald.base.BaseException;
import com.pr.herald.base.RespEntity;
import com.pr.herald.contants.Constants;
import com.pr.herald.dto.CategoryRequestDto;
import com.pr.herald.models.Categories;
import com.pr.herald.service.CategoryServ;
@RestController
@RequestMapping("/category")
public class CategoryController
{
@Autowired
CategoryServ category;
@RequestMapping(value = "/add", method = RequestMethod.POST)
public ResponseEntity addCategory(@RequestBody CategoryRequestDto dto) throws BaseException
{
category.addCategory(dto.convertToModels());
return new ResponseEntity<String>(Constants.addSuccess, HttpStatus.OK);
}
@RequestMapping(value = "/findAll", method = RequestMethod.GET)
public ResponseEntity<RespEntity<List<Categories>>> findAllCategory()
{
return new ResponseEntity<RespEntity<List<Categories>>>
((new RespEntity<List<Categories>>(category.findAllCategory(),"Success")), HttpStatus.OK
);
}
@RequestMapping(value = "/update", method = RequestMethod.PUT)
public ResponseEntity updateCategory(@RequestBody CategoryRequestDto dto)
{
category.updateCategory(dto.convertToModels());
return new ResponseEntity<String>(Constants.updatSuccess, HttpStatus.OK);
}
}
| 1,739 | 0.781484 | 0.781484 | 49 | 33.489796 | 28.354982 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.285714 | false | false |
14
|
d804b22b22d2e564e9ac8c6599f63f892f79856d
| 28,905,129,911,114 |
84d8b2cb490fe146be5bc0c2d860b3e3cbdda531
|
/src/com/tollService/models/LeaderBoard.java
|
0a3812bf813cc77e5fcadec11783049b78833c91
|
[] |
no_license
|
turtlevelocity/toll-service-problem
|
https://github.com/turtlevelocity/toll-service-problem
|
bcf9490291739f8d6a18dacd9388caea028a5a04
|
d51d8c52bb5fb5348f5d5861d8f8a44277ddfe76
|
refs/heads/master
| 2023-06-10T18:23:06.249000 | 2021-06-30T15:58:17 | 2021-06-30T15:58:17 | 380,414,205 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tollService.models;
public class LeaderBoard {
private Integer totalVehicles;
private double totalAmount;
public LeaderBoard(Integer totalVehicles, double totalAmount){
this.totalVehicles = totalVehicles;
this.totalAmount = totalAmount;
}
public double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(double amount) {
this.totalAmount+=amount;
}
public Integer getTotalVehicles() {
return totalVehicles;
}
public void setTotalVehicles(Integer numberOfVehicles){
this.totalVehicles+=numberOfVehicles;
}
}
|
UTF-8
|
Java
| 638 |
java
|
LeaderBoard.java
|
Java
|
[] | null |
[] |
package com.tollService.models;
public class LeaderBoard {
private Integer totalVehicles;
private double totalAmount;
public LeaderBoard(Integer totalVehicles, double totalAmount){
this.totalVehicles = totalVehicles;
this.totalAmount = totalAmount;
}
public double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(double amount) {
this.totalAmount+=amount;
}
public Integer getTotalVehicles() {
return totalVehicles;
}
public void setTotalVehicles(Integer numberOfVehicles){
this.totalVehicles+=numberOfVehicles;
}
}
| 638 | 0.689655 | 0.689655 | 27 | 22.629629 | 20.157064 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.37037 | false | false |
14
|
286abaa39f9df6aa597c3c2385d390e851caa6c9
| 15,187,004,411,363 |
d27b632dd6fc0060b0a8b589a64e1e015aa1397f
|
/app/src/main/java/com/xiaochencode/androidloader/LoaderWithListViewActivity.java
|
633d8b572f981fd3dd6b3045b3520f670f16b195
|
[] |
no_license
|
xiaochencode/AndroidLoader
|
https://github.com/xiaochencode/AndroidLoader
|
463dc3853a56ccd6439f7bfe71d26ef45c87f751
|
2abf3a053d168a0de1ad55bffd86f8d20447aaab
|
refs/heads/master
| 2016-04-12T09:24:42.040000 | 2015-11-09T07:51:55 | 2015-11-09T07:51:55 | 45,823,260 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.xiaochencode.androidloader;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.xiaochencode.androidloader.bean.Student;
import com.xiaochencode.androidloader.db.StudentProvider;
public class LoaderWithListViewActivity extends AppCompatActivity implements View.OnClickListener{
Button btn_add;
Button btn_delete;
Button btn_update;
ListView lv_student;
CursorAdapter mCursorAdapter;
LayoutInflater mInflater;
private static final int LOADER_ID =1 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loader_with_list_view);
mInflater=LayoutInflater.from(this);
btn_add= (Button) findViewById(R.id.btn_add);
btn_delete= (Button) findViewById(R.id.btn_delete);
btn_update= (Button) findViewById(R.id.btn_update);
lv_student= (ListView) findViewById(R.id.lv_student);
btn_add.setOnClickListener(this);
btn_delete.setOnClickListener(this);
btn_update.setOnClickListener(this);
/**
* 没有使用Loader机制传统的CursorAdapter
*/
// Cursor cursor=getContentResolver().query(StudentProvider.URI_STUDENT_ALL,null,null,null,null);
// while (cursor.moveToNext()){
// String name=cursor.getString(cursor.getColumnIndex(Student.COLUMN_NAME));
// String gender=cursor.getString(cursor.getColumnIndex(Student.COLUMN_GENDER));
// int age=cursor.getInt(cursor.getColumnIndex(Student.COLUMN_AGE));
// Log.d("testGetAll", name + "---" + gender + "---" + age);
// }
//// cursor.close();
//
// mInflater=LayoutInflater.from(this);
//
// mCursorAdapter=new CursorAdapter(this,cursor,false) {
// @Override
// public View newView(Context context, Cursor cursor, ViewGroup parent) {
// return mInflater.inflate(R.layout.item_list_student,parent,false);
// }
//
// @Override
// public void bindView(View view, Context context, Cursor cursor) {
// TextView tv_name= (TextView) view.findViewById(R.id.tv_name);
// TextView tv_gender= (TextView) view.findViewById(R.id.tv_gender);
// TextView tv_age= (TextView) view.findViewById(R.id.tv_age);
//
// tv_name.setText(cursor.getString(cursor.getColumnIndex(Student.COLUMN_NAME)));
// tv_gender.setText(cursor.getString(cursor.getColumnIndex(Student.COLUMN_GENDER)));
// tv_age.setText(""+cursor.getInt(cursor.getColumnIndex(Student.COLUMN_AGE)));
// }
// };
initLoader();
mCursorAdapter=new CursorAdapter(this,null,false) {
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return mInflater.inflate(R.layout.item_list_student,parent,false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tv_name= (TextView) view.findViewById(R.id.tv_name);
TextView tv_gender= (TextView) view.findViewById(R.id.tv_gender);
TextView tv_age= (TextView) view.findViewById(R.id.tv_age);
tv_name.setText(cursor.getString(cursor.getColumnIndex(Student.COLUMN_NAME)));
tv_gender.setText(cursor.getString(cursor.getColumnIndex(Student.COLUMN_GENDER)));
tv_age.setText(""+cursor.getInt(cursor.getColumnIndex(Student.COLUMN_AGE)));
}
};
lv_student.setAdapter(mCursorAdapter);
}
private void initLoader() {
getSupportLoaderManager().initLoader(LOADER_ID, null, new LoaderManager.LoaderCallbacks<Cursor>() {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader loader = new CursorLoader(LoaderWithListViewActivity.this, StudentProvider.URI_STUDENT_ALL, null, null, null, null);
return loader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (loader.getId() == LOADER_ID) {
mCursorAdapter.swapCursor(data);
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
});
testStudentProvider();
}
private void testStudentProvider() {
Cursor cursor=getContentResolver().query(StudentProvider.URI_STUDENT_ALL, null, "name=?", new String[]{"position4"}, null);
cursor.moveToFirst();
String name=cursor.getString(cursor.getColumnIndex(Student.COLUMN_NAME));
System.out.println(name);
Uri uri= ContentUris.withAppendedId(StudentProvider.URI_STUDENT_ALL,5);
cursor=getContentResolver().query(uri,null,null,null,null);
cursor.moveToFirst();
System.out.println(cursor.getString(cursor.getColumnIndex(Student.COLUMN_NAME)) + ",query one");
cursor.close();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_loader_with_list_view, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_add:
ContentValues contentValues=new ContentValues();
contentValues.put(Student.COLUMN_NAME,"add");
contentValues.put(Student.COLUMN_GENDER,"female");
contentValues.put(Student.COLUMN_AGE,23);
getContentResolver().insert(StudentProvider.URI_STUDENT_ALL,contentValues);
break;
case R.id.btn_delete:
/**
* 测试删除add的数据
*/
Uri deleteOneUri=ContentUris.withAppendedId(StudentProvider.URI_STUDENT_ALL,1);
getContentResolver().delete(deleteOneUri,null,null);
// getContentResolver().delete(StudentProvider.URI_STUDENT_ALL,"name = ?",new String[]{"add"});
break;
case R.id.btn_update:
contentValues=new ContentValues();
contentValues.put(Student.COLUMN_NAME,"update");
contentValues.put(Student.COLUMN_GENDER,"female");
contentValues.put(Student.COLUMN_AGE, 23);
getContentResolver().update(StudentProvider.URI_STUDENT_ALL,contentValues,"name=?",new String[]{"position4"});
break;
}
}
}
|
UTF-8
|
Java
| 7,882 |
java
|
LoaderWithListViewActivity.java
|
Java
|
[] | null |
[] |
package com.xiaochencode.androidloader;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.xiaochencode.androidloader.bean.Student;
import com.xiaochencode.androidloader.db.StudentProvider;
public class LoaderWithListViewActivity extends AppCompatActivity implements View.OnClickListener{
Button btn_add;
Button btn_delete;
Button btn_update;
ListView lv_student;
CursorAdapter mCursorAdapter;
LayoutInflater mInflater;
private static final int LOADER_ID =1 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loader_with_list_view);
mInflater=LayoutInflater.from(this);
btn_add= (Button) findViewById(R.id.btn_add);
btn_delete= (Button) findViewById(R.id.btn_delete);
btn_update= (Button) findViewById(R.id.btn_update);
lv_student= (ListView) findViewById(R.id.lv_student);
btn_add.setOnClickListener(this);
btn_delete.setOnClickListener(this);
btn_update.setOnClickListener(this);
/**
* 没有使用Loader机制传统的CursorAdapter
*/
// Cursor cursor=getContentResolver().query(StudentProvider.URI_STUDENT_ALL,null,null,null,null);
// while (cursor.moveToNext()){
// String name=cursor.getString(cursor.getColumnIndex(Student.COLUMN_NAME));
// String gender=cursor.getString(cursor.getColumnIndex(Student.COLUMN_GENDER));
// int age=cursor.getInt(cursor.getColumnIndex(Student.COLUMN_AGE));
// Log.d("testGetAll", name + "---" + gender + "---" + age);
// }
//// cursor.close();
//
// mInflater=LayoutInflater.from(this);
//
// mCursorAdapter=new CursorAdapter(this,cursor,false) {
// @Override
// public View newView(Context context, Cursor cursor, ViewGroup parent) {
// return mInflater.inflate(R.layout.item_list_student,parent,false);
// }
//
// @Override
// public void bindView(View view, Context context, Cursor cursor) {
// TextView tv_name= (TextView) view.findViewById(R.id.tv_name);
// TextView tv_gender= (TextView) view.findViewById(R.id.tv_gender);
// TextView tv_age= (TextView) view.findViewById(R.id.tv_age);
//
// tv_name.setText(cursor.getString(cursor.getColumnIndex(Student.COLUMN_NAME)));
// tv_gender.setText(cursor.getString(cursor.getColumnIndex(Student.COLUMN_GENDER)));
// tv_age.setText(""+cursor.getInt(cursor.getColumnIndex(Student.COLUMN_AGE)));
// }
// };
initLoader();
mCursorAdapter=new CursorAdapter(this,null,false) {
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return mInflater.inflate(R.layout.item_list_student,parent,false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tv_name= (TextView) view.findViewById(R.id.tv_name);
TextView tv_gender= (TextView) view.findViewById(R.id.tv_gender);
TextView tv_age= (TextView) view.findViewById(R.id.tv_age);
tv_name.setText(cursor.getString(cursor.getColumnIndex(Student.COLUMN_NAME)));
tv_gender.setText(cursor.getString(cursor.getColumnIndex(Student.COLUMN_GENDER)));
tv_age.setText(""+cursor.getInt(cursor.getColumnIndex(Student.COLUMN_AGE)));
}
};
lv_student.setAdapter(mCursorAdapter);
}
private void initLoader() {
getSupportLoaderManager().initLoader(LOADER_ID, null, new LoaderManager.LoaderCallbacks<Cursor>() {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader loader = new CursorLoader(LoaderWithListViewActivity.this, StudentProvider.URI_STUDENT_ALL, null, null, null, null);
return loader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (loader.getId() == LOADER_ID) {
mCursorAdapter.swapCursor(data);
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
});
testStudentProvider();
}
private void testStudentProvider() {
Cursor cursor=getContentResolver().query(StudentProvider.URI_STUDENT_ALL, null, "name=?", new String[]{"position4"}, null);
cursor.moveToFirst();
String name=cursor.getString(cursor.getColumnIndex(Student.COLUMN_NAME));
System.out.println(name);
Uri uri= ContentUris.withAppendedId(StudentProvider.URI_STUDENT_ALL,5);
cursor=getContentResolver().query(uri,null,null,null,null);
cursor.moveToFirst();
System.out.println(cursor.getString(cursor.getColumnIndex(Student.COLUMN_NAME)) + ",query one");
cursor.close();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_loader_with_list_view, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_add:
ContentValues contentValues=new ContentValues();
contentValues.put(Student.COLUMN_NAME,"add");
contentValues.put(Student.COLUMN_GENDER,"female");
contentValues.put(Student.COLUMN_AGE,23);
getContentResolver().insert(StudentProvider.URI_STUDENT_ALL,contentValues);
break;
case R.id.btn_delete:
/**
* 测试删除add的数据
*/
Uri deleteOneUri=ContentUris.withAppendedId(StudentProvider.URI_STUDENT_ALL,1);
getContentResolver().delete(deleteOneUri,null,null);
// getContentResolver().delete(StudentProvider.URI_STUDENT_ALL,"name = ?",new String[]{"add"});
break;
case R.id.btn_update:
contentValues=new ContentValues();
contentValues.put(Student.COLUMN_NAME,"update");
contentValues.put(Student.COLUMN_GENDER,"female");
contentValues.put(Student.COLUMN_AGE, 23);
getContentResolver().update(StudentProvider.URI_STUDENT_ALL,contentValues,"name=?",new String[]{"position4"});
break;
}
}
}
| 7,882 | 0.637452 | 0.635669 | 194 | 39.463917 | 32.192257 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.814433 | false | false |
14
|
520b39f955e7576f83f195fc9b62a6d4fd049861
| 8,899,172,250,056 |
96670d2b28a3fb75d2f8258f31fc23d370af8a03
|
/reverse_engineered/sources/com/facebook/stetho/inspector/database/ContentProviderDatabaseDriver.java
|
bac8b3a225b2dea48d9d098fe313ac4bbe036f7a
|
[] |
no_license
|
P79N6A/speedx
|
https://github.com/P79N6A/speedx
|
81a25b63e4f98948e7de2e4254390cab5612dcbd
|
800b6158c7494b03f5c477a8cf2234139889578b
|
refs/heads/master
| 2020-05-30T18:43:52.613000 | 2019-06-02T07:57:10 | 2019-06-02T08:15:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.facebook.stetho.inspector.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import com.facebook.stetho.inspector.protocol.module.Database$DatabaseDriver;
import com.facebook.stetho.inspector.protocol.module.Database$DatabaseDriver.ExecuteResultHandler;
import com.facebook.stetho.inspector.protocol.module.Database.ExecuteSQLResponse;
import java.util.ArrayList;
import java.util.List;
public class ContentProviderDatabaseDriver extends Database$DatabaseDriver {
private static final String sDatabaseName = "content-providers";
private final ContentProviderSchema[] mContentProviderSchemas;
private List<String> mDatabaseNames;
private List<String> mTableNames;
public ContentProviderDatabaseDriver(Context context, ContentProviderSchema... contentProviderSchemaArr) {
super(context);
this.mContentProviderSchemas = contentProviderSchemaArr;
}
public List<String> getDatabaseNames() {
if (this.mDatabaseNames == null && this.mContentProviderSchemas != null) {
this.mDatabaseNames = new ArrayList();
this.mDatabaseNames.add(sDatabaseName);
}
return this.mDatabaseNames;
}
public List<String> getTableNames(String str) {
if (this.mTableNames == null) {
this.mTableNames = new ArrayList();
for (ContentProviderSchema tableName : this.mContentProviderSchemas) {
this.mTableNames.add(tableName.getTableName());
}
}
return this.mTableNames;
}
public ExecuteSQLResponse executeSQL(String str, String str2, ExecuteResultHandler<ExecuteSQLResponse> executeResultHandler) throws SQLiteException {
ContentProviderSchema contentProviderSchema = this.mContentProviderSchemas[this.mTableNames.indexOf(fetchTableName(str2))];
Cursor query = this.mContext.getContentResolver().query(contentProviderSchema.getUri(), contentProviderSchema.getProjection(), null, null, null);
try {
ExecuteSQLResponse executeSQLResponse = (ExecuteSQLResponse) executeResultHandler.handleSelect(query);
return executeSQLResponse;
} finally {
query.close();
}
}
private String fetchTableName(String str) {
for (String str2 : this.mTableNames) {
if (str.contains(str2)) {
return str2;
}
}
return "";
}
}
|
UTF-8
|
Java
| 2,492 |
java
|
ContentProviderDatabaseDriver.java
|
Java
|
[] | null |
[] |
package com.facebook.stetho.inspector.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import com.facebook.stetho.inspector.protocol.module.Database$DatabaseDriver;
import com.facebook.stetho.inspector.protocol.module.Database$DatabaseDriver.ExecuteResultHandler;
import com.facebook.stetho.inspector.protocol.module.Database.ExecuteSQLResponse;
import java.util.ArrayList;
import java.util.List;
public class ContentProviderDatabaseDriver extends Database$DatabaseDriver {
private static final String sDatabaseName = "content-providers";
private final ContentProviderSchema[] mContentProviderSchemas;
private List<String> mDatabaseNames;
private List<String> mTableNames;
public ContentProviderDatabaseDriver(Context context, ContentProviderSchema... contentProviderSchemaArr) {
super(context);
this.mContentProviderSchemas = contentProviderSchemaArr;
}
public List<String> getDatabaseNames() {
if (this.mDatabaseNames == null && this.mContentProviderSchemas != null) {
this.mDatabaseNames = new ArrayList();
this.mDatabaseNames.add(sDatabaseName);
}
return this.mDatabaseNames;
}
public List<String> getTableNames(String str) {
if (this.mTableNames == null) {
this.mTableNames = new ArrayList();
for (ContentProviderSchema tableName : this.mContentProviderSchemas) {
this.mTableNames.add(tableName.getTableName());
}
}
return this.mTableNames;
}
public ExecuteSQLResponse executeSQL(String str, String str2, ExecuteResultHandler<ExecuteSQLResponse> executeResultHandler) throws SQLiteException {
ContentProviderSchema contentProviderSchema = this.mContentProviderSchemas[this.mTableNames.indexOf(fetchTableName(str2))];
Cursor query = this.mContext.getContentResolver().query(contentProviderSchema.getUri(), contentProviderSchema.getProjection(), null, null, null);
try {
ExecuteSQLResponse executeSQLResponse = (ExecuteSQLResponse) executeResultHandler.handleSelect(query);
return executeSQLResponse;
} finally {
query.close();
}
}
private String fetchTableName(String str) {
for (String str2 : this.mTableNames) {
if (str.contains(str2)) {
return str2;
}
}
return "";
}
}
| 2,492 | 0.711477 | 0.70947 | 60 | 40.533333 | 37.808495 | 153 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false |
14
|
826deb09bf9b600405c88f21327f05a578df262c
| 19,705,309,964,279 |
468d535199943ddeffa936c6ec6681353076e7b2
|
/plugin-sa-history-datax-writer/src/main/java/cn/sensorsdata/datax/plugin/converter/Long2DateConverter.java
|
12fe500cf6dd754c0286233a0a09096ae124650e
|
[] |
no_license
|
yyzswqw/datax-plugin
|
https://github.com/yyzswqw/datax-plugin
|
279ad54af403504a162209aa8672729a72aad002
|
1f2b0080197d7a8a3328e04ec351d7ae7a9f88b7
|
refs/heads/master
| 2023-06-14T03:05:16.793000 | 2021-07-09T08:06:08 | 2021-07-09T08:06:08 | 383,977,652 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.sensorsdata.datax.plugin.converter;
import cn.sensorsdata.datax.plugin.Converter;
import cn.sensorsdata.datax.plugin.util.NullUtil;
import java.util.Date;
import java.util.Map;
public class Long2DateConverter implements Converter {
@Override
public Object transform(String targetColumnName, Object value, Map<String, Object> param) {
if (NullUtil.isNullOrBlank(value)) {
return (Date) null;
}
return new Date((Long) value);
}
}
|
UTF-8
|
Java
| 491 |
java
|
Long2DateConverter.java
|
Java
|
[] | null |
[] |
package cn.sensorsdata.datax.plugin.converter;
import cn.sensorsdata.datax.plugin.Converter;
import cn.sensorsdata.datax.plugin.util.NullUtil;
import java.util.Date;
import java.util.Map;
public class Long2DateConverter implements Converter {
@Override
public Object transform(String targetColumnName, Object value, Map<String, Object> param) {
if (NullUtil.isNullOrBlank(value)) {
return (Date) null;
}
return new Date((Long) value);
}
}
| 491 | 0.712831 | 0.710794 | 18 | 26.277779 | 25.381107 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false |
14
|
c6b89377ecf430b79f846f6ea73b4cb6c7197c16
| 1,786,706,465,820 |
fe3a252db62a88035354bd2274b0f26dee69cd88
|
/src/main/java/com/msy/controller/GoodsController.java
|
139ba5f6b647eb4245d29aa73738813aa420b36e
|
[
"MIT"
] |
permissive
|
g453030291/msy2
|
https://github.com/g453030291/msy2
|
30494c308e3e555542e7afb9abfe18818267180b
|
437359a359cb8f3550a288c3f1c74d79e6271eeb
|
refs/heads/master
| 2022-05-31T15:53:58.242000 | 2020-03-08T03:16:25 | 2020-03-08T03:16:25 | 221,471,847 | 0 | 0 |
MIT
| false | 2022-05-20T21:29:21 | 2019-11-13T13:57:50 | 2020-03-08T03:16:47 | 2022-05-20T21:29:21 | 1,066 | 0 | 0 | 1 |
HTML
| false | false |
package com.msy.controller;
import com.msy.entity.*;
import com.msy.service.BrandService;
import com.msy.service.GoodsService;
import com.msy.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/pc/goods")
public class GoodsController {
@Autowired
private GoodsService goodsService;
@Autowired
private BrandService brandService;
@RequestMapping("/toGoodsList.page")
public String toGoodsListPage(Model model){
List<Brand> brands = brandService.listAllBrand();
model.addAttribute("brands",brands);
return "pc/goods/goodsList";
}
@ResponseBody
@RequestMapping("/getGoodsList.json")
public PageResult<List<Goods>> getClientList(TableModel<Goods> tableModel,Goods goods){
tableModel.setData(goods);
if(StringUtils.isEmpty(tableModel.getField())){
tableModel.setField("id");
}
if(StringUtils.isEmpty(tableModel.getOrder())){
tableModel.setOrder("desc");
}
PageResult<List<Goods>> listPageResult = goodsService.listGoods(tableModel);
return listPageResult;
}
@RequestMapping("/toAddGoods.page")
public String toAddGoods(Model model,Integer id){
Goods goods = null;
List<Brand> brands = brandService.listAllBrand();
if(StringUtils.isEmpty(id)){
//add
goods = new Goods();
}else{
//update 根据id查找商品
goods = goodsService.findGoodsById(id);
}
model.addAttribute("goods",goods);
model.addAttribute("brands",brands);
return "pc/goods/addGoods";
}
@ResponseBody
@RequestMapping("/addGoods.form")
@Transactional(rollbackFor = Exception.class)
public String addGoods(Goods goods){
//根据品牌id查找品牌
Brand brand = brandService.findBrandById(goods.getBrand_id().toString());
goods.setBrand_name(brand.getName());
goods.setState("下架");
Goods goods1 = goodsService.addGoods(goods);
return goods1.getId().toString();
}
@ResponseBody
@RequestMapping("/updateGoods.form")
public String updateGoods(Goods goods){
//根据品牌id查找品牌
Brand brand = brandService.findBrandById(goods.getBrand_id().toString());
goods.setBrand_name(brand.getName());
Integer count = goodsService.updateGoods(goods);
return count.toString();
}
// @RequestMapping("/toUpdateGoods.page")
// public String toUpdateGoods(String id, Model model){
// Goods goods = null;
// Level level = null;
// com.msy.entity.Model model1 = null;
// Guige guige = null;
// List<Brand> brands = brandService.listAllBrand();
// if(StringUtils.isEmpty(id)){
// goods = new Goods();
// level = new Level();
// model1 = new com.msy.entity.Model();
// guige = new Guige();
// }else{
// //根据id查询规格
// guige = brandService.findguigeById(id);
// //根据id查询型号
// model1 = brandService.findModelById(guige.getModel_id());
// //根据id查询级别
// level = brandService.findLevelById(model1.getLevel_id());
// //根据id查询商品
// goods = goodsService.findGoodsById(level.getGoods_id());
// }
// model.addAttribute("goods",goods);
// model.addAttribute("brands",brands);
// model.addAttribute("model",model1);
// model.addAttribute("level",level);
// model.addAttribute("guige",guige);
// return "pc/goods/updateGoods";
// }
@ResponseBody
@RequestMapping("/upDown.json")
public String upDown(String id,String state){
Integer count = null;
if("上架".equals(state)){
count = goodsService.upDown(id,"下架");
}else{
count = goodsService.upDown(id,"上架");
}
return count.toString();
}
}
|
UTF-8
|
Java
| 3,848 |
java
|
GoodsController.java
|
Java
|
[] | null |
[] |
package com.msy.controller;
import com.msy.entity.*;
import com.msy.service.BrandService;
import com.msy.service.GoodsService;
import com.msy.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/pc/goods")
public class GoodsController {
@Autowired
private GoodsService goodsService;
@Autowired
private BrandService brandService;
@RequestMapping("/toGoodsList.page")
public String toGoodsListPage(Model model){
List<Brand> brands = brandService.listAllBrand();
model.addAttribute("brands",brands);
return "pc/goods/goodsList";
}
@ResponseBody
@RequestMapping("/getGoodsList.json")
public PageResult<List<Goods>> getClientList(TableModel<Goods> tableModel,Goods goods){
tableModel.setData(goods);
if(StringUtils.isEmpty(tableModel.getField())){
tableModel.setField("id");
}
if(StringUtils.isEmpty(tableModel.getOrder())){
tableModel.setOrder("desc");
}
PageResult<List<Goods>> listPageResult = goodsService.listGoods(tableModel);
return listPageResult;
}
@RequestMapping("/toAddGoods.page")
public String toAddGoods(Model model,Integer id){
Goods goods = null;
List<Brand> brands = brandService.listAllBrand();
if(StringUtils.isEmpty(id)){
//add
goods = new Goods();
}else{
//update 根据id查找商品
goods = goodsService.findGoodsById(id);
}
model.addAttribute("goods",goods);
model.addAttribute("brands",brands);
return "pc/goods/addGoods";
}
@ResponseBody
@RequestMapping("/addGoods.form")
@Transactional(rollbackFor = Exception.class)
public String addGoods(Goods goods){
//根据品牌id查找品牌
Brand brand = brandService.findBrandById(goods.getBrand_id().toString());
goods.setBrand_name(brand.getName());
goods.setState("下架");
Goods goods1 = goodsService.addGoods(goods);
return goods1.getId().toString();
}
@ResponseBody
@RequestMapping("/updateGoods.form")
public String updateGoods(Goods goods){
//根据品牌id查找品牌
Brand brand = brandService.findBrandById(goods.getBrand_id().toString());
goods.setBrand_name(brand.getName());
Integer count = goodsService.updateGoods(goods);
return count.toString();
}
// @RequestMapping("/toUpdateGoods.page")
// public String toUpdateGoods(String id, Model model){
// Goods goods = null;
// Level level = null;
// com.msy.entity.Model model1 = null;
// Guige guige = null;
// List<Brand> brands = brandService.listAllBrand();
// if(StringUtils.isEmpty(id)){
// goods = new Goods();
// level = new Level();
// model1 = new com.msy.entity.Model();
// guige = new Guige();
// }else{
// //根据id查询规格
// guige = brandService.findguigeById(id);
// //根据id查询型号
// model1 = brandService.findModelById(guige.getModel_id());
// //根据id查询级别
// level = brandService.findLevelById(model1.getLevel_id());
// //根据id查询商品
// goods = goodsService.findGoodsById(level.getGoods_id());
// }
// model.addAttribute("goods",goods);
// model.addAttribute("brands",brands);
// model.addAttribute("model",model1);
// model.addAttribute("level",level);
// model.addAttribute("guige",guige);
// return "pc/goods/updateGoods";
// }
@ResponseBody
@RequestMapping("/upDown.json")
public String upDown(String id,String state){
Integer count = null;
if("上架".equals(state)){
count = goodsService.upDown(id,"下架");
}else{
count = goodsService.upDown(id,"上架");
}
return count.toString();
}
}
| 3,848 | 0.729144 | 0.727273 | 129 | 27.992249 | 20.081036 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.031008 | false | false |
14
|
4737ed41dfd13d331b0d4e908314090062318247
| 19,997,367,792,155 |
6633606079f85ffc7f1b3d2c42908116f8a78fb7
|
/src/main/java/com/employee/management/controller/impl/EmployeeControllerImpl.java
|
43164d01d6a778e272c03e385cb5e3d5c6a89690
|
[] |
no_license
|
Umartahir93/Employee-Management-System
|
https://github.com/Umartahir93/Employee-Management-System
|
a4a4193ee134b0811e1f7dbfe24859a17caf9b12
|
f2e46558cd558277f96b3b93cc76377ef48cf551
|
refs/heads/master
| 2023-05-25T22:49:23.162000 | 2020-04-16T07:23:28 | 2020-04-16T07:23:28 | 255,293,476 | 2 | 0 | null | false | 2021-06-04T22:08:50 | 2020-04-13T10:16:52 | 2021-01-12T17:47:47 | 2021-06-04T22:08:50 | 1,702 | 0 | 0 | 3 |
Java
| false | false |
package com.employee.management.controller.impl;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import com.employee.management.controller.EmployeeController;
import com.employee.management.domain.Employee;
import com.employee.management.domain.Response;
import com.employee.management.service.EmployeeService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Implementation class for Employee Controller. It contains all end points implementation to
* process requests
*
* @author umar.tahir
*
*/
@Slf4j
@RestController
@AllArgsConstructor
public class EmployeeControllerImpl implements EmployeeController {
@Autowired
EmployeeService service;
/**
* This end point is used to retrieve employee resource present against its name and can be access
* by any user with roles of admin or viewer
*
* @param name
* @return Employee Resource
*/
@Override
public ResponseEntity<List<Employee>> getEmployeeByName(String name) {
log.info("Get the resurce by {} Execution started ", name);
return ResponseEntity.ok().body(service.getByEmployeeName(name));
}
/**
* This end point is used to retrieve list of all employee resources and is used by users who have
* roles of admin or viewer
*
* @return Collection of All Employee Resources
*/
@Override
public ResponseEntity<List<Employee>> getAllEmployees() {
log.info("Get the resurces Execution started ");
return ResponseEntity.ok().body(service.getAllEmployee());
}
/**
* This end point is used to save employee resource in data store and used by all the users
*
* @param Employee
* @return Resource that is saved in data source with response description
*/
@Override
public ResponseEntity<Response> saveEmployee(@Valid Employee employeeDto) {
log.info("save the resurces Execution started with input {} ", employeeDto.toString());
return ResponseEntity.status(HttpStatus.CREATED)
.body(new Response("Resource Created", "Created", service.saveEmployee(employeeDto)));
}
/**
* This end point is used to update employee resource in data store if it is present and this end
* point is used by user with admin role
*
* @param Employee
* @return Resource that is updated in data source with response description
*/
@Override
public ResponseEntity<Response> updateEmployee(Employee inputEmployeeDto) {
log.info("update the resurces Execution started with input {}", inputEmployeeDto.toString());
return ResponseEntity
.ok(new Response("Resporce Updated", "Updated", service.updateEmployee(inputEmployeeDto)));
}
/**
* This end point remove employee resource identified by Id and is used by user with admin role
*
* @param id
* @return Response with Resource removed details
*
*/
@Override
public ResponseEntity<Response> deleteEmployee(int id) {
log.info("delete the resurces Execution started with id {}", id);
service.deleteEmployee(id);
return ResponseEntity
.ok(new Response("Resource Removed", "Resource with id has been removed", null));
}
/**
* This end point is added to practice @Transactional and 2nd level cache. It is not following
* best coding standards as implemented on other end points. Also its test case is not added.
*
* @param employee
* @return
*/
@Override
public ResponseEntity<String> saveEmployeeList(List<Employee> employee) {
log.info("save the resurces Execution started with input {} ", employee.toString());
service.saveEmployeeList(employee);
return ResponseEntity.status(HttpStatus.CREATED).body("Resources Created");
}
}
|
UTF-8
|
Java
| 3,911 |
java
|
EmployeeControllerImpl.java
|
Java
|
[
{
"context": "plementation to\n * process requests\n * \n * @author umar.tahir\n *\n */\n\n@Slf4j\n@RestController\n@AllArgsConstructo",
"end": 748,
"score": 0.9225682020187378,
"start": 738,
"tag": "NAME",
"value": "umar.tahir"
}
] | null |
[] |
package com.employee.management.controller.impl;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import com.employee.management.controller.EmployeeController;
import com.employee.management.domain.Employee;
import com.employee.management.domain.Response;
import com.employee.management.service.EmployeeService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Implementation class for Employee Controller. It contains all end points implementation to
* process requests
*
* @author umar.tahir
*
*/
@Slf4j
@RestController
@AllArgsConstructor
public class EmployeeControllerImpl implements EmployeeController {
@Autowired
EmployeeService service;
/**
* This end point is used to retrieve employee resource present against its name and can be access
* by any user with roles of admin or viewer
*
* @param name
* @return Employee Resource
*/
@Override
public ResponseEntity<List<Employee>> getEmployeeByName(String name) {
log.info("Get the resurce by {} Execution started ", name);
return ResponseEntity.ok().body(service.getByEmployeeName(name));
}
/**
* This end point is used to retrieve list of all employee resources and is used by users who have
* roles of admin or viewer
*
* @return Collection of All Employee Resources
*/
@Override
public ResponseEntity<List<Employee>> getAllEmployees() {
log.info("Get the resurces Execution started ");
return ResponseEntity.ok().body(service.getAllEmployee());
}
/**
* This end point is used to save employee resource in data store and used by all the users
*
* @param Employee
* @return Resource that is saved in data source with response description
*/
@Override
public ResponseEntity<Response> saveEmployee(@Valid Employee employeeDto) {
log.info("save the resurces Execution started with input {} ", employeeDto.toString());
return ResponseEntity.status(HttpStatus.CREATED)
.body(new Response("Resource Created", "Created", service.saveEmployee(employeeDto)));
}
/**
* This end point is used to update employee resource in data store if it is present and this end
* point is used by user with admin role
*
* @param Employee
* @return Resource that is updated in data source with response description
*/
@Override
public ResponseEntity<Response> updateEmployee(Employee inputEmployeeDto) {
log.info("update the resurces Execution started with input {}", inputEmployeeDto.toString());
return ResponseEntity
.ok(new Response("Resporce Updated", "Updated", service.updateEmployee(inputEmployeeDto)));
}
/**
* This end point remove employee resource identified by Id and is used by user with admin role
*
* @param id
* @return Response with Resource removed details
*
*/
@Override
public ResponseEntity<Response> deleteEmployee(int id) {
log.info("delete the resurces Execution started with id {}", id);
service.deleteEmployee(id);
return ResponseEntity
.ok(new Response("Resource Removed", "Resource with id has been removed", null));
}
/**
* This end point is added to practice @Transactional and 2nd level cache. It is not following
* best coding standards as implemented on other end points. Also its test case is not added.
*
* @param employee
* @return
*/
@Override
public ResponseEntity<String> saveEmployeeList(List<Employee> employee) {
log.info("save the resurces Execution started with input {} ", employee.toString());
service.saveEmployeeList(employee);
return ResponseEntity.status(HttpStatus.CREATED).body("Resources Created");
}
}
| 3,911 | 0.734083 | 0.733061 | 125 | 30.271999 | 32.923519 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.312 | false | false |
5
|
ae4089416a914957b7919cf1141c18f43429500c
| 10,651,518,958,049 |
a8e2d15fcab76f88010ab6b6d79f4b44e1ec80be
|
/src/main/java/com/customDS/CustomDS/CustomDsApplication.java
|
cf04fba93ac8d8980c63c32895fb7b472078517e
|
[] |
no_license
|
Jaycs16/CustomDS
|
https://github.com/Jaycs16/CustomDS
|
c6df773356aa7e26bce66363bed7dda5e65918a2
|
1a770878d28a64f075fa22e7f34164d475a10056
|
refs/heads/master
| 2022-12-08T14:21:45.399000 | 2020-09-01T12:10:44 | 2020-09-01T12:10:44 | 288,261,350 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.customDS.CustomDS;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CustomDsApplication {
public static void main(String[] args) {
SpringApplication.run(CustomDsApplication.class, args);
}
}
|
UTF-8
|
Java
| 318 |
java
|
CustomDsApplication.java
|
Java
|
[] | null |
[] |
package com.customDS.CustomDS;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CustomDsApplication {
public static void main(String[] args) {
SpringApplication.run(CustomDsApplication.class, args);
}
}
| 318 | 0.823899 | 0.823899 | 13 | 23.461538 | 23.928146 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false |
5
|
9b7316375241f806368af088f6cb7734c0455018
| 34,479,997,489,955 |
d01992cc7a5afb55f9db913c19471e0b8edb2bbc
|
/src/biblio_univ/useful/MariaDBConnection.java
|
be2db07072ea782364c107eeef9e499381ac2cee
|
[
"MIT"
] |
permissive
|
THammami01/SGBiblioUniv
|
https://github.com/THammami01/SGBiblioUniv
|
4f98cb8c8a14a81f77db8322fb90fa42263f5e54
|
d7c367231ea896d9eb418597174a612cfa04a1b7
|
refs/heads/main
| 2023-02-07T01:38:55.142000 | 2020-12-21T01:39:17 | 2020-12-21T01:39:17 | 322,920,460 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package biblio_univ.useful;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
public class MariaDBConnection {
private Connection connection;
private Statement st;
private ResultSet rs;
private String query;
private boolean hostedOnline = false;
public String isConnected;
private String dburlLocal = "jdbc:mariadb://localhost:3306/BiblioUniv";
private String usernameLocal = "root";
private String passwordLocal = "";
private String dburlOnline = "jdbc:mariadb://remotemysql.com:3306/zFSKj0KaNq";
private String usernameOnline = "zFSKj0KaNq";
private String passwordOnline = "Y3uEhSBH22";
public MariaDBConnection() {
try {
try {
Class.forName("org.mariadb.jdbc.Driver");
} catch(Exception e) {
isConnected = e.getMessage();
}
if(hostedOnline)
connection = DriverManager.getConnection(dburlOnline, usernameOnline, passwordOnline);
else
connection = DriverManager.getConnection(dburlLocal, usernameLocal, passwordLocal);
st = connection.createStatement();
} catch (Exception e) {
isConnected = e.toString();
System.out.println(e);
}
}
public void close() {
if(connection != null) {
try {
connection.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
public String[] getCredentials() {
String[] credentials = new String[2];
query = "SELECT * FROM Utilisateurs;";
try {
rs = st.executeQuery(query);
rs.next();
credentials[0] = rs.getString("nomUtilisateur");
credentials[1] = rs.getString("motDePasse");
} catch (Exception e) {
credentials[0] = "ERR01";
System.out.println(e);
}
return credentials;
}
public Abonne rechercherAbonne(int idAbonne) {
Abonne abonne;
query = "SELECT * FROM Abonnes WHERE idAbonne = " + idAbonne + ";";
try {
rs = st.executeQuery(query);
if(!rs.next()) {
return new Abonne(-2);
}
String dateComplet = AllInOne.getDateComplet(rs.getTimestamp("date_abonnement"));
abonne = new Abonne(
rs.getInt("idAbonne"),
rs.getString("prenom"),
rs.getString("nom"),
rs.getInt("num_tel"),
rs.getInt("etu_ou_ens") == 0 ? EstEOuE.ETUDIANT : EstEOuE.ENSEIGNANT,
dateComplet
);
return abonne;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
public int ajouterAbonne(Abonne nouvAbonne) {
query = "INSERT INTO Abonnes (nom, prenom, etu_ou_ens, num_tel) VALUES(\"" +
nouvAbonne.getNom() + "\", \"" +
nouvAbonne.getPrenom() + "\", " +
(nouvAbonne.getEstEOuE() == EstEOuE.ETUDIANT ? 0 : 1) + ", " +
nouvAbonne.getNumTel() + ");";
try {
if(st.executeUpdate(query) > 0) {
query = "SELECT MAX(idAbonne) as maxId FROM Abonnes;";
rs = st.executeQuery(query);
rs.next();
return rs.getInt("maxId");
} else {
return -1;
}
} catch (Exception e) {
System.out.println(e);
return -1;
}
}
public boolean modifierAbonne(Abonne abonneModifie) {
query = "UPDATE Abonnes SET prenom = \"" + abonneModifie.getPrenom() +
"\", nom = \"" + abonneModifie.getNom() +
"\", etu_ou_ens = " + (abonneModifie.getEstEOuE() == EstEOuE.ETUDIANT ? 0 : 1) +
", num_tel = " + abonneModifie.getNumTel() +
" WHERE idAbonne = " + abonneModifie.getId() + ";";
try {
if(st.executeUpdate(query) > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
public boolean supprimerAbonne(int idAbonne) {
query = "DELETE FROM Abonnes WHERE idAbonne = " + idAbonne + ";";
try {
if(st.executeUpdate(query) > 0)
return true;
else
return false;
} catch (Exception e) {
System.out.println(e);
return false;
}
}
public Livre rechercherLivre(int idLivre) {
Livre livre;
query = "SELECT * FROM Livres WHERE idLivre = " + idLivre + ";";
try {
rs = st.executeQuery(query);
if(!rs.next()) {
return new Livre(-2);
}
String dateAjoutComplet = AllInOne.getDateComplet(rs.getTimestamp("date_ajout"));
livre = new Livre(
rs.getInt("idLivre"),
rs.getString("titre"),
rs.getString("isbn"),
dateAjoutComplet
);
return livre;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
public int ajouterLivre(Livre nouvLivre) {
query = "INSERT INTO Livres (titre, isbn) VALUES(\"" +
nouvLivre.getTitre() + "\", \"" +
nouvLivre.getISBN() + "\");";
try {
if(st.executeUpdate(query) > 0) {
query = "SELECT MAX(idLivre) as maxId FROM Livres;";
rs = st.executeQuery(query);
rs.next();
return rs.getInt("maxId");
} else {
return -1;
}
} catch (Exception e) {
System.out.println(e);
return -1;
}
}
public boolean modifierLivre(Livre livreModifie) {
query = "UPDATE Livres SET titre = \"" + livreModifie.getTitre() +
"\", isbn = \"" + livreModifie.getISBN() +
"\" WHERE idLivre = " + livreModifie.getId() + ";";
try {
if(st.executeUpdate(query) > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
public boolean supprimerLivre(int idLivre) {
query = "DELETE FROM Livres WHERE idLivre = " + idLivre + ";";
try {
if(st.executeUpdate(query) > 0)
return true;
else
return false;
} catch (Exception e) {
System.out.println(e);
return false;
}
}
public int ajouterEmprunt(Emprunt nouvEmprunt) {
try {
query = "SELECT idLivre FROM Livres WHERE idLivre = " + nouvEmprunt.getIdLivre() + ";";
rs = st.executeQuery(query);
if(!rs.next())
return -1; // Livre DOES NOT EXIST
query = "SELECT idAbonne FROM Abonnes WHERE idAbonne = " + nouvEmprunt.getIdAbonne() + ";";
rs = st.executeQuery(query);
if(!rs.next())
return -2; // Abonne DOES NOT EXIST
query = "SELECT Count(*) as NbEmpruntsDeLAbonne FROM Emprunts WHERE idAbonne = " + nouvEmprunt.getIdAbonne() +
" AND date_rendu IS NULL;";
rs = st.executeQuery(query);
rs.next();
if(rs.getInt("NbEmpruntsDeLAbonne") >= 2)
return -3; // NbEmpruntsDeLAbonne IS >= 2
query = "SELECT idLivre FROM Emprunts WHERE idLivre = " + nouvEmprunt.getIdLivre() + " AND date_rendu IS NULL;";
rs = st.executeQuery(query);
if(rs.next())
return -4; // Livre IS emprunté
query = "INSERT INTO Emprunts (idLivre, idAbonne) VALUES(" +
nouvEmprunt.getIdLivre() + ", " +
nouvEmprunt.getIdAbonne() + ");";
if(st.executeUpdate(query) > 0) {
query = "SELECT MAX(idEmprunt) as maxId FROM Emprunts;";
rs = st.executeQuery(query);
rs.next();
return rs.getInt("maxId"); // SUCCUSSFULLY Emprunté AND RETURNING BACK THE ID
} else {
return -5; // ERROR WHILE THE Emprunt
}
} catch (Exception e) {
System.out.println(e);
return -6; // ERROR WHILE CONNECTING TO DATABASE
}
}
public int remettreEmprunt(int idEmprunt) {
query = "UPDATE Emprunts SET date_rendu = current_timestamp() WHERE idEmprunt = " + idEmprunt + " AND date_rendu IS NULL;";
try {
if(st.executeUpdate(query) > 0) {
return 0; // SUCCESSFULLY GIVEN BACK
} else {
return 1; // ID DOES NOT EXIST OR BOOK IS GIVEN BACK
}
} catch (Exception e) {
System.out.println(e);
return 2; // ERROR
}
}
// public String rechercherPrets(int id, boolean estIdLivre, boolean tousLesLivres) {
//
// if(estIdLivre) {
// query = "SELECT * FROM Emprunts" +
// "WHERE idLivre = " + id +
//
//
// (tousLesLivres ? "" : " AND date_rendu IS NULL") + ";";
// }
//
//
// try {
//
//// rs = st.executeQuery(query);
//// rs.next();
//// return rs.getInt("maxId");
//
// } catch (Exception e) {
// System.out.println(e);
// return null; // ERROR
// }
//
// }
//
public String rechercherTousPretsNonRendus() {
query = "SELECT CONCAT('[', E.idEmprunt, '] ', A.prenom, ' ', A.nom, ' (', A.idAbonne, ') a emprunté \"', L.titre, '\" (', L.idLivre, ') le ' ) as res, date_pret FROM Emprunts as E, Livres as L, Abonnes as A WHERE E.idLivre = L.idLivre AND E.idAbonne = A.idAbonne AND E.date_rendu IS NULL ORDER BY E.date_rendu DESC;";
String res = "<html>";
try {
rs = st.executeQuery(query);
while(rs.next())
res += rs.getString("res") + AllInOne.getDateComplet(rs.getTimestamp("date_pret")) + " et n'a pas rendu encore.<br/><br/>";
res += "</html>";
return res;
} catch(Exception e) {
System.out.println(e);
return null;
}
}
public String rechercherTousPretsAvecIdLivre(int idLivre) {
query = "SELECT CONCAT('[', E.idEmprunt, '] ', A.prenom, ' ', A.nom, ' (', A.idAbonne, ') a emprunté \"', L.titre, '\" (', L.idLivre, ') le ' ) as res, date_pret, date_rendu FROM Emprunts as E, Livres as L, Abonnes as A WHERE E.idLivre = L.idLivre AND E.idAbonne = A.idAbonne AND E.idLivre = " + idLivre + " ORDER BY E.date_rendu DESC;";
String res = "<html>";
try {
rs = st.executeQuery(query);
while(rs.next()) {
res += rs.getString("res") + AllInOne.getDateComplet(rs.getTimestamp("date_pret"));
if(rs.getTimestamp("date_rendu") != null)
res += " et a rendu le " + AllInOne.getDateComplet(rs.getTimestamp("date_rendu"));
else
res += " et n'a pas rendu encore";
res += ".<br/><br/>";
}
res += "</html>";
return res;
} catch(Exception e) {
System.out.println(e);
return null;
}
}
public String rechercherTousPretsAvecIdAbonne(int idAbonne) {
query = "SELECT CONCAT('[', E.idEmprunt, '] ', A.prenom, ' ', A.nom, ' (', A.idAbonne, ') a emprunté \"', L.titre, '\" (', L.idLivre, ') le ' ) as res, date_pret, date_rendu FROM Emprunts as E, Livres as L, Abonnes as A WHERE E.idLivre = L.idLivre AND E.idAbonne = A.idAbonne AND E.idAbonne = " + idAbonne + " ORDER BY E.date_rendu DESC;";
String res = "<html>";
try {
rs = st.executeQuery(query);
while(rs.next()) {
res += rs.getString("res") + AllInOne.getDateComplet(rs.getTimestamp("date_pret"));
if(rs.getTimestamp("date_rendu") != null)
res += " et a rendu le " + AllInOne.getDateComplet(rs.getTimestamp("date_rendu"));
else
res += " et n'a pas rendu encore";
res += ".<br/><br/>";
}
res += "</html>";
return res;
} catch(Exception e) {
System.out.println(e);
return null;
}
}
public String rechercherTousPretsNonRendusAvant7Jours() {
query = "SELECT (CURRENT_TIMESTAMP() - DATE_PRET) as nbSeconds, CONCAT('[', E.idEmprunt, '] ', A.prenom, ' ', A.nom, ' (', A.idAbonne, ') a emprunté \"', L.titre, '\" (', L.idLivre, ') le ' ) as res, date_pret FROM Emprunts as E, Livres as L, Abonnes as A WHERE E.idLivre = L.idLivre AND E.idAbonne = A.idAbonne AND E.date_rendu IS NULL AND (CURRENT_TIMESTAMP() - DATE_PRET) > 604800 ORDER BY (CURRENT_TIMESTAMP() - DATE_PRET) DESC;";
String res = "<html>";
try {
rs = st.executeQuery(query);
while(rs.next())
res += rs.getString("res") + AllInOne.getDateComplet(rs.getTimestamp("date_pret")) + " et n'a pas rendu avant 7 jours.<br/><br/>";
res += "</html>";
return res;
} catch(Exception e) {
System.out.println(e);
return null;
}
}
public String[] rechercherTop10() {
query = "SELECT L.titre, COUNT(*) as nbEmprunts FROM Emprunts as E, Livres as L WHERE E.idLivre = L.idLivre GROUP BY L.titre ORDER BY nbEmprunts DESC;";
String[] top10 = new String[10];
try {
rs = st.executeQuery(query);
int i = 0;
while(rs.next())
top10[i++] = String.format("(%d fois) %s", rs.getInt("nbEmprunts"), rs.getString("titre"));
for(; i<10; i++)
top10[i] = "N/A";
} catch(Exception e) {
System.out.println(e);
}
return top10;
}
}
|
WINDOWS-1250
|
Java
| 12,703 |
java
|
MariaDBConnection.java
|
Java
|
[
{
"context": "06/zFSKj0KaNq\";\n\tprivate String usernameOnline = \"zFSKj0KaNq\";\n\tprivate String passwordOnline = \"Y3uEhSBH22\";\n",
"end": 672,
"score": 0.9991944432258606,
"start": 662,
"tag": "USERNAME",
"value": "zFSKj0KaNq"
},
{
"context": "= \"zFSKj0KaNq\";\n\tprivate String passwordOnline = \"Y3uEhSBH22\";\n\t\n\t\n\tpublic MariaDBConnection() {\n\t\t\n\t try {",
"end": 719,
"score": 0.9994614124298096,
"start": 709,
"tag": "PASSWORD",
"value": "Y3uEhSBH22"
}
] | null |
[] |
package biblio_univ.useful;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
public class MariaDBConnection {
private Connection connection;
private Statement st;
private ResultSet rs;
private String query;
private boolean hostedOnline = false;
public String isConnected;
private String dburlLocal = "jdbc:mariadb://localhost:3306/BiblioUniv";
private String usernameLocal = "root";
private String passwordLocal = "";
private String dburlOnline = "jdbc:mariadb://remotemysql.com:3306/zFSKj0KaNq";
private String usernameOnline = "zFSKj0KaNq";
private String passwordOnline = "<PASSWORD>";
public MariaDBConnection() {
try {
try {
Class.forName("org.mariadb.jdbc.Driver");
} catch(Exception e) {
isConnected = e.getMessage();
}
if(hostedOnline)
connection = DriverManager.getConnection(dburlOnline, usernameOnline, passwordOnline);
else
connection = DriverManager.getConnection(dburlLocal, usernameLocal, passwordLocal);
st = connection.createStatement();
} catch (Exception e) {
isConnected = e.toString();
System.out.println(e);
}
}
public void close() {
if(connection != null) {
try {
connection.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
public String[] getCredentials() {
String[] credentials = new String[2];
query = "SELECT * FROM Utilisateurs;";
try {
rs = st.executeQuery(query);
rs.next();
credentials[0] = rs.getString("nomUtilisateur");
credentials[1] = rs.getString("motDePasse");
} catch (Exception e) {
credentials[0] = "ERR01";
System.out.println(e);
}
return credentials;
}
public Abonne rechercherAbonne(int idAbonne) {
Abonne abonne;
query = "SELECT * FROM Abonnes WHERE idAbonne = " + idAbonne + ";";
try {
rs = st.executeQuery(query);
if(!rs.next()) {
return new Abonne(-2);
}
String dateComplet = AllInOne.getDateComplet(rs.getTimestamp("date_abonnement"));
abonne = new Abonne(
rs.getInt("idAbonne"),
rs.getString("prenom"),
rs.getString("nom"),
rs.getInt("num_tel"),
rs.getInt("etu_ou_ens") == 0 ? EstEOuE.ETUDIANT : EstEOuE.ENSEIGNANT,
dateComplet
);
return abonne;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
public int ajouterAbonne(Abonne nouvAbonne) {
query = "INSERT INTO Abonnes (nom, prenom, etu_ou_ens, num_tel) VALUES(\"" +
nouvAbonne.getNom() + "\", \"" +
nouvAbonne.getPrenom() + "\", " +
(nouvAbonne.getEstEOuE() == EstEOuE.ETUDIANT ? 0 : 1) + ", " +
nouvAbonne.getNumTel() + ");";
try {
if(st.executeUpdate(query) > 0) {
query = "SELECT MAX(idAbonne) as maxId FROM Abonnes;";
rs = st.executeQuery(query);
rs.next();
return rs.getInt("maxId");
} else {
return -1;
}
} catch (Exception e) {
System.out.println(e);
return -1;
}
}
public boolean modifierAbonne(Abonne abonneModifie) {
query = "UPDATE Abonnes SET prenom = \"" + abonneModifie.getPrenom() +
"\", nom = \"" + abonneModifie.getNom() +
"\", etu_ou_ens = " + (abonneModifie.getEstEOuE() == EstEOuE.ETUDIANT ? 0 : 1) +
", num_tel = " + abonneModifie.getNumTel() +
" WHERE idAbonne = " + abonneModifie.getId() + ";";
try {
if(st.executeUpdate(query) > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
public boolean supprimerAbonne(int idAbonne) {
query = "DELETE FROM Abonnes WHERE idAbonne = " + idAbonne + ";";
try {
if(st.executeUpdate(query) > 0)
return true;
else
return false;
} catch (Exception e) {
System.out.println(e);
return false;
}
}
public Livre rechercherLivre(int idLivre) {
Livre livre;
query = "SELECT * FROM Livres WHERE idLivre = " + idLivre + ";";
try {
rs = st.executeQuery(query);
if(!rs.next()) {
return new Livre(-2);
}
String dateAjoutComplet = AllInOne.getDateComplet(rs.getTimestamp("date_ajout"));
livre = new Livre(
rs.getInt("idLivre"),
rs.getString("titre"),
rs.getString("isbn"),
dateAjoutComplet
);
return livre;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
public int ajouterLivre(Livre nouvLivre) {
query = "INSERT INTO Livres (titre, isbn) VALUES(\"" +
nouvLivre.getTitre() + "\", \"" +
nouvLivre.getISBN() + "\");";
try {
if(st.executeUpdate(query) > 0) {
query = "SELECT MAX(idLivre) as maxId FROM Livres;";
rs = st.executeQuery(query);
rs.next();
return rs.getInt("maxId");
} else {
return -1;
}
} catch (Exception e) {
System.out.println(e);
return -1;
}
}
public boolean modifierLivre(Livre livreModifie) {
query = "UPDATE Livres SET titre = \"" + livreModifie.getTitre() +
"\", isbn = \"" + livreModifie.getISBN() +
"\" WHERE idLivre = " + livreModifie.getId() + ";";
try {
if(st.executeUpdate(query) > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
public boolean supprimerLivre(int idLivre) {
query = "DELETE FROM Livres WHERE idLivre = " + idLivre + ";";
try {
if(st.executeUpdate(query) > 0)
return true;
else
return false;
} catch (Exception e) {
System.out.println(e);
return false;
}
}
public int ajouterEmprunt(Emprunt nouvEmprunt) {
try {
query = "SELECT idLivre FROM Livres WHERE idLivre = " + nouvEmprunt.getIdLivre() + ";";
rs = st.executeQuery(query);
if(!rs.next())
return -1; // Livre DOES NOT EXIST
query = "SELECT idAbonne FROM Abonnes WHERE idAbonne = " + nouvEmprunt.getIdAbonne() + ";";
rs = st.executeQuery(query);
if(!rs.next())
return -2; // Abonne DOES NOT EXIST
query = "SELECT Count(*) as NbEmpruntsDeLAbonne FROM Emprunts WHERE idAbonne = " + nouvEmprunt.getIdAbonne() +
" AND date_rendu IS NULL;";
rs = st.executeQuery(query);
rs.next();
if(rs.getInt("NbEmpruntsDeLAbonne") >= 2)
return -3; // NbEmpruntsDeLAbonne IS >= 2
query = "SELECT idLivre FROM Emprunts WHERE idLivre = " + nouvEmprunt.getIdLivre() + " AND date_rendu IS NULL;";
rs = st.executeQuery(query);
if(rs.next())
return -4; // Livre IS emprunté
query = "INSERT INTO Emprunts (idLivre, idAbonne) VALUES(" +
nouvEmprunt.getIdLivre() + ", " +
nouvEmprunt.getIdAbonne() + ");";
if(st.executeUpdate(query) > 0) {
query = "SELECT MAX(idEmprunt) as maxId FROM Emprunts;";
rs = st.executeQuery(query);
rs.next();
return rs.getInt("maxId"); // SUCCUSSFULLY Emprunté AND RETURNING BACK THE ID
} else {
return -5; // ERROR WHILE THE Emprunt
}
} catch (Exception e) {
System.out.println(e);
return -6; // ERROR WHILE CONNECTING TO DATABASE
}
}
public int remettreEmprunt(int idEmprunt) {
query = "UPDATE Emprunts SET date_rendu = current_timestamp() WHERE idEmprunt = " + idEmprunt + " AND date_rendu IS NULL;";
try {
if(st.executeUpdate(query) > 0) {
return 0; // SUCCESSFULLY GIVEN BACK
} else {
return 1; // ID DOES NOT EXIST OR BOOK IS GIVEN BACK
}
} catch (Exception e) {
System.out.println(e);
return 2; // ERROR
}
}
// public String rechercherPrets(int id, boolean estIdLivre, boolean tousLesLivres) {
//
// if(estIdLivre) {
// query = "SELECT * FROM Emprunts" +
// "WHERE idLivre = " + id +
//
//
// (tousLesLivres ? "" : " AND date_rendu IS NULL") + ";";
// }
//
//
// try {
//
//// rs = st.executeQuery(query);
//// rs.next();
//// return rs.getInt("maxId");
//
// } catch (Exception e) {
// System.out.println(e);
// return null; // ERROR
// }
//
// }
//
public String rechercherTousPretsNonRendus() {
query = "SELECT CONCAT('[', E.idEmprunt, '] ', A.prenom, ' ', A.nom, ' (', A.idAbonne, ') a emprunté \"', L.titre, '\" (', L.idLivre, ') le ' ) as res, date_pret FROM Emprunts as E, Livres as L, Abonnes as A WHERE E.idLivre = L.idLivre AND E.idAbonne = A.idAbonne AND E.date_rendu IS NULL ORDER BY E.date_rendu DESC;";
String res = "<html>";
try {
rs = st.executeQuery(query);
while(rs.next())
res += rs.getString("res") + AllInOne.getDateComplet(rs.getTimestamp("date_pret")) + " et n'a pas rendu encore.<br/><br/>";
res += "</html>";
return res;
} catch(Exception e) {
System.out.println(e);
return null;
}
}
public String rechercherTousPretsAvecIdLivre(int idLivre) {
query = "SELECT CONCAT('[', E.idEmprunt, '] ', A.prenom, ' ', A.nom, ' (', A.idAbonne, ') a emprunté \"', L.titre, '\" (', L.idLivre, ') le ' ) as res, date_pret, date_rendu FROM Emprunts as E, Livres as L, Abonnes as A WHERE E.idLivre = L.idLivre AND E.idAbonne = A.idAbonne AND E.idLivre = " + idLivre + " ORDER BY E.date_rendu DESC;";
String res = "<html>";
try {
rs = st.executeQuery(query);
while(rs.next()) {
res += rs.getString("res") + AllInOne.getDateComplet(rs.getTimestamp("date_pret"));
if(rs.getTimestamp("date_rendu") != null)
res += " et a rendu le " + AllInOne.getDateComplet(rs.getTimestamp("date_rendu"));
else
res += " et n'a pas rendu encore";
res += ".<br/><br/>";
}
res += "</html>";
return res;
} catch(Exception e) {
System.out.println(e);
return null;
}
}
public String rechercherTousPretsAvecIdAbonne(int idAbonne) {
query = "SELECT CONCAT('[', E.idEmprunt, '] ', A.prenom, ' ', A.nom, ' (', A.idAbonne, ') a emprunté \"', L.titre, '\" (', L.idLivre, ') le ' ) as res, date_pret, date_rendu FROM Emprunts as E, Livres as L, Abonnes as A WHERE E.idLivre = L.idLivre AND E.idAbonne = A.idAbonne AND E.idAbonne = " + idAbonne + " ORDER BY E.date_rendu DESC;";
String res = "<html>";
try {
rs = st.executeQuery(query);
while(rs.next()) {
res += rs.getString("res") + AllInOne.getDateComplet(rs.getTimestamp("date_pret"));
if(rs.getTimestamp("date_rendu") != null)
res += " et a rendu le " + AllInOne.getDateComplet(rs.getTimestamp("date_rendu"));
else
res += " et n'a pas rendu encore";
res += ".<br/><br/>";
}
res += "</html>";
return res;
} catch(Exception e) {
System.out.println(e);
return null;
}
}
public String rechercherTousPretsNonRendusAvant7Jours() {
query = "SELECT (CURRENT_TIMESTAMP() - DATE_PRET) as nbSeconds, CONCAT('[', E.idEmprunt, '] ', A.prenom, ' ', A.nom, ' (', A.idAbonne, ') a emprunté \"', L.titre, '\" (', L.idLivre, ') le ' ) as res, date_pret FROM Emprunts as E, Livres as L, Abonnes as A WHERE E.idLivre = L.idLivre AND E.idAbonne = A.idAbonne AND E.date_rendu IS NULL AND (CURRENT_TIMESTAMP() - DATE_PRET) > 604800 ORDER BY (CURRENT_TIMESTAMP() - DATE_PRET) DESC;";
String res = "<html>";
try {
rs = st.executeQuery(query);
while(rs.next())
res += rs.getString("res") + AllInOne.getDateComplet(rs.getTimestamp("date_pret")) + " et n'a pas rendu avant 7 jours.<br/><br/>";
res += "</html>";
return res;
} catch(Exception e) {
System.out.println(e);
return null;
}
}
public String[] rechercherTop10() {
query = "SELECT L.titre, COUNT(*) as nbEmprunts FROM Emprunts as E, Livres as L WHERE E.idLivre = L.idLivre GROUP BY L.titre ORDER BY nbEmprunts DESC;";
String[] top10 = new String[10];
try {
rs = st.executeQuery(query);
int i = 0;
while(rs.next())
top10[i++] = String.format("(%d fois) %s", rs.getInt("nbEmprunts"), rs.getString("titre"));
for(; i<10; i++)
top10[i] = "N/A";
} catch(Exception e) {
System.out.println(e);
}
return top10;
}
}
| 12,703 | 0.571316 | 0.565645 | 482 | 25.344398 | 39.354671 | 436 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.639004 | false | false |
5
|
4141e6c39f5b45f8979385a0c05df5c31bc9cd01
| 33,835,752,394,242 |
c85b297f80e0b85aa0236b814ff3caceb50054ec
|
/__Rabbit_.java
|
7ab851d14940be26f7d55672ffe3aef58e4ffd07
|
[] |
no_license
|
gr4per/jrobots
|
https://github.com/gr4per/jrobots
|
ced8dd7bd26d56e74765723492938e298380e8f6
|
1b76b658911be24dd29a1733392ad49b644b2921
|
refs/heads/master
| 2022-01-06T03:06:44.553000 | 2019-06-14T17:20:06 | 2019-06-14T17:20:06 | 110,950,777 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class __Rabbit_ extends JJRobot {
void main() {
while(true) {
go(rand(1000),rand(1000));
}
}
void go(int dest_x, int dest_y) {
int course;
course = plot_course(dest_x,dest_y);
drive(course,50);
while(distance(loc_x(),loc_y(),dest_x,dest_y) > 50);
drive(course,0);
while (speed() > 0);
}
int distance(int x1, int y1, int x2, int y2) {
int x, y;
x = x1 - x2;
y = y1 - y2;
int d = sqrt((x*x) + (y*y));
return(d);
}
int plot_course(int xx, int yy) {
int d;
int x,y;
int scale;
int curx, cury;
scale = 100000;
curx = loc_x();
cury = loc_y();
x = curx - xx;
y = cury - yy;
if (x == 0) {
if (yy > cury)
d = 90;
else
d = 270;
} else {
if (yy < cury) {
if (xx > curx)
d = 360 + atan((scale * y) / x);
else
d = 180 + atan((scale * y) / x);
} else {
if (xx > curx)
d = atan((scale * y) / x);
else
d = 180 + atan((scale * y) / x);
}
}
return (d);
}
}
|
UTF-8
|
Java
| 1,040 |
java
|
__Rabbit_.java
|
Java
|
[] | null |
[] |
public class __Rabbit_ extends JJRobot {
void main() {
while(true) {
go(rand(1000),rand(1000));
}
}
void go(int dest_x, int dest_y) {
int course;
course = plot_course(dest_x,dest_y);
drive(course,50);
while(distance(loc_x(),loc_y(),dest_x,dest_y) > 50);
drive(course,0);
while (speed() > 0);
}
int distance(int x1, int y1, int x2, int y2) {
int x, y;
x = x1 - x2;
y = y1 - y2;
int d = sqrt((x*x) + (y*y));
return(d);
}
int plot_course(int xx, int yy) {
int d;
int x,y;
int scale;
int curx, cury;
scale = 100000;
curx = loc_x();
cury = loc_y();
x = curx - xx;
y = cury - yy;
if (x == 0) {
if (yy > cury)
d = 90;
else
d = 270;
} else {
if (yy < cury) {
if (xx > curx)
d = 360 + atan((scale * y) / x);
else
d = 180 + atan((scale * y) / x);
} else {
if (xx > curx)
d = atan((scale * y) / x);
else
d = 180 + atan((scale * y) / x);
}
}
return (d);
}
}
| 1,040 | 0.457692 | 0.416346 | 57 | 16.245613 | 12.761346 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.824561 | false | false |
5
|
d7bdf347bb5b932ab765845d2297727685874460
| 29,386,166,305,874 |
759ddd0c07440917ab190347e664e599ac884e48
|
/ThrowsException/src/Main.java
|
cd2ece82c3127ded4225f916d042386de1b88c36
|
[] |
no_license
|
TamakiRinko/Java_Study
|
https://github.com/TamakiRinko/Java_Study
|
58182d6546dfc7445937e3196084232c229a364e
|
f29a3deee2f9d59f10695963c0c15cde8c24c0c2
|
refs/heads/master
| 2020-06-27T21:01:43.911000 | 2019-09-05T11:39:49 | 2019-09-05T11:39:49 | 200,047,766 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException, FileFormatException {
File file = new File("testException.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String result = readData(br, 100);
System.out.println(result);
}
public static String readData(BufferedReader in, int leastLength) throws IOException, FileFormatException {
int n = 0;
char[] ch = new char[10]; //每次读10个
int readLen = 0;
String result = new String("");
while(true){
readLen = in.read(ch, 0, 10);
if(readLen == -1){
if(n < leastLength){
//未达到最低读取字节数,抛出
throw new FileFormatException("\n长度未达标,读取到的内容为:\n" + result);
}
else{
break;
}
}
result = result + String.valueOf(ch);
n += readLen;
}
return result;
}
}
|
UTF-8
|
Java
| 1,099 |
java
|
Main.java
|
Java
|
[] | null |
[] |
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException, FileFormatException {
File file = new File("testException.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String result = readData(br, 100);
System.out.println(result);
}
public static String readData(BufferedReader in, int leastLength) throws IOException, FileFormatException {
int n = 0;
char[] ch = new char[10]; //每次读10个
int readLen = 0;
String result = new String("");
while(true){
readLen = in.read(ch, 0, 10);
if(readLen == -1){
if(n < leastLength){
//未达到最低读取字节数,抛出
throw new FileFormatException("\n长度未达标,读取到的内容为:\n" + result);
}
else{
break;
}
}
result = result + String.valueOf(ch);
n += readLen;
}
return result;
}
}
| 1,099 | 0.51784 | 0.505304 | 32 | 31.40625 | 25.396677 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65625 | false | false |
5
|
666f22435fc47d82946ad79d4ede165a8ac6300e
| 35,132,832,512,170 |
3370a0d2a9e3c73340b895de3566f6e32aa3ca4a
|
/alwin-middleware-grapescode/alwin-core/src/main/java/com/codersteam/alwin/core/service/impl/issue/IssueCreatorServiceImpl.java
|
14b33566c3461ffd79ad19d5d132f41915f645fc
|
[] |
no_license
|
Wilczek01/alwin-projects
|
https://github.com/Wilczek01/alwin-projects
|
8af8e14601bd826b2ec7b3a4ce31a7d0f522b803
|
17cebb64f445206320fed40c3281c99949c47ca3
|
refs/heads/master
| 2023-01-11T16:37:59.535000 | 2020-03-24T09:01:01 | 2020-03-24T09:01:01 | 249,659,398 | 0 | 0 | null | false | 2023-01-07T16:18:14 | 2020-03-24T09:02:28 | 2020-03-24T09:06:35 | 2023-01-07T16:18:13 | 9,574 | 0 | 0 | 36 |
Java
| false | false |
package com.codersteam.alwin.core.service.impl.issue;
import com.codersteam.aida.core.api.model.AidaInvoiceWithCorrectionsDto;
import com.codersteam.aida.core.api.service.InvoiceService;
import com.codersteam.alwin.common.issue.IssueTypeName;
import com.codersteam.alwin.common.issue.Segment;
import com.codersteam.alwin.core.api.model.currency.Currency;
import com.codersteam.alwin.core.api.model.issue.Balance;
import com.codersteam.alwin.core.api.model.issue.IssueTypeConfigurationDto;
import com.codersteam.alwin.core.api.model.issue.SegmentDto;
import com.codersteam.alwin.core.api.service.AidaService;
import com.codersteam.alwin.core.api.service.DateProvider;
import com.codersteam.alwin.core.api.service.activity.ActivityService;
import com.codersteam.alwin.core.api.service.customer.CustomerVerifierService;
import com.codersteam.alwin.core.api.service.debt.BalanceCalculatorService;
import com.codersteam.alwin.core.api.service.issue.IssueCreateResult;
import com.codersteam.alwin.core.api.service.issue.IssueCreatorService;
import com.codersteam.alwin.core.local.DPDService;
import com.codersteam.alwin.core.local.LocalInvoiceService;
import com.codersteam.alwin.core.service.impl.customer.CustomerServiceImpl;
import com.codersteam.alwin.core.service.impl.issue.preparator.BalancePreparator;
import com.codersteam.alwin.core.util.DateUtils;
import com.codersteam.alwin.db.dao.IssueDao;
import com.codersteam.alwin.db.dao.IssueTypeConfigurationDao;
import com.codersteam.alwin.db.dao.IssueTypeDao;
import com.codersteam.alwin.db.dao.OperatorDao;
import com.codersteam.alwin.jpa.customer.Customer;
import com.codersteam.alwin.jpa.issue.Issue;
import com.codersteam.alwin.jpa.issue.IssueInvoice;
import com.codersteam.alwin.jpa.issue.IssueType;
import com.codersteam.alwin.jpa.operator.Operator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.*;
import static com.codersteam.alwin.common.AlwinConstants.ZERO;
import static com.codersteam.alwin.core.api.model.currency.Currency.forStringValue;
import static com.codersteam.alwin.core.service.AlwinParameters.ISSUE_DEFAULT_PRIORITY;
import static com.codersteam.alwin.core.service.impl.issue.preparator.DatePreparator.fillDates;
import static com.codersteam.alwin.jpa.type.IssueState.NEW;
import static java.lang.String.format;
import static javax.transaction.Transactional.TxType.REQUIRES_NEW;
@Stateless
public class IssueCreatorServiceImpl implements IssueCreatorService {
private static final Logger LOG = LoggerFactory.getLogger(IssueCreatorServiceImpl.class.getName());
private IssueTypeDao issueTypeDao;
private OperatorDao operatorDao;
private InvoiceService aidaInvoiceService;
private DateProvider dateProvider;
private ActivityService activityService;
private BalanceCalculatorService balanceCalculatorService;
private LocalInvoiceService localInvoiceService;
private CustomerServiceImpl customerService;
private IssueTypeConfigurationDao issueTypeConfigurationDao;
private CustomerVerifierService customerVerifierService;
private DPDService dpdService;
private IssueDao issueDao;
private IssueServiceImpl issueService;
public IssueCreatorServiceImpl() {
}
@Inject
public IssueCreatorServiceImpl(IssueTypeDao issueTypeDao,
OperatorDao operatorDao,
DateProvider dateProvider,
ActivityService activityService,
BalanceCalculatorService balanceCalculatorService,
AidaService aidaService,
CustomerServiceImpl customerService,
LocalInvoiceService localInvoiceService,
IssueTypeConfigurationDao issueTypeConfigurationDao,
CustomerVerifierService customerVerifierService,
DPDService dpdService,
IssueDao issueDao,
IssueServiceImpl issueService) {
this.issueTypeDao = issueTypeDao;
this.operatorDao = operatorDao;
this.dateProvider = dateProvider;
this.activityService = activityService;
this.balanceCalculatorService = balanceCalculatorService;
this.aidaInvoiceService = aidaService.getInvoiceService();
this.localInvoiceService = localInvoiceService;
this.customerService = customerService;
this.issueTypeConfigurationDao = issueTypeConfigurationDao;
this.customerVerifierService = customerVerifierService;
this.dpdService = dpdService;
this.issueDao = issueDao;
this.issueService = issueService;
}
@Override
@Transactional
public IssueCreateResult createIssueManually(final Long extCompanyId, final Long issueTypeId, final Date expirationDate, final Long assigneeId) {
LOG.info("Creating issue for extCompanyId={}, issueTypeId={}, expirationDate={}, operatorId={}", extCompanyId, issueTypeId, expirationDate,
assigneeId);
final Customer customer = customerService.getCustomerWithAdditionalData(extCompanyId);
final IssueType issueType = getIssueType(issueTypeId);
final Date issueExpirationDate = getExpirationDate(expirationDate, issueType, customer.getCompany().getSegment());
final CompanyInvoices companyInvoices = findCompanyInvoices(extCompanyId, issueExpirationDate);
final Operator assignee = getAssignee(assigneeId);
final Issue issue = manuallyCreateIssueWithInvoicesAndActivities(extCompanyId, customer, issueTypeId, issueExpirationDate, companyInvoices, assignee);
issueService.assignOperatorByPostalCodeForDirectDebtCollection(issue);
LOG.info("Issue {} for company (AIDA id) {} successfully created.", issue.getId(), extCompanyId);
return new IssueCreateResult(issue.getId());
}
@Override
@Transactional(REQUIRES_NEW)
public void createIssue(Long extCompanyId, IssueTypeConfigurationDto issueConfiguration) {
LOG.info("Creating issue for extCompanyId={}, issueTypeName={}, issueTypeSegment={}", extCompanyId,
issueConfiguration.getIssueType().getName(), issueConfiguration.getSegment().getKey());
Customer customer = customerService.getCustomerWithAdditionalData(extCompanyId);
Segment customerSegment = customer.getCompany().getSegment();
Segment issueTypeSegment = SegmentDto.segmentByKey(issueConfiguration.getSegment().getKey());
if (customerSegment != issueTypeSegment) {
// w przypadku niewłaściwego segmentu zlecenie nie jest zakładane
LOG.info("Issue for extCompanyId={} not created due improper segment: companySegment={}, issueTypeSegment={}",
extCompanyId, customerSegment, issueTypeSegment);
return;
}
List<AidaInvoiceWithCorrectionsDto> startInvoices = aidaInvoiceService.getBalanceStartInvoicesByCompanyId(extCompanyId, dateProvider.getCurrentDateStartOfDay(), true);
Date dpdStartDate = dpdService.calculateDPDStartDateForNewIssue(startInvoices, extCompanyId, issueConfiguration.getMinBalanceStart());
if (dpdStartDate == null) {
LOG.info("dpdStartDate is null, aborting");
return;
}
Long dpd = DateUtils.daysBetween(dpdStartDate, dateProvider.getCurrentDate());
LOG.info("Current dpd: {}, max dpd: {}", dpd, issueConfiguration.getDuration() + issueConfiguration.getDpdStart());
if (dpd > issueConfiguration.getDuration() + issueConfiguration.getDpdStart()) {
LOG.info("Issue with type: {}, for company (AIDA id) {} not created because dpdStartDate: {} would make dpd too high",
issueConfiguration.getIssueType().getName(), extCompanyId, dpdStartDate);
return;
}
Date issueExpirationDate = DateUtils.datePlusDays(dpdStartDate, issueConfiguration.getDuration() + issueConfiguration.getDpdStart());
CompanyInvoices companyInvoices = findCompanyInvoices(extCompanyId, issueExpirationDate);
LOG.info("Ready to create issue, extCompanyId: {}, company: {}, issueType: {}, issueExpirationDate: {}, dpdStartDate: {}",
extCompanyId, customer.getCompany().getCompanyName(), issueConfiguration.getIssueType().getName(), issueExpirationDate, dpdStartDate);
Issue issue = automaticallyCreateIssueWithInvoicesAndActivities(
extCompanyId,
customer,
issueConfiguration.getIssueType().getId(),
issueExpirationDate,
companyInvoices,
dpdStartDate);
LOG.info("Issue id={} type={} for company (AIDA id) {} successfully created automatically.",
issue.getId(),
issue.getIssueType().getName(),
extCompanyId);
}
protected boolean isBalanceEnoughToCreateIssue(final AidaInvoiceWithCorrectionsDto invoice, final BigDecimal minBalanceStart) {
final BigDecimal balance = invoice.getBalanceOnDocument() == null ? ZERO : invoice.getBalanceOnDocument();
final Currency currency = forStringValue(invoice.getCurrency(), invoice.getNumber());
return customerVerifierService.isBalanceEnoughToCreateIssue(balance, currency, invoice.getExchangeRate(), minBalanceStart);
}
private Date calculateExpirationDate(final IssueTypeName issueTypeName, final Segment segment) {
final Integer duration = issueTypeConfigurationDao.findDurationByTypeAndSegment(issueTypeName, segment);
return dateProvider.getDateStartOfDayPlusDays(duration);
}
private Date getExpirationDate(final Date expirationDate, final IssueType issueType, final Segment segment) {
if (expirationDate != null) {
return expirationDate;
}
return calculateExpirationDate(issueType.getName(), segment);
}
private CompanyInvoices findCompanyInvoices(Long extCompanyId, Date issueExpirationDate) {
Date issueStartDate = dateProvider.getCurrentDateStartOfDay();
List<AidaInvoiceWithCorrectionsDto> startInvoices = aidaInvoiceService.getBalanceStartInvoicesByCompanyId(extCompanyId, issueStartDate, true);
List<AidaInvoiceWithCorrectionsDto> additionalInvoices = aidaInvoiceService.getBalanceAdditionalInvoicesWithActiveContractByCompanyId(extCompanyId, issueStartDate,
issueExpirationDate);
return new CompanyInvoices(extCompanyId, startInvoices, additionalInvoices);
}
private Issue manuallyCreateIssueWithInvoicesAndActivities(Long extCompanyId, Customer customer, Long issueTypeId,
Date issueExpirationDate, CompanyInvoices companyInvoices, Operator assignee) {
Date dpdStartDate = dpdService.calculateDPDStartDateForNewIssue(companyInvoices.getStartInvoices(), extCompanyId, BigDecimal.ZERO);
Issue issue = createIssue(companyInvoices, issueTypeId, issueExpirationDate, customer, true, assignee, dpdStartDate);
updateIssueWithInvoices(issue, companyInvoices.getAllInvoices(), extCompanyId);
saveIssueActivities(issue);
return issue;
}
private Issue automaticallyCreateIssueWithInvoicesAndActivities(Long extCompanyId, Customer customer, Long issueTypeId,
Date issueExpirationDate, CompanyInvoices companyInvoices, Date dpdStartDate) {
Issue issue = createIssue(companyInvoices, issueTypeId, issueExpirationDate, customer, false, null, dpdStartDate);
updateIssueWithInvoices(issue, companyInvoices.getAllInvoices(), extCompanyId);
saveIssueActivities(issue);
return issue;
}
private Issue createIssue(CompanyInvoices companyInvoices, Long issueTypeId, Date expirationDate, Customer customer,
boolean createdManually, Operator assignee, Date dpdStartDate) {
Issue issue = new Issue();
issue.setAssignee(assignee);
issue.setCustomer(customer);
issue = fillDates(issue, dateProvider.getCurrentDateStartOfDay(), expirationDate, dpdStartDate);
issue.setTerminationCause(null);
issue.setIssueType(prepareIssueType(issueTypeId));
issue.setIssueState(NEW);
issue = fillBalance(issue, companyInvoices);
issue.setExcludedFromStats(false);
issue.setPriority(ISSUE_DEFAULT_PRIORITY);
issue.setCreatedManually(createdManually);
issueDao.createIssue(issue);
return issue;
}
private IssueType prepareIssueType(final Long issueTypeId) {
final IssueType issueType = new IssueType();
issueType.setId(issueTypeId);
return issueType;
}
private Issue fillBalance(final Issue issue, final CompanyInvoices companyInvoices) {
final Map<Currency, Balance> balances = balanceCalculatorService.calculateBalancesFromIssueSubjectInvoices(null, companyInvoices.getExtCompanyId(),
companyInvoices.getStartInvoices(), dateProvider.getCurrentDateStartOfDay());
return BalancePreparator.fillBalance(issue, balances);
}
private void updateIssueWithInvoices(final Issue entity, final Collection<AidaInvoiceWithCorrectionsDto> customerInvoicesForIssuesCreation,
final Long extCompanyId) {
final Set<String> contractsOutOfService = customerService.findActiveContractOutOfServiceNumbers(extCompanyId);
final List<IssueInvoice> issueInvoices = localInvoiceService.prepareInvoices(customerInvoicesForIssuesCreation, entity, contractsOutOfService);
entity.setIssueInvoices(issueInvoices);
}
private void saveIssueActivities(final Issue issue) {
if (issue.getAssignee() != null) {
activityService.createAndAssignDefaultActivitiesForIssue(issue.getId(), issue.getIssueType().getId(), issue.getAssignee().getId());
} else {
activityService.createDefaultActivitiesForIssue(issue.getId(), issue.getIssueType().getId());
}
}
protected IssueType getIssueType(final Long issueTypeId) {
final Optional<IssueType> issueType = issueTypeDao.findIssueTypeById(issueTypeId);
return issueType.orElseThrow(() -> new IllegalArgumentException(format("Not existing issue type id [%s]", issueTypeId)));
}
private Operator getAssignee(final Long assigneeId) {
if (assigneeId != null) {
return operatorDao.get(assigneeId).orElse(null);
}
return null;
}
}
|
UTF-8
|
Java
| 14,856 |
java
|
IssueCreatorServiceImpl.java
|
Java
|
[] | null |
[] |
package com.codersteam.alwin.core.service.impl.issue;
import com.codersteam.aida.core.api.model.AidaInvoiceWithCorrectionsDto;
import com.codersteam.aida.core.api.service.InvoiceService;
import com.codersteam.alwin.common.issue.IssueTypeName;
import com.codersteam.alwin.common.issue.Segment;
import com.codersteam.alwin.core.api.model.currency.Currency;
import com.codersteam.alwin.core.api.model.issue.Balance;
import com.codersteam.alwin.core.api.model.issue.IssueTypeConfigurationDto;
import com.codersteam.alwin.core.api.model.issue.SegmentDto;
import com.codersteam.alwin.core.api.service.AidaService;
import com.codersteam.alwin.core.api.service.DateProvider;
import com.codersteam.alwin.core.api.service.activity.ActivityService;
import com.codersteam.alwin.core.api.service.customer.CustomerVerifierService;
import com.codersteam.alwin.core.api.service.debt.BalanceCalculatorService;
import com.codersteam.alwin.core.api.service.issue.IssueCreateResult;
import com.codersteam.alwin.core.api.service.issue.IssueCreatorService;
import com.codersteam.alwin.core.local.DPDService;
import com.codersteam.alwin.core.local.LocalInvoiceService;
import com.codersteam.alwin.core.service.impl.customer.CustomerServiceImpl;
import com.codersteam.alwin.core.service.impl.issue.preparator.BalancePreparator;
import com.codersteam.alwin.core.util.DateUtils;
import com.codersteam.alwin.db.dao.IssueDao;
import com.codersteam.alwin.db.dao.IssueTypeConfigurationDao;
import com.codersteam.alwin.db.dao.IssueTypeDao;
import com.codersteam.alwin.db.dao.OperatorDao;
import com.codersteam.alwin.jpa.customer.Customer;
import com.codersteam.alwin.jpa.issue.Issue;
import com.codersteam.alwin.jpa.issue.IssueInvoice;
import com.codersteam.alwin.jpa.issue.IssueType;
import com.codersteam.alwin.jpa.operator.Operator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.*;
import static com.codersteam.alwin.common.AlwinConstants.ZERO;
import static com.codersteam.alwin.core.api.model.currency.Currency.forStringValue;
import static com.codersteam.alwin.core.service.AlwinParameters.ISSUE_DEFAULT_PRIORITY;
import static com.codersteam.alwin.core.service.impl.issue.preparator.DatePreparator.fillDates;
import static com.codersteam.alwin.jpa.type.IssueState.NEW;
import static java.lang.String.format;
import static javax.transaction.Transactional.TxType.REQUIRES_NEW;
@Stateless
public class IssueCreatorServiceImpl implements IssueCreatorService {
private static final Logger LOG = LoggerFactory.getLogger(IssueCreatorServiceImpl.class.getName());
private IssueTypeDao issueTypeDao;
private OperatorDao operatorDao;
private InvoiceService aidaInvoiceService;
private DateProvider dateProvider;
private ActivityService activityService;
private BalanceCalculatorService balanceCalculatorService;
private LocalInvoiceService localInvoiceService;
private CustomerServiceImpl customerService;
private IssueTypeConfigurationDao issueTypeConfigurationDao;
private CustomerVerifierService customerVerifierService;
private DPDService dpdService;
private IssueDao issueDao;
private IssueServiceImpl issueService;
public IssueCreatorServiceImpl() {
}
@Inject
public IssueCreatorServiceImpl(IssueTypeDao issueTypeDao,
OperatorDao operatorDao,
DateProvider dateProvider,
ActivityService activityService,
BalanceCalculatorService balanceCalculatorService,
AidaService aidaService,
CustomerServiceImpl customerService,
LocalInvoiceService localInvoiceService,
IssueTypeConfigurationDao issueTypeConfigurationDao,
CustomerVerifierService customerVerifierService,
DPDService dpdService,
IssueDao issueDao,
IssueServiceImpl issueService) {
this.issueTypeDao = issueTypeDao;
this.operatorDao = operatorDao;
this.dateProvider = dateProvider;
this.activityService = activityService;
this.balanceCalculatorService = balanceCalculatorService;
this.aidaInvoiceService = aidaService.getInvoiceService();
this.localInvoiceService = localInvoiceService;
this.customerService = customerService;
this.issueTypeConfigurationDao = issueTypeConfigurationDao;
this.customerVerifierService = customerVerifierService;
this.dpdService = dpdService;
this.issueDao = issueDao;
this.issueService = issueService;
}
@Override
@Transactional
public IssueCreateResult createIssueManually(final Long extCompanyId, final Long issueTypeId, final Date expirationDate, final Long assigneeId) {
LOG.info("Creating issue for extCompanyId={}, issueTypeId={}, expirationDate={}, operatorId={}", extCompanyId, issueTypeId, expirationDate,
assigneeId);
final Customer customer = customerService.getCustomerWithAdditionalData(extCompanyId);
final IssueType issueType = getIssueType(issueTypeId);
final Date issueExpirationDate = getExpirationDate(expirationDate, issueType, customer.getCompany().getSegment());
final CompanyInvoices companyInvoices = findCompanyInvoices(extCompanyId, issueExpirationDate);
final Operator assignee = getAssignee(assigneeId);
final Issue issue = manuallyCreateIssueWithInvoicesAndActivities(extCompanyId, customer, issueTypeId, issueExpirationDate, companyInvoices, assignee);
issueService.assignOperatorByPostalCodeForDirectDebtCollection(issue);
LOG.info("Issue {} for company (AIDA id) {} successfully created.", issue.getId(), extCompanyId);
return new IssueCreateResult(issue.getId());
}
@Override
@Transactional(REQUIRES_NEW)
public void createIssue(Long extCompanyId, IssueTypeConfigurationDto issueConfiguration) {
LOG.info("Creating issue for extCompanyId={}, issueTypeName={}, issueTypeSegment={}", extCompanyId,
issueConfiguration.getIssueType().getName(), issueConfiguration.getSegment().getKey());
Customer customer = customerService.getCustomerWithAdditionalData(extCompanyId);
Segment customerSegment = customer.getCompany().getSegment();
Segment issueTypeSegment = SegmentDto.segmentByKey(issueConfiguration.getSegment().getKey());
if (customerSegment != issueTypeSegment) {
// w przypadku niewłaściwego segmentu zlecenie nie jest zakładane
LOG.info("Issue for extCompanyId={} not created due improper segment: companySegment={}, issueTypeSegment={}",
extCompanyId, customerSegment, issueTypeSegment);
return;
}
List<AidaInvoiceWithCorrectionsDto> startInvoices = aidaInvoiceService.getBalanceStartInvoicesByCompanyId(extCompanyId, dateProvider.getCurrentDateStartOfDay(), true);
Date dpdStartDate = dpdService.calculateDPDStartDateForNewIssue(startInvoices, extCompanyId, issueConfiguration.getMinBalanceStart());
if (dpdStartDate == null) {
LOG.info("dpdStartDate is null, aborting");
return;
}
Long dpd = DateUtils.daysBetween(dpdStartDate, dateProvider.getCurrentDate());
LOG.info("Current dpd: {}, max dpd: {}", dpd, issueConfiguration.getDuration() + issueConfiguration.getDpdStart());
if (dpd > issueConfiguration.getDuration() + issueConfiguration.getDpdStart()) {
LOG.info("Issue with type: {}, for company (AIDA id) {} not created because dpdStartDate: {} would make dpd too high",
issueConfiguration.getIssueType().getName(), extCompanyId, dpdStartDate);
return;
}
Date issueExpirationDate = DateUtils.datePlusDays(dpdStartDate, issueConfiguration.getDuration() + issueConfiguration.getDpdStart());
CompanyInvoices companyInvoices = findCompanyInvoices(extCompanyId, issueExpirationDate);
LOG.info("Ready to create issue, extCompanyId: {}, company: {}, issueType: {}, issueExpirationDate: {}, dpdStartDate: {}",
extCompanyId, customer.getCompany().getCompanyName(), issueConfiguration.getIssueType().getName(), issueExpirationDate, dpdStartDate);
Issue issue = automaticallyCreateIssueWithInvoicesAndActivities(
extCompanyId,
customer,
issueConfiguration.getIssueType().getId(),
issueExpirationDate,
companyInvoices,
dpdStartDate);
LOG.info("Issue id={} type={} for company (AIDA id) {} successfully created automatically.",
issue.getId(),
issue.getIssueType().getName(),
extCompanyId);
}
protected boolean isBalanceEnoughToCreateIssue(final AidaInvoiceWithCorrectionsDto invoice, final BigDecimal minBalanceStart) {
final BigDecimal balance = invoice.getBalanceOnDocument() == null ? ZERO : invoice.getBalanceOnDocument();
final Currency currency = forStringValue(invoice.getCurrency(), invoice.getNumber());
return customerVerifierService.isBalanceEnoughToCreateIssue(balance, currency, invoice.getExchangeRate(), minBalanceStart);
}
private Date calculateExpirationDate(final IssueTypeName issueTypeName, final Segment segment) {
final Integer duration = issueTypeConfigurationDao.findDurationByTypeAndSegment(issueTypeName, segment);
return dateProvider.getDateStartOfDayPlusDays(duration);
}
private Date getExpirationDate(final Date expirationDate, final IssueType issueType, final Segment segment) {
if (expirationDate != null) {
return expirationDate;
}
return calculateExpirationDate(issueType.getName(), segment);
}
private CompanyInvoices findCompanyInvoices(Long extCompanyId, Date issueExpirationDate) {
Date issueStartDate = dateProvider.getCurrentDateStartOfDay();
List<AidaInvoiceWithCorrectionsDto> startInvoices = aidaInvoiceService.getBalanceStartInvoicesByCompanyId(extCompanyId, issueStartDate, true);
List<AidaInvoiceWithCorrectionsDto> additionalInvoices = aidaInvoiceService.getBalanceAdditionalInvoicesWithActiveContractByCompanyId(extCompanyId, issueStartDate,
issueExpirationDate);
return new CompanyInvoices(extCompanyId, startInvoices, additionalInvoices);
}
private Issue manuallyCreateIssueWithInvoicesAndActivities(Long extCompanyId, Customer customer, Long issueTypeId,
Date issueExpirationDate, CompanyInvoices companyInvoices, Operator assignee) {
Date dpdStartDate = dpdService.calculateDPDStartDateForNewIssue(companyInvoices.getStartInvoices(), extCompanyId, BigDecimal.ZERO);
Issue issue = createIssue(companyInvoices, issueTypeId, issueExpirationDate, customer, true, assignee, dpdStartDate);
updateIssueWithInvoices(issue, companyInvoices.getAllInvoices(), extCompanyId);
saveIssueActivities(issue);
return issue;
}
private Issue automaticallyCreateIssueWithInvoicesAndActivities(Long extCompanyId, Customer customer, Long issueTypeId,
Date issueExpirationDate, CompanyInvoices companyInvoices, Date dpdStartDate) {
Issue issue = createIssue(companyInvoices, issueTypeId, issueExpirationDate, customer, false, null, dpdStartDate);
updateIssueWithInvoices(issue, companyInvoices.getAllInvoices(), extCompanyId);
saveIssueActivities(issue);
return issue;
}
private Issue createIssue(CompanyInvoices companyInvoices, Long issueTypeId, Date expirationDate, Customer customer,
boolean createdManually, Operator assignee, Date dpdStartDate) {
Issue issue = new Issue();
issue.setAssignee(assignee);
issue.setCustomer(customer);
issue = fillDates(issue, dateProvider.getCurrentDateStartOfDay(), expirationDate, dpdStartDate);
issue.setTerminationCause(null);
issue.setIssueType(prepareIssueType(issueTypeId));
issue.setIssueState(NEW);
issue = fillBalance(issue, companyInvoices);
issue.setExcludedFromStats(false);
issue.setPriority(ISSUE_DEFAULT_PRIORITY);
issue.setCreatedManually(createdManually);
issueDao.createIssue(issue);
return issue;
}
private IssueType prepareIssueType(final Long issueTypeId) {
final IssueType issueType = new IssueType();
issueType.setId(issueTypeId);
return issueType;
}
private Issue fillBalance(final Issue issue, final CompanyInvoices companyInvoices) {
final Map<Currency, Balance> balances = balanceCalculatorService.calculateBalancesFromIssueSubjectInvoices(null, companyInvoices.getExtCompanyId(),
companyInvoices.getStartInvoices(), dateProvider.getCurrentDateStartOfDay());
return BalancePreparator.fillBalance(issue, balances);
}
private void updateIssueWithInvoices(final Issue entity, final Collection<AidaInvoiceWithCorrectionsDto> customerInvoicesForIssuesCreation,
final Long extCompanyId) {
final Set<String> contractsOutOfService = customerService.findActiveContractOutOfServiceNumbers(extCompanyId);
final List<IssueInvoice> issueInvoices = localInvoiceService.prepareInvoices(customerInvoicesForIssuesCreation, entity, contractsOutOfService);
entity.setIssueInvoices(issueInvoices);
}
private void saveIssueActivities(final Issue issue) {
if (issue.getAssignee() != null) {
activityService.createAndAssignDefaultActivitiesForIssue(issue.getId(), issue.getIssueType().getId(), issue.getAssignee().getId());
} else {
activityService.createDefaultActivitiesForIssue(issue.getId(), issue.getIssueType().getId());
}
}
protected IssueType getIssueType(final Long issueTypeId) {
final Optional<IssueType> issueType = issueTypeDao.findIssueTypeById(issueTypeId);
return issueType.orElseThrow(() -> new IllegalArgumentException(format("Not existing issue type id [%s]", issueTypeId)));
}
private Operator getAssignee(final Long assigneeId) {
if (assigneeId != null) {
return operatorDao.get(assigneeId).orElse(null);
}
return null;
}
}
| 14,856 | 0.729146 | 0.729011 | 269 | 54.215614 | 42.491787 | 175 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.081784 | false | false |
5
|
1390c94a4ef72c85155dda76a1307786bac36bb4
| 37,134,287,252,757 |
10749b2a004bda9c1961c3ab55a3cdea8112d86d
|
/agendaweb/src/main/java/br/senac/tads/pi3b/agendaweb/ExemploServlet.java
|
4e9cb7db70d83b5530d935c8446d0c960b8955bc
|
[
"MIT"
] |
permissive
|
ftsuda-senac/tads3-pi3b-2018-1
|
https://github.com/ftsuda-senac/tads3-pi3b-2018-1
|
43a9e219d0b27aafc286dcb106302d995ea90221
|
8cba8b3c2bc0a087e7a3a770d6dc2cd04e854579
|
refs/heads/master
| 2021-01-24T16:39:58.751000 | 2018-05-09T01:26:43 | 2018-05-09T01:26:43 | 123,206,560 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.senac.tads.pi3b.agendaweb;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author fernando.tsuda
*/
@WebServlet(name = "ExemploServlet", urlPatterns = {"/exemplo1"})
public class ExemploServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String mensagem = "Primeiro exemplo Servlet";
// Configuração da resposta a ser retornada
response.setContentType("text/html"); // Tipo de conteúdo
response.setCharacterEncoding("UTF-8"); // Codificação do conteúdo
// Abre o objeto de saída para enviar a mensagem ao cliente
try (PrintWriter out = response.getWriter()) {
out.println("<html>");
out.println("<head>");
out.println("<meta charset=\"utf-8\">");
out.println("<title>Exemplo Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>" + mensagem + "</h1>");
out.println("</body>");
out.println("</html>");
out.flush();
}
}
}
|
UTF-8
|
Java
| 1,649 |
java
|
ExemploServlet.java
|
Java
|
[
{
"context": "t.http.HttpServletResponse;\r\n\r\n/**\r\n *\r\n * @author fernando.tsuda\r\n */\r\n@WebServlet(name = \"ExemploServle",
"end": 535,
"score": 0.7576131820678711,
"start": 531,
"tag": "NAME",
"value": "fern"
},
{
"context": "p.HttpServletResponse;\r\n\r\n/**\r\n *\r\n * @author fernando.tsuda\r\n */\r\n@WebServlet(name = \"ExemploServlet\", url",
"end": 542,
"score": 0.7399037480354309,
"start": 535,
"tag": "USERNAME",
"value": "ando.ts"
},
{
"context": "ervletResponse;\r\n\r\n/**\r\n *\r\n * @author fernando.tsuda\r\n */\r\n@WebServlet(name = \"ExemploServlet\", urlPat",
"end": 545,
"score": 0.8115628957748413,
"start": 542,
"tag": "NAME",
"value": "uda"
}
] | null |
[] |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.senac.tads.pi3b.agendaweb;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author fernando.tsuda
*/
@WebServlet(name = "ExemploServlet", urlPatterns = {"/exemplo1"})
public class ExemploServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String mensagem = "Primeiro exemplo Servlet";
// Configuração da resposta a ser retornada
response.setContentType("text/html"); // Tipo de conteúdo
response.setCharacterEncoding("UTF-8"); // Codificação do conteúdo
// Abre o objeto de saída para enviar a mensagem ao cliente
try (PrintWriter out = response.getWriter()) {
out.println("<html>");
out.println("<head>");
out.println("<meta charset=\"utf-8\">");
out.println("<title>Exemplo Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>" + mensagem + "</h1>");
out.println("</body>");
out.println("</html>");
out.flush();
}
}
}
| 1,649 | 0.633983 | 0.630329 | 48 | 32.208332 | 24.503366 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5625 | false | false |
5
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.