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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8471b91b280470391eba2b65331c4dfb04af1d1c | 22,909,355,571,441 | c87ccd328b057e618fc4f643dfa9f50f4744f215 | /priceisright/Layer.java | 8fd5e33cb51c321a747abc5e6fb57bc488d3b9af | [] | no_license | Suzzzz/Price-Is-Right-Neural-network | https://github.com/Suzzzz/Price-Is-Right-Neural-network | 300455da79f80d671ee906ec438b605257da1b26 | fdc2adcc82e3ebf422036db7f338a934f91c4b49 | refs/heads/master | 2020-04-10T15:47:22.666000 | 2018-12-10T05:41:30 | 2018-12-10T05:41:30 | 161,122,902 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package priceisright;
import java.util.ArrayList;
/*
* This class is basically a wrapper of ArrayList.
*/
public class Layer
{
ArrayList<Neuron> contents=new ArrayList<Neuron>();
public Layer(Neuron n)
{
contents=new ArrayList<Neuron>();
contents.add(n);
}
public Layer(ArrayList<Neuron> data)
{contents=data;}
public Neuron get(int i)
{return contents.get(i);}
public int size()
{return contents.size();}
}
| UTF-8 | Java | 424 | java | Layer.java | Java | [] | null | [] | package priceisright;
import java.util.ArrayList;
/*
* This class is basically a wrapper of ArrayList.
*/
public class Layer
{
ArrayList<Neuron> contents=new ArrayList<Neuron>();
public Layer(Neuron n)
{
contents=new ArrayList<Neuron>();
contents.add(n);
}
public Layer(ArrayList<Neuron> data)
{contents=data;}
public Neuron get(int i)
{return contents.get(i);}
public int size()
{return contents.size();}
}
| 424 | 0.716981 | 0.716981 | 27 | 14.703704 | 15.529696 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 12 |
2a5e752f241aa7a2519a9b9478e223129ebc7af8 | 22,402,549,417,132 | c413ee40612dd0e02b8b667f245ab7bbbfa10cf7 | /Then New Boston/src/simon/programming/private1.java | 4dc2208da70b2e4f8ff5921a32d2d1b1ac314f12 | [] | no_license | ghazi20734/simondid-programming-projects | https://github.com/ghazi20734/simondid-programming-projects | 30362bc8dfe158486390a90ba2c6550ddcf75496 | 4d254d980f2a211480451940b523642cb411806e | refs/heads/master | 2021-01-10T22:10:58.036000 | 2012-01-22T21:00:26 | 2012-01-22T21:00:26 | 37,366,096 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package simon.programming;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class private1 extends Activity implements OnClickListener {
Button bsave1,bsave2,bsave3,bDon;
EditText input;
String inputData1,inputData2,inputData3;
Intent a;
Bundle basket1,basket2,basket3;
String bread;
Bundle basket;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.private1);
initialize();
}
private void initialize() {
// TODO Auto-generated method stub
input = (EditText)findViewById(R.id.edInput);
bsave1 = (Button) findViewById(R.id.bSave1);
bsave2 = (Button)findViewById(R.id.bSave2);
bsave3 = (Button)findViewById(R.id.bSave3);
bDon = (Button) findViewById(R.id.bDon);
bDon.setOnClickListener(this);
bsave1.setOnClickListener(this);
bsave2.setOnClickListener(this);
bsave3.setOnClickListener(this);
basket = new Bundle();
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.bSave1:
bread = input.getText().toString();
basket.putString("key1", bread);
a = new Intent(private1.this,private2.class);
a.putExtras(basket);
input.setText("");
break;
case R.id.bSave2:
bread = input.getText().toString();
basket.putString("key2", bread);
a = new Intent(private1.this,private2.class);
a.putExtras(basket);
input.setText("");
break;
case R.id.bSave3:
bread = input.getText().toString();
basket.putString("key3", bread);
a = new Intent(private1.this,private2.class);
a.putExtras(basket);
input.setText("");
break;
case R.id.bDon:
startActivity(a);
break;
}
}
}
| UTF-8 | Java | 2,062 | java | private1.java | Java | [] | null | [] | package simon.programming;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class private1 extends Activity implements OnClickListener {
Button bsave1,bsave2,bsave3,bDon;
EditText input;
String inputData1,inputData2,inputData3;
Intent a;
Bundle basket1,basket2,basket3;
String bread;
Bundle basket;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.private1);
initialize();
}
private void initialize() {
// TODO Auto-generated method stub
input = (EditText)findViewById(R.id.edInput);
bsave1 = (Button) findViewById(R.id.bSave1);
bsave2 = (Button)findViewById(R.id.bSave2);
bsave3 = (Button)findViewById(R.id.bSave3);
bDon = (Button) findViewById(R.id.bDon);
bDon.setOnClickListener(this);
bsave1.setOnClickListener(this);
bsave2.setOnClickListener(this);
bsave3.setOnClickListener(this);
basket = new Bundle();
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.bSave1:
bread = input.getText().toString();
basket.putString("key1", bread);
a = new Intent(private1.this,private2.class);
a.putExtras(basket);
input.setText("");
break;
case R.id.bSave2:
bread = input.getText().toString();
basket.putString("key2", bread);
a = new Intent(private1.this,private2.class);
a.putExtras(basket);
input.setText("");
break;
case R.id.bSave3:
bread = input.getText().toString();
basket.putString("key3", bread);
a = new Intent(private1.this,private2.class);
a.putExtras(basket);
input.setText("");
break;
case R.id.bDon:
startActivity(a);
break;
}
}
}
| 2,062 | 0.674103 | 0.658584 | 89 | 21.168539 | 16.572779 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.370786 | false | false | 12 |
03ba21daf56888a8365542d1f1eef76a16ed23e3 | 15,255,723,861,448 | e288102135deedf71d2624f33bb0d112f8573bf7 | /src/com/saber/pojo/Course.java | 6f2a3fe7f6903b734cefbcf18e9588c79484581b | [] | no_license | BonjourMondo/Cg3L | https://github.com/BonjourMondo/Cg3L | 9c0c89ebf879c444a7ac4a1041e4ff95a2c39a94 | 0eda02ccfa2880a7cbcc22298fdb3418ca05e340 | refs/heads/master | 2021-01-22T13:53:09.683000 | 2017-08-19T08:35:57 | 2017-08-19T08:35:57 | 100,694,152 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.saber.pojo;
/**
* Created by Saber on 2017/7/3.
*/
public class Course {//课程
private String source;
private String describe;
private String key;
private String course_source;//课程的source
public String getCourse_source() {
return course_source;
}
public void setCourse_source(String course_source) {
this.course_source = course_source;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDescribe() {
return describe;
}
public void setDescribe(String describe) {
this.describe = describe;
}
}
| UTF-8 | Java | 884 | java | Course.java | Java | [
{
"context": "package com.saber.pojo;\r\n\r\n/**\r\n * Created by Saber on 2017/7/3.\r\n */\r\npublic class Course {//课程\r\n ",
"end": 51,
"score": 0.979094386100769,
"start": 46,
"tag": "USERNAME",
"value": "Saber"
}
] | null | [] | package com.saber.pojo;
/**
* Created by Saber on 2017/7/3.
*/
public class Course {//课程
private String source;
private String describe;
private String key;
private String course_source;//课程的source
public String getCourse_source() {
return course_source;
}
public void setCourse_source(String course_source) {
this.course_source = course_source;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDescribe() {
return describe;
}
public void setDescribe(String describe) {
this.describe = describe;
}
}
| 884 | 0.572082 | 0.565217 | 47 | 16.595745 | 16.332527 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.276596 | false | false | 12 |
293bce72e7d55874c82369ffc6f2fce953cf9089 | 4,784,593,573,518 | 79c419d2c1133c3552492dabacc04cdeed4f7ea9 | /common-util/src/main/java/com/blog/bean/JWTProperties.java | 0c0a96fcb27d356d2a980e58b8cb19d36a2691fb | [] | no_license | 13827475135/blog | https://github.com/13827475135/blog | 21c3d2b1d0c5ceb62e709763e26f2bdf325ab823 | 77e3933242f1db61cb58b9c5ae99d1ea75e702d7 | refs/heads/master | 2022-12-03T14:55:11.552000 | 2020-12-10T05:49:51 | 2020-12-10T05:49:51 | 192,933,639 | 0 | 0 | null | false | 2022-11-21T22:37:34 | 2019-06-20T14:21:26 | 2020-12-10T05:49:54 | 2022-11-21T22:37:31 | 74 | 0 | 0 | 10 | Java | false | false | package com.blog.bean;
/**
* JWT 配置文件
*
* @author Nicholas
* @since 2019-06-27
*/
public class JWTProperties {
//token的过期时间
private long tokenExpireTime;
//临时token的过期时间
private long tempTokenExpireTime;
//token的公共加密盐
private String secret;
public long getTokenExpireTime() {
return tokenExpireTime;
}
public void setTokenExpireTime(long tokenExpireTime) {
this.tokenExpireTime = tokenExpireTime;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public long getTempTokenExpireTime() {
return tempTokenExpireTime;
}
public JWTProperties setTempTokenExpireTime(long tempTokenExpireTime) {
this.tempTokenExpireTime = tempTokenExpireTime;
return this;
}
}
| UTF-8 | Java | 943 | java | JWTProperties.java | Java | [
{
"context": "com.blog.bean;\r\n\r\n/**\r\n * JWT 配置文件\r\n *\r\n * @author Nicholas\r\n * @since 2019-06-27\r\n */\r\npublic class JWTPrope",
"end": 67,
"score": 0.999777615070343,
"start": 59,
"tag": "NAME",
"value": "Nicholas"
}
] | null | [] | package com.blog.bean;
/**
* JWT 配置文件
*
* @author Nicholas
* @since 2019-06-27
*/
public class JWTProperties {
//token的过期时间
private long tokenExpireTime;
//临时token的过期时间
private long tempTokenExpireTime;
//token的公共加密盐
private String secret;
public long getTokenExpireTime() {
return tokenExpireTime;
}
public void setTokenExpireTime(long tokenExpireTime) {
this.tokenExpireTime = tokenExpireTime;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public long getTempTokenExpireTime() {
return tempTokenExpireTime;
}
public JWTProperties setTempTokenExpireTime(long tempTokenExpireTime) {
this.tempTokenExpireTime = tempTokenExpireTime;
return this;
}
}
| 943 | 0.630701 | 0.621802 | 44 | 18.431818 | 18.735476 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 12 |
14d2c8da2724943cac9cf8b704b63b2459fee946 | 20,633,022,933,073 | dc9bb5b33b4d3331bbf885f18dc3b1bb5d7f1753 | /Ecommerce_Sakkaravarthi/app/src/main/java/com/example/ecommerce_sakkaravarthi/CitySelectActivity.java | 271dba81e0ac5c7f17cf14ac9f2b4b6f7dae836f | [] | no_license | kanulp/Assignment_work | https://github.com/kanulp/Assignment_work | ccef186f40a79055564b6275a580f487a3849595 | 3a35afb276157774fcfa994a7d9c58f9379db7c6 | refs/heads/master | 2022-07-16T15:24:17.084000 | 2020-11-13T05:58:01 | 2020-11-13T05:58:01 | 229,602,404 | 0 | 0 | null | false | 2022-06-22T23:11:12 | 2019-12-22T17:09:48 | 2020-11-13T05:58:17 | 2022-06-22T23:11:11 | 85,268 | 0 | 0 | 2 | Python | false | false | package com.example.ecommerce_sakkaravarthi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class CitySelectActivity extends AppCompatActivity {
ArrayList<String> cityList = new ArrayList<String>();
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_select);
loadCategories();
getSupportActionBar().setTitle("Select City");
listView = findViewById(R.id.listview);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>
(CitySelectActivity.this, android.R.layout.simple_list_item_1, cityList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// TODO Auto-generated method stub
String value=adapter.getItem(position);
Intent intent = new Intent(CitySelectActivity.this,RestaurantListActivity.class);
startActivity(intent);
}
});
}
public void loadCategories(){
cityList.add("Toronto");
cityList.add("Calgary");
cityList.add("Hamilton");
cityList.add("London");
cityList.add("Peterborough");
cityList.add("Windsor");
cityList.add("Winnipeg");
cityList.add("Ottawa");
cityList.add("Halifax");
}
}
| UTF-8 | Java | 1,777 | java | CitySelectActivity.java | Java | [] | null | [] | package com.example.ecommerce_sakkaravarthi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class CitySelectActivity extends AppCompatActivity {
ArrayList<String> cityList = new ArrayList<String>();
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_select);
loadCategories();
getSupportActionBar().setTitle("Select City");
listView = findViewById(R.id.listview);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>
(CitySelectActivity.this, android.R.layout.simple_list_item_1, cityList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// TODO Auto-generated method stub
String value=adapter.getItem(position);
Intent intent = new Intent(CitySelectActivity.this,RestaurantListActivity.class);
startActivity(intent);
}
});
}
public void loadCategories(){
cityList.add("Toronto");
cityList.add("Calgary");
cityList.add("Hamilton");
cityList.add("London");
cityList.add("Peterborough");
cityList.add("Windsor");
cityList.add("Winnipeg");
cityList.add("Ottawa");
cityList.add("Halifax");
}
}
| 1,777 | 0.669105 | 0.668543 | 54 | 31.907408 | 25.176613 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.685185 | false | false | 12 |
c5cd2a53095cdb0c473d42f3e1528c5ca0fed845 | 8,778,913,186,799 | 6c0a49f0c2a302336708d8d45a8bd42ef5aa0bd7 | /app/src/main/java/dk/kultur/historiejagtenfyn/data/models/InfoDetailsDataModel.java | 727c641377e8bf5c5cd3e15744ac68b39a871ed0 | [] | no_license | mskyblue/Android-app_StoryHuntFyn | https://github.com/mskyblue/Android-app_StoryHuntFyn | 276bb99b274f8923ffd02b14607c04d675e732af | a4d0d220e2d54a9b5a9b3f1e58bf02273b9b5cb1 | refs/heads/master | 2021-01-01T17:03:10.060000 | 2017-07-10T12:40:58 | 2017-07-10T12:40:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dk.kultur.historiejagtenfyn.data.models;
import android.content.Context;
import dk.kultur.historiejagtenfyn.data.operations.AbsAsyncOperation;
import dk.kultur.historiejagtenfyn.data.operations.GetInfoDetailsOperation;
import dk.kultur.historiejagtenfyn.data.parse.models.InfoModelHis;
/**
* Created by Lina on 2014.07.02.
*/
public class InfoDetailsDataModel extends AbsSingleOperationDataModel {
private final Context context;
private InfoModelHis languageInfo;
/**
*
* @param context
*/
public InfoDetailsDataModel(Context context) {
this.context = context;
}
/**
* Returns languageInfo object with info in it
* Use fields infoTitle and infoText for displaying
* @return info text object
*/
public InfoModelHis getLanguageInfo() {
return languageInfo;
}
@Override
protected AbsAsyncOperation<?> createAsyncOperation() {
return new GetInfoDetailsOperation(context);
}
@Override
protected void handleLoadedData(AbsAsyncOperation<?> operation) {
languageInfo = (InfoModelHis) operation.getResult();
}
}
| UTF-8 | Java | 1,145 | java | InfoDetailsDataModel.java | Java | [
{
"context": "data.parse.models.InfoModelHis;\n\n/**\n * Created by Lina on 2014.07.02.\n */\npublic class InfoDetailsDataMo",
"end": 319,
"score": 0.902912437915802,
"start": 315,
"tag": "NAME",
"value": "Lina"
}
] | null | [] | package dk.kultur.historiejagtenfyn.data.models;
import android.content.Context;
import dk.kultur.historiejagtenfyn.data.operations.AbsAsyncOperation;
import dk.kultur.historiejagtenfyn.data.operations.GetInfoDetailsOperation;
import dk.kultur.historiejagtenfyn.data.parse.models.InfoModelHis;
/**
* Created by Lina on 2014.07.02.
*/
public class InfoDetailsDataModel extends AbsSingleOperationDataModel {
private final Context context;
private InfoModelHis languageInfo;
/**
*
* @param context
*/
public InfoDetailsDataModel(Context context) {
this.context = context;
}
/**
* Returns languageInfo object with info in it
* Use fields infoTitle and infoText for displaying
* @return info text object
*/
public InfoModelHis getLanguageInfo() {
return languageInfo;
}
@Override
protected AbsAsyncOperation<?> createAsyncOperation() {
return new GetInfoDetailsOperation(context);
}
@Override
protected void handleLoadedData(AbsAsyncOperation<?> operation) {
languageInfo = (InfoModelHis) operation.getResult();
}
}
| 1,145 | 0.716157 | 0.70917 | 44 | 25.022728 | 24.974068 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 12 |
71e34555d8a8ed8afa3d878762582b55a1130ce4 | 33,432,025,452,927 | 82d40c20aa5d0db0c9080035848c806ecd4401e0 | /app/src/main/java/com/example/app_anima/RecyTrainAdapter.java | eace610a57a187c08e49f338b330b8cf2825adb8 | [] | no_license | Yg323/app_anima | https://github.com/Yg323/app_anima | 7d87185eb113f4362479377c9edcfe67387e11b0 | f0880b7fff70aba09b47bb97a66213fc31946fe9 | refs/heads/master | 2023-03-12T17:05:09.138000 | 2021-03-05T02:52:26 | 2021-03-05T02:52:26 | 299,396,984 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.app_anima;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyTrainAdapter extends RecyclerView.Adapter<RecyTrainAdapter.ViewHolder>{
private ArrayList<RecyTrainItem> mData=null;
RecyTrainAdapter(ArrayList<RecyTrainItem>list){
mData = list;
}
public interface OnItemClickListener {
void onItemClick(View v, int pos);
}
private OnItemClickListener onItemClickListener = null;
public void setOnItemClickListener (OnItemClickListener listener) {
this.onItemClickListener = listener;
}
@Override
public RecyTrainAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
Context context = parent.getContext() ;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ;
View view = inflater.inflate(R.layout.item_train, parent, false) ;
RecyTrainAdapter.ViewHolder vh = new RecyTrainAdapter.ViewHolder(view) ;
return vh ;
}
// onBindViewHolder() - position에 해당하는 데이터를 뷰홀더의 아이템뷰에 표시.
@Override
public void onBindViewHolder(RecyTrainAdapter.ViewHolder holder, int position) {
RecyTrainItem item = mData.get(position) ;
holder.iv_trainIcon.setImageDrawable(item.getDrawable()) ;
holder.tv_trainTitle.setText(item.getTitle()) ;
}
// getItemCount() - 전체 데이터 갯수 리턴.
@Override
public int getItemCount() {
return mData.size() ;
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView iv_trainIcon ;
TextView tv_trainTitle ;
ViewHolder(View itemView) {
super(itemView) ;
// 뷰 객체에 대한 참조. (hold strong reference)
iv_trainIcon = itemView.findViewById(R.id.iv_trainIcon) ;
tv_trainTitle = itemView.findViewById(R.id.tv_trainTitle) ;
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
if (onItemClickListener != null) onItemClickListener.onItemClick(v, pos);
}
}
});
}
}
}
| UTF-8 | Java | 2,599 | java | RecyTrainAdapter.java | Java | [] | null | [] | package com.example.app_anima;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyTrainAdapter extends RecyclerView.Adapter<RecyTrainAdapter.ViewHolder>{
private ArrayList<RecyTrainItem> mData=null;
RecyTrainAdapter(ArrayList<RecyTrainItem>list){
mData = list;
}
public interface OnItemClickListener {
void onItemClick(View v, int pos);
}
private OnItemClickListener onItemClickListener = null;
public void setOnItemClickListener (OnItemClickListener listener) {
this.onItemClickListener = listener;
}
@Override
public RecyTrainAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
Context context = parent.getContext() ;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ;
View view = inflater.inflate(R.layout.item_train, parent, false) ;
RecyTrainAdapter.ViewHolder vh = new RecyTrainAdapter.ViewHolder(view) ;
return vh ;
}
// onBindViewHolder() - position에 해당하는 데이터를 뷰홀더의 아이템뷰에 표시.
@Override
public void onBindViewHolder(RecyTrainAdapter.ViewHolder holder, int position) {
RecyTrainItem item = mData.get(position) ;
holder.iv_trainIcon.setImageDrawable(item.getDrawable()) ;
holder.tv_trainTitle.setText(item.getTitle()) ;
}
// getItemCount() - 전체 데이터 갯수 리턴.
@Override
public int getItemCount() {
return mData.size() ;
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView iv_trainIcon ;
TextView tv_trainTitle ;
ViewHolder(View itemView) {
super(itemView) ;
// 뷰 객체에 대한 참조. (hold strong reference)
iv_trainIcon = itemView.findViewById(R.id.iv_trainIcon) ;
tv_trainTitle = itemView.findViewById(R.id.tv_trainTitle) ;
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
if (onItemClickListener != null) onItemClickListener.onItemClick(v, pos);
}
}
});
}
}
}
| 2,599 | 0.663366 | 0.663366 | 74 | 33.12162 | 28.194284 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 12 |
46c25364813fa70d45aa0d0e5e3d15c876020026 | 11,398,843,238,014 | 774dccc811091c814a84f245158d8116272aaa3f | /src/main/java/cn/icyzx/util/GetServerUtil.java | 1f8c137a120fe00650e6e619a2056a6ebf6adb58 | [] | no_license | zk-123/cyzx | https://github.com/zk-123/cyzx | 44f28f64173b41b30833b6c3f17277bf66a22012 | 0aa170854c1bdb541a4b208b6ce09e8328cf6a8d | refs/heads/master | 2017-11-24T20:10:49.063000 | 2017-09-06T12:15:50 | 2017-09-06T12:15:53 | 64,903,655 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.icyzx.util;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.util.Properties;
/**
* Created by zk on 2016/9/28.
*/
public class GetServerUtil {
private static Properties properties = new Properties();
private static Logger logger = Logger.getLogger(GetServerUtil.class);
static {
try {
properties.load(GetServerUtil.class.getClassLoader().getResourceAsStream("server.properties"));
} catch (IOException e) {
logger.error("读取不到server.properties");
e.printStackTrace();
}
}
public static String getServerName() {
return properties.getProperty("server");
}
public static String getJdbcUrl() {
return properties.getProperty("jdbc.url");
}
public static String getJdbcUsername() {
return properties.getProperty("jdbc.username");
}
public static String getJdbcPassword() {
return properties.getProperty("jdbc.password");
}
public static String getJdbcDriver() {
return properties.getProperty("jdbc.driver");
}
}
| UTF-8 | Java | 1,119 | java | GetServerUtil.java | Java | [
{
"context": "n;\nimport java.util.Properties;\n\n/**\n * Created by zk on 2016/9/28.\n */\npublic class GetServerUtil {\n\n ",
"end": 136,
"score": 0.9973728656768799,
"start": 134,
"tag": "USERNAME",
"value": "zk"
}
] | null | [] | package cn.icyzx.util;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.util.Properties;
/**
* Created by zk on 2016/9/28.
*/
public class GetServerUtil {
private static Properties properties = new Properties();
private static Logger logger = Logger.getLogger(GetServerUtil.class);
static {
try {
properties.load(GetServerUtil.class.getClassLoader().getResourceAsStream("server.properties"));
} catch (IOException e) {
logger.error("读取不到server.properties");
e.printStackTrace();
}
}
public static String getServerName() {
return properties.getProperty("server");
}
public static String getJdbcUrl() {
return properties.getProperty("jdbc.url");
}
public static String getJdbcUsername() {
return properties.getProperty("jdbc.username");
}
public static String getJdbcPassword() {
return properties.getProperty("jdbc.password");
}
public static String getJdbcDriver() {
return properties.getProperty("jdbc.driver");
}
}
| 1,119 | 0.658866 | 0.652565 | 46 | 23.152174 | 24.75354 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.304348 | false | false | 12 |
995f117ba2e07b798d58d0b6d75c06347d730822 | 8,486,855,416,974 | a6a1f5447310b338f9107104611f68c272ca6d4a | /plugins/griffon-swing/trunk/src/templates/artifacts/Controller.java | 3790485b1b11a0d2d1b1a6230b215e192095a2ca | [
"Apache-2.0"
] | permissive | codehaus/griffon | https://github.com/codehaus/griffon | 0561d286a6b80245b32879d925a5d53f017e17d5 | 7c3bfbad8b9e5e269375da8af5207e10ee0bc104 | refs/heads/master | 2023-07-20T00:32:29.902000 | 2012-03-02T21:12:59 | 2012-03-02T21:12:59 | 36,229,267 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | @artifact.package@import java.awt.event.ActionEvent;
import org.codehaus.griffon.runtime.core.AbstractGriffonController;
public class @artifact.name@ extends AbstractGriffonController {
// these will be injected by Griffon
private @artifact.name.plain@Model model;
private @artifact.name.plain@View view;
public void setModel(@artifact.name.plain@Model model) {
this.model = model;
}
public void setView(@artifact.name.plain@View view) {
this.view = view;
}
/*
Remember to use proper threading when dealing with
long computations.
Please read chapter 9 of the Griffon Guide to know more.
public void action(final ActionEvent e) {
execOutside(new Runnable() {
public void run() {
// action code
}
});
}
*/
}
| UTF-8 | Java | 852 | java | Controller.java | Java | [] | null | [] | @artifact.package@import java.awt.event.ActionEvent;
import org.codehaus.griffon.runtime.core.AbstractGriffonController;
public class @artifact.name@ extends AbstractGriffonController {
// these will be injected by Griffon
private @artifact.name.plain@Model model;
private @artifact.name.plain@View view;
public void setModel(@artifact.name.plain@Model model) {
this.model = model;
}
public void setView(@artifact.name.plain@View view) {
this.view = view;
}
/*
Remember to use proper threading when dealing with
long computations.
Please read chapter 9 of the Griffon Guide to know more.
public void action(final ActionEvent e) {
execOutside(new Runnable() {
public void run() {
// action code
}
});
}
*/
}
| 852 | 0.643192 | 0.642019 | 30 | 27.4 | 23.237326 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.233333 | false | false | 12 |
5173d2c2e9a16f555365881d95e0030fbde525d2 | 11,089,605,603,546 | d1c7f8b86483800236afae40571f587382186e38 | /src/main/java/com/namvn/shopping/persistence/entity/Bill.java | a2881a8802cf8cf6a3e48d40892a3b984e95a763 | [] | no_license | 5namtroinhuthe/hjy345afwjhkpoiyu | https://github.com/5namtroinhuthe/hjy345afwjhkpoiyu | 1ae5135c337a0511bff54bdc46187f419f8129e5 | 8e6302fcc30c8724d7bb7bdc92f94acd5d638bc7 | refs/heads/master | 2020-04-03T19:44:55.741000 | 2018-11-25T12:49:49 | 2018-11-25T12:49:49 | 155,534,160 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.namvn.shopping.persistence.entity;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "bill")
public class Bill implements Serializable {
@Id
@Column(name = "bill_id", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long billId;
private String nameBill;
private String nameUser;
private String address;
private String email;
private String tel;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
@OneToOne(mappedBy = "bill",cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private UserOrder userOrder;
public Long getBillId() {
return billId;
}
public void setBillId(Long billId) {
this.billId = billId;
}
public String getNameBill() {
return nameBill;
}
public void setNameBill(String nameBill) {
this.nameBill = nameBill;
}
public String getNameUser() {
return nameUser;
}
public void setNameUser(String nameUser) {
this.nameUser = nameUser;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
| UTF-8 | Java | 1,643 | java | Bill.java | Java | [] | null | [] | package com.namvn.shopping.persistence.entity;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "bill")
public class Bill implements Serializable {
@Id
@Column(name = "bill_id", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long billId;
private String nameBill;
private String nameUser;
private String address;
private String email;
private String tel;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
@OneToOne(mappedBy = "bill",cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private UserOrder userOrder;
public Long getBillId() {
return billId;
}
public void setBillId(Long billId) {
this.billId = billId;
}
public String getNameBill() {
return nameBill;
}
public void setNameBill(String nameBill) {
this.nameBill = nameBill;
}
public String getNameUser() {
return nameUser;
}
public void setNameUser(String nameUser) {
this.nameUser = nameUser;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
| 1,643 | 0.61899 | 0.61899 | 80 | 19.5375 | 16.957258 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35 | false | false | 12 |
0dfe3ce4a910739c18d220ad2d4822e1983ef699 | 29,394,756,174,095 | 11e7e21a300841866078d40c62575f0b7a902aac | /src/main/java/com/telehot/tpdata/data/service/BusinessService.java | 9aa85a4a82d5f058f05ca86636601ce1e81fa134 | [] | no_license | dolceDawn/tp_data | https://github.com/dolceDawn/tp_data | 613d320f6d8eaaca3bb6b571ae294755657e4614 | 801dc89e933b5824c3077a909787ac2a2243f812 | refs/heads/master | 2020-04-03T05:23:14.923000 | 2018-10-28T06:59:10 | 2018-10-28T06:59:10 | 155,033,218 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.telehot.tpdata.data.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.fasterxml.jackson.core.type.TypeReference;
import com.telehot.platform.app.jpa.spring.criteria.Criteria;
import com.telehot.platform.app.jpa.spring.criteria.Restrictions;
import com.telehot.platform.app.spring.ApplicationContextHelper;
import com.telehot.platform.app.spring.service.BaseService;
import com.telehot.platform.app.utils.JsonUtils;
import com.telehot.times.comm.constants.StatusConstant;
import com.telehot.times.comm.constants.SysConstant;
import com.telehot.tpdata.data.constant.DataConstant;
import com.telehot.tpdata.data.controller.BusinessController;
import com.telehot.tpdata.data.manager.BusinessManager;
import com.telehot.tpdata.data.model.Business;
import com.telehot.tpdata.data.util.ProcessEchoUtil;
/**
* 基础设置接口实现
* @author zhangliming
* @version $Id$
* @since
* @see
*
*/
@Service
@Transactional
public class BusinessService extends BaseService<Business, Long> {
/** 校验常量类型 */
public static final String FLAG_CODE = "code";
/** 校验常量类型 */
public static final String FLAG_NAME = "name";
/** 业务服务类 */
@Autowired
BusinessManager businessManager;
/**
* 业务数据关联服务类
*/
@Autowired
TableReBizService tableReBizService;
/**
* 数据表服务类
*/
@Autowired
DataTableService dataTableService;
/**
* 数据字段服务类
*/
@Autowired
DataFieldService dataFieldService;
/**
* 应用服务类
*/
@Autowired
ApplicationService applicationService;
/**
*〈简述〉根据应用id查找业务列表
*〈详细描述〉根据应用id查找业务列表
* @author zhangliming
* @param appId 应用id
* @return 查询结果
*/
public List<Business> findBizByAppId(Long appId) {
return businessManager.findBizByAppId(appId);
}
/**
*〈简述〉根据应用id查找已起动业务列表
*〈详细描述〉根据应用id查找业务列表
* @author zhangliming
* @param appId 应用id
* @return 查询结果
*/
public List<Business> findOnBizByAppId(Long appId) {
return businessManager.findOnBizByAppId(appId);
}
/**
*〈简述〉根据应用id删除具体业务
*〈详细描述〉
* @author zhangliming
* @param appId 应用id
*/
public void deleteBizByAppId(Long appId) {
List<Business> bizList = businessManager.findBizByAppId(appId);
for (Business biz : bizList) {
biz.setIsDisabled(SysConstant.HAS_DELETED);
}
businessManager.save(bizList);
}
/**
*〈简述〉校验重复编码
*〈详细描述〉
* @author zhangliming
* @param param String 待校验值
* @param appId Long 应用id
* @param flag name/code
* @param id Long id
* @return 校验结果
*/
public boolean isExistCode(String param, Long appId, String flag, Long id) {
Criteria<Business> criteria = Criteria.forClass(Business.class);
if (FLAG_CODE.equals(flag)) {
criteria.add(Restrictions.eq("code", param));
} else {
criteria.add(Restrictions.eq("name", param));
}
// 如果是编辑,去掉当前id的对象
if (id != null) {
criteria.add(Restrictions.ne("id", id));
}
//过滤掉其他应用下的业务
criteria.add(Restrictions.eq("applicationId", appId));
criteria.add(Restrictions.eq("isDisabled", 0));
List<Business> list = businessManager.findAll(criteria);
// 若list长度大于0,则代表该编码已存在
if (list != null && list.size() > 0) {
return false;
}
return true;
}
/**
*〈简述〉更新指定节点状态
*〈详细描述〉更新指定节点状态
* @author zhangliming
* @param bizId Long 业务id
* @param code String 节点code
* @param status int 状态
*/
public void updateBizNodeStatus(Long bizId, String code, int status) {
Business business = this.findOne(bizId);
@SuppressWarnings("unchecked")
Map<String, Integer> nodeStatusMap = (HashMap<String, Integer>) JsonUtils.fromJson(business.getNodeStatus(), Object.class);
nodeStatusMap.put(code, status);
business.setNodeStatus(JsonUtils.toJson(nodeStatusMap));
this.save(business);
}
/**
*〈简述〉变更一个节点后,更新所有业务节点状态
*〈详细描述〉变更一个节点后,更新所有业务节点状态
* @author zhangliming
* @param biz Long 业务id
* @param code String 节点编码
* @param isEdit Boolean 是否编辑
* @return Business 更新对象
*/
public Business initNormalNodesStatus(Business biz, String code, boolean isEdit) {
Map<String, Integer> nodeStatusMap = new HashMap<String, Integer>();
if (code.equals(BusinessController.INTER_CODE)) {
if (isEdit) {
nodeStatusMap.put(BusinessController.INTER_CODE, 1);
} else {
nodeStatusMap.put(BusinessController.INTER_CODE, 0);
}
nodeStatusMap.put(BusinessController.TABLE_CODE, 0);
nodeStatusMap.put(BusinessController.PROCESS_CODE, 0);
nodeStatusMap.put(BusinessController.RESULT_CODE, 0);
} else if (code.equals(BusinessController.TABLE_CODE)) {
nodeStatusMap.put(BusinessController.INTER_CODE, DataConstant.BUSINESS_NODE_STATUS_NEXTSTEP);
nodeStatusMap.put(BusinessController.TABLE_CODE, 1);
nodeStatusMap.put(BusinessController.PROCESS_CODE, 0);
nodeStatusMap.put(BusinessController.RESULT_CODE, 0);
} else if (code.equals(BusinessController.PROCESS_CODE)) {
nodeStatusMap.put(BusinessController.INTER_CODE, DataConstant.BUSINESS_NODE_STATUS_NEXTSTEP);
nodeStatusMap.put(BusinessController.TABLE_CODE, DataConstant.BUSINESS_NODE_STATUS_NEXTSTEP);
nodeStatusMap.put(BusinessController.PROCESS_CODE, 1);
nodeStatusMap.put(BusinessController.RESULT_CODE, 0);
} else {
nodeStatusMap.put(BusinessController.INTER_CODE, DataConstant.BUSINESS_NODE_STATUS_NEXTSTEP);
nodeStatusMap.put(BusinessController.TABLE_CODE, DataConstant.BUSINESS_NODE_STATUS_NEXTSTEP);
nodeStatusMap.put(BusinessController.PROCESS_CODE, DataConstant.BUSINESS_NODE_STATUS_NEXTSTEP);
nodeStatusMap.put(BusinessController.RESULT_CODE, 1);
}
biz.setNodeStatus(JsonUtils.toJson(nodeStatusMap));
return biz;
}
/**
*〈简述〉判断业务节点是否结束
*〈详细描述〉判断业务节点是否结束
* @author zhangliming
* @param business Business
* @return boolean
*/
public boolean isBizOver(Business business) {
Map<String, Integer> nodeStatusMap = JsonUtils.fromJson(business.getNodeStatus(), new TypeReference<Map<String, Integer>>() { });
int result = nodeStatusMap.get(BusinessController.RESULT_CODE);
if (result == 1) {
return true;
}
return false;
}
/**
*〈简述〉业务启动
*〈详细描述〉业务启动
* @author zhangliming
* @param bizId Long 业务ID
* @return boolean
*/
public boolean startUp(Long bizId) {
Business biz = findOne(bizId);
ProcessEchoUtil.updateNodeMsg(ProcessEchoUtil.PROCESS_KEY_BIZ_START, null, ProcessEchoUtil.NODE_START, null);
try {
ApplicationContextHelper.getBean(DataTableService.class).generateTables(biz);
} catch (Exception e) {
ProcessEchoUtil.updateNodeMsg(ProcessEchoUtil.PROCESS_KEY_BIZ_START, "1", ProcessEchoUtil.TAG_ERROR, e.getMessage());
e.printStackTrace();
return false;
}
ProcessEchoUtil.updateNodeMsg(ProcessEchoUtil.PROCESS_KEY_BIZ_START, "1", ProcessEchoUtil.NODE_END, null);
try {
ApplicationContextHelper.getBean(BizInterfaceService.class).startUp(bizId);
} catch (Exception e) {
ProcessEchoUtil.updateNodeMsg(ProcessEchoUtil.PROCESS_KEY_BIZ_START, "2", ProcessEchoUtil.TAG_ERROR, e.getMessage());
e.printStackTrace();
return false;
}
ProcessEchoUtil.updateNodeMsg(ProcessEchoUtil.PROCESS_KEY_BIZ_START, "2", ProcessEchoUtil.NODE_END, null);
try {
ApplicationContextHelper.getBean(DataProcessService.class).startUp(bizId);
} catch (Exception e) {
ProcessEchoUtil.updateNodeMsg(ProcessEchoUtil.PROCESS_KEY_BIZ_START, "3", ProcessEchoUtil.TAG_ERROR, e.getMessage());
e.printStackTrace();
return false;
}
ProcessEchoUtil.updateNodeMsg(ProcessEchoUtil.PROCESS_KEY_BIZ_START, "3", ProcessEchoUtil.NODE_END, null);
return true;
}
/**
*
*〈简述〉终止
*〈详细描述〉终止
* @author zrz
* @param bizId Long
* @return boolean
*/
public boolean shutdown(Long bizId) {
Business biz = findOne(bizId);
ApplicationContextHelper.getBean(BizInterfaceService.class).shutdown(bizId);
ApplicationContextHelper.getBean(DataProcessService.class).shutdown(bizId);
biz.setStatus(StatusConstant.STATUS_OFFLINE);
save(biz);
return true;
}
}
| UTF-8 | Java | 9,832 | java | BusinessService.java | Java | [
{
"context": ".util.ProcessEchoUtil;\n\n/**\n * 基础设置接口实现\n * @author zhangliming\n * @version $Id$\n * @since\n * @see\n *\n */\n@Servic",
"end": 1066,
"score": 0.9988254308700562,
"start": 1055,
"tag": "USERNAME",
"value": "zhangliming"
},
{
"context": "应用id查找业务列表\n *〈详细描述〉根据应用id查找业务列表\n * @author zhangliming\n * @param appId 应用id\n * @return 查询结果\n ",
"end": 1858,
"score": 0.9994725584983826,
"start": 1847,
"tag": "USERNAME",
"value": "zhangliming"
},
{
"context": "d查找已起动业务列表\n *〈详细描述〉根据应用id查找业务列表\n * @author zhangliming\n * @param appId 应用id\n * @return 查询结果\n ",
"end": 2117,
"score": 0.999468982219696,
"start": 2106,
"tag": "USERNAME",
"value": "zhangliming"
},
{
"context": " *〈简述〉根据应用id删除具体业务\n *〈详细描述〉\n * @author zhangliming\n * @param appId 应用id\n */ \n public void",
"end": 2361,
"score": 0.9994177222251892,
"start": 2350,
"tag": "USERNAME",
"value": "zhangliming"
},
{
"context": " /**\n *〈简述〉校验重复编码\n *〈详细描述〉\n * @author zhangliming\n * @param param String 待校验值\n * @param app",
"end": 2730,
"score": 0.9992879629135132,
"start": 2719,
"tag": "USERNAME",
"value": "zhangliming"
},
{
"context": " *〈简述〉更新指定节点状态\n *〈详细描述〉更新指定节点状态\n * @author zhangliming\n * @param bizId Long 业务id \n * @param code",
"end": 3750,
"score": 0.999419093132019,
"start": 3739,
"tag": "USERNAME",
"value": "zhangliming"
},
{
"context": "节点状态\n *〈详细描述〉变更一个节点后,更新所有业务节点状态\n * @author zhangliming\n * @param biz Long 业务id\n * @param code St",
"end": 4382,
"score": 0.999421238899231,
"start": 4371,
"tag": "USERNAME",
"value": "zhangliming"
},
{
"context": "述〉判断业务节点是否结束\n *〈详细描述〉判断业务节点是否结束\n * @author zhangliming\n * @param business Business\n * @return bo",
"end": 6495,
"score": 0.9986391067504883,
"start": 6484,
"tag": "USERNAME",
"value": "zhangliming"
},
{
"context": "/**\n *〈简述〉业务启动\n *〈详细描述〉业务启动\n * @author zhangliming\n * @param bizId Long 业务ID\n * @return boo",
"end": 6977,
"score": 0.9987294673919678,
"start": 6966,
"tag": "USERNAME",
"value": "zhangliming"
},
{
"context": " * \n *〈简述〉终止\n *〈详细描述〉终止\n * @author zrz\n * @param bizId Long\n * @return boolean\n ",
"end": 8678,
"score": 0.9989643096923828,
"start": 8675,
"tag": "USERNAME",
"value": "zrz"
}
] | null | [] | package com.telehot.tpdata.data.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.fasterxml.jackson.core.type.TypeReference;
import com.telehot.platform.app.jpa.spring.criteria.Criteria;
import com.telehot.platform.app.jpa.spring.criteria.Restrictions;
import com.telehot.platform.app.spring.ApplicationContextHelper;
import com.telehot.platform.app.spring.service.BaseService;
import com.telehot.platform.app.utils.JsonUtils;
import com.telehot.times.comm.constants.StatusConstant;
import com.telehot.times.comm.constants.SysConstant;
import com.telehot.tpdata.data.constant.DataConstant;
import com.telehot.tpdata.data.controller.BusinessController;
import com.telehot.tpdata.data.manager.BusinessManager;
import com.telehot.tpdata.data.model.Business;
import com.telehot.tpdata.data.util.ProcessEchoUtil;
/**
* 基础设置接口实现
* @author zhangliming
* @version $Id$
* @since
* @see
*
*/
@Service
@Transactional
public class BusinessService extends BaseService<Business, Long> {
/** 校验常量类型 */
public static final String FLAG_CODE = "code";
/** 校验常量类型 */
public static final String FLAG_NAME = "name";
/** 业务服务类 */
@Autowired
BusinessManager businessManager;
/**
* 业务数据关联服务类
*/
@Autowired
TableReBizService tableReBizService;
/**
* 数据表服务类
*/
@Autowired
DataTableService dataTableService;
/**
* 数据字段服务类
*/
@Autowired
DataFieldService dataFieldService;
/**
* 应用服务类
*/
@Autowired
ApplicationService applicationService;
/**
*〈简述〉根据应用id查找业务列表
*〈详细描述〉根据应用id查找业务列表
* @author zhangliming
* @param appId 应用id
* @return 查询结果
*/
public List<Business> findBizByAppId(Long appId) {
return businessManager.findBizByAppId(appId);
}
/**
*〈简述〉根据应用id查找已起动业务列表
*〈详细描述〉根据应用id查找业务列表
* @author zhangliming
* @param appId 应用id
* @return 查询结果
*/
public List<Business> findOnBizByAppId(Long appId) {
return businessManager.findOnBizByAppId(appId);
}
/**
*〈简述〉根据应用id删除具体业务
*〈详细描述〉
* @author zhangliming
* @param appId 应用id
*/
public void deleteBizByAppId(Long appId) {
List<Business> bizList = businessManager.findBizByAppId(appId);
for (Business biz : bizList) {
biz.setIsDisabled(SysConstant.HAS_DELETED);
}
businessManager.save(bizList);
}
/**
*〈简述〉校验重复编码
*〈详细描述〉
* @author zhangliming
* @param param String 待校验值
* @param appId Long 应用id
* @param flag name/code
* @param id Long id
* @return 校验结果
*/
public boolean isExistCode(String param, Long appId, String flag, Long id) {
Criteria<Business> criteria = Criteria.forClass(Business.class);
if (FLAG_CODE.equals(flag)) {
criteria.add(Restrictions.eq("code", param));
} else {
criteria.add(Restrictions.eq("name", param));
}
// 如果是编辑,去掉当前id的对象
if (id != null) {
criteria.add(Restrictions.ne("id", id));
}
//过滤掉其他应用下的业务
criteria.add(Restrictions.eq("applicationId", appId));
criteria.add(Restrictions.eq("isDisabled", 0));
List<Business> list = businessManager.findAll(criteria);
// 若list长度大于0,则代表该编码已存在
if (list != null && list.size() > 0) {
return false;
}
return true;
}
/**
*〈简述〉更新指定节点状态
*〈详细描述〉更新指定节点状态
* @author zhangliming
* @param bizId Long 业务id
* @param code String 节点code
* @param status int 状态
*/
public void updateBizNodeStatus(Long bizId, String code, int status) {
Business business = this.findOne(bizId);
@SuppressWarnings("unchecked")
Map<String, Integer> nodeStatusMap = (HashMap<String, Integer>) JsonUtils.fromJson(business.getNodeStatus(), Object.class);
nodeStatusMap.put(code, status);
business.setNodeStatus(JsonUtils.toJson(nodeStatusMap));
this.save(business);
}
/**
*〈简述〉变更一个节点后,更新所有业务节点状态
*〈详细描述〉变更一个节点后,更新所有业务节点状态
* @author zhangliming
* @param biz Long 业务id
* @param code String 节点编码
* @param isEdit Boolean 是否编辑
* @return Business 更新对象
*/
public Business initNormalNodesStatus(Business biz, String code, boolean isEdit) {
Map<String, Integer> nodeStatusMap = new HashMap<String, Integer>();
if (code.equals(BusinessController.INTER_CODE)) {
if (isEdit) {
nodeStatusMap.put(BusinessController.INTER_CODE, 1);
} else {
nodeStatusMap.put(BusinessController.INTER_CODE, 0);
}
nodeStatusMap.put(BusinessController.TABLE_CODE, 0);
nodeStatusMap.put(BusinessController.PROCESS_CODE, 0);
nodeStatusMap.put(BusinessController.RESULT_CODE, 0);
} else if (code.equals(BusinessController.TABLE_CODE)) {
nodeStatusMap.put(BusinessController.INTER_CODE, DataConstant.BUSINESS_NODE_STATUS_NEXTSTEP);
nodeStatusMap.put(BusinessController.TABLE_CODE, 1);
nodeStatusMap.put(BusinessController.PROCESS_CODE, 0);
nodeStatusMap.put(BusinessController.RESULT_CODE, 0);
} else if (code.equals(BusinessController.PROCESS_CODE)) {
nodeStatusMap.put(BusinessController.INTER_CODE, DataConstant.BUSINESS_NODE_STATUS_NEXTSTEP);
nodeStatusMap.put(BusinessController.TABLE_CODE, DataConstant.BUSINESS_NODE_STATUS_NEXTSTEP);
nodeStatusMap.put(BusinessController.PROCESS_CODE, 1);
nodeStatusMap.put(BusinessController.RESULT_CODE, 0);
} else {
nodeStatusMap.put(BusinessController.INTER_CODE, DataConstant.BUSINESS_NODE_STATUS_NEXTSTEP);
nodeStatusMap.put(BusinessController.TABLE_CODE, DataConstant.BUSINESS_NODE_STATUS_NEXTSTEP);
nodeStatusMap.put(BusinessController.PROCESS_CODE, DataConstant.BUSINESS_NODE_STATUS_NEXTSTEP);
nodeStatusMap.put(BusinessController.RESULT_CODE, 1);
}
biz.setNodeStatus(JsonUtils.toJson(nodeStatusMap));
return biz;
}
/**
*〈简述〉判断业务节点是否结束
*〈详细描述〉判断业务节点是否结束
* @author zhangliming
* @param business Business
* @return boolean
*/
public boolean isBizOver(Business business) {
Map<String, Integer> nodeStatusMap = JsonUtils.fromJson(business.getNodeStatus(), new TypeReference<Map<String, Integer>>() { });
int result = nodeStatusMap.get(BusinessController.RESULT_CODE);
if (result == 1) {
return true;
}
return false;
}
/**
*〈简述〉业务启动
*〈详细描述〉业务启动
* @author zhangliming
* @param bizId Long 业务ID
* @return boolean
*/
public boolean startUp(Long bizId) {
Business biz = findOne(bizId);
ProcessEchoUtil.updateNodeMsg(ProcessEchoUtil.PROCESS_KEY_BIZ_START, null, ProcessEchoUtil.NODE_START, null);
try {
ApplicationContextHelper.getBean(DataTableService.class).generateTables(biz);
} catch (Exception e) {
ProcessEchoUtil.updateNodeMsg(ProcessEchoUtil.PROCESS_KEY_BIZ_START, "1", ProcessEchoUtil.TAG_ERROR, e.getMessage());
e.printStackTrace();
return false;
}
ProcessEchoUtil.updateNodeMsg(ProcessEchoUtil.PROCESS_KEY_BIZ_START, "1", ProcessEchoUtil.NODE_END, null);
try {
ApplicationContextHelper.getBean(BizInterfaceService.class).startUp(bizId);
} catch (Exception e) {
ProcessEchoUtil.updateNodeMsg(ProcessEchoUtil.PROCESS_KEY_BIZ_START, "2", ProcessEchoUtil.TAG_ERROR, e.getMessage());
e.printStackTrace();
return false;
}
ProcessEchoUtil.updateNodeMsg(ProcessEchoUtil.PROCESS_KEY_BIZ_START, "2", ProcessEchoUtil.NODE_END, null);
try {
ApplicationContextHelper.getBean(DataProcessService.class).startUp(bizId);
} catch (Exception e) {
ProcessEchoUtil.updateNodeMsg(ProcessEchoUtil.PROCESS_KEY_BIZ_START, "3", ProcessEchoUtil.TAG_ERROR, e.getMessage());
e.printStackTrace();
return false;
}
ProcessEchoUtil.updateNodeMsg(ProcessEchoUtil.PROCESS_KEY_BIZ_START, "3", ProcessEchoUtil.NODE_END, null);
return true;
}
/**
*
*〈简述〉终止
*〈详细描述〉终止
* @author zrz
* @param bizId Long
* @return boolean
*/
public boolean shutdown(Long bizId) {
Business biz = findOne(bizId);
ApplicationContextHelper.getBean(BizInterfaceService.class).shutdown(bizId);
ApplicationContextHelper.getBean(DataProcessService.class).shutdown(bizId);
biz.setStatus(StatusConstant.STATUS_OFFLINE);
save(biz);
return true;
}
}
| 9,832 | 0.651562 | 0.649252 | 267 | 33.052433 | 30.081118 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.576779 | false | false | 12 |
49dc93a3e4677605df78c3f2e0c6112c97de7ca3 | 6,957,847,087,710 | a95734760da442f16cebf06a761227bfe17d844d | /src/sample/views/screens/WinScreen.java | f0c57a35a4d568be2819807e057cd4c9bbae0527 | [] | no_license | AndresTam/BattleShip | https://github.com/AndresTam/BattleShip | 36accc18015d012023c6e3566fc6a7d42685d0ef | bead288a48edea21e5524dcece0a6f4c97137b74 | refs/heads/main | 2023-06-09T20:07:20.413000 | 2021-07-01T17:46:14 | 2021-07-01T17:46:14 | 375,456,135 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sample.views.screens;
import javafx.event.Event;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.event.EventHandler;
import sample.Main;
public class WinScreen extends Stage implements EventHandler {
private Scene escena;
private Label lblInstructions;
private Button btnAcept;
private VBox vBox;
private String message;
public WinScreen(boolean result){
UICreate(result);
this.setTitle("Jugador 1");
this.setScene(escena);
this.show();
}
private void UICreate(boolean result) {
if(result == true){
message = "!!!Felicidades, has ganado el juego¡¡¡";
} else{
message = "Mala suerte, has perdido el juego";
}
lblInstructions = new Label(message);
lblInstructions.setId("lblInstructions");
btnAcept = new Button("Aceptar");
vBox = new VBox();
btnAcept.setOnAction(event -> {
System.exit(0);
});
vBox.getChildren().addAll(lblInstructions, btnAcept);
escena = new Scene(vBox,500,300);
escena.getStylesheets().add(getClass().getResource("../../css/styles.css").toExternalForm());
}
@Override
public void handle(Event event) {
}
}
| UTF-8 | Java | 1,400 | java | WinScreen.java | Java | [] | null | [] | package sample.views.screens;
import javafx.event.Event;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.event.EventHandler;
import sample.Main;
public class WinScreen extends Stage implements EventHandler {
private Scene escena;
private Label lblInstructions;
private Button btnAcept;
private VBox vBox;
private String message;
public WinScreen(boolean result){
UICreate(result);
this.setTitle("Jugador 1");
this.setScene(escena);
this.show();
}
private void UICreate(boolean result) {
if(result == true){
message = "!!!Felicidades, has ganado el juego¡¡¡";
} else{
message = "Mala suerte, has perdido el juego";
}
lblInstructions = new Label(message);
lblInstructions.setId("lblInstructions");
btnAcept = new Button("Aceptar");
vBox = new VBox();
btnAcept.setOnAction(event -> {
System.exit(0);
});
vBox.getChildren().addAll(lblInstructions, btnAcept);
escena = new Scene(vBox,500,300);
escena.getStylesheets().add(getClass().getResource("../../css/styles.css").toExternalForm());
}
@Override
public void handle(Event event) {
}
}
| 1,400 | 0.634216 | 0.62849 | 52 | 25.865385 | 21.021994 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.653846 | false | false | 12 |
9b2b6fd83cd544781e181791f7f8c32fb10a7de8 | 12,567,074,328,081 | b2016b74acf02c0117128b505baac48338d825c9 | /src/main/java/newbee/morningGlory/ref/loader/MGQiangHuaEquipmentConfigLoader.java | f785131bc17ce1dab91a36c9e83731c89f4a84bd | [] | no_license | atom-chen/server | https://github.com/atom-chen/server | 979830e60778a3fba1740ea3afb2e38937e84cea | c44e12a3efe5435d55590c9c0fd9e26cec58ed65 | refs/heads/master | 2020-06-17T02:54:13.348000 | 2017-10-13T18:40:21 | 2017-10-13T18:40:21 | 195,772,502 | 0 | 1 | null | true | 2019-07-08T08:46:37 | 2019-07-08T08:46:37 | 2017-10-12T04:18:14 | 2017-10-13T18:45:50 | 4,222 | 0 | 0 | 0 | null | false | false | /**
* Copyright 2013-2015 Sophia
*
* 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 newbee.morningGlory.ref.loader;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import newbee.morningGlory.ref.RefKey;
import org.apache.log4j.Logger;
import sophia.mmorpg.equipmentSmith.smith.qiangHua.MGQiangHuaDataRef;
import sophia.mmorpg.equipmentSmith.smith.qiangHua.MGQiangHuaEquipmentConfig;
import sophia.mmorpg.equipmentSmith.smith.qiangHua.MGQiangHuaRefKey;
import sophia.mmorpg.equipmentSmith.smith.qiangHua.MGQiangHuaScrollDataRef;
import sophia.mmorpg.equipmentSmith.smith.qiangHua.MGSpecialEquipmentQiangHuaDataRef;
import sophia.mmorpg.equipmentSmith.smith.qiangHua.MGSpecialEquipmentQiangHuaDataRefKey;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public final class MGQiangHuaEquipmentConfigLoader extends AbstractGameRefObjectLoader<MGQiangHuaEquipmentConfig> {
private static final Logger logger = Logger.getLogger(MGQiangHuaEquipmentConfigLoader.class);
public MGQiangHuaEquipmentConfigLoader() {
super(RefKey.equipStrengthening);
}
@Override
protected MGQiangHuaEquipmentConfig create() {
return new MGQiangHuaEquipmentConfig();
}
@Override
protected void fillNonPropertyDictionary(MGQiangHuaEquipmentConfig ref, JsonObject refData) {
String refId = refData.getAsJsonObject().get("refId").getAsString();
if ("equip_strengthening_base".equals(refId)) {
JsonObject qiangHuaConfigData = refData.getAsJsonObject().get("configData").getAsJsonObject();
Map<MGQiangHuaRefKey, MGQiangHuaDataRef> qiangHuaDataRefMap = new HashMap<MGQiangHuaRefKey, MGQiangHuaDataRef>();
if (qiangHuaConfigData != null) {
for (Entry<String,JsonElement> entry : qiangHuaConfigData.entrySet()) {
JsonElement jsonElement = entry.getValue();
JsonObject property = jsonElement.getAsJsonObject().get("property").getAsJsonObject();
byte playerPrefessionId = property.get("professionId").getAsByte();
byte equipmentBodyAreaId = property.get("kind").getAsByte();
byte qiangHuaLevel = property.get("strengtheningLevel").getAsByte();
MGQiangHuaRefKey qiangHuaKey = MGQiangHuaRefKey.get(playerPrefessionId, equipmentBodyAreaId, qiangHuaLevel);
MGQiangHuaDataRef qiangHuaRef = new MGQiangHuaDataRef();
fillPropertyDictionary(qiangHuaRef.getProperty(), property);
qiangHuaDataRefMap.put(qiangHuaKey, qiangHuaRef);
}
}
ref.setId(MGQiangHuaEquipmentConfig.QiangHua_Id);
ref.setQiangHuaDataRefMap(qiangHuaDataRefMap);
} else if ("equip_strengthening_expand".equals(refId)) {
JsonObject expandConfigData = refData.getAsJsonObject().get("configData").getAsJsonObject();
Map<MGSpecialEquipmentQiangHuaDataRefKey, MGSpecialEquipmentQiangHuaDataRef> specialEquipmentQiangHuaDataRefMap = new HashMap<MGSpecialEquipmentQiangHuaDataRefKey, MGSpecialEquipmentQiangHuaDataRef>();
if (expandConfigData != null) {
for (Entry<String,JsonElement> entry : expandConfigData.entrySet()) {
JsonElement jsonElement = entry.getValue();
JsonObject property = jsonElement.getAsJsonObject().get("property").getAsJsonObject();
String itemRefId = property.get("itemRefId").getAsString();
String id = jsonElement.getAsJsonObject().get("id").getAsString();
int strengtheningLevel = property.get("strengtheningLevel").getAsInt();
MGSpecialEquipmentQiangHuaDataRefKey specialEquipmentQiangHuaDataRefKey = MGSpecialEquipmentQiangHuaDataRefKey.get(itemRefId, strengtheningLevel);
MGSpecialEquipmentQiangHuaDataRef specialEquipmentQiangHuaDataRef = new MGSpecialEquipmentQiangHuaDataRef();
specialEquipmentQiangHuaDataRef.setId(id);
fillPropertyDictionary(specialEquipmentQiangHuaDataRef.getProperty(), property);
specialEquipmentQiangHuaDataRefMap.put(specialEquipmentQiangHuaDataRefKey, specialEquipmentQiangHuaDataRef);
}
}
ref.setId(MGQiangHuaEquipmentConfig.Special_Id);
ref.setSpecialEquipmentQiangHuaDataRefMap(specialEquipmentQiangHuaDataRefMap);
} else if ("equip_strengthening_scroll".equals(refId)) {
JsonObject scrollConfigData = refData.getAsJsonObject().get("configData").getAsJsonObject();
Map<String, MGQiangHuaScrollDataRef> mgQiangHuaScrollDataRefMap = new HashMap<String, MGQiangHuaScrollDataRef>();
if (scrollConfigData != null) {
for (Entry<String,JsonElement> entry : scrollConfigData.entrySet()) {
JsonElement jsonElement = entry.getValue();
JsonObject property = jsonElement.getAsJsonObject().get("property").getAsJsonObject();
String itemRefId =jsonElement.getAsJsonObject().get("itemRefId").getAsString();
MGQiangHuaScrollDataRef mgQiangHuaScrollDataRef = new MGQiangHuaScrollDataRef();
mgQiangHuaScrollDataRef.setId(itemRefId);
fillPropertyDictionary(mgQiangHuaScrollDataRef.getProperty(), property);
mgQiangHuaScrollDataRefMap.put(itemRefId, mgQiangHuaScrollDataRef);
}
}
ref.setId(MGQiangHuaEquipmentConfig.QiangHuaScroll_Id);
ref.setMgQiangHuaDScrollataRefMap(mgQiangHuaScrollDataRefMap);
}
}
}
| UTF-8 | Java | 5,621 | java | MGQiangHuaEquipmentConfigLoader.java | Java | [] | null | [] | /**
* Copyright 2013-2015 Sophia
*
* 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 newbee.morningGlory.ref.loader;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import newbee.morningGlory.ref.RefKey;
import org.apache.log4j.Logger;
import sophia.mmorpg.equipmentSmith.smith.qiangHua.MGQiangHuaDataRef;
import sophia.mmorpg.equipmentSmith.smith.qiangHua.MGQiangHuaEquipmentConfig;
import sophia.mmorpg.equipmentSmith.smith.qiangHua.MGQiangHuaRefKey;
import sophia.mmorpg.equipmentSmith.smith.qiangHua.MGQiangHuaScrollDataRef;
import sophia.mmorpg.equipmentSmith.smith.qiangHua.MGSpecialEquipmentQiangHuaDataRef;
import sophia.mmorpg.equipmentSmith.smith.qiangHua.MGSpecialEquipmentQiangHuaDataRefKey;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public final class MGQiangHuaEquipmentConfigLoader extends AbstractGameRefObjectLoader<MGQiangHuaEquipmentConfig> {
private static final Logger logger = Logger.getLogger(MGQiangHuaEquipmentConfigLoader.class);
public MGQiangHuaEquipmentConfigLoader() {
super(RefKey.equipStrengthening);
}
@Override
protected MGQiangHuaEquipmentConfig create() {
return new MGQiangHuaEquipmentConfig();
}
@Override
protected void fillNonPropertyDictionary(MGQiangHuaEquipmentConfig ref, JsonObject refData) {
String refId = refData.getAsJsonObject().get("refId").getAsString();
if ("equip_strengthening_base".equals(refId)) {
JsonObject qiangHuaConfigData = refData.getAsJsonObject().get("configData").getAsJsonObject();
Map<MGQiangHuaRefKey, MGQiangHuaDataRef> qiangHuaDataRefMap = new HashMap<MGQiangHuaRefKey, MGQiangHuaDataRef>();
if (qiangHuaConfigData != null) {
for (Entry<String,JsonElement> entry : qiangHuaConfigData.entrySet()) {
JsonElement jsonElement = entry.getValue();
JsonObject property = jsonElement.getAsJsonObject().get("property").getAsJsonObject();
byte playerPrefessionId = property.get("professionId").getAsByte();
byte equipmentBodyAreaId = property.get("kind").getAsByte();
byte qiangHuaLevel = property.get("strengtheningLevel").getAsByte();
MGQiangHuaRefKey qiangHuaKey = MGQiangHuaRefKey.get(playerPrefessionId, equipmentBodyAreaId, qiangHuaLevel);
MGQiangHuaDataRef qiangHuaRef = new MGQiangHuaDataRef();
fillPropertyDictionary(qiangHuaRef.getProperty(), property);
qiangHuaDataRefMap.put(qiangHuaKey, qiangHuaRef);
}
}
ref.setId(MGQiangHuaEquipmentConfig.QiangHua_Id);
ref.setQiangHuaDataRefMap(qiangHuaDataRefMap);
} else if ("equip_strengthening_expand".equals(refId)) {
JsonObject expandConfigData = refData.getAsJsonObject().get("configData").getAsJsonObject();
Map<MGSpecialEquipmentQiangHuaDataRefKey, MGSpecialEquipmentQiangHuaDataRef> specialEquipmentQiangHuaDataRefMap = new HashMap<MGSpecialEquipmentQiangHuaDataRefKey, MGSpecialEquipmentQiangHuaDataRef>();
if (expandConfigData != null) {
for (Entry<String,JsonElement> entry : expandConfigData.entrySet()) {
JsonElement jsonElement = entry.getValue();
JsonObject property = jsonElement.getAsJsonObject().get("property").getAsJsonObject();
String itemRefId = property.get("itemRefId").getAsString();
String id = jsonElement.getAsJsonObject().get("id").getAsString();
int strengtheningLevel = property.get("strengtheningLevel").getAsInt();
MGSpecialEquipmentQiangHuaDataRefKey specialEquipmentQiangHuaDataRefKey = MGSpecialEquipmentQiangHuaDataRefKey.get(itemRefId, strengtheningLevel);
MGSpecialEquipmentQiangHuaDataRef specialEquipmentQiangHuaDataRef = new MGSpecialEquipmentQiangHuaDataRef();
specialEquipmentQiangHuaDataRef.setId(id);
fillPropertyDictionary(specialEquipmentQiangHuaDataRef.getProperty(), property);
specialEquipmentQiangHuaDataRefMap.put(specialEquipmentQiangHuaDataRefKey, specialEquipmentQiangHuaDataRef);
}
}
ref.setId(MGQiangHuaEquipmentConfig.Special_Id);
ref.setSpecialEquipmentQiangHuaDataRefMap(specialEquipmentQiangHuaDataRefMap);
} else if ("equip_strengthening_scroll".equals(refId)) {
JsonObject scrollConfigData = refData.getAsJsonObject().get("configData").getAsJsonObject();
Map<String, MGQiangHuaScrollDataRef> mgQiangHuaScrollDataRefMap = new HashMap<String, MGQiangHuaScrollDataRef>();
if (scrollConfigData != null) {
for (Entry<String,JsonElement> entry : scrollConfigData.entrySet()) {
JsonElement jsonElement = entry.getValue();
JsonObject property = jsonElement.getAsJsonObject().get("property").getAsJsonObject();
String itemRefId =jsonElement.getAsJsonObject().get("itemRefId").getAsString();
MGQiangHuaScrollDataRef mgQiangHuaScrollDataRef = new MGQiangHuaScrollDataRef();
mgQiangHuaScrollDataRef.setId(itemRefId);
fillPropertyDictionary(mgQiangHuaScrollDataRef.getProperty(), property);
mgQiangHuaScrollDataRefMap.put(itemRefId, mgQiangHuaScrollDataRef);
}
}
ref.setId(MGQiangHuaEquipmentConfig.QiangHuaScroll_Id);
ref.setMgQiangHuaDScrollataRefMap(mgQiangHuaScrollDataRefMap);
}
}
}
| 5,621 | 0.787226 | 0.784914 | 122 | 45.073769 | 39.861271 | 204 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.688524 | false | false | 12 |
77c3792fd4291c6aae9133a69a41661164d3df43 | 33,002,528,709,337 | 27dc5c1b98fe599ba63dd5cc891ad3cda46fb1ed | /app/src/main/java/com/mersiyanov/dmitry/yadgallery/ui/mvp/PicturesContract.java | a6c72a9d7b3a9a3929ab4ff3cc3a938c5ae8c232 | [] | no_license | dmersiyanov/yad-gallery | https://github.com/dmersiyanov/yad-gallery | a6a61daa00a567d878f3527ffcc21cada56776c8 | d8af6567fff4e4f6a1b66485417818f80e81459d | refs/heads/master | 2020-03-11T18:12:16.250000 | 2018-05-22T07:53:22 | 2018-05-22T07:53:22 | 130,170,475 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mersiyanov.dmitry.yadgallery.ui.mvp;
import com.mersiyanov.dmitry.yadgallery.pojo.Item;
import com.mersiyanov.dmitry.yadgallery.pojo.ResponseFileList;
import java.util.List;
import io.reactivex.Single;
public class PicturesContract {
public interface View {
void showLoading();
void showError();
void showData(List<Item> itemlist);
}
public interface Presenter {
void attachView(View view);
void detachView();
void getPictures(String token);
}
public interface Repo {
Single<ResponseFileList> load(String token);
void initDB();
void closeDB();
}
}
| UTF-8 | Java | 672 | java | PicturesContract.java | Java | [] | null | [] | package com.mersiyanov.dmitry.yadgallery.ui.mvp;
import com.mersiyanov.dmitry.yadgallery.pojo.Item;
import com.mersiyanov.dmitry.yadgallery.pojo.ResponseFileList;
import java.util.List;
import io.reactivex.Single;
public class PicturesContract {
public interface View {
void showLoading();
void showError();
void showData(List<Item> itemlist);
}
public interface Presenter {
void attachView(View view);
void detachView();
void getPictures(String token);
}
public interface Repo {
Single<ResponseFileList> load(String token);
void initDB();
void closeDB();
}
}
| 672 | 0.662202 | 0.662202 | 38 | 16.68421 | 18.598394 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false | 12 |
3196782ed969ac91df408a842233e640eb906164 | 33,002,528,708,036 | 75d555577b075bfcd1a3782df98bb8f3b25698e6 | /app/src/main/java/ua/kaganovych/kach/adapters/CategoriesAdapter.java | 535e55c8bbaa34a8cb679ccba918b7698a05592e | [] | no_license | kaganovych/Kach | https://github.com/kaganovych/Kach | b7a83844cd6a7743d977f1b3881e71a240574d63 | a1ad88238d5ca5985efcb8e00a744b47063c6bec | refs/heads/master | 2021-12-14T03:08:43.537000 | 2015-09-30T17:00:25 | 2015-09-30T17:00:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ua.kaganovych.kach.adapters;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import ua.kaganovych.kach.R;
import ua.kaganovych.kach.dialogs.CommonDialogFragment;
import ua.kaganovych.kach.model.Categories;
import ua.kaganovych.kach.provider.workout.WorkoutContentValues;
public class CategoriesAdapter extends ArrayAdapter<Categories> {
private FragmentActivity mActivity;
private int mDayOfTheWeek;
public CategoriesAdapter(Context context, ArrayList<Categories> list, FragmentActivity activity, int day_of_the_week) {
super(context, 0, list);
mActivity = activity;
mDayOfTheWeek = day_of_the_week;
}
private static class ViewHolder {
private TextView mName;
private ImageView mAddButton;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Categories item = getItem(position);
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.category_item, parent, false);
viewHolder.mName = (TextView)convertView.findViewById(R.id.title_text_view);
viewHolder.mAddButton = (ImageView)convertView.findViewById(R.id.add_category_button);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)convertView.getTag();
}
viewHolder.mName.setText(item.getName());
viewHolder.mName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CommonDialogFragment.newInstance(item.getName()).show(mActivity.getSupportFragmentManager(), "");
}
});
viewHolder.mAddButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), "Added: " + item.getName() + " Day: " + mDayOfTheWeek, Toast.LENGTH_SHORT).show();
WorkoutContentValues cv = new WorkoutContentValues();
cv.putCategory(item.getName());
cv.putDayOfTheWeek(mDayOfTheWeek);
cv.insert(getContext().getContentResolver());
}
});
return convertView;
}
}
| UTF-8 | Java | 2,626 | java | CategoriesAdapter.java | Java | [] | null | [] | package ua.kaganovych.kach.adapters;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import ua.kaganovych.kach.R;
import ua.kaganovych.kach.dialogs.CommonDialogFragment;
import ua.kaganovych.kach.model.Categories;
import ua.kaganovych.kach.provider.workout.WorkoutContentValues;
public class CategoriesAdapter extends ArrayAdapter<Categories> {
private FragmentActivity mActivity;
private int mDayOfTheWeek;
public CategoriesAdapter(Context context, ArrayList<Categories> list, FragmentActivity activity, int day_of_the_week) {
super(context, 0, list);
mActivity = activity;
mDayOfTheWeek = day_of_the_week;
}
private static class ViewHolder {
private TextView mName;
private ImageView mAddButton;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Categories item = getItem(position);
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.category_item, parent, false);
viewHolder.mName = (TextView)convertView.findViewById(R.id.title_text_view);
viewHolder.mAddButton = (ImageView)convertView.findViewById(R.id.add_category_button);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)convertView.getTag();
}
viewHolder.mName.setText(item.getName());
viewHolder.mName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CommonDialogFragment.newInstance(item.getName()).show(mActivity.getSupportFragmentManager(), "");
}
});
viewHolder.mAddButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), "Added: " + item.getName() + " Day: " + mDayOfTheWeek, Toast.LENGTH_SHORT).show();
WorkoutContentValues cv = new WorkoutContentValues();
cv.putCategory(item.getName());
cv.putDayOfTheWeek(mDayOfTheWeek);
cv.insert(getContext().getContentResolver());
}
});
return convertView;
}
}
| 2,626 | 0.675171 | 0.67441 | 72 | 35.472221 | 30.686123 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.722222 | false | false | 12 |
1c9116f26bc12716b73f396f14377086d915e000 | 25,829,933,350,460 | 3f041fe8da3b54caaa6c4280a52f4bb9e7c28468 | /src/com/neusoft/com/gongjulei/Test2.java | b07c253dda6abc1c2ca2dfc663f35454d3b35ba6 | [] | no_license | mengxiangfang99/myHomework | https://github.com/mengxiangfang99/myHomework | 13296d1b4e26f33668df3ccce7ff16064b97c0ce | dcf5f5600421a34e6b1ec9083558beed0758784e | refs/heads/master | 2021-08-31T13:27:16.234000 | 2017-12-21T13:29:51 | 2017-12-21T13:29:51 | 115,008,598 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.neusoft.com.gongjulei;
public class Test2 {
public static void main(String[] args) {
if(args.length > 0) {
String s = args[0];
char[] c = s.toCharArray();
int count = 0;
for (int i = 0; i < c.length; i++) {
if(c[i] == 'e')
count++;
}
System.out.println(s);
System.out.println("这个字符串中有"+ count +"个e字符");
}
System.out.println("输入参数");
}
}
| GB18030 | Java | 420 | java | Test2.java | Java | [] | null | [] | package com.neusoft.com.gongjulei;
public class Test2 {
public static void main(String[] args) {
if(args.length > 0) {
String s = args[0];
char[] c = s.toCharArray();
int count = 0;
for (int i = 0; i < c.length; i++) {
if(c[i] == 'e')
count++;
}
System.out.println(s);
System.out.println("这个字符串中有"+ count +"个e字符");
}
System.out.println("输入参数");
}
}
| 420 | 0.566327 | 0.553571 | 19 | 19.631578 | 14.466697 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.684211 | false | false | 12 |
19354f8a14632196e996c626870b6be7113bc728 | 24,550,033,118,701 | 5023b61779cfb43e0bb296864d91cca092c8316f | /src/main/java/com/uni/bookstore/service/AuthorServiceImp.java | 0ad2415c168390c5447b1644b5adb2745dbebd1b | [] | no_license | Szintai/tobbretegu | https://github.com/Szintai/tobbretegu | 8893c504853b2657b56d85e6a5eb1baa2f0292eb | 43f88dec0d079f078b676486cf5b1a366fb9dc15 | refs/heads/master | 2020-09-23T02:37:17.081000 | 2019-12-02T13:34:01 | 2019-12-02T13:34:01 | 225,380,970 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.uni.bookstore.service;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.uni.bookstore.exception.NoResourceException;
import com.uni.bookstore.model.Author;
import com.uni.bookstore.repository.AuthorRepository;
import com.uni.bookstore.repository.BookRepository;
@Service
public class AuthorServiceImp implements AuthorService{
private final AuthorRepository authorRepository;
private final BookRepository bookRepository;
public AuthorServiceImp(AuthorRepository authorRepository, BookRepository bookRepository) {
this.authorRepository=authorRepository;
this.bookRepository=bookRepository;
}
@Override
public Author save(Author author) {
return authorRepository.save(author);
}
@Override
public List<Author> saveAll(List<Author> authors) {
return authorRepository.saveAll(authors);
}
@Override
public Author findById(Long id) {
Optional<Author> optionalAuthor= authorRepository.findById(id);
return optionalAuthor.map(o -> optionalAuthor.get()).orElseThrow(NoResourceException::new);
}
@Override
public List<Author> findAll() {
return authorRepository.findAll();
}
@Override
public void deleteById(Long id) {
bookRepository.deleteById(id);
authorRepository.deleteById(id);
}
}
| UTF-8 | Java | 1,304 | java | AuthorServiceImp.java | Java | [] | null | [] | package com.uni.bookstore.service;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.uni.bookstore.exception.NoResourceException;
import com.uni.bookstore.model.Author;
import com.uni.bookstore.repository.AuthorRepository;
import com.uni.bookstore.repository.BookRepository;
@Service
public class AuthorServiceImp implements AuthorService{
private final AuthorRepository authorRepository;
private final BookRepository bookRepository;
public AuthorServiceImp(AuthorRepository authorRepository, BookRepository bookRepository) {
this.authorRepository=authorRepository;
this.bookRepository=bookRepository;
}
@Override
public Author save(Author author) {
return authorRepository.save(author);
}
@Override
public List<Author> saveAll(List<Author> authors) {
return authorRepository.saveAll(authors);
}
@Override
public Author findById(Long id) {
Optional<Author> optionalAuthor= authorRepository.findById(id);
return optionalAuthor.map(o -> optionalAuthor.get()).orElseThrow(NoResourceException::new);
}
@Override
public List<Author> findAll() {
return authorRepository.findAll();
}
@Override
public void deleteById(Long id) {
bookRepository.deleteById(id);
authorRepository.deleteById(id);
}
}
| 1,304 | 0.794479 | 0.794479 | 53 | 23.603773 | 24.341393 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.188679 | false | false | 12 |
355a6b1d5340aa44a5df42d4bc73589b5792b99d | 26,800,595,955,179 | 11cf6ac0b0409a3641ad5e1cdb1bb26447878310 | /new-merchant-quote-service-api/src/main/java/nz/co/smartpay/service/CSVService.java | ef7bd0f8c296d448a363dcea9aa35a2fb82e54e3 | [] | no_license | YacoobHolden/new-merchant-quote-service | https://github.com/YacoobHolden/new-merchant-quote-service | 0063fd5e23d80facc6bd7b7f3a4ce7f2d21b9513 | 133941261aa3b8c1a226f3f1df48eb813175a9d3 | refs/heads/master | 2023-01-22T13:19:29.670000 | 2020-12-09T19:43:42 | 2020-12-09T19:43:42 | 319,559,632 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package nz.co.smartpay.service;
import nz.co.smartpay.csv.CSVReader;
import nz.co.smartpay.csv.CSVRow;
import nz.co.smartpay.orm.model.TerminalPricing;
import nz.co.smartpay.orm.model.TransactionCountPricing;
import nz.co.smartpay.orm.model.TransactionVolumePricing;
import nz.co.smartpay.orm.repository.TerminalPricingRepository;
import nz.co.smartpay.orm.repository.TransactionCountPricingRepository;
import nz.co.smartpay.orm.repository.TransactionVolumePricingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.transaction.Transactional;
import java.util.List;
@Service
public class CSVService {
private CSVReader reader;
private TerminalPricingRepository terminalPricingRepository;
private TransactionCountPricingRepository transactionCountPricingRepository;
private TransactionVolumePricingRepository transactionVolumePricingRepository;
@Autowired
public CSVService(CSVReader reader,
TerminalPricingRepository terminalPricingRepository,
TransactionCountPricingRepository transactionCountPricingRepository,
TransactionVolumePricingRepository transactionVolumePricingRepository) {
this.terminalPricingRepository = terminalPricingRepository;
this.transactionCountPricingRepository = transactionCountPricingRepository;
this.transactionVolumePricingRepository = transactionVolumePricingRepository;
this.reader = reader;
}
@Transactional
public void updateCSV(MultipartFile file) throws Exception {
List<CSVRow> csvRows = reader.readCSVRowsFromFile(file);
// @ todo - Insert in one insert statement
for (CSVRow row : csvRows) {
// Add new terminal entry
if (CSVRow.RowType.TERMINAL.equals(row.getRowType())) {
// Check existing
TerminalPricing existing = terminalPricingRepository.findByIndustry(row.getIndustry());
if (existing != null) {
existing.setPrice(row.getPrice());
terminalPricingRepository.save(existing);
continue;
}
// Otherwise save new row
TerminalPricing pricing = TerminalPricing.builder()
.industry(row.getIndustry())
.price(row.getPrice())
.build();
terminalPricingRepository.save(pricing);
} else if (CSVRow.RowType.TRANSACTION_COUNT.equals(row.getRowType())) {
// Add new transaction count entry
// Check existing
TransactionCountPricing existing = transactionCountPricingRepository.findByIndustryAndCount(row.getIndustry(), row.getValue().longValue());
if (existing != null) {
existing.setPrice(row.getPrice());
transactionCountPricingRepository.save(existing);
continue;
}
// Otherwise save new row
TransactionCountPricing pricing = TransactionCountPricing.builder()
.industry(row.getIndustry())
.transactionCount(row.getValue().longValue())
.price(row.getPrice())
.build();
transactionCountPricingRepository.save(pricing);
} else if (CSVRow.RowType.TRANSACTION_VOLUME.equals(row.getRowType())) {
// Add new transaction volume entry
// Check existing
TransactionVolumePricing existing = transactionVolumePricingRepository.findByIndustryAndVolume(row.getIndustry(), row.getValue());
if (existing != null) {
existing.setPrice(row.getPrice());
transactionVolumePricingRepository.save(existing);
continue;
}
// Otherwise save new row
TransactionVolumePricing pricing = TransactionVolumePricing.builder()
.industry(row.getIndustry())
.transactionVolume(row.getValue())
.price(row.getPrice())
.build();
transactionVolumePricingRepository.save(pricing);
}
}
}
}
| UTF-8 | Java | 4,469 | java | CSVService.java | Java | [] | null | [] | package nz.co.smartpay.service;
import nz.co.smartpay.csv.CSVReader;
import nz.co.smartpay.csv.CSVRow;
import nz.co.smartpay.orm.model.TerminalPricing;
import nz.co.smartpay.orm.model.TransactionCountPricing;
import nz.co.smartpay.orm.model.TransactionVolumePricing;
import nz.co.smartpay.orm.repository.TerminalPricingRepository;
import nz.co.smartpay.orm.repository.TransactionCountPricingRepository;
import nz.co.smartpay.orm.repository.TransactionVolumePricingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.transaction.Transactional;
import java.util.List;
@Service
public class CSVService {
private CSVReader reader;
private TerminalPricingRepository terminalPricingRepository;
private TransactionCountPricingRepository transactionCountPricingRepository;
private TransactionVolumePricingRepository transactionVolumePricingRepository;
@Autowired
public CSVService(CSVReader reader,
TerminalPricingRepository terminalPricingRepository,
TransactionCountPricingRepository transactionCountPricingRepository,
TransactionVolumePricingRepository transactionVolumePricingRepository) {
this.terminalPricingRepository = terminalPricingRepository;
this.transactionCountPricingRepository = transactionCountPricingRepository;
this.transactionVolumePricingRepository = transactionVolumePricingRepository;
this.reader = reader;
}
@Transactional
public void updateCSV(MultipartFile file) throws Exception {
List<CSVRow> csvRows = reader.readCSVRowsFromFile(file);
// @ todo - Insert in one insert statement
for (CSVRow row : csvRows) {
// Add new terminal entry
if (CSVRow.RowType.TERMINAL.equals(row.getRowType())) {
// Check existing
TerminalPricing existing = terminalPricingRepository.findByIndustry(row.getIndustry());
if (existing != null) {
existing.setPrice(row.getPrice());
terminalPricingRepository.save(existing);
continue;
}
// Otherwise save new row
TerminalPricing pricing = TerminalPricing.builder()
.industry(row.getIndustry())
.price(row.getPrice())
.build();
terminalPricingRepository.save(pricing);
} else if (CSVRow.RowType.TRANSACTION_COUNT.equals(row.getRowType())) {
// Add new transaction count entry
// Check existing
TransactionCountPricing existing = transactionCountPricingRepository.findByIndustryAndCount(row.getIndustry(), row.getValue().longValue());
if (existing != null) {
existing.setPrice(row.getPrice());
transactionCountPricingRepository.save(existing);
continue;
}
// Otherwise save new row
TransactionCountPricing pricing = TransactionCountPricing.builder()
.industry(row.getIndustry())
.transactionCount(row.getValue().longValue())
.price(row.getPrice())
.build();
transactionCountPricingRepository.save(pricing);
} else if (CSVRow.RowType.TRANSACTION_VOLUME.equals(row.getRowType())) {
// Add new transaction volume entry
// Check existing
TransactionVolumePricing existing = transactionVolumePricingRepository.findByIndustryAndVolume(row.getIndustry(), row.getValue());
if (existing != null) {
existing.setPrice(row.getPrice());
transactionVolumePricingRepository.save(existing);
continue;
}
// Otherwise save new row
TransactionVolumePricing pricing = TransactionVolumePricing.builder()
.industry(row.getIndustry())
.transactionVolume(row.getValue())
.price(row.getPrice())
.build();
transactionVolumePricingRepository.save(pricing);
}
}
}
}
| 4,469 | 0.636832 | 0.636832 | 95 | 46.042107 | 30.074614 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.484211 | false | false | 12 |
0341a49111ef797a13fa65765e4447bd843f5a15 | 10,496,900,094,142 | cec90f56a1ef1bad510aa80da8c498c10ef265e6 | /src/main/java/com/the151suggestions/part6/s91/IdentifierEnum.java | c6ddb1bfd83e40f7f72d474160a1f833f6c15c1c | [
"Apache-2.0"
] | permissive | kangangithub/The151Suggestions | https://github.com/kangangithub/The151Suggestions | 3e3a775e902f048e446992960bacda242ceb0400 | 6ce875622e9fb36a49cca66ff2631fbca3388d0a | refs/heads/master | 2019-01-23T06:29:47.797000 | 2017-08-23T13:45:42 | 2017-08-23T13:45:42 | 86,223,182 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.the151suggestions.part6.s91;
/**
* 定义枚举,结合权限级别,鉴权方法
* Created by ankang on 2017-08-16.
*/
public enum IdentifierEnum implements Identifier {
GUEST, USER, ADMIN; //权限级别
@Override
public boolean identify(IdentifierEnum identifierEnum) { //鉴权方法
switch (identifierEnum) {
case GUEST:
return false;
case USER:
return true;
case ADMIN:
return true;
default:
throw new AssertionError("执行到此处就出错");
}
}
}
| UTF-8 | Java | 617 | java | IdentifierEnum.java | Java | [
{
"context": ".part6.s91;\n\n/**\n * 定义枚举,结合权限级别,鉴权方法\n * Created by ankang on 2017-08-16.\n */\npublic enum IdentifierEnum imp",
"end": 86,
"score": 0.9975417256355286,
"start": 80,
"tag": "USERNAME",
"value": "ankang"
}
] | null | [] | package com.the151suggestions.part6.s91;
/**
* 定义枚举,结合权限级别,鉴权方法
* Created by ankang on 2017-08-16.
*/
public enum IdentifierEnum implements Identifier {
GUEST, USER, ADMIN; //权限级别
@Override
public boolean identify(IdentifierEnum identifierEnum) { //鉴权方法
switch (identifierEnum) {
case GUEST:
return false;
case USER:
return true;
case ADMIN:
return true;
default:
throw new AssertionError("执行到此处就出错");
}
}
}
| 617 | 0.558348 | 0.533214 | 23 | 23.217392 | 17.717485 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false | 12 |
1b8e108ef60fb87009737df150d25ee746c5b4af | 29,411,936,105,919 | 9d32980f5989cd4c55cea498af5d6a413e08b7a2 | /A92s_10_0_0/src/main/java/com/android/framework/protobuf/nano/android/ParcelableMessageNanoCreator.java | 57fe537532a0a0f78e30c9250d905fcdfe9b25ae | [] | no_license | liuhaosource/OppoFramework | https://github.com/liuhaosource/OppoFramework | e7cc3bcd16958f809eec624b9921043cde30c831 | ebe39acabf5eae49f5f991c5ce677d62b683f1b6 | refs/heads/master | 2023-06-03T23:06:17.572000 | 2020-11-30T08:40:07 | 2020-11-30T08:40:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.android.framework.protobuf.nano.android;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import com.android.framework.protobuf.nano.InvalidProtocolBufferNanoException;
import com.android.framework.protobuf.nano.MessageNano;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
public final class ParcelableMessageNanoCreator<T extends MessageNano> implements Parcelable.Creator<T> {
private static final String TAG = "PMNCreator";
private final Class<T> mClazz;
public ParcelableMessageNanoCreator(Class<T> clazz) {
this.mClazz = clazz;
}
@Override // android.os.Parcelable.Creator
public T createFromParcel(Parcel in) {
String className = in.readString();
byte[] data = in.createByteArray();
T proto = null;
try {
proto = (MessageNano) Class.forName(className, false, getClass().getClassLoader()).asSubclass(MessageNano.class).getConstructor(new Class[0]).newInstance(new Object[0]);
MessageNano.mergeFrom(proto, data);
return proto;
} catch (ClassNotFoundException e) {
Log.e(TAG, "Exception trying to create proto from parcel", e);
return proto;
} catch (NoSuchMethodException e2) {
Log.e(TAG, "Exception trying to create proto from parcel", e2);
return proto;
} catch (InvocationTargetException e3) {
Log.e(TAG, "Exception trying to create proto from parcel", e3);
return proto;
} catch (IllegalAccessException e4) {
Log.e(TAG, "Exception trying to create proto from parcel", e4);
return proto;
} catch (InstantiationException e5) {
Log.e(TAG, "Exception trying to create proto from parcel", e5);
return proto;
} catch (InvalidProtocolBufferNanoException e6) {
Log.e(TAG, "Exception trying to create proto from parcel", e6);
return proto;
}
}
/* JADX DEBUG: Failed to find minimal casts for resolve overloaded methods, cast all args instead
method: ClspMth{java.lang.reflect.Array.newInstance(java.lang.Class<?>, int):java.lang.Object throws java.lang.NegativeArraySizeException}
arg types: [java.lang.Class<T>, int]
candidates:
ClspMth{java.lang.reflect.Array.newInstance(java.lang.Class<?>, int[]):java.lang.Object VARARG throws java.lang.IllegalArgumentException, java.lang.NegativeArraySizeException}
ClspMth{java.lang.reflect.Array.newInstance(java.lang.Class<?>, int):java.lang.Object throws java.lang.NegativeArraySizeException} */
@Override // android.os.Parcelable.Creator
public T[] newArray(int i) {
return (MessageNano[]) Array.newInstance((Class<?>) this.mClazz, i);
}
static <T extends MessageNano> void writeToParcel(Class<T> clazz, MessageNano message, Parcel out) {
out.writeString(clazz.getName());
out.writeByteArray(MessageNano.toByteArray(message));
}
}
| UTF-8 | Java | 3,040 | java | ParcelableMessageNanoCreator.java | Java | [] | null | [] | package com.android.framework.protobuf.nano.android;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import com.android.framework.protobuf.nano.InvalidProtocolBufferNanoException;
import com.android.framework.protobuf.nano.MessageNano;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
public final class ParcelableMessageNanoCreator<T extends MessageNano> implements Parcelable.Creator<T> {
private static final String TAG = "PMNCreator";
private final Class<T> mClazz;
public ParcelableMessageNanoCreator(Class<T> clazz) {
this.mClazz = clazz;
}
@Override // android.os.Parcelable.Creator
public T createFromParcel(Parcel in) {
String className = in.readString();
byte[] data = in.createByteArray();
T proto = null;
try {
proto = (MessageNano) Class.forName(className, false, getClass().getClassLoader()).asSubclass(MessageNano.class).getConstructor(new Class[0]).newInstance(new Object[0]);
MessageNano.mergeFrom(proto, data);
return proto;
} catch (ClassNotFoundException e) {
Log.e(TAG, "Exception trying to create proto from parcel", e);
return proto;
} catch (NoSuchMethodException e2) {
Log.e(TAG, "Exception trying to create proto from parcel", e2);
return proto;
} catch (InvocationTargetException e3) {
Log.e(TAG, "Exception trying to create proto from parcel", e3);
return proto;
} catch (IllegalAccessException e4) {
Log.e(TAG, "Exception trying to create proto from parcel", e4);
return proto;
} catch (InstantiationException e5) {
Log.e(TAG, "Exception trying to create proto from parcel", e5);
return proto;
} catch (InvalidProtocolBufferNanoException e6) {
Log.e(TAG, "Exception trying to create proto from parcel", e6);
return proto;
}
}
/* JADX DEBUG: Failed to find minimal casts for resolve overloaded methods, cast all args instead
method: ClspMth{java.lang.reflect.Array.newInstance(java.lang.Class<?>, int):java.lang.Object throws java.lang.NegativeArraySizeException}
arg types: [java.lang.Class<T>, int]
candidates:
ClspMth{java.lang.reflect.Array.newInstance(java.lang.Class<?>, int[]):java.lang.Object VARARG throws java.lang.IllegalArgumentException, java.lang.NegativeArraySizeException}
ClspMth{java.lang.reflect.Array.newInstance(java.lang.Class<?>, int):java.lang.Object throws java.lang.NegativeArraySizeException} */
@Override // android.os.Parcelable.Creator
public T[] newArray(int i) {
return (MessageNano[]) Array.newInstance((Class<?>) this.mClazz, i);
}
static <T extends MessageNano> void writeToParcel(Class<T> clazz, MessageNano message, Parcel out) {
out.writeString(clazz.getName());
out.writeByteArray(MessageNano.toByteArray(message));
}
}
| 3,040 | 0.686513 | 0.682566 | 64 | 46.5 | 40.025383 | 181 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.875 | false | false | 12 |
2d1c6d4cb93d76405dffbb942308f748f96d35cf | 10,642,928,978,614 | f86e1065d68b37de01687fca54c444eb85079485 | /src/ui/JTextPane1.java | 3c89288c203c7556ac0e5f291a16f3851edb2a2e | [] | no_license | 667521lxc/Softare-Design3 | https://github.com/667521lxc/Softare-Design3 | 20bc2c149661d13793d4f743c9fa8eafd3bb27ee | b521948273593ebd0f5978b60721696cb344f770 | refs/heads/master | 2020-06-01T09:31:12.181000 | 2019-06-08T12:24:53 | 2019-06-08T12:24:53 | 190,732,323 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ui;
/**
* 聊天消息框使用此类实现,主要是两个方法:setBlack_Bold_20和setBlue_Italic_Bold_22设置字体
* 对齐还要改
*/
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class JTextPane1{
public JTextPane textPane;
public JTextPane1(){
textPane=new JTextPane();
textPane.setBackground(Color.white);
textPane.setEditable(false);
}
public void setBlack_Bold_20(String str){
SimpleAttributeSet attrset=new SimpleAttributeSet();
//StyleConstants.setAlignment(attrset, StyleConstants.ALIGN_RIGHT);
StyleConstants.setForeground(attrset,Color.black);
StyleConstants.setBold(attrset,true);
StyleConstants.setFontSize(attrset,14);
//StyleConstants.setAlignment(attrset, StyleConstants.ALIGN_LEFT);
insert(str,attrset);
}
public void setBlue_Italic_Bold_22(String str){
SimpleAttributeSet attrset=new SimpleAttributeSet();
//StyleConstants.setAlignment(attrset, StyleConstants.ALIGN_RIGHT);
StyleConstants.setForeground(attrset,Color.blue);
StyleConstants.setFontSize(attrset,17);
insert(str,attrset);
}
//这个方法最主要的用途是将字符串插入到JTextPane中。
public void insert(String str,AttributeSet attrset){
Document docs=textPane.getDocument();//利用getDocument()方法取得JTextPane的Document instance.0
str=str+"\n";
try{
docs.insertString(docs.getLength(),str,attrset);
}catch(BadLocationException ble){
System.out.println("BadLocationException:"+ble);
}
}
} | UTF-8 | Java | 1,549 | java | JTextPane1.java | Java | [] | null | [] | package ui;
/**
* 聊天消息框使用此类实现,主要是两个方法:setBlack_Bold_20和setBlue_Italic_Bold_22设置字体
* 对齐还要改
*/
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class JTextPane1{
public JTextPane textPane;
public JTextPane1(){
textPane=new JTextPane();
textPane.setBackground(Color.white);
textPane.setEditable(false);
}
public void setBlack_Bold_20(String str){
SimpleAttributeSet attrset=new SimpleAttributeSet();
//StyleConstants.setAlignment(attrset, StyleConstants.ALIGN_RIGHT);
StyleConstants.setForeground(attrset,Color.black);
StyleConstants.setBold(attrset,true);
StyleConstants.setFontSize(attrset,14);
//StyleConstants.setAlignment(attrset, StyleConstants.ALIGN_LEFT);
insert(str,attrset);
}
public void setBlue_Italic_Bold_22(String str){
SimpleAttributeSet attrset=new SimpleAttributeSet();
//StyleConstants.setAlignment(attrset, StyleConstants.ALIGN_RIGHT);
StyleConstants.setForeground(attrset,Color.blue);
StyleConstants.setFontSize(attrset,17);
insert(str,attrset);
}
//这个方法最主要的用途是将字符串插入到JTextPane中。
public void insert(String str,AttributeSet attrset){
Document docs=textPane.getDocument();//利用getDocument()方法取得JTextPane的Document instance.0
str=str+"\n";
try{
docs.insertString(docs.getLength(),str,attrset);
}catch(BadLocationException ble){
System.out.println("BadLocationException:"+ble);
}
}
} | 1,549 | 0.744948 | 0.734495 | 43 | 31.418604 | 23.160946 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.325581 | false | false | 12 |
c81adca03704317020788bbb918720673846d9ea | 1,271,310,370,529 | 67025111b03b9b5bef3bedcd9da0b0a6ed806e52 | /app/src/main/java/ir/artapps/tinyshop/model/ModelRepoInterface.java | 10a26a0efacdcfa85d210da82c92e20f36c416ea | [] | no_license | navidkom/TinyShop | https://github.com/navidkom/TinyShop | c073ea27545585cbbb607beefcd7a4f56669aef2 | 0520bd9ce78c49f2351afd1c4cae2e9aafd044a6 | refs/heads/master | 2020-04-27T18:56:58.372000 | 2019-03-09T17:57:37 | 2019-03-09T17:57:37 | 174,594,673 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ir.artapps.tinyshop.model;
import java.util.List;
import ir.artapps.tinyshop.model.entities.Category;
import ir.artapps.tinyshop.model.entities.Order;
import ir.artapps.tinyshop.model.entities.Product;
/**
* Created by navid on 09,March,2019
*/
public interface ModelRepoInterface {
List<Category> getCategories();
List<Product> getProducts(String categoryId);
List<Order> getOrders();
void addOrder(Order order);
}
| UTF-8 | Java | 448 | java | ModelRepoInterface.java | Java | [
{
"context": "inyshop.model.entities.Product;\n\n/**\n * Created by navid on 09,March,2019\n */\npublic interface ModelRepoIn",
"end": 235,
"score": 0.9958859086036682,
"start": 230,
"tag": "USERNAME",
"value": "navid"
}
] | null | [] | package ir.artapps.tinyshop.model;
import java.util.List;
import ir.artapps.tinyshop.model.entities.Category;
import ir.artapps.tinyshop.model.entities.Order;
import ir.artapps.tinyshop.model.entities.Product;
/**
* Created by navid on 09,March,2019
*/
public interface ModelRepoInterface {
List<Category> getCategories();
List<Product> getProducts(String categoryId);
List<Order> getOrders();
void addOrder(Order order);
}
| 448 | 0.754464 | 0.741071 | 20 | 21.4 | 19.925863 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55 | false | false | 12 |
5e2d616cafc97c3281d89d34bf915ed44f1cbc8d | 12,111,807,809,262 | d68b23a8af66b07f6e443e1ad485fa16150b0dc0 | /csharp-psi-impl/src/main/java/consulo/csharp/lang/impl/psi/source/CSharpTypeDefStatementImpl.java | 345663a72bac59dc93e1f0df4433a7d4e0f6d543 | [
"Apache-2.0"
] | permissive | consulo/consulo-csharp | https://github.com/consulo/consulo-csharp | 34e1f591b31411cfa4ac6b96e82522e5ffbf80ad | ccb078d27b4ba37be9bb3f2c258aad9fb152a640 | refs/heads/master | 2023-08-31T16:12:36.841000 | 2023-08-17T10:56:13 | 2023-08-17T10:56:13 | 21,350,424 | 51 | 9 | Apache-2.0 | false | 2023-01-01T16:33:23 | 2014-06-30T12:35:16 | 2022-05-13T07:07:55 | 2023-01-01T16:33:22 | 12,676 | 51 | 5 | 52 | Java | false | false | /*
* Copyright 2013-2017 consulo.io
*
* 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 consulo.csharp.lang.impl.psi.source;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import consulo.csharp.lang.impl.psi.CSharpStubElementSets;
import consulo.language.ast.ASTNode;
import org.jetbrains.annotations.NonNls;
import consulo.language.psi.PsiElement;
import consulo.language.psi.stub.EmptyStub;
import consulo.language.util.IncorrectOperationException;
import consulo.annotation.access.RequiredReadAction;
import consulo.csharp.lang.impl.psi.CSharpElementVisitor;
import consulo.csharp.lang.psi.CSharpIdentifier;
import consulo.csharp.lang.impl.psi.CSharpStubElements;
import consulo.csharp.lang.psi.CSharpTokens;
import consulo.csharp.lang.psi.CSharpTypeDefStatement;
import consulo.dotnet.psi.DotNetType;
import consulo.dotnet.psi.resolve.DotNetTypeRef;
/**
* @author VISTALL
* @since 11.02.14
*/
public class CSharpTypeDefStatementImpl extends CSharpStubElementImpl<EmptyStub<CSharpTypeDefStatement>> implements CSharpTypeDefStatement
{
public CSharpTypeDefStatementImpl(@Nonnull ASTNode node)
{
super(node);
}
public CSharpTypeDefStatementImpl(@Nonnull EmptyStub<CSharpTypeDefStatement> stub)
{
super(stub, CSharpStubElements.TYPE_DEF_STATEMENT);
}
@RequiredReadAction
@Nonnull
@Override
public PsiElement getUsingKeywordElement()
{
return findNotNullChildByType(CSharpTokens.USING_KEYWORD);
}
@Override
@RequiredReadAction
public String getName()
{
CSharpIdentifier nameIdentifier = getNameIdentifier();
return nameIdentifier == null ? null : nameIdentifier.getValue();
}
@Override
public void accept(@Nonnull CSharpElementVisitor visitor)
{
visitor.visitTypeDefStatement(this);
}
@Override
public PsiElement setName(@NonNls @Nonnull String s) throws IncorrectOperationException
{
return null;
}
@RequiredReadAction
@Override
@Nullable
public DotNetType getType()
{
return getStubOrPsiChildByIndex(CSharpStubElementSets.TYPE_SET, 0);
}
@RequiredReadAction
@Override
@Nonnull
public DotNetTypeRef toTypeRef()
{
DotNetType type = getType();
return type == null ? DotNetTypeRef.ERROR_TYPE : type.toTypeRef();
}
@Nullable
@Override
@RequiredReadAction
public CSharpIdentifier getNameIdentifier()
{
return getStubOrPsiChild(CSharpStubElements.IDENTIFIER);
}
@Nullable
@Override
@RequiredReadAction
public PsiElement getReferenceElement()
{
return getType();
}
@RequiredReadAction
@Override
public int getTextOffset()
{
PsiElement nameIdentifier = getNameIdentifier();
return nameIdentifier == null ? super.getTextOffset() : nameIdentifier.getTextOffset();
}
}
| UTF-8 | Java | 3,192 | java | CSharpTypeDefStatementImpl.java | Java | [
{
"context": ".dotnet.psi.resolve.DotNetTypeRef;\n\n/**\n * @author VISTALL\n * @since 11.02.14\n */\npublic class CSharpTypeDef",
"end": 1415,
"score": 0.9963390231132507,
"start": 1408,
"tag": "NAME",
"value": "VISTALL"
}
] | null | [] | /*
* Copyright 2013-2017 consulo.io
*
* 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 consulo.csharp.lang.impl.psi.source;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import consulo.csharp.lang.impl.psi.CSharpStubElementSets;
import consulo.language.ast.ASTNode;
import org.jetbrains.annotations.NonNls;
import consulo.language.psi.PsiElement;
import consulo.language.psi.stub.EmptyStub;
import consulo.language.util.IncorrectOperationException;
import consulo.annotation.access.RequiredReadAction;
import consulo.csharp.lang.impl.psi.CSharpElementVisitor;
import consulo.csharp.lang.psi.CSharpIdentifier;
import consulo.csharp.lang.impl.psi.CSharpStubElements;
import consulo.csharp.lang.psi.CSharpTokens;
import consulo.csharp.lang.psi.CSharpTypeDefStatement;
import consulo.dotnet.psi.DotNetType;
import consulo.dotnet.psi.resolve.DotNetTypeRef;
/**
* @author VISTALL
* @since 11.02.14
*/
public class CSharpTypeDefStatementImpl extends CSharpStubElementImpl<EmptyStub<CSharpTypeDefStatement>> implements CSharpTypeDefStatement
{
public CSharpTypeDefStatementImpl(@Nonnull ASTNode node)
{
super(node);
}
public CSharpTypeDefStatementImpl(@Nonnull EmptyStub<CSharpTypeDefStatement> stub)
{
super(stub, CSharpStubElements.TYPE_DEF_STATEMENT);
}
@RequiredReadAction
@Nonnull
@Override
public PsiElement getUsingKeywordElement()
{
return findNotNullChildByType(CSharpTokens.USING_KEYWORD);
}
@Override
@RequiredReadAction
public String getName()
{
CSharpIdentifier nameIdentifier = getNameIdentifier();
return nameIdentifier == null ? null : nameIdentifier.getValue();
}
@Override
public void accept(@Nonnull CSharpElementVisitor visitor)
{
visitor.visitTypeDefStatement(this);
}
@Override
public PsiElement setName(@NonNls @Nonnull String s) throws IncorrectOperationException
{
return null;
}
@RequiredReadAction
@Override
@Nullable
public DotNetType getType()
{
return getStubOrPsiChildByIndex(CSharpStubElementSets.TYPE_SET, 0);
}
@RequiredReadAction
@Override
@Nonnull
public DotNetTypeRef toTypeRef()
{
DotNetType type = getType();
return type == null ? DotNetTypeRef.ERROR_TYPE : type.toTypeRef();
}
@Nullable
@Override
@RequiredReadAction
public CSharpIdentifier getNameIdentifier()
{
return getStubOrPsiChild(CSharpStubElements.IDENTIFIER);
}
@Nullable
@Override
@RequiredReadAction
public PsiElement getReferenceElement()
{
return getType();
}
@RequiredReadAction
@Override
public int getTextOffset()
{
PsiElement nameIdentifier = getNameIdentifier();
return nameIdentifier == null ? super.getTextOffset() : nameIdentifier.getTextOffset();
}
}
| 3,192 | 0.786654 | 0.780702 | 121 | 25.380165 | 26.929739 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.991736 | false | false | 12 |
aa11bbfe956c3075b75cb9af832af74281a0f6af | 12,111,807,810,606 | 69928da3bdac5c225336aedfb29a8bd6cd6200dc | /src/com/expense_recoder/util/Constants.java | 6fe34f617fb79b8ff350b6c117c52d346d5fdbdf | [] | no_license | RanaRanvijaySingh/Expense_Recoder | https://github.com/RanaRanvijaySingh/Expense_Recoder | 5dff6d6b1516c3eb390dab7a9073af6717ce3a21 | dc540d44d3e997c476bddf1ae8e8e37ef694cb69 | refs/heads/master | 2021-05-29T16:31:21.508000 | 2014-02-07T14:17:24 | 2014-02-07T14:17:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.expense_recoder.util;
public class Constants {
public final static int SPLASH_TIME = 2000;
public final static int TEXT_SIZE_TITLE = 20;
public final static int TEXT_SIZE_GENERAL = 18;
public final static int HEIGHT_EDIT_TEXT = 60;
public final static int WIDTH = 110;
public final static int NAMES = 0;
public final static int EVENTS = 1;
public static String NAME = "Name";
public static String EVENT = "Event";
public static String DATA = "Data";
public static final String SELECTED_TRIP = "Trip";
public static final float EDIT_TEXT_SIZE_GENERAL = 14;
public static boolean IS_ADDING_FIRST_TIME = true;
} | UTF-8 | Java | 636 | java | Constants.java | Java | [] | null | [] | package com.expense_recoder.util;
public class Constants {
public final static int SPLASH_TIME = 2000;
public final static int TEXT_SIZE_TITLE = 20;
public final static int TEXT_SIZE_GENERAL = 18;
public final static int HEIGHT_EDIT_TEXT = 60;
public final static int WIDTH = 110;
public final static int NAMES = 0;
public final static int EVENTS = 1;
public static String NAME = "Name";
public static String EVENT = "Event";
public static String DATA = "Data";
public static final String SELECTED_TRIP = "Trip";
public static final float EDIT_TEXT_SIZE_GENERAL = 14;
public static boolean IS_ADDING_FIRST_TIME = true;
} | 636 | 0.743711 | 0.716981 | 19 | 32.526318 | 18.184343 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.421053 | false | false | 12 |
9f83a98f4075a0b7315c673653dc1ed31cc63e8f | 30,709,016,235,545 | 536da3e7695677e6285f47846b8b70c072c7f392 | /third-test/src/main/java/com/java/thirdtest/Calculate/ThirTest.java | 07ea1fc5aacf055b9a97a2917280c17ee651e63c | [] | no_license | luobotee/luobote | https://github.com/luobotee/luobote | 476db45055973ad90b61f1394aa87d82c81a4bb0 | d830c6d34658b1725cbefb90ef290ae95085204d | refs/heads/master | 2023-06-06T07:32:34.041000 | 2021-06-17T06:03:54 | 2021-06-17T06:03:59 | 370,013,739 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.java.thirdtest.Calculate;
import com.java.thirdtest.entity.Thirtest;
import java.time.LocalDateTime;
public class ThirTest {
public static Thirtest calculate(Thirtest thirtest) {
Double eoc = thirtest.getEoc();
Double d = thirtest.getD();
Double a = thirtest.getA();
Double mel = thirtest.getMel();
Double sl = 20 * (Math.log10(eoc)) + 20 * Math.log10(d) - a - mel;
thirtest.setSl(sl);
LocalDateTime time = LocalDateTime.now();
thirtest.setDate(time);
return thirtest;
}
}
| UTF-8 | Java | 569 | java | ThirTest.java | Java | [] | null | [] | package com.java.thirdtest.Calculate;
import com.java.thirdtest.entity.Thirtest;
import java.time.LocalDateTime;
public class ThirTest {
public static Thirtest calculate(Thirtest thirtest) {
Double eoc = thirtest.getEoc();
Double d = thirtest.getD();
Double a = thirtest.getA();
Double mel = thirtest.getMel();
Double sl = 20 * (Math.log10(eoc)) + 20 * Math.log10(d) - a - mel;
thirtest.setSl(sl);
LocalDateTime time = LocalDateTime.now();
thirtest.setDate(time);
return thirtest;
}
}
| 569 | 0.636204 | 0.622144 | 20 | 27.450001 | 20.570549 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 12 |
953196abe694ffd9b1e8b404c24cb574c920d02a | 25,108,378,815,135 | 8946d7b1103c07bf45f0ae557f71de626bfb2a50 | /app/src/main/java/com/covid/ui/main/MainActivity.java | 11ea69644bc06ae415deaf70a7a4706c437f44a2 | [] | no_license | Mustafa-Muhamed-Mansour/Covid | https://github.com/Mustafa-Muhamed-Mansour/Covid | f8ea3d9fc2525ae2ccfd73587287a50049966c44 | 11a8c799dece0662adb23a7d6b105e2af61bf475 | refs/heads/master | 2023-09-01T14:07:59.836000 | 2021-10-09T12:45:12 | 2021-10-09T12:45:12 | 410,042,363 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.covid.ui.main;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import com.covid.R;
import com.covid.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity
{
private ActivityMainBinding activityMainBinding;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
}
} | UTF-8 | Java | 549 | java | MainActivity.java | Java | [] | null | [] | package com.covid.ui.main;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import com.covid.R;
import com.covid.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity
{
private ActivityMainBinding activityMainBinding;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
}
} | 549 | 0.785064 | 0.785064 | 23 | 22.913044 | 25.366724 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false | 12 |
3050741d6aa333dec751fcda7351927b3a268cf2 | 3,633,542,347,810 | 90d320aa661232a653e3652d8ac48b34ba2f22f0 | /src/ch7/Beetle.java | d800102631c5ab4087d9f0b40f681a5648dc5deb | [] | no_license | Broken-pants/ThinkingInJava | https://github.com/Broken-pants/ThinkingInJava | 871441e804b640664636093d5753f66d8c1f2b17 | 04e8de5e28a7c5d73a187b81017f7c12f371d10f | refs/heads/master | 2020-05-30T17:01:34.701000 | 2019-03-15T07:33:35 | 2019-03-15T07:33:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ch7;
import static net.mindview.util.Print.print;
class Insect{
private int i=9;
protected int j;
Insect() {
print("i="+i+" ,j="+j);
j = 39;
}
static int printInit(String s){
print(s);
return 47;
}
private static int x1 = printInit("static Insect.x1 initialized");
}
public class Beetle extends Insect{
private int k = printInit("Beetle.k initialized");
public Beetle(){
print("k="+k);
print("j="+j);
}
private static int x2 =printInit("static Beetle.x2 initialized");
public static void main(String[] args) {
print("Beetle constructor");
Beetle beetle = new Beetle();
}
}/* Output:
static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
i=9 ,j=0
Beetle.k initialized
k=47
j=39
*///£º~
| WINDOWS-1252 | Java | 788 | java | Beetle.java | Java | [] | null | [] | package ch7;
import static net.mindview.util.Print.print;
class Insect{
private int i=9;
protected int j;
Insect() {
print("i="+i+" ,j="+j);
j = 39;
}
static int printInit(String s){
print(s);
return 47;
}
private static int x1 = printInit("static Insect.x1 initialized");
}
public class Beetle extends Insect{
private int k = printInit("Beetle.k initialized");
public Beetle(){
print("k="+k);
print("j="+j);
}
private static int x2 =printInit("static Beetle.x2 initialized");
public static void main(String[] args) {
print("Beetle constructor");
Beetle beetle = new Beetle();
}
}/* Output:
static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
i=9 ,j=0
Beetle.k initialized
k=47
j=39
*///£º~
| 788 | 0.652672 | 0.629771 | 38 | 18.68421 | 17.218573 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.210526 | false | false | 12 |
4335e385b2a099f2b24757635e3b6a17deab7e3f | 16,363,825,423,698 | 48abaa3636916f9323668f981a4b6c8985f1d092 | /AD2015C2_Server/src/dominio/RemitoProvCC.java | f3395b66d629304954435b08f6a70a7296105c3b | [] | no_license | szapasil/AD2015C2 | https://github.com/szapasil/AD2015C2 | 3f8a44a753775af3c581f01fd6a0c7bccd9f2ade | 713e1ca39d39823e800bc69da104f31a132b4186 | refs/heads/master | 2020-12-24T14:53:07.895000 | 2015-12-14T18:11:28 | 2015-12-14T18:11:28 | 40,509,236 | 0 | 1 | null | false | 2015-12-14T18:11:29 | 2015-08-10T22:30:06 | 2015-08-30T17:55:26 | 2015-12-14T18:11:28 | 5,446 | 0 | 1 | 0 | Java | null | null | package dominio;
import hbt.HibernateDAO;
import java.io.IOException;
import java.rmi.RemoteException;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import app.CC;
import entities.ItemRPCCENT;
import entities.OrdenDeCompraENT;
import entities.RemitoProvCCENT;
public class RemitoProvCC {
private int numero;
private Proveedor proveedor;
private Date fecha;
private List<OrdenDeCompra> ordenesDeCompra;
private List<ItemRPCC> items;
public RemitoProvCC(int numero, Proveedor proveedor, Date fecha) {
super();
this.numero = numero;
this.proveedor = proveedor;
this.fecha = fecha;
this.ordenesDeCompra = new ArrayList<OrdenDeCompra>();
this.items = new ArrayList<ItemRPCC>();
}
public RemitoProvCC() {
}
public int getNumero() {
return numero;
}
public void setNumero(int numero) {
this.numero = numero;
}
public Proveedor getProveedor() {
return proveedor;
}
public void setProveedor(Proveedor proveedor) {
this.proveedor = proveedor;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public List<OrdenDeCompra> getOrdenesDeCompra() {
return ordenesDeCompra;
}
public void setOrdenesDeCompra(List<OrdenDeCompra> ordenesDeCompra) {
this.ordenesDeCompra = ordenesDeCompra;
}
public List<ItemRPCC> getItems() {
return items;
}
public void setItems(List<ItemRPCC> items) {
this.items = items;
}
public void persistirse() {
RemitoProvCCENT rpccENT = toENT();
HibernateDAO.getInstancia().saveOrUpdate(rpccENT);
}
public RemitoProvCCENT toENT() {
List<ItemRPCCENT> itemsENT = new ArrayList<ItemRPCCENT>();
List<OrdenDeCompraENT> ocsENT = new ArrayList<OrdenDeCompraENT>();
RemitoProvCCENT rpccENT = new RemitoProvCCENT(numero, fecha, proveedor.toENT());
for (ItemRPCC item : items) {
itemsENT.add(item.toENT(rpccENT));
}
rpccENT.setItems(itemsENT);
for (OrdenDeCompra oc : ordenesDeCompra) {
ocsENT.add(oc.toENT());
// ocsENT.add(oc.toENT(rpccENT));?????????
}
rpccENT.setOrdenesDeCompra(ocsENT);
return rpccENT;
}
public static RemitoProvCC fromXML(String nombreArchivo) {
RemitoProvCC rpcc = new RemitoProvCC();
Document doc = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse(nombreArchivo);
NodeList nRPCC = doc.getElementsByTagName("RemitoProvCC");
for(int j=0;j < nRPCC.getLength(); j++){
if(nRPCC.item(j).hasChildNodes()){
Element eleRPCC = (Element)nRPCC.item(j);
rpcc.setNumero(Integer.parseInt(eleRPCC.getElementsByTagName("Numero").item(0).getTextContent()));
rpcc.setProveedor(CC.getInstancia().buscarProveedor(eleRPCC.getElementsByTagName("Proveedor").item(0).getTextContent()));
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date parsed = format.parse(eleRPCC.getElementsByTagName("Fecha").item(0).getTextContent());
rpcc.setFecha(new java.sql.Date(parsed.getTime()));
//OCs
NodeList nListOCs = doc.getElementsByTagName("OC");
rpcc.ordenesDeCompra = new ArrayList<OrdenDeCompra>();
for (int i=0;i < nListOCs.getLength(); i++){
if (nListOCs.item(i).hasChildNodes()){
Element eleOC = (Element)nListOCs.item(i);
OrdenDeCompra oc = CC.getInstancia().buscarOC(Integer.parseInt(eleOC.getElementsByTagName("NumeroOC").item(0).getTextContent()));
if(oc==null)
rpcc.ordenesDeCompra.add(oc);
else
System.out.println("La OC " + eleOC.getElementsByTagName("NumeroOC").item(0).getTextContent() + " no existe");
}
}
//Items
NodeList nListItems = doc.getElementsByTagName("Item");
rpcc.items = new ArrayList<ItemRPCC>();
for (int h=0;h < nListItems.getLength(); h++){
if (nListItems.item(h).hasChildNodes()){
Element eleItem = (Element)nListItems.item(h);
ItemRPCC irpcc = new ItemRPCC();
Rodamiento rod = CC.getInstancia().buscarRodamiento(eleItem.getElementsByTagName("CodRodamiento").item(0).getTextContent());
if(rod==null){
irpcc.setRodamiento(rod);
irpcc.setCantidad(Integer.parseInt(eleItem.getElementsByTagName("Cantidad").item(0).getTextContent()));
rpcc.items.add(irpcc);
}
else
System.out.println("El Rodamiento " + eleItem.getElementsByTagName("CodRodamiento").item(0).getTextContent() + " no existe");
}
}
// File f = new File(nombreArchivo); LUEGO PONER
// f.delete();
}
}
} catch (NumberFormatException e) {e.printStackTrace();
} catch (DOMException e) {e.printStackTrace();
} catch (RemoteException e) {e.printStackTrace();
} catch (ParserConfigurationException e) {e.printStackTrace();
} catch (SAXException e) {e.printStackTrace();
} catch (IOException e) {e.printStackTrace();
} catch (ParseException e) {e.printStackTrace();
} return rpcc;
}
}
| UTF-8 | Java | 5,528 | java | RemitoProvCC.java | Java | [
{
"context": "\r\n\t\t\t\t\t}\r\n//\t\t\t\t\tFile f = new File(nombreArchivo); LUEGO PONER\r\n//\t\t\t\t\tf.delete();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (Numb",
"end": 5089,
"score": 0.7638289928436279,
"start": 5078,
"tag": "NAME",
"value": "LUEGO PONER"
}
] | null | [] | package dominio;
import hbt.HibernateDAO;
import java.io.IOException;
import java.rmi.RemoteException;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import app.CC;
import entities.ItemRPCCENT;
import entities.OrdenDeCompraENT;
import entities.RemitoProvCCENT;
public class RemitoProvCC {
private int numero;
private Proveedor proveedor;
private Date fecha;
private List<OrdenDeCompra> ordenesDeCompra;
private List<ItemRPCC> items;
public RemitoProvCC(int numero, Proveedor proveedor, Date fecha) {
super();
this.numero = numero;
this.proveedor = proveedor;
this.fecha = fecha;
this.ordenesDeCompra = new ArrayList<OrdenDeCompra>();
this.items = new ArrayList<ItemRPCC>();
}
public RemitoProvCC() {
}
public int getNumero() {
return numero;
}
public void setNumero(int numero) {
this.numero = numero;
}
public Proveedor getProveedor() {
return proveedor;
}
public void setProveedor(Proveedor proveedor) {
this.proveedor = proveedor;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public List<OrdenDeCompra> getOrdenesDeCompra() {
return ordenesDeCompra;
}
public void setOrdenesDeCompra(List<OrdenDeCompra> ordenesDeCompra) {
this.ordenesDeCompra = ordenesDeCompra;
}
public List<ItemRPCC> getItems() {
return items;
}
public void setItems(List<ItemRPCC> items) {
this.items = items;
}
public void persistirse() {
RemitoProvCCENT rpccENT = toENT();
HibernateDAO.getInstancia().saveOrUpdate(rpccENT);
}
public RemitoProvCCENT toENT() {
List<ItemRPCCENT> itemsENT = new ArrayList<ItemRPCCENT>();
List<OrdenDeCompraENT> ocsENT = new ArrayList<OrdenDeCompraENT>();
RemitoProvCCENT rpccENT = new RemitoProvCCENT(numero, fecha, proveedor.toENT());
for (ItemRPCC item : items) {
itemsENT.add(item.toENT(rpccENT));
}
rpccENT.setItems(itemsENT);
for (OrdenDeCompra oc : ordenesDeCompra) {
ocsENT.add(oc.toENT());
// ocsENT.add(oc.toENT(rpccENT));?????????
}
rpccENT.setOrdenesDeCompra(ocsENT);
return rpccENT;
}
public static RemitoProvCC fromXML(String nombreArchivo) {
RemitoProvCC rpcc = new RemitoProvCC();
Document doc = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse(nombreArchivo);
NodeList nRPCC = doc.getElementsByTagName("RemitoProvCC");
for(int j=0;j < nRPCC.getLength(); j++){
if(nRPCC.item(j).hasChildNodes()){
Element eleRPCC = (Element)nRPCC.item(j);
rpcc.setNumero(Integer.parseInt(eleRPCC.getElementsByTagName("Numero").item(0).getTextContent()));
rpcc.setProveedor(CC.getInstancia().buscarProveedor(eleRPCC.getElementsByTagName("Proveedor").item(0).getTextContent()));
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date parsed = format.parse(eleRPCC.getElementsByTagName("Fecha").item(0).getTextContent());
rpcc.setFecha(new java.sql.Date(parsed.getTime()));
//OCs
NodeList nListOCs = doc.getElementsByTagName("OC");
rpcc.ordenesDeCompra = new ArrayList<OrdenDeCompra>();
for (int i=0;i < nListOCs.getLength(); i++){
if (nListOCs.item(i).hasChildNodes()){
Element eleOC = (Element)nListOCs.item(i);
OrdenDeCompra oc = CC.getInstancia().buscarOC(Integer.parseInt(eleOC.getElementsByTagName("NumeroOC").item(0).getTextContent()));
if(oc==null)
rpcc.ordenesDeCompra.add(oc);
else
System.out.println("La OC " + eleOC.getElementsByTagName("NumeroOC").item(0).getTextContent() + " no existe");
}
}
//Items
NodeList nListItems = doc.getElementsByTagName("Item");
rpcc.items = new ArrayList<ItemRPCC>();
for (int h=0;h < nListItems.getLength(); h++){
if (nListItems.item(h).hasChildNodes()){
Element eleItem = (Element)nListItems.item(h);
ItemRPCC irpcc = new ItemRPCC();
Rodamiento rod = CC.getInstancia().buscarRodamiento(eleItem.getElementsByTagName("CodRodamiento").item(0).getTextContent());
if(rod==null){
irpcc.setRodamiento(rod);
irpcc.setCantidad(Integer.parseInt(eleItem.getElementsByTagName("Cantidad").item(0).getTextContent()));
rpcc.items.add(irpcc);
}
else
System.out.println("El Rodamiento " + eleItem.getElementsByTagName("CodRodamiento").item(0).getTextContent() + " no existe");
}
}
// File f = new File(nombreArchivo); <NAME>
// f.delete();
}
}
} catch (NumberFormatException e) {e.printStackTrace();
} catch (DOMException e) {e.printStackTrace();
} catch (RemoteException e) {e.printStackTrace();
} catch (ParserConfigurationException e) {e.printStackTrace();
} catch (SAXException e) {e.printStackTrace();
} catch (IOException e) {e.printStackTrace();
} catch (ParseException e) {e.printStackTrace();
} return rpcc;
}
}
| 5,523 | 0.689942 | 0.687229 | 172 | 30.139534 | 28.483845 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.872093 | false | false | 12 |
1e3208e07e33a53db8fe383092c22d411d1dabc1 | 4,157,528,366,266 | 4b177266900d3607653e38f688378036118287a8 | /src/main/java/com/elephant/dao/uploadproduct/ProductDao.java | e1cde4341a07e6ec50bf384ae5803fc3c5c1ca35 | [] | no_license | vinuthasr/Ehaenterprise | https://github.com/vinuthasr/Ehaenterprise | 49af031c2a837ee60d4b2784844028210bfe3b28 | afbcab872c378001000e482bcc8f126a5497634a | refs/heads/master | 2022-07-07T17:59:20.778000 | 2019-12-26T08:54:33 | 2019-12-26T08:54:33 | 179,013,771 | 0 | 1 | null | false | 2022-06-30T20:17:09 | 2019-04-02T06:32:40 | 2019-12-26T08:54:44 | 2022-06-30T20:17:07 | 625 | 0 | 1 | 4 | Java | false | false | package com.elephant.dao.uploadproduct;
import java.util.List;
import com.elephant.domain.uploadproduct.BulkProduct;
import com.elephant.domain.uploadproduct.ProductDomain;
import com.elephant.model.uploadproduct.ProductModel1;
import com.elephant.response.Response;
public interface ProductDao {
// public List<ProductDomain> getProductByCatagory(String categoryName, String colors, Float discount, Double length, double min,double max, String materialType, String fabricPurity, String pattern, String border, String borderType, String zariType, String blouse, String blouseColor, Double blouseLength)throws Exception;
public Response addproduct(ProductDomain update)throws Exception;
public Response updateProduct(ProductDomain update)throws Exception;
public Response deleteproduct(String productId)throws Exception;
public Response deleteProduct(String productId, boolean isActive)throws Exception;
public Response save(ProductDomain update)throws Exception;
public ProductDomain getProductById(String productId)throws Exception;
public List<ProductDomain> getProductByDiscount(float discount)throws Exception;
public List<ProductDomain> uploadFile(List<ProductDomain> productuploadList)throws Exception;
public List<ProductDomain> getProductByColor(String colors)throws Exception;
public List<ProductDomain> getProductByOccassion(String occassion)throws Exception;
public List<ProductDomain> getProductByPrice(double price)throws Exception;
public List<ProductDomain> getProductByPriceRange(double minPrice, double maxPrice)throws Exception;
public List<ProductDomain> getProductByMaterialType(String materialType)throws Exception;
public List<ProductDomain> getProductByBorder(String border)throws Exception;
public List<ProductDomain> getProductByBorderType(String borderType)throws Exception;
public List<ProductDomain> getProductByZariType(String zariType)throws Exception;
public List<ProductDomain> getProductByBlouse(String blouse) throws Exception;
public List<ProductDomain> getProductByPattern(String pattern)throws Exception;
public List<ProductDomain> getProductByFabricPurity(String fabricPurity)throws Exception;
public List<ProductDomain> getProductByBlouseColor(String blouseColor)throws Exception;
public List<ProductDomain> getProductByBlouseLength(Double blouseLength)throws Exception;
public List<ProductDomain> getProductBySareeLength(Double length)throws Exception;
public List<ProductDomain> getProducts()throws Exception;
public List<ProductDomain> getProductByFilterDiscount(float discount)throws Exception;
public List<ProductDomain> getPriceSortingLowToHigh()throws Exception;
public List<ProductDomain> getPriceSortingHighToLow()throws Exception;
public List<ProductDomain> getProductByTypesSortingPriceLowToHigh(String types)throws Exception;
public List<ProductDomain> getProductByTypesSortingPriceHighToLow(String types)throws Exception;
public List<ProductDomain> getByNewProducts()throws Exception;
public List<ProductDomain> getProductBycategoryId(String categoryId)throws Exception;
public Response deleteproductByCategoryId(String categoryId, boolean isActive)throws Exception;
public List<ProductDomain> getProductsByPriceRange(String categoryName, double minPrice, double maxPrice)throws Exception;
public List<ProductDomain> getProductByCatagory1(ProductModel1 pm1);
public ProductDomain isSKUExist(String sku);
public Response saveBulkProduct(BulkProduct bulkProduct)throws Exception;
public Float[] getProductDiscounts();
public List<ProductDomain> getProductByName(String productName);
}
| UTF-8 | Java | 3,844 | java | ProductDao.java | Java | [] | null | [] | package com.elephant.dao.uploadproduct;
import java.util.List;
import com.elephant.domain.uploadproduct.BulkProduct;
import com.elephant.domain.uploadproduct.ProductDomain;
import com.elephant.model.uploadproduct.ProductModel1;
import com.elephant.response.Response;
public interface ProductDao {
// public List<ProductDomain> getProductByCatagory(String categoryName, String colors, Float discount, Double length, double min,double max, String materialType, String fabricPurity, String pattern, String border, String borderType, String zariType, String blouse, String blouseColor, Double blouseLength)throws Exception;
public Response addproduct(ProductDomain update)throws Exception;
public Response updateProduct(ProductDomain update)throws Exception;
public Response deleteproduct(String productId)throws Exception;
public Response deleteProduct(String productId, boolean isActive)throws Exception;
public Response save(ProductDomain update)throws Exception;
public ProductDomain getProductById(String productId)throws Exception;
public List<ProductDomain> getProductByDiscount(float discount)throws Exception;
public List<ProductDomain> uploadFile(List<ProductDomain> productuploadList)throws Exception;
public List<ProductDomain> getProductByColor(String colors)throws Exception;
public List<ProductDomain> getProductByOccassion(String occassion)throws Exception;
public List<ProductDomain> getProductByPrice(double price)throws Exception;
public List<ProductDomain> getProductByPriceRange(double minPrice, double maxPrice)throws Exception;
public List<ProductDomain> getProductByMaterialType(String materialType)throws Exception;
public List<ProductDomain> getProductByBorder(String border)throws Exception;
public List<ProductDomain> getProductByBorderType(String borderType)throws Exception;
public List<ProductDomain> getProductByZariType(String zariType)throws Exception;
public List<ProductDomain> getProductByBlouse(String blouse) throws Exception;
public List<ProductDomain> getProductByPattern(String pattern)throws Exception;
public List<ProductDomain> getProductByFabricPurity(String fabricPurity)throws Exception;
public List<ProductDomain> getProductByBlouseColor(String blouseColor)throws Exception;
public List<ProductDomain> getProductByBlouseLength(Double blouseLength)throws Exception;
public List<ProductDomain> getProductBySareeLength(Double length)throws Exception;
public List<ProductDomain> getProducts()throws Exception;
public List<ProductDomain> getProductByFilterDiscount(float discount)throws Exception;
public List<ProductDomain> getPriceSortingLowToHigh()throws Exception;
public List<ProductDomain> getPriceSortingHighToLow()throws Exception;
public List<ProductDomain> getProductByTypesSortingPriceLowToHigh(String types)throws Exception;
public List<ProductDomain> getProductByTypesSortingPriceHighToLow(String types)throws Exception;
public List<ProductDomain> getByNewProducts()throws Exception;
public List<ProductDomain> getProductBycategoryId(String categoryId)throws Exception;
public Response deleteproductByCategoryId(String categoryId, boolean isActive)throws Exception;
public List<ProductDomain> getProductsByPriceRange(String categoryName, double minPrice, double maxPrice)throws Exception;
public List<ProductDomain> getProductByCatagory1(ProductModel1 pm1);
public ProductDomain isSKUExist(String sku);
public Response saveBulkProduct(BulkProduct bulkProduct)throws Exception;
public Float[] getProductDiscounts();
public List<ProductDomain> getProductByName(String productName);
}
| 3,844 | 0.799948 | 0.798907 | 157 | 22.484076 | 41.916145 | 322 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.66879 | false | false | 12 |
832f21ee088db301b8658ba6f960f0a6ba549163 | 4,157,528,368,130 | 1a02bd5d554b51b6cb55f279b59617eae1b4cfce | /Pro52.java | 81bf81f1bb22b49fe2e566c2471aea9696d8f396 | [] | no_license | guvian/make-green | https://github.com/guvian/make-green | e091170a06857ed363dbe70c7f3f73675082d4f6 | f773cac57927fed58edd64e173cb86605dc7e9e1 | refs/heads/master | 2020-05-22T01:38:45.437000 | 2017-03-07T04:07:22 | 2017-03-07T04:07:22 | 61,716,921 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class Pro52 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] a = new int[8];
System.out.println("Enter the four Co_ordinates(8 values) :");
for (int i = 0; i < a.length; i++) {
a[i] = scanner.nextInt();
}
for (int j = 2; j < a.length; j = j + 2) {
if (a[0] / a[j] == 1) {
int temp = a[2];
int temp1 = a[3];
a[2] = a[j];
a[3] = a[j + 1];
a[j] = temp;
a[j + 1] = temp1;
}
}
int p = Math.abs(a[1] - a[3]);
int q = Math.abs(a[5] - a[7]);
int r = Math.abs(a[2] - a[4]);
int s = Math.abs(a[0] - a[6]);
if (p == q && p == r && p == s) {
System.out.println("The given Co_ordinates forms a square.");
} else {
System.out.println("The given Co_ordinates does not forms a square.");
}
scanner.close();
}
}
| UTF-8 | Java | 842 | java | Pro52.java | Java | [] | null | [] | import java.util.Scanner;
public class Pro52 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] a = new int[8];
System.out.println("Enter the four Co_ordinates(8 values) :");
for (int i = 0; i < a.length; i++) {
a[i] = scanner.nextInt();
}
for (int j = 2; j < a.length; j = j + 2) {
if (a[0] / a[j] == 1) {
int temp = a[2];
int temp1 = a[3];
a[2] = a[j];
a[3] = a[j + 1];
a[j] = temp;
a[j + 1] = temp1;
}
}
int p = Math.abs(a[1] - a[3]);
int q = Math.abs(a[5] - a[7]);
int r = Math.abs(a[2] - a[4]);
int s = Math.abs(a[0] - a[6]);
if (p == q && p == r && p == s) {
System.out.println("The given Co_ordinates forms a square.");
} else {
System.out.println("The given Co_ordinates does not forms a square.");
}
scanner.close();
}
}
| 842 | 0.524941 | 0.495249 | 32 | 25.3125 | 18.480459 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.90625 | false | false | 12 |
55046ab9d0900fc50426bc464ecee77f805b27d7 | 29,996,051,608,016 | aa0b62c30de6061e262d8aa7984fe62c4196c796 | /Status.java | 7b4b4b0b2c59027168e7a70a97860f33b6a6985f | [] | no_license | TretornESP/WebServer | https://github.com/TretornESP/WebServer | 11403cd1e45c36554e3c564b711cfc73794f627a | e42c7f00a1d7afea684843f882fbc72c8dd05199 | refs/heads/master | 2020-04-30T20:00:39.284000 | 2019-03-22T02:01:38 | 2019-03-22T02:01:38 | 177,054,402 | 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 webserver;
/**
*
* @author xabie
*/
public enum Status {
OK("200 OK", 200), BAD_REQUEST("400 Bad Request", 400), FORBIDDEN("403 Forbidden", 403), NOT_FOUND("404 Not Found", 404), NOT_MODIFIED("304 Not Modified", 304);
private final String descr;
private final int code;
private Status(String descr, int code) {
this.descr = descr;
this.code = code;
}
@Override
public String toString() {
return descr;
}
public int getCode() {
return code;
}
}
| UTF-8 | Java | 754 | java | Status.java | Java | [
{
"context": "r.\r\n */\r\npackage webserver;\r\n\r\n/**\r\n *\r\n * @author xabie\r\n */\r\npublic enum Status {\r\n OK(\"200 OK\", 200)",
"end": 237,
"score": 0.999371349811554,
"start": 232,
"tag": "USERNAME",
"value": "xabie"
}
] | 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 webserver;
/**
*
* @author xabie
*/
public enum Status {
OK("200 OK", 200), BAD_REQUEST("400 Bad Request", 400), FORBIDDEN("403 Forbidden", 403), NOT_FOUND("404 Not Found", 404), NOT_MODIFIED("304 Not Modified", 304);
private final String descr;
private final int code;
private Status(String descr, int code) {
this.descr = descr;
this.code = code;
}
@Override
public String toString() {
return descr;
}
public int getCode() {
return code;
}
}
| 754 | 0.602122 | 0.562334 | 30 | 23.133333 | 31.906878 | 164 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false | 12 |
c44840192560b2e61624a36556072f4d40c13b1f | 22,660,247,482,165 | a067004baf39e0779f72228f7400b66d25e00846 | /learn-reactivespring/src/test/java/com/learnreactivespring/fluxandmonoplayground/CustomException.java | a41f05d931bdafed6d2c63408909b4dc81044764 | [] | no_license | humantornado9/reactivespring | https://github.com/humantornado9/reactivespring | 0a26f436374b7e09e48ab8c1b330d7af61ca6f9e | 46c3727b48c3331711239b00e6e523d483976991 | refs/heads/master | 2020-07-09T22:44:42.231000 | 2019-08-26T01:19:28 | 2019-08-26T01:19:28 | 204,098,923 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.learnreactivespring.fluxandmonoplayground;
public class CustomException extends Throwable {
private String errorMessage;
public CustomException(Throwable e) {
this.errorMessage = e.getMessage();
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
| UTF-8 | Java | 386 | java | CustomException.java | Java | [] | null | [] | package com.learnreactivespring.fluxandmonoplayground;
public class CustomException extends Throwable {
private String errorMessage;
public CustomException(Throwable e) {
this.errorMessage = e.getMessage();
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
| 386 | 0.753886 | 0.753886 | 18 | 20.444445 | 20.467379 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.277778 | false | false | 12 |
94ed8c214e986b946052bf88ee7e3cf6aac1eee7 | 7,430,293,448,427 | 89ce97f01414fdf5801604c6f61eb8b66fa1f70a | /regexgenerator/RegexGenerator/src/test/RegexTest.java | 902630c102a1400c4f5851de48380f2e128ca405 | [] | no_license | communityalex/RegexGenerator | https://github.com/communityalex/RegexGenerator | 4980b4f8e8766e531df4f44291f8b47572a19bf1 | 062f1227032baa03335aac6e3b03e581f6755ddb | refs/heads/master | 2016-06-13T20:39:43.104000 | 2016-04-21T02:53:52 | 2016-04-21T02:53:52 | 56,644,642 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package test;
import main.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
public class RegexTest {
RegexGenerator generator;
@Test
public void regexGenerator_multipleIncludesNoExcludes_correctRegex(){
generator = new RegexGenerator.Builder()
.include("A-Z", "a-z").qualifier(Regex.ZERO_OR_MORE_TIMES).add()
.build();
assertEquals("A-Za-z*?", generator.getRegex());
}
@Test
public void regexGenerator_multipleExcludesNoIncludes_correctRegex(){
generator = new RegexGenerator.Builder()
.exclude("A-Z", "a-z").add()
.build();
assertEquals("^A-Za-z", generator.getRegex());
}
@Test
public void regexGenerator_multipleIncludesForChars1To6_correctRegex(){
generator = new RegexGenerator.Builder()
.include(Regex.ALPHANUMERIC).forChars("1,5").add()
.build();
assertEquals("\\p{Alpha}{1,5}",generator.getRegex());
}
/*
@Test
public void regexGenerator_multipleIncludesForChar0To4_filterWorks(){
generator = new RegexGenerator.Builder()
.include("A-Z").qualifiers(Regex.ASTERISK).forChars("0,4").add()
.build();
System.out.println(generator.getRegex());
Pattern p = Pattern.compile(generator.getRegex());
Matcher m = p.matcher("AAAA");
assertTrue(m.matches());
}*/
@Test
public void regexGenerator_htmlTagChecker_correctRegex(){
generator = new RegexGenerator.Builder()
.include("<").add()
.include(Regex.ANY_CHARACTER).qualifier("+").group("initial").add()
.include(">").add()
.exclude("<", ">").qualifier("+").add()
.include("</").add()
.getGroup("initial").add()
.include(">").add()
.build();
assertEquals("<(.+)>^<>+</\\1>",generator.getRegex());
}
/*
@Test
public void regexGenerator_htmlTagChecker_correctFilter(){
generator = new RegexGenerator.Builder()
.include("<").add()
.include(Regex.ANY_CHARACTER).qualifier("+").group("initial").add()
.include(">").add()
.exclude("<", ">").qualifier("+").add()
.include("</").add()
.getGroup("initial").add()
.include(">").add()
.build();
Pattern p = Pattern.compile(generator.getRegex());
Matcher m = p.matcher("<tag>dataandstuff</tag>");
assertTrue(m.matches());
}*/
@Test
public void regexGenerator_multipleIncludesForAllChars_correctRegex(){
generator = new RegexGenerator.Builder()
.include("A-Z").forChars("1,5").add()
.include("a-z").forChars("5,6").add()
.include(Regex.WORD).exclude(Regex.DIGIT).add()
.build();
assertEquals("A-Z{1,5}a-z{5,6}\\w^\\d",generator.getRegex());
}
@Test
public void regexGenerator_multipleIncludesForAllChars_plainText(){
generator = new RegexGenerator.Builder()
.include("A-Z").forChars("1,5").add()
.build();
assertEquals("For characters 1 to 5:\n * Include: A-Z",generator.getRegexAsPlainText());
}
}
| UTF-8 | Java | 3,034 | java | RegexTest.java | Java | [] | null | [] | package test;
import main.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
public class RegexTest {
RegexGenerator generator;
@Test
public void regexGenerator_multipleIncludesNoExcludes_correctRegex(){
generator = new RegexGenerator.Builder()
.include("A-Z", "a-z").qualifier(Regex.ZERO_OR_MORE_TIMES).add()
.build();
assertEquals("A-Za-z*?", generator.getRegex());
}
@Test
public void regexGenerator_multipleExcludesNoIncludes_correctRegex(){
generator = new RegexGenerator.Builder()
.exclude("A-Z", "a-z").add()
.build();
assertEquals("^A-Za-z", generator.getRegex());
}
@Test
public void regexGenerator_multipleIncludesForChars1To6_correctRegex(){
generator = new RegexGenerator.Builder()
.include(Regex.ALPHANUMERIC).forChars("1,5").add()
.build();
assertEquals("\\p{Alpha}{1,5}",generator.getRegex());
}
/*
@Test
public void regexGenerator_multipleIncludesForChar0To4_filterWorks(){
generator = new RegexGenerator.Builder()
.include("A-Z").qualifiers(Regex.ASTERISK).forChars("0,4").add()
.build();
System.out.println(generator.getRegex());
Pattern p = Pattern.compile(generator.getRegex());
Matcher m = p.matcher("AAAA");
assertTrue(m.matches());
}*/
@Test
public void regexGenerator_htmlTagChecker_correctRegex(){
generator = new RegexGenerator.Builder()
.include("<").add()
.include(Regex.ANY_CHARACTER).qualifier("+").group("initial").add()
.include(">").add()
.exclude("<", ">").qualifier("+").add()
.include("</").add()
.getGroup("initial").add()
.include(">").add()
.build();
assertEquals("<(.+)>^<>+</\\1>",generator.getRegex());
}
/*
@Test
public void regexGenerator_htmlTagChecker_correctFilter(){
generator = new RegexGenerator.Builder()
.include("<").add()
.include(Regex.ANY_CHARACTER).qualifier("+").group("initial").add()
.include(">").add()
.exclude("<", ">").qualifier("+").add()
.include("</").add()
.getGroup("initial").add()
.include(">").add()
.build();
Pattern p = Pattern.compile(generator.getRegex());
Matcher m = p.matcher("<tag>dataandstuff</tag>");
assertTrue(m.matches());
}*/
@Test
public void regexGenerator_multipleIncludesForAllChars_correctRegex(){
generator = new RegexGenerator.Builder()
.include("A-Z").forChars("1,5").add()
.include("a-z").forChars("5,6").add()
.include(Regex.WORD).exclude(Regex.DIGIT).add()
.build();
assertEquals("A-Z{1,5}a-z{5,6}\\w^\\d",generator.getRegex());
}
@Test
public void regexGenerator_multipleIncludesForAllChars_plainText(){
generator = new RegexGenerator.Builder()
.include("A-Z").forChars("1,5").add()
.build();
assertEquals("For characters 1 to 5:\n * Include: A-Z",generator.getRegexAsPlainText());
}
}
| 3,034 | 0.642386 | 0.634806 | 104 | 27.173077 | 23.833736 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.394231 | false | false | 12 |
deba35c0cffe47180dcc06b66f2964529e34616d | 27,384,711,506,903 | b31d92f15714c87259fff56f7711a8a542bf3a17 | /sm_service/src/main/java/com/yuan/sm/service/SelfService.java | e25cb2eec179e6cc21dab19127da2bb8c8489ee2 | [] | no_license | linyuanpapapa/Spring-Mybatis-management | https://github.com/linyuanpapapa/Spring-Mybatis-management | b0a6684069f8fd1dd029c47b919bb616c2b1c03c | f4cf8dbb5d291753f715c93ced30d2070f877228 | refs/heads/master | 2022-06-29T19:21:40.662000 | 2020-01-31T11:35:40 | 2020-01-31T11:38:18 | 237,417,539 | 0 | 0 | null | false | 2022-06-21T02:43:22 | 2020-01-31T11:34:23 | 2020-01-31T11:39:18 | 2022-06-21T02:43:19 | 16,140 | 0 | 0 | 2 | Java | false | false | package com.yuan.sm.service;
import com.yuan.sm.entity.Staff;
public interface SelfService {
public Staff login(String account, String password);
public void editPassword(Integer id,String password);
}
| UTF-8 | Java | 212 | java | SelfService.java | Java | [] | null | [] | package com.yuan.sm.service;
import com.yuan.sm.entity.Staff;
public interface SelfService {
public Staff login(String account, String password);
public void editPassword(Integer id,String password);
}
| 212 | 0.768868 | 0.768868 | 8 | 25.5 | 22.056746 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 12 |
fe879da0049fbf6afc720b8d90fe1dc1faf31b9d | 16,149,077,061,398 | 711a0d42eabcb5f8a7ec9f6f7d487f93d1f7b35e | /Project_A/app/src/main/java/com/example/project_a/EventRecordAdapter.java | d207816295f4a3755955894c050131a89ee2e0cf | [] | no_license | wingkar/Project_A | https://github.com/wingkar/Project_A | 63212545ca1cb5f6b4d9cef34b5ede772379bef6 | 3235b8834f4c8a357136ada912db91e96d4ecac7 | refs/heads/master | 2022-11-18T19:09:37.760000 | 2020-06-29T01:01:38 | 2020-06-29T01:01:38 | 274,283,406 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.project_a;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class EventRecordAdapter extends RecyclerView.Adapter<EventRecordAdapter.ViewHolder> {
ArrayList<EventDTO> items = new ArrayList<>();
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.activity_event_record_item, parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
final EventDTO item = items.get(position);
holder.setItem(item);
holder.TextView1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
@Override
public int getItemCount() {
return items.size();
}
public void addItem(EventDTO item){
items.add(item);
}
public static class ViewHolder extends RecyclerView.ViewHolder{
TextView TextView1,TextView2,TextView3;
ImageView imageView;
LinearLayout parentLayout;
public ViewHolder(@NonNull View itemView) {
super(itemView);
TextView1 = itemView.findViewById(R.id.textView1);
TextView2 = itemView.findViewById(R.id.textView2);
TextView3 = itemView.findViewById(R.id.textView3);
imageView = itemView.findViewById(R.id.imageView);
parentLayout=itemView.findViewById(R.id.parentLayout);
}
public void setItem(EventDTO item){
TextView1.setText(item.getEvent1());
TextView2.setText(item.getEvent2());
TextView3.setText(item.getDate());
imageView.setImageResource(item.getResId());
}
}
}
| UTF-8 | Java | 2,350 | java | EventRecordAdapter.java | Java | [] | null | [] | package com.example.project_a;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class EventRecordAdapter extends RecyclerView.Adapter<EventRecordAdapter.ViewHolder> {
ArrayList<EventDTO> items = new ArrayList<>();
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.activity_event_record_item, parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
final EventDTO item = items.get(position);
holder.setItem(item);
holder.TextView1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
@Override
public int getItemCount() {
return items.size();
}
public void addItem(EventDTO item){
items.add(item);
}
public static class ViewHolder extends RecyclerView.ViewHolder{
TextView TextView1,TextView2,TextView3;
ImageView imageView;
LinearLayout parentLayout;
public ViewHolder(@NonNull View itemView) {
super(itemView);
TextView1 = itemView.findViewById(R.id.textView1);
TextView2 = itemView.findViewById(R.id.textView2);
TextView3 = itemView.findViewById(R.id.textView3);
imageView = itemView.findViewById(R.id.imageView);
parentLayout=itemView.findViewById(R.id.parentLayout);
}
public void setItem(EventDTO item){
TextView1.setText(item.getEvent1());
TextView2.setText(item.getEvent2());
TextView3.setText(item.getDate());
imageView.setImageResource(item.getResId());
}
}
}
| 2,350 | 0.664255 | 0.657872 | 80 | 28.375 | 26.138752 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4875 | false | false | 12 |
53c848f871e3d8e2e409755f35b36cd538a3381a | 2,963,527,459,372 | 0f896801af9784c77a0417fcbbae733cc029f506 | /src/com/ele/String/StringFormat.java | 63e194e228c4a03d1e386712d0a498066303ba71 | [] | no_license | elevenhome/core-java | https://github.com/elevenhome/core-java | 4ab0999ea9614ca9e7244a45722682b0a7ab0cd6 | 7176eb3730296001abb3524357f043282e67b99b | refs/heads/master | 2020-03-21T18:56:23.787000 | 2019-04-28T10:19:00 | 2019-04-28T10:19:00 | 138,921,908 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ele.String;
import java.net.URLEncoder;
/**
* @ClassName StringFormat
* @Description TODO
* @Author zzw
* @Date
*/
//String url = "http://open.ikanshu.cn/qxt/smspush.aspx?usercode=1004&code=8a7f91ebe3955347dd8af73fe437facb&phonenumber=" + phoneNumber + "&msg=" + URLEncoder.encode(msg, "UTF-8");
public class StringFormat {
public static void main(String[] args) throws Exception{
String templet = "【中文书城】您的验证码为:%s,请勿泄露。如非本人操作,请忽略此短信,谢谢!";
String checkNum = "123456";
String msg = String.format(templet, checkNum);
System.out.println(msg);
msg = URLEncoder.encode("您好", "UTF-8");
System.out.println(msg);
String phone = "15810490536";
String url = "http://open.ikanshu.cn/qxt/smspush.aspx?usercode=1004&code=8a7f91ebe3955347dd8af73fe437facb&phonenumber=%s&msg=%s";
System.out.println(String.format(url,phone,msg));
}
}
| UTF-8 | Java | 1,000 | java | StringFormat.java | Java | [
{
"context": "sName StringFormat\n * @Description TODO\n * @Author zzw\n * @Date\n */\n\n//String url = \"http://open.ikanshu",
"end": 120,
"score": 0.9997086524963379,
"start": 117,
"tag": "USERNAME",
"value": "zzw"
}
] | null | [] | package com.ele.String;
import java.net.URLEncoder;
/**
* @ClassName StringFormat
* @Description TODO
* @Author zzw
* @Date
*/
//String url = "http://open.ikanshu.cn/qxt/smspush.aspx?usercode=1004&code=8a7f91ebe3955347dd8af73fe437facb&phonenumber=" + phoneNumber + "&msg=" + URLEncoder.encode(msg, "UTF-8");
public class StringFormat {
public static void main(String[] args) throws Exception{
String templet = "【中文书城】您的验证码为:%s,请勿泄露。如非本人操作,请忽略此短信,谢谢!";
String checkNum = "123456";
String msg = String.format(templet, checkNum);
System.out.println(msg);
msg = URLEncoder.encode("您好", "UTF-8");
System.out.println(msg);
String phone = "15810490536";
String url = "http://open.ikanshu.cn/qxt/smspush.aspx?usercode=1004&code=8a7f91ebe3955347dd8af73fe437facb&phonenumber=%s&msg=%s";
System.out.println(String.format(url,phone,msg));
}
}
| 1,000 | 0.672078 | 0.606061 | 30 | 29.799999 | 40.35955 | 180 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.566667 | false | false | 12 |
2375d45752751fd59d43376769a8344b7ada6fcf | 2,963,527,458,504 | 5f0065aab6d0f440ad03c73712705534e478d1e0 | /src/main/java/com/springtranet/intranet/dao/impl/GrupoDAOImpl.java | c9709f00532b29adb163312fac68589aa313862a | [
"MIT"
] | permissive | DaniSancas/Springtranet | https://github.com/DaniSancas/Springtranet | 1e98212aa1511406a3cbbb89102c87f581966084 | e975a2bd5eb9a02a23519439185e3f32fbfa7af2 | refs/heads/master | 2016-09-15T17:01:10.358000 | 2016-03-10T17:29:10 | 2016-03-10T17:29:10 | 33,491,519 | 0 | 1 | null | false | 2016-03-10T17:29:10 | 2015-04-06T16:13:45 | 2015-04-20T14:41:58 | 2016-03-10T17:29:10 | 732 | 0 | 1 | 0 | CSS | null | null | package com.springtranet.intranet.dao.impl;
import java.util.List;
import org.hibernate.Criteria;
import org.springframework.stereotype.Repository;
import com.springtranet.intranet.dao.AbstractDAO;
import com.springtranet.intranet.dao.GrupoDAO;
import com.springtranet.intranet.model.Grupo;
@Repository
public class GrupoDAOImpl extends AbstractDAO implements GrupoDAO {
@Override
@SuppressWarnings("unchecked")
public List<Grupo> getAllGrupos() {
Criteria criteria = this.getCurrentSession().createCriteria(Grupo.class);
return criteria.list();
}
@Override
public Grupo getGrupo(long id) {
return (Grupo) this.getCurrentSession().get(Grupo.class, id);
}
@Override
public long save(Grupo grupo) {
return (Long) this.getCurrentSession().save(grupo);
}
@Override
public void update(Grupo grupo) {
this.getCurrentSession().merge(grupo);
}
@Override
public void delete(long id) {
Grupo grupo = getGrupo(id);
this.getCurrentSession().delete(grupo);
}
}
| UTF-8 | Java | 992 | java | GrupoDAOImpl.java | Java | [] | null | [] | package com.springtranet.intranet.dao.impl;
import java.util.List;
import org.hibernate.Criteria;
import org.springframework.stereotype.Repository;
import com.springtranet.intranet.dao.AbstractDAO;
import com.springtranet.intranet.dao.GrupoDAO;
import com.springtranet.intranet.model.Grupo;
@Repository
public class GrupoDAOImpl extends AbstractDAO implements GrupoDAO {
@Override
@SuppressWarnings("unchecked")
public List<Grupo> getAllGrupos() {
Criteria criteria = this.getCurrentSession().createCriteria(Grupo.class);
return criteria.list();
}
@Override
public Grupo getGrupo(long id) {
return (Grupo) this.getCurrentSession().get(Grupo.class, id);
}
@Override
public long save(Grupo grupo) {
return (Long) this.getCurrentSession().save(grupo);
}
@Override
public void update(Grupo grupo) {
this.getCurrentSession().merge(grupo);
}
@Override
public void delete(long id) {
Grupo grupo = getGrupo(id);
this.getCurrentSession().delete(grupo);
}
}
| 992 | 0.760081 | 0.760081 | 43 | 22.069767 | 21.781574 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.046512 | false | false | 12 |
a0fa7f234c39119c3815cd38bf7355ae5a609ff0 | 5,798,205,871,449 | d71c6cd308d1d69bbc049e6db58323e89093ae1f | /src/org/usfirst/frc/team2642/robot/subsystems/ArmWinch.java | 7fb71ec7c6a005e1e12392c305a66766850e1706 | [] | no_license | PCRpreseasonprep/Excalibot | https://github.com/PCRpreseasonprep/Excalibot | ea1ab4ffa34f6ae4fcb7b4707f3e9d4919a40e36 | 0067fc9d25fc8f393aaf88f4caba2ccb28c3113b | refs/heads/master | 2021-05-01T07:30:27.014000 | 2016-02-24T01:00:17 | 2016-02-24T01:00:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.usfirst.frc.team2642.robot.subsystems;
import org.usfirst.frc.team2642.robot.RobotMap;
import org.usfirst.frc.team2642.robot.commands.MoveBigArm;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
*/
public class ArmWinch extends Subsystem {
Relay bigarmwinch = new Relay(RobotMap.bigArmWinch);
public void raisearm(){
bigarmwinch.set(Relay.Value.kForward);
}
public void lowerarm(){
bigarmwinch.set(Relay.Value.kReverse);
}
public void idlearm(){
bigarmwinch.set(Relay.Value.kOff);
}
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand() {
setDefaultCommand(new MoveBigArm());
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
}
| UTF-8 | Java | 849 | java | ArmWinch.java | Java | [] | null | [] | package org.usfirst.frc.team2642.robot.subsystems;
import org.usfirst.frc.team2642.robot.RobotMap;
import org.usfirst.frc.team2642.robot.commands.MoveBigArm;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
*/
public class ArmWinch extends Subsystem {
Relay bigarmwinch = new Relay(RobotMap.bigArmWinch);
public void raisearm(){
bigarmwinch.set(Relay.Value.kForward);
}
public void lowerarm(){
bigarmwinch.set(Relay.Value.kReverse);
}
public void idlearm(){
bigarmwinch.set(Relay.Value.kOff);
}
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand() {
setDefaultCommand(new MoveBigArm());
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
}
| 849 | 0.727915 | 0.713781 | 32 | 25.5 | 21.10391 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.78125 | false | false | 12 |
edbf691e1f42a145ffc0542a165854e4a02e03e1 | 24,489,903,549,540 | 65ea4127afe0dd84023d3999cfd93db1cf3a67cc | /src/main/java/com/example/demo/entity/vo/StockAvgVo.java | 8e2e27e6841d91d8e23d53d7dff6f81adafec459 | [] | no_license | p78o233/ShareDemo | https://github.com/p78o233/ShareDemo | 70da6b987a551118ec06d87ccfc2a71e285608da | 1a766a6330e897265bd959c252ec0f4d7e745e70 | refs/heads/master | 2022-07-04T05:05:40.815000 | 2021-10-20T02:35:05 | 2021-10-20T02:35:05 | 203,951,301 | 1 | 0 | null | false | 2022-06-29T17:36:26 | 2019-08-23T07:52:48 | 2021-10-20T02:48:50 | 2022-06-29T17:36:24 | 13,253 | 0 | 0 | 2 | Java | false | false | package com.example.demo.entity.vo;/*
* @author p78o2
* @date 2020/7/22
*/
//股票列表获取历史平均值,最近平均值,方差
public class StockAvgVo {
private String stockNum;
private String stockName;
// 历史平均值
private float hisAvg;
// 近5天
private float fiveAvg;
// 近10天
private float tenAvg;
// 近20天
private float twentyAvg;
// 方差
private float hisVariance;
private float fiveVariance;
private float tenVariance;
private float twentyVariance;
@Override
public String toString() {
return "StockAvgVo{" +
"stockNum='" + stockNum + '\'' +
", stockName='" + stockName + '\'' +
", hisAvg=" + hisAvg +
", fiveAvg=" + fiveAvg +
", tenAvg=" + tenAvg +
", twentyAvg=" + twentyAvg +
", hisVariance=" + hisVariance +
", fiveVariance=" + fiveVariance +
", tenVariance=" + tenVariance +
", twentyVariance=" + twentyVariance +
'}';
}
public StockAvgVo() {
}
public String getStockNum() {
return stockNum;
}
public void setStockNum(String stockNum) {
this.stockNum = stockNum;
}
public String getStockName() {
return stockName;
}
public void setStockName(String stockName) {
this.stockName = stockName;
}
public float getHisAvg() {
return hisAvg;
}
public void setHisAvg(float hisAvg) {
this.hisAvg = hisAvg;
}
public float getFiveAvg() {
return fiveAvg;
}
public void setFiveAvg(float fiveAvg) {
this.fiveAvg = fiveAvg;
}
public float getTenAvg() {
return tenAvg;
}
public void setTenAvg(float tenAvg) {
this.tenAvg = tenAvg;
}
public float getTwentyAvg() {
return twentyAvg;
}
public void setTwentyAvg(float twentyAvg) {
this.twentyAvg = twentyAvg;
}
public float getHisVariance() {
return hisVariance;
}
public void setHisVariance(float hisVariance) {
this.hisVariance = hisVariance;
}
public float getFiveVariance() {
return fiveVariance;
}
public void setFiveVariance(float fiveVariance) {
this.fiveVariance = fiveVariance;
}
public float getTenVariance() {
return tenVariance;
}
public void setTenVariance(float tenVariance) {
this.tenVariance = tenVariance;
}
public float getTwentyVariance() {
return twentyVariance;
}
public void setTwentyVariance(float twentyVariance) {
this.twentyVariance = twentyVariance;
}
public StockAvgVo(String stockNum, String stockName, float hisAvg, float fiveAvg, float tenAvg, float twentyAvg, float hisVariance, float fiveVariance, float tenVariance, float twentyVariance) {
this.stockNum = stockNum;
this.stockName = stockName;
this.hisAvg = hisAvg;
this.fiveAvg = fiveAvg;
this.tenAvg = tenAvg;
this.twentyAvg = twentyAvg;
this.hisVariance = hisVariance;
this.fiveVariance = fiveVariance;
this.tenVariance = tenVariance;
this.twentyVariance = twentyVariance;
}
}
| UTF-8 | Java | 3,324 | java | StockAvgVo.java | Java | [
{
"context": "package com.example.demo.entity.vo;/*\n * @author p78o2\n * @date 2020/7/22\n */\n//股票列表获取历史平均值,最近平均值,方差\npub",
"end": 54,
"score": 0.9995495676994324,
"start": 49,
"tag": "USERNAME",
"value": "p78o2"
}
] | null | [] | package com.example.demo.entity.vo;/*
* @author p78o2
* @date 2020/7/22
*/
//股票列表获取历史平均值,最近平均值,方差
public class StockAvgVo {
private String stockNum;
private String stockName;
// 历史平均值
private float hisAvg;
// 近5天
private float fiveAvg;
// 近10天
private float tenAvg;
// 近20天
private float twentyAvg;
// 方差
private float hisVariance;
private float fiveVariance;
private float tenVariance;
private float twentyVariance;
@Override
public String toString() {
return "StockAvgVo{" +
"stockNum='" + stockNum + '\'' +
", stockName='" + stockName + '\'' +
", hisAvg=" + hisAvg +
", fiveAvg=" + fiveAvg +
", tenAvg=" + tenAvg +
", twentyAvg=" + twentyAvg +
", hisVariance=" + hisVariance +
", fiveVariance=" + fiveVariance +
", tenVariance=" + tenVariance +
", twentyVariance=" + twentyVariance +
'}';
}
public StockAvgVo() {
}
public String getStockNum() {
return stockNum;
}
public void setStockNum(String stockNum) {
this.stockNum = stockNum;
}
public String getStockName() {
return stockName;
}
public void setStockName(String stockName) {
this.stockName = stockName;
}
public float getHisAvg() {
return hisAvg;
}
public void setHisAvg(float hisAvg) {
this.hisAvg = hisAvg;
}
public float getFiveAvg() {
return fiveAvg;
}
public void setFiveAvg(float fiveAvg) {
this.fiveAvg = fiveAvg;
}
public float getTenAvg() {
return tenAvg;
}
public void setTenAvg(float tenAvg) {
this.tenAvg = tenAvg;
}
public float getTwentyAvg() {
return twentyAvg;
}
public void setTwentyAvg(float twentyAvg) {
this.twentyAvg = twentyAvg;
}
public float getHisVariance() {
return hisVariance;
}
public void setHisVariance(float hisVariance) {
this.hisVariance = hisVariance;
}
public float getFiveVariance() {
return fiveVariance;
}
public void setFiveVariance(float fiveVariance) {
this.fiveVariance = fiveVariance;
}
public float getTenVariance() {
return tenVariance;
}
public void setTenVariance(float tenVariance) {
this.tenVariance = tenVariance;
}
public float getTwentyVariance() {
return twentyVariance;
}
public void setTwentyVariance(float twentyVariance) {
this.twentyVariance = twentyVariance;
}
public StockAvgVo(String stockNum, String stockName, float hisAvg, float fiveAvg, float tenAvg, float twentyAvg, float hisVariance, float fiveVariance, float tenVariance, float twentyVariance) {
this.stockNum = stockNum;
this.stockName = stockName;
this.hisAvg = hisAvg;
this.fiveAvg = fiveAvg;
this.tenAvg = tenAvg;
this.twentyAvg = twentyAvg;
this.hisVariance = hisVariance;
this.fiveVariance = fiveVariance;
this.tenVariance = tenVariance;
this.twentyVariance = twentyVariance;
}
}
| 3,324 | 0.594843 | 0.590239 | 134 | 23.313433 | 22.827522 | 198 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.447761 | false | false | 12 |
310c55ce0ad917de4db122c389b84617a79815bd | 26,310,969,679,823 | 97524f5559a53e151719ad2099e092c09ee8d30b | /02_FONTES/core/seguranca-core/src/main/java/br/gov/to/sefaz/seg/business/gestao/service/impl/PerfilSistemaServiceImpl.java | 5d637e580b11bfde27b2cd831c3ff7235c5186b2 | [] | no_license | fredsilva/sistema | https://github.com/fredsilva/sistema | 46a4809e96b016f733c715da3c8f57e47996ccbd | 14dad24f7be8561611d3cdf5d7a8460b1c4300f6 | refs/heads/master | 2021-01-12T04:40:34.493000 | 2016-12-20T14:44:51 | 2016-12-20T14:44:51 | 77,699,605 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.gov.to.sefaz.seg.business.gestao.service.impl;
import br.gov.to.sefaz.business.service.impl.DefaultCrudService;
import br.gov.to.sefaz.business.service.validation.ValidationContext;
import br.gov.to.sefaz.business.service.validation.ValidationSuite;
import br.gov.to.sefaz.seg.business.gestao.service.PerfilPapelService;
import br.gov.to.sefaz.seg.business.gestao.service.PerfilSistemaService;
import br.gov.to.sefaz.seg.business.gestao.service.filter.PerfilSistemaFilter;
import br.gov.to.sefaz.seg.persistence.entity.PerfilPapel;
import br.gov.to.sefaz.seg.persistence.entity.PerfilSistema;
import br.gov.to.sefaz.seg.persistence.repository.PerfilSistemaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* Implementação do serviço {@link PerfilSistemaService}.
*
* @author <a href="mailto:thiago.luz@ntconsult.com.br">thiago.luz</a>
* @since 25/07/2016 17:10:00
*/
@Service
public class PerfilSistemaServiceImpl extends DefaultCrudService<PerfilSistema, Long>
implements PerfilSistemaService {
private final PerfilPapelService perfilPapelService;
@Autowired
public PerfilSistemaServiceImpl(PerfilSistemaRepository repository, PerfilPapelService perfilPapelService) {
super(repository);
this.perfilPapelService = perfilPapelService;
}
@Override
protected PerfilSistemaRepository getRepository() {
return (PerfilSistemaRepository) super.getRepository();
}
@Override
public List<PerfilSistema> findAllPerfilSistemaByPapel(Long idPapel) {
return getRepository().findAllPerfilSistemaByPapel(idPapel);
}
@Override
public Collection<PerfilSistema> findAllPerfilSistema(PerfilSistemaFilter filter) {
return getRepository().findAllPerfilSistema(filter.getNomePerfil());
}
@Override
public PerfilSistema findOneComplete(Long id) {
return getRepository().findOneComplete(id);
}
@Override
@Transactional
public PerfilSistema saveOrUpdatePerfilSistema(@ValidationSuite(clazz = PerfilSistema.class, context =
ValidationContext.SAVE) PerfilSistema dto) {
Set<PerfilPapel> perfilPapel = dto.getPerfilPapel();
dto.setPerfilPapel(null);
dto.setUsuarioPerfil(null);
PerfilSistema save = save(dto);
perfilPapel.forEach(pp -> pp.setIdentificacaoPerfil(save.getIdentificacaoPerfil()));
perfilPapelService.deleteAllWithPerfilId(save.getIdentificacaoPerfil());
perfilPapelService.save(perfilPapel);
return save;
}
@Override
public Optional<PerfilSistema> delete(@ValidationSuite(clazz = PerfilSistema.class,
context = ValidationContext.DELETE) Long id) {
perfilPapelService.deleteAllWithPerfilId(id);
return super.delete(id);
}
}
| UTF-8 | Java | 3,036 | java | PerfilSistemaServiceImpl.java | Java | [
{
"context": "filSistemaService}.\n *\n * @author <a href=\"mailto:thiago.luz@ntconsult.com.br\">thiago.luz</a>\n * @since 25/07/2016 17:10:00\n */",
"end": 1077,
"score": 0.9999315142631531,
"start": 1050,
"tag": "EMAIL",
"value": "thiago.luz@ntconsult.com.br"
},
{
"context": "thor <a href=\"mailto:thiago.luz@ntconsult.com.br\">thiago.luz</a>\n * @since 25/07/2016 17:10:00\n */\n@Service\np",
"end": 1088,
"score": 0.729834258556366,
"start": 1079,
"tag": "USERNAME",
"value": "thiago.lu"
},
{
"context": "ref=\"mailto:thiago.luz@ntconsult.com.br\">thiago.luz</a>\n * @since 25/07/2016 17:10:00\n */\n@Service\npu",
"end": 1089,
"score": 0.7344847917556763,
"start": 1088,
"tag": "NAME",
"value": "z"
}
] | null | [] | package br.gov.to.sefaz.seg.business.gestao.service.impl;
import br.gov.to.sefaz.business.service.impl.DefaultCrudService;
import br.gov.to.sefaz.business.service.validation.ValidationContext;
import br.gov.to.sefaz.business.service.validation.ValidationSuite;
import br.gov.to.sefaz.seg.business.gestao.service.PerfilPapelService;
import br.gov.to.sefaz.seg.business.gestao.service.PerfilSistemaService;
import br.gov.to.sefaz.seg.business.gestao.service.filter.PerfilSistemaFilter;
import br.gov.to.sefaz.seg.persistence.entity.PerfilPapel;
import br.gov.to.sefaz.seg.persistence.entity.PerfilSistema;
import br.gov.to.sefaz.seg.persistence.repository.PerfilSistemaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* Implementação do serviço {@link PerfilSistemaService}.
*
* @author <a href="mailto:<EMAIL>">thiago.luz</a>
* @since 25/07/2016 17:10:00
*/
@Service
public class PerfilSistemaServiceImpl extends DefaultCrudService<PerfilSistema, Long>
implements PerfilSistemaService {
private final PerfilPapelService perfilPapelService;
@Autowired
public PerfilSistemaServiceImpl(PerfilSistemaRepository repository, PerfilPapelService perfilPapelService) {
super(repository);
this.perfilPapelService = perfilPapelService;
}
@Override
protected PerfilSistemaRepository getRepository() {
return (PerfilSistemaRepository) super.getRepository();
}
@Override
public List<PerfilSistema> findAllPerfilSistemaByPapel(Long idPapel) {
return getRepository().findAllPerfilSistemaByPapel(idPapel);
}
@Override
public Collection<PerfilSistema> findAllPerfilSistema(PerfilSistemaFilter filter) {
return getRepository().findAllPerfilSistema(filter.getNomePerfil());
}
@Override
public PerfilSistema findOneComplete(Long id) {
return getRepository().findOneComplete(id);
}
@Override
@Transactional
public PerfilSistema saveOrUpdatePerfilSistema(@ValidationSuite(clazz = PerfilSistema.class, context =
ValidationContext.SAVE) PerfilSistema dto) {
Set<PerfilPapel> perfilPapel = dto.getPerfilPapel();
dto.setPerfilPapel(null);
dto.setUsuarioPerfil(null);
PerfilSistema save = save(dto);
perfilPapel.forEach(pp -> pp.setIdentificacaoPerfil(save.getIdentificacaoPerfil()));
perfilPapelService.deleteAllWithPerfilId(save.getIdentificacaoPerfil());
perfilPapelService.save(perfilPapel);
return save;
}
@Override
public Optional<PerfilSistema> delete(@ValidationSuite(clazz = PerfilSistema.class,
context = ValidationContext.DELETE) Long id) {
perfilPapelService.deleteAllWithPerfilId(id);
return super.delete(id);
}
}
| 3,016 | 0.759974 | 0.755358 | 83 | 35.542168 | 31.269255 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.457831 | false | false | 12 |
8359fab304f3e617c950f9741c4506881758ae8e | 33,165,737,486,046 | 33718cf662fa9e51e391ac7f71a51ec52cd67974 | /app/src/main/java/com/inventory/ibrahim/inventory/home.java | 6b153c31235fb5a863e9923f80cdc508ecd91ed4 | [] | no_license | ibrahimGhailani/Inventory | https://github.com/ibrahimGhailani/Inventory | 17e42b504f6c2b1013143015350cd7d5e3ddfbbb | e8c8cebe1a1c7cb08425f8a22719676bd5c5e2ea | refs/heads/master | 2015-08-14T15:17:39.864000 | 2014-11-10T18:47:23 | 2014-11-10T18:47:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.inventory.ibrahim.inventory;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.ListEntry;
import com.google.gdata.data.spreadsheet.ListFeed;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class home extends Activity {
protected ListView inventoryList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
inventoryList = (ListView) findViewById(R.id.listView);
//Get spreadsheet data using a different thread
SpreadsheetRetriever sh = new SpreadsheetRetriever();
sh.execute();
}
//After the data is retrieved from SpreadsheetRetriever, the data will be displayed as a list
public void displayItems(ArrayList<InventoryItem> items){
//final StableArrayAdapter adapter = new StableArrayAdapter(this, android.R.layout.simple_gallery_item, items);
final MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, items);
inventoryList.setAdapter(adapter);
}
//This class pulls all the data from the spreadsheet on a new thread
public class SpreadsheetRetriever extends AsyncTask<Void, Void, ArrayList<InventoryItem>>{
//Using Googles spreadsheet api get the data from the spreadsheet
@Override
public ArrayList<InventoryItem> doInBackground(Void... params) {
System.out.println("Doinbackground");
SpreadsheetService service =
new SpreadsheetService("MySpreadsheetIntegration-v1");
try {
ArrayList <InventoryItem> rows = new ArrayList<InventoryItem>();
// Define the URL to request. This should never change.
URL SPREADSHEET_FEED_URL = new URL(
"https://spreadsheets.google.com/feeds/worksheets/16RianjTWGaHBEBe-_YXgasXN9WYk1idCt5exYgd1QzM/public/full");
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL,
SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
SpreadsheetEntry spreadsheet = spreadsheets.get(0);
// Fetch the list feed of the worksheet.
URL listFeedUrl = spreadsheet.getWorksheetFeedUrl();
ListFeed listFeed = service.getFeed(listFeedUrl, ListFeed.class);
InventoryItem i;
// Iterate through each row, save info to an inventoryItem and store it in an arraylist
for (ListEntry row : listFeed.getEntries()) {
i = new InventoryItem();
i.setTitle(row.getCustomElements().getValue("item"));
i.setCost(row.getCustomElements().getValue("cost"));
rows.add(i);
}
return rows;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//After the data is retrieved call displayItems()
@Override
public void onPostExecute(ArrayList<InventoryItem> items){
if(items != null) {
displayItems(items);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| UTF-8 | Java | 4,532 | java | home.java | Java | [] | null | [] | package com.inventory.ibrahim.inventory;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.ListEntry;
import com.google.gdata.data.spreadsheet.ListFeed;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class home extends Activity {
protected ListView inventoryList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
inventoryList = (ListView) findViewById(R.id.listView);
//Get spreadsheet data using a different thread
SpreadsheetRetriever sh = new SpreadsheetRetriever();
sh.execute();
}
//After the data is retrieved from SpreadsheetRetriever, the data will be displayed as a list
public void displayItems(ArrayList<InventoryItem> items){
//final StableArrayAdapter adapter = new StableArrayAdapter(this, android.R.layout.simple_gallery_item, items);
final MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, items);
inventoryList.setAdapter(adapter);
}
//This class pulls all the data from the spreadsheet on a new thread
public class SpreadsheetRetriever extends AsyncTask<Void, Void, ArrayList<InventoryItem>>{
//Using Googles spreadsheet api get the data from the spreadsheet
@Override
public ArrayList<InventoryItem> doInBackground(Void... params) {
System.out.println("Doinbackground");
SpreadsheetService service =
new SpreadsheetService("MySpreadsheetIntegration-v1");
try {
ArrayList <InventoryItem> rows = new ArrayList<InventoryItem>();
// Define the URL to request. This should never change.
URL SPREADSHEET_FEED_URL = new URL(
"https://spreadsheets.google.com/feeds/worksheets/16RianjTWGaHBEBe-_YXgasXN9WYk1idCt5exYgd1QzM/public/full");
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL,
SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
SpreadsheetEntry spreadsheet = spreadsheets.get(0);
// Fetch the list feed of the worksheet.
URL listFeedUrl = spreadsheet.getWorksheetFeedUrl();
ListFeed listFeed = service.getFeed(listFeedUrl, ListFeed.class);
InventoryItem i;
// Iterate through each row, save info to an inventoryItem and store it in an arraylist
for (ListEntry row : listFeed.getEntries()) {
i = new InventoryItem();
i.setTitle(row.getCustomElements().getValue("item"));
i.setCost(row.getCustomElements().getValue("cost"));
rows.add(i);
}
return rows;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//After the data is retrieved call displayItems()
@Override
public void onPostExecute(ArrayList<InventoryItem> items){
if(items != null) {
displayItems(items);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 4,532 | 0.648941 | 0.647176 | 118 | 37.398304 | 29.818985 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.525424 | false | false | 12 |
c32b59c1b3798c4e801ca2afd8e50c1e8cd97a2c | 12,876,311,989,895 | ffaff3bc61e02640584d08d9dce69f0f14db4efc | /Spel/Vak.java | dc5d906ffc0e45878042b2f5e0147b79d42182b0 | [] | no_license | Rochendiil/Chess-online | https://github.com/Rochendiil/Chess-online | 961a909427456a41aa7c90b2352db6b64a681cde | ec11e828e3bebbc805c2246c8af05255a51fd600 | refs/heads/master | 2020-03-09T18:41:38.951000 | 2018-04-10T13:39:24 | 2018-04-10T13:39:24 | 128,938,374 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Spel;
import Stuk.SchaakStuk;
import java.awt.Point;
import java.io.Serializable;
/*
* 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.
*/
/**
*
* @author luukj
*/
public class Vak implements Serializable {
private String naam;
private SchaakStuk stuk;
private boolean kleur;
private Point positie;
public Vak(String naam, SchaakStuk stuk, Point positie) {
this.naam = naam;
this.stuk = stuk;
this.positie = positie;
}
public Point getPositie() {
return positie;
}
public String getNaam() {
return naam;
}
public SchaakStuk getStuk() {
return stuk;
}
public void setStuk(SchaakStuk stuk) {
this.stuk = stuk;
this.stuk.setPositie(positie);
}
public void removeStuk(){
this.stuk = null;
}
}
| UTF-8 | Java | 996 | java | Vak.java | Java | [
{
"context": "the template in the editor.\n */\n\n/**\n *\n * @author luukj\n */\npublic class Vak implements Serializable {\n ",
"end": 302,
"score": 0.9995797276496887,
"start": 297,
"tag": "USERNAME",
"value": "luukj"
}
] | null | [] | package Spel;
import Stuk.SchaakStuk;
import java.awt.Point;
import java.io.Serializable;
/*
* 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.
*/
/**
*
* @author luukj
*/
public class Vak implements Serializable {
private String naam;
private SchaakStuk stuk;
private boolean kleur;
private Point positie;
public Vak(String naam, SchaakStuk stuk, Point positie) {
this.naam = naam;
this.stuk = stuk;
this.positie = positie;
}
public Point getPositie() {
return positie;
}
public String getNaam() {
return naam;
}
public SchaakStuk getStuk() {
return stuk;
}
public void setStuk(SchaakStuk stuk) {
this.stuk = stuk;
this.stuk.setPositie(positie);
}
public void removeStuk(){
this.stuk = null;
}
}
| 996 | 0.618474 | 0.618474 | 53 | 17.792454 | 17.749151 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.415094 | false | false | 12 |
f4af3f043c59ae1536731ffa091f31718259721c | 12,876,311,990,773 | c01c76a09c9a4ed92a1e853389bb7bab1e51e7b3 | /src/main/java/br/com/fiap/entity/Gif.java | f29e534edd6fdc216933fba2db4c1c0f1e58a59d | [] | no_license | pceamanda/netgifs | https://github.com/pceamanda/netgifs | 45fd5edfdd112642258334d0204a4539ce8e585c | 4f0e062f4943b9dae022db8fadd7779e353fa58b | refs/heads/master | 2021-08-31T10:16:21.563000 | 2017-12-21T02:06:50 | 2017-12-21T02:06:50 | 114,043,419 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.fiap.entity;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "GIF")
public class Gif {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "GIF_ID")
private Integer id;
@Column(name = "PATH")
private String path;
@Column(name = "NAME")
private String name;
@Column(name = "DESCRIPTION")
private String description;
@Column(name = "ETA_RATING")
private Integer etaRating;
@Column(name = "LANGUAGE")
private String language;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "CATEGORY_ID")
private Category category;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getEtaRating() {
return etaRating;
}
public void setEtaRating(Integer etaRating) {
this.etaRating = etaRating;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Gif gif = (Gif) o;
return Objects.equals(id, gif.id) &&
Objects.equals(name, gif.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
| UTF-8 | Java | 2,057 | java | Gif.java | Java | [] | null | [] | package br.com.fiap.entity;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "GIF")
public class Gif {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "GIF_ID")
private Integer id;
@Column(name = "PATH")
private String path;
@Column(name = "NAME")
private String name;
@Column(name = "DESCRIPTION")
private String description;
@Column(name = "ETA_RATING")
private Integer etaRating;
@Column(name = "LANGUAGE")
private String language;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "CATEGORY_ID")
private Category category;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getEtaRating() {
return etaRating;
}
public void setEtaRating(Integer etaRating) {
this.etaRating = etaRating;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Gif gif = (Gif) o;
return Objects.equals(id, gif.id) &&
Objects.equals(name, gif.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
| 2,057 | 0.594069 | 0.594069 | 104 | 18.778847 | 16.49881 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.326923 | false | false | 12 |
86e850c32eee23142099a40d3fc0c261b1fea84d | 16,870,631,574,024 | da51f2a23142cecc1351a60506b172a638025cdf | /photos/src/main/java/com/sergioburik/photos/services/PostItemService.java | 1ed2abea583aa2a0f531f62ade1e8ecfdd1dd055 | [] | no_license | alikkakold/photos | https://github.com/alikkakold/photos | 44b5b20f6913d67a0218c087e6d676e71e0eebb1 | b7d8f189fda7eaf8a2e8ff584cc4096e332b6605 | refs/heads/main | 2023-07-01T23:23:08.530000 | 2021-08-03T17:10:47 | 2021-08-03T17:10:47 | 392,394,757 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sergioburik.photos.services;
import com.sergioburik.photos.models.Post;
import com.sergioburik.photos.models.PostItem;
import com.sergioburik.photos.models.UserRole;
import com.sergioburik.photos.repositories.PostItemRepository;
import com.sergioburik.photos.tools.ImageCrop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.UUID;
@Component
public class PostItemService {
@Autowired
PostItemRepository postItemRepository;
@Value("${upload.path}")
String uploadPath;
@Autowired
ImageCrop imageCrop;
public PostItem save(MultipartFile file, Post post) throws Exception {
PostItem postItem = new PostItem();
if (file != null && !file.getOriginalFilename().isEmpty()) {
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
String resultFilename = imageCrop.saveSquareImage(file);
postItem.setPost(post);
postItem.setItemFileName(resultFilename);
} else {
throw new Exception("Unable to save photo");
}
return postItemRepository.save(postItem);
}
}
| UTF-8 | Java | 1,449 | java | PostItemService.java | Java | [] | null | [] | package com.sergioburik.photos.services;
import com.sergioburik.photos.models.Post;
import com.sergioburik.photos.models.PostItem;
import com.sergioburik.photos.models.UserRole;
import com.sergioburik.photos.repositories.PostItemRepository;
import com.sergioburik.photos.tools.ImageCrop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.UUID;
@Component
public class PostItemService {
@Autowired
PostItemRepository postItemRepository;
@Value("${upload.path}")
String uploadPath;
@Autowired
ImageCrop imageCrop;
public PostItem save(MultipartFile file, Post post) throws Exception {
PostItem postItem = new PostItem();
if (file != null && !file.getOriginalFilename().isEmpty()) {
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
String resultFilename = imageCrop.saveSquareImage(file);
postItem.setPost(post);
postItem.setItemFileName(resultFilename);
} else {
throw new Exception("Unable to save photo");
}
return postItemRepository.save(postItem);
}
}
| 1,449 | 0.710145 | 0.710145 | 50 | 27.98 | 22.881863 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52 | false | false | 12 |
d4c5eb7393d8adc1cee26719154eac34cda091a4 | 16,870,631,575,420 | d56fe57fc2f6cb98117b62c24ca8230538e8cb60 | /cassy-core/src/main/java/org/salemelrahal/cassy/simulation/model/field/FieldController.java | 743c2c0b3ad5f85d55d2676b850f8f30639f8563 | [] | no_license | selrahal/cassy | https://github.com/selrahal/cassy | ad7d32fdfb25b2a71b75dd6654cfd15efac9aa6e | e34bfa97ae63940cf8ae48d9e45ab586c50e82e8 | refs/heads/master | 2020-02-26T13:54:42.707000 | 2015-06-19T22:26:00 | 2015-06-19T22:26:00 | 37,734,590 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.salemelrahal.cassy.simulation.model.field;
public interface FieldController {
public void reset(Field field);
public void randomize(Field field);
public void click(Field field, int x, int y);
public void drag(Field field, int x, int y);
}
| UTF-8 | Java | 257 | java | FieldController.java | Java | [] | null | [] | package org.salemelrahal.cassy.simulation.model.field;
public interface FieldController {
public void reset(Field field);
public void randomize(Field field);
public void click(Field field, int x, int y);
public void drag(Field field, int x, int y);
}
| 257 | 0.762646 | 0.762646 | 9 | 27.555555 | 20.276484 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.444444 | false | false | 12 |
606b35ef7d08cbc4adca0f6fa5ff8167e07c3286 | 24,086,176,626,354 | 63e36d35f51bea83017ec712179302a62608333e | /OnePlusCamera/com/oneplus/gallery2/media/BaseMediaSet.java | 0b147de2c73c0e7c4db02f9380ea69c0c6ccd72f | [] | no_license | hiepgaf/oneplus_blobs_decompiled | https://github.com/hiepgaf/oneplus_blobs_decompiled | 672aa002fa670bdcba8fdf34113bc4b8e85f8294 | e1ab1f2dd111f905ff1eee18b6a072606c01c518 | refs/heads/master | 2021-06-26T11:24:21.954000 | 2017-08-26T12:45:56 | 2017-08-26T12:45:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.oneplus.gallery2.media;
import android.content.Intent;
import android.os.Handler;
import android.os.SystemClock;
import android.util.LongSparseArray;
import com.oneplus.base.BaseApplication;
import com.oneplus.base.BasicBaseObject;
import com.oneplus.base.CallbackHandle;
import com.oneplus.base.EventArgs;
import com.oneplus.base.Handle;
import com.oneplus.base.HandlerUtils;
import com.oneplus.base.Log;
import com.oneplus.base.PropertyChangeEventArgs;
import com.oneplus.base.PropertyChangedCallback;
import com.oneplus.base.PropertyKey;
import com.oneplus.base.PropertySource;
import com.oneplus.gallery2.ExtraKey;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
public abstract class BaseMediaSet
extends BasicBaseObject
implements MediaSet
{
private static final int COVER_MEDIA_UPDATE_FLAGS_MASK = Media.FLAG_LAST_MODIFIED_TIME_CHANGED | GroupedMedia.FLAG_COVER_CHANGED;
private static final long DURATION_COMMIT_MEDIA_SYNC_DELAY = 500L;
private static final boolean PRINT_MEDIA_DEBUG_LOG = false;
private boolean m_ContainsHiddenMedia;
private final List<Media> m_CoverMediaList = new ArrayList();
private LongSparseArray<Object> m_Extra;
private final Set<Media> m_HiddenMedia = new HashSet();
private boolean m_IsDelayedMediaSyncCommitScheduled;
private PropertyChangedCallback<Locale> m_LocaleChangedCallback;
private final Set<Media> m_Media = new HashSet();
private Handle m_MediaChangeCBHandle;
private Handle m_MediaIterationClientHandle;
private long m_MediaIterationStartTime;
private final PropertyChangedCallback<Boolean> m_MediaTableStateChangedCB = new PropertyChangedCallback()
{
public void onPropertyChanged(PropertySource paramAnonymousPropertySource, PropertyKey<Boolean> paramAnonymousPropertyKey, PropertyChangeEventArgs<Boolean> paramAnonymousPropertyChangeEventArgs)
{
if (!((Boolean)paramAnonymousPropertyChangeEventArgs.getNewValue()).booleanValue()) {
return;
}
paramAnonymousPropertySource.removeCallback(paramAnonymousPropertyKey, this);
BaseMediaSet.this.onMediaTableReady();
}
};
private final List<MediaListImpl> m_OpenedMediaLists = new ArrayList();
private final Set<Media> m_PendingAddingMedia = new HashSet();
private final Set<Media> m_PendingRemovingMedia = new HashSet();
private int m_PhotoCount;
private final MediaSource m_Source;
private final MediaType m_TargetMediaType;
private int m_VideoCount;
protected BaseMediaSet(MediaSource paramMediaSource, MediaType paramMediaType)
{
label140:
label147:
int i;
if (paramMediaSource != null)
{
if (paramMediaType == MediaType.UNKNOWN) {
break label175;
}
this.m_Source = paramMediaSource;
this.m_TargetMediaType = paramMediaType;
this.m_LocaleChangedCallback = onPrepareLocaleChangedCallback();
if (this.m_LocaleChangedCallback != null) {
break label185;
}
if (!((Boolean)paramMediaSource.get(MediaSource.PROP_IS_MEDIA_TABLE_READY)).booleanValue()) {
break label201;
}
onMediaTableReady();
if (canSyncMediaBeforeMediaTableReady()) {
break label217;
}
i = getNameResourceId();
if (i != 0) {
break label224;
}
}
for (;;)
{
enablePropertyLogs(PROP_COVER_HASH_CODE, 1);
return;
throw new IllegalArgumentException("No media source");
label175:
throw new IllegalArgumentException("No target media type");
label185:
BaseApplication.current().addCallback(BaseApplication.PROP_LOCALE, this.m_LocaleChangedCallback);
break;
label201:
paramMediaSource.addCallback(MediaSource.PROP_IS_MEDIA_TABLE_READY, this.m_MediaTableStateChangedCB);
break label140;
label217:
setupMedia();
break label147;
label224:
setReadOnly(PROP_NAME, BaseApplication.current().getString(i));
}
}
private boolean addHiddenMedia(Media paramMedia)
{
if (paramMedia == null) {}
while (paramMedia.isVisible()) {
return false;
}
boolean bool = this.m_HiddenMedia.add(paramMedia);
if (!bool) {
return bool;
}
setReadOnly(MediaSet.PROP_HIDDEN_MEDIA_COUNT, Integer.valueOf(this.m_HiddenMedia.size()));
return bool;
}
private void onMediaListReleased(MediaListImpl paramMediaListImpl)
{
if (this.m_OpenedMediaLists.remove(paramMediaListImpl))
{
Log.v(this.TAG, "[", getId(), "] onMediaListReleased() - Opened media list count : ", Integer.valueOf(this.m_OpenedMediaLists.size()));
return;
}
}
private boolean removeHiddenMedia(Media paramMedia)
{
boolean bool;
if (paramMedia != null)
{
bool = this.m_HiddenMedia.remove(paramMedia);
if (!bool) {
return bool;
}
}
else
{
return false;
}
setReadOnly(MediaSet.PROP_HIDDEN_MEDIA_COUNT, Integer.valueOf(this.m_HiddenMedia.size()));
return bool;
}
private void scheduleCommitMediaSync()
{
if (this.m_IsDelayedMediaSyncCommitScheduled) {
return;
}
this.m_IsDelayedMediaSyncCommitScheduled = HandlerUtils.post(this, new CommitMediaSyncRunnable(null), 500L);
}
private boolean setContainsHiddenMediaProp(boolean paramBoolean)
{
boolean bool = this.m_ContainsHiddenMedia;
if (bool != paramBoolean)
{
this.m_ContainsHiddenMedia = paramBoolean;
if (!paramBoolean)
{
localIterator = this.m_HiddenMedia.iterator();
while (localIterator.hasNext()) {
removeMedia((Media)localIterator.next(), false);
}
}
}
else
{
return false;
}
Iterator localIterator = this.m_HiddenMedia.iterator();
while (localIterator.hasNext()) {
addMedia((Media)localIterator.next(), false);
}
commitMediaSync();
return notifyPropertyChanged(PROP_CONTAINS_HIDDEN_MEDIA, Boolean.valueOf(bool), Boolean.valueOf(paramBoolean));
}
private void setupMedia()
{
if (Handle.isValid(this.m_MediaChangeCBHandle)) {
if (!Handle.isValid(this.m_MediaIterationClientHandle)) {
break label42;
}
}
for (;;)
{
if (Handle.isValid(this.m_MediaIterationClientHandle)) {
break label53;
}
return;
this.m_MediaChangeCBHandle = onPrepareMediaChangeCallback();
break;
label42:
this.m_MediaIterationClientHandle = onPrepareMediaIterationClient();
}
label53:
this.m_Source.scheduleMediaIteration(0);
}
private boolean shouldContainsMediaInternal(Media paramMedia, int paramInt)
{
if (this.m_TargetMediaType == null) {}
while (paramMedia.getType() == this.m_TargetMediaType) {
return shouldContainsMedia(paramMedia, paramInt);
}
return false;
}
private void updateCoverMediaList()
{
this.m_CoverMediaList.clear();
if (this.m_Media.size() <= 12)
{
this.m_CoverMediaList.addAll(this.m_Media);
Collections.sort(this.m_CoverMediaList, COVER_MEDIA_COMPARATOR);
}
for (;;)
{
updateCoverHashCode();
return;
Iterator localIterator = this.m_Media.iterator();
while (localIterator.hasNext())
{
Media localMedia = (Media)localIterator.next();
int i = Collections.binarySearch(this.m_CoverMediaList, localMedia, COVER_MEDIA_COMPARATOR) ^ 0xFFFFFFFF;
if ((i >= 0) && (i < 12)) {
this.m_CoverMediaList.add(i, localMedia);
}
}
}
}
protected boolean addMedia(Media paramMedia, boolean paramBoolean)
{
if (paramMedia != null)
{
if (!paramMedia.isVisible()) {
break label47;
}
if (this.m_Media.contains(paramMedia)) {
break label62;
}
if (!this.m_PendingRemovingMedia.remove(paramMedia)) {
break label64;
}
label39:
if (paramBoolean) {
break label79;
}
}
for (;;)
{
return true;
return false;
label47:
addHiddenMedia(paramMedia);
if (this.m_ContainsHiddenMedia) {
break;
}
return false;
label62:
return false;
label64:
if (this.m_PendingAddingMedia.add(paramMedia)) {
break label39;
}
return false;
label79:
commitMediaSync();
}
}
protected void addMediaToMediaLists(Media paramMedia)
{
int i = this.m_OpenedMediaLists.size() - 1;
while (i >= 0)
{
((MediaListImpl)this.m_OpenedMediaLists.get(i)).addMedia(paramMedia);
i -= 1;
}
}
protected void addMediaToMediaLists(Collection<Media> paramCollection)
{
MediaListImpl localMediaListImpl = null;
if (paramCollection == null) {}
while (this.m_OpenedMediaLists.isEmpty()) {
return;
}
ArrayList localArrayList = new ArrayList(paramCollection);
int i = this.m_OpenedMediaLists.size() - 1;
paramCollection = localMediaListImpl;
if (i >= 0)
{
localMediaListImpl = (MediaListImpl)this.m_OpenedMediaLists.get(i);
if (localMediaListImpl.getComparator() == paramCollection) {}
for (;;)
{
localMediaListImpl.addMedia(localArrayList, true);
i -= 1;
break;
paramCollection = localMediaListImpl.getComparator();
Collections.sort(localArrayList, paramCollection);
}
}
}
protected boolean canSyncMediaBeforeMediaTableReady()
{
return true;
}
protected void checkMediaPositionInMediaLists(Media paramMedia, int paramInt)
{
int i = this.m_OpenedMediaLists.size() - 1;
if (i >= 0)
{
MediaListImpl localMediaListImpl = (MediaListImpl)this.m_OpenedMediaLists.get(i);
if ((localMediaListImpl.getComparator().getEffectiveMediaUpdateFlags() & paramInt) == 0) {}
for (;;)
{
i -= 1;
break;
localMediaListImpl.checkMediaIndex(paramMedia);
}
}
}
protected void clearExtras()
{
this.m_Extra = null;
}
protected void clearMedia()
{
verifyAccess();
if (!this.m_Media.isEmpty())
{
int i = this.m_PhotoCount;
int j = this.m_VideoCount;
this.m_PendingAddingMedia.clear();
this.m_PendingRemovingMedia.clear();
this.m_Media.clear();
this.m_CoverMediaList.clear();
this.m_PhotoCount = 0;
this.m_VideoCount = 0;
notifyPropertyChanged(PROP_PHOTO_COUNT, Integer.valueOf(i), Integer.valueOf(this.m_PhotoCount));
notifyPropertyChanged(PROP_VIDEO_COUNT, Integer.valueOf(j), Integer.valueOf(this.m_VideoCount));
setReadOnly(PROP_MEDIA_COUNT, null);
updateCoverHashCode();
return;
}
}
protected void commitMediaSync()
{
int i1 = 0;
int i2 = 0;
verifyAccess();
int n;
int i;
int j;
label53:
label57:
label61:
Media localMedia;
if (this.m_PendingRemovingMedia.isEmpty())
{
n = 0;
i = 0;
j = 0;
if (this.m_PendingAddingMedia.isEmpty())
{
k = i2;
if (n != 0) {
break label486;
}
if (k != 0) {
break label493;
}
if (j != 0) {
break label500;
}
if (i != 0) {
break label537;
}
setReadOnly(PROP_MEDIA_COUNT, Integer.valueOf(this.m_Media.size()));
}
}
else
{
localIterator = this.m_PendingRemovingMedia.iterator();
i = 0;
k = 0;
m = 0;
j = 0;
while (localIterator.hasNext())
{
localMedia = (Media)localIterator.next();
if (this.m_Media.remove(localMedia)) {
switch ($SWITCH_TABLE$com$oneplus$gallery2$media$MediaType()[localMedia.getType().ordinal()])
{
default:
break;
case 2:
j -= 1;
case 3:
for (;;)
{
if (k == 0) {
break label201;
}
i = 1;
break;
m -= 1;
}
label201:
if (Collections.binarySearch(this.m_CoverMediaList, localMedia, COVER_MEDIA_COMPARATOR) < 0)
{
i = 1;
}
else
{
i = 1;
k = 1;
}
break;
}
}
}
if (i == 0) {}
for (;;)
{
this.m_PendingRemovingMedia.clear();
i = m;
n = k;
break;
removeMediaFromMediaLists(this.m_PendingRemovingMedia);
}
}
Iterator localIterator = this.m_PendingAddingMedia.iterator();
int m = 0;
int k = i1;
for (;;)
{
if (localIterator.hasNext())
{
localMedia = (Media)localIterator.next();
if (this.m_Media.add(localMedia)) {
switch ($SWITCH_TABLE$com$oneplus$gallery2$media$MediaType()[localMedia.getType().ordinal()])
{
default:
break;
case 2:
j += 1;
case 3:
for (;;)
{
if (n == 0) {
break label376;
}
k = 1;
break;
i += 1;
}
label376:
k = Collections.binarySearch(this.m_CoverMediaList, localMedia, COVER_MEDIA_COMPARATOR) ^ 0xFFFFFFFF;
if (k < 0) {}
while (k >= 12)
{
k = 1;
break;
}
this.m_CoverMediaList.add(k, localMedia);
while (this.m_CoverMediaList.size() > 12) {
this.m_CoverMediaList.remove(this.m_CoverMediaList.size() - 1);
}
}
}
}
else
{
if (k == 0) {}
for (;;)
{
this.m_PendingAddingMedia.clear();
k = m;
break;
addMediaToMediaLists(this.m_PendingAddingMedia);
}
label486:
updateCoverMediaList();
break label53;
label493:
updateCoverHashCode();
break label53;
label500:
this.m_PhotoCount += j;
notifyPropertyChanged(PROP_PHOTO_COUNT, Integer.valueOf(this.m_PhotoCount - j), Integer.valueOf(this.m_PhotoCount));
break label57;
label537:
this.m_VideoCount += i;
notifyPropertyChanged(PROP_VIDEO_COUNT, Integer.valueOf(this.m_VideoCount - i), Integer.valueOf(this.m_VideoCount));
break label61;
k = 1;
m = 1;
}
}
}
protected void completeDeletion(Handle paramHandle, boolean paramBoolean, int paramInt)
{
verifyAccess();
if (paramHandle == null) {}
while (!(paramHandle instanceof CallbackHandle)) {
return;
}
if (((Boolean)get(PROP_IS_DELETING)).booleanValue())
{
paramHandle = (CallbackHandle)paramHandle;
if (paramHandle.getCallback() != null) {
break label88;
}
setReadOnly(PROP_IS_DELETING, Boolean.valueOf(false));
if (paramBoolean) {
break label104;
}
}
for (;;)
{
onDeletionCompleted(paramBoolean, paramInt);
if (paramBoolean) {
break label120;
}
if (!((Boolean)get(PROP_IS_RELEASED)).booleanValue()) {
break label165;
}
return;
return;
label88:
((MediaSet.DeletionCallback)paramHandle.getCallback()).onDeletionCompleted(this, paramBoolean, paramInt);
break;
label104:
this.m_CoverMediaList.clear();
updateCoverHashCode();
}
label120:
clearMedia();
raise(EVENT_DELETED, EventArgs.EMPTY);
paramHandle = new Intent("com.oneplus.gallery2.media.action.MEDIA_SET_DELETED");
paramHandle.putExtra("MediaSetId", getId());
BaseApplication.current().sendBroadcast(paramHandle);
return;
label165:
commitMediaSync();
}
public boolean contains(Media paramMedia)
{
if (paramMedia == null) {}
while (!this.m_Media.contains(paramMedia)) {
return false;
}
return true;
}
public Handle delete(MediaSet.DeletionCallback paramDeletionCallback, int paramInt)
{
verifyAccess();
if (((Boolean)get(PROP_IS_RELEASED)).booleanValue()) {}
while (((Boolean)get(PROP_IS_DELETING)).booleanValue()) {
return null;
}
setReadOnly(PROP_IS_DELETING, Boolean.valueOf(true));
CallbackHandle local2 = new CallbackHandle("DeleteMediaSet", paramDeletionCallback, null)
{
protected void onClose(int paramAnonymousInt) {}
};
if (paramDeletionCallback == null) {}
for (;;)
{
startDeletion(local2, paramInt);
return local2;
paramDeletionCallback.onDeletionStarted(this, paramInt);
}
}
public <TValue> TValue get(PropertyKey<TValue> paramPropertyKey)
{
if (paramPropertyKey != PROP_CONTAINS_HIDDEN_MEDIA)
{
if (paramPropertyKey != PROP_PHOTO_COUNT)
{
if (paramPropertyKey == PROP_VIDEO_COUNT) {
break label43;
}
return (TValue)super.get(paramPropertyKey);
}
}
else {
return Boolean.valueOf(this.m_ContainsHiddenMedia);
}
return Integer.valueOf(this.m_PhotoCount);
label43:
return Integer.valueOf(this.m_VideoCount);
}
public <T> T getExtra(ExtraKey<T> paramExtraKey, T paramT)
{
if (this.m_Extra == null) {}
do
{
return paramT;
paramExtraKey = this.m_Extra.get(paramExtraKey.getId());
} while (paramExtraKey == null);
return paramExtraKey;
}
public final Handler getHandler()
{
return this.m_Source.getHandler();
}
protected final Iterable<Media> getMedia()
{
return this.m_Media;
}
protected int getNameResourceId()
{
return 0;
}
public <T extends MediaSource> T getSource()
{
return this.m_Source;
}
public MediaType getTargetMediaType()
{
return this.m_TargetMediaType;
}
public boolean isVisibilityChangeSupported()
{
return false;
}
protected void onDeletionCompleted(boolean paramBoolean, int paramInt) {}
protected void onIterateMedia(Media paramMedia)
{
if (!shouldContainsMediaInternal(paramMedia, 0)) {
return;
}
addMedia(paramMedia, false);
}
protected void onLocaleChanged(Locale paramLocale1, Locale paramLocale2)
{
int i = getNameResourceId();
if (i == 0) {
return;
}
setReadOnly(PROP_NAME, BaseApplication.current().getString(i));
}
protected void onMediaCreated(Media paramMedia, int paramInt)
{
if (!shouldContainsMediaInternal(paramMedia, paramInt)) {
return;
}
if (!((Boolean)paramMedia.getSource().get(MediaSource.PROP_IS_MEDIA_TABLE_READY)).booleanValue())
{
addMedia(paramMedia, false);
scheduleCommitMediaSync();
return;
}
addMedia(paramMedia, true);
}
protected void onMediaDeleted(Media paramMedia, int paramInt)
{
removeHiddenMedia(paramMedia);
if (!((Boolean)paramMedia.getSource().get(MediaSource.PROP_IS_MEDIA_TABLE_READY)).booleanValue())
{
removeMedia(paramMedia, false);
scheduleCommitMediaSync();
return;
}
removeMedia(paramMedia, true);
}
protected void onMediaIterationEnded()
{
long l1 = SystemClock.elapsedRealtime();
long l2 = this.m_MediaIterationStartTime;
Log.d(this.TAG, "onMediaIterationEnded() - Take ", Long.valueOf(l1 - l2), " ms to iterate media");
commitMediaSync();
}
protected void onMediaIterationStarted()
{
this.m_MediaIterationStartTime = SystemClock.elapsedRealtime();
}
protected void onMediaTableReady()
{
if (!canSyncMediaBeforeMediaTableReady())
{
setupMedia();
return;
}
commitMediaSync();
}
protected void onMediaUpdated(Media paramMedia, int paramInt)
{
boolean bool2 = true;
boolean bool1 = true;
if (!paramMedia.getSource().isRecycledMedia(paramMedia))
{
if (!shouldContainsMediaInternal(paramMedia, paramInt))
{
removeHiddenMedia(paramMedia);
removeMedia(paramMedia, true);
}
}
else {
return;
}
int i;
if ((Media.FLAG_VISIBILITY_CHANGED & paramInt) == 0)
{
i = 0;
label55:
if (i != 0) {
break label132;
}
label59:
if (!paramMedia.isVisible()) {
break label159;
}
}
for (;;)
{
if (i == 0)
{
label72:
if (addMedia(paramMedia, bool1)) {
break label203;
}
if (!this.m_Media.contains(paramMedia)) {
break;
}
checkMediaPositionInMediaLists(paramMedia, paramInt);
if ((!this.m_CoverMediaList.contains(paramMedia)) || ((COVER_MEDIA_UPDATE_FLAGS_MASK & paramInt) == 0)) {
break;
}
updateCoverHashCode();
return;
i = 1;
break label55;
label132:
if (!paramMedia.isVisible())
{
addHiddenMedia(paramMedia);
break label59;
}
removeHiddenMedia(paramMedia);
break label59;
label159:
if (!this.m_ContainsHiddenMedia)
{
addHiddenMedia(paramMedia);
if (i != 0) {
break label213;
}
}
}
}
label203:
label213:
for (bool1 = bool2;; bool1 = false)
{
removeMedia(paramMedia, bool1);
if (i == 0) {
break;
}
scheduleCommitMediaSync();
return;
bool1 = false;
break label72;
if (i == 0) {
return;
}
scheduleCommitMediaSync();
return;
}
}
protected PropertyChangedCallback<Locale> onPrepareLocaleChangedCallback()
{
new PropertyChangedCallback()
{
public void onPropertyChanged(PropertySource paramAnonymousPropertySource, PropertyKey<Locale> paramAnonymousPropertyKey, PropertyChangeEventArgs<Locale> paramAnonymousPropertyChangeEventArgs)
{
BaseMediaSet.this.onLocaleChanged((Locale)paramAnonymousPropertyChangeEventArgs.getOldValue(), (Locale)paramAnonymousPropertyChangeEventArgs.getNewValue());
}
};
}
protected Handle onPrepareMediaChangeCallback()
{
this.m_Source.addMediaChangedCallback(new MediaChangeCallback()
{
public void onMediaCreated(MediaSource paramAnonymousMediaSource, Media paramAnonymousMedia, int paramAnonymousInt)
{
BaseMediaSet.this.onMediaCreated(paramAnonymousMedia, paramAnonymousInt);
}
public void onMediaDeleted(MediaSource paramAnonymousMediaSource, Media paramAnonymousMedia, int paramAnonymousInt)
{
BaseMediaSet.this.onMediaDeleted(paramAnonymousMedia, paramAnonymousInt);
}
public void onMediaUpdated(MediaSource paramAnonymousMediaSource, Media paramAnonymousMedia, int paramAnonymousInt)
{
BaseMediaSet.this.onMediaUpdated(paramAnonymousMedia, paramAnonymousInt);
}
});
}
protected Iterable<Media> onPrepareMediaForMediaList()
{
return this.m_Media;
}
protected Handle onPrepareMediaIterationClient()
{
this.m_Source.addMediaIterationClient(new MediaIterationClient()
{
public void onIterate(Media paramAnonymousMedia)
{
BaseMediaSet.this.onIterateMedia(paramAnonymousMedia);
}
public void onIterationEnded()
{
BaseMediaSet.this.onMediaIterationEnded();
}
public void onIterationStarted()
{
BaseMediaSet.this.onMediaIterationStarted();
}
}, this.m_TargetMediaType);
}
protected void onRelease()
{
this.m_Source.removeCallback(MediaSource.PROP_IS_MEDIA_TABLE_READY, this.m_MediaTableStateChangedCB);
if (this.m_LocaleChangedCallback == null) {}
for (;;)
{
this.m_MediaChangeCBHandle = Handle.close(this.m_MediaChangeCBHandle);
this.m_MediaIterationClientHandle = Handle.close(this.m_MediaIterationClientHandle);
clearMedia();
super.onRelease();
return;
BaseApplication.current().removeCallback(BaseApplication.PROP_LOCALE, this.m_LocaleChangedCallback);
}
}
public MediaList openMediaList(MediaComparator paramMediaComparator, int paramInt1, int paramInt2)
{
Object localObject1 = null;
verifyAccess();
MediaListImpl localMediaListImpl;
long l1;
Object localObject3;
Object localObject2;
if (!((Boolean)get(PROP_IS_RELEASED)).booleanValue())
{
if (paramInt1 != 0)
{
localMediaListImpl = new MediaListImpl(paramMediaComparator, paramInt1);
this.m_OpenedMediaLists.add(localMediaListImpl);
Log.v(this.TAG, "[", getId(), "] openMediaList() - Opened media list count : ", Integer.valueOf(this.m_OpenedMediaLists.size()));
l1 = SystemClock.elapsedRealtime();
localObject3 = onPrepareMediaForMediaList();
if (paramInt1 != 1) {
break label142;
}
localObject3 = ((Iterable)localObject3).iterator();
for (;;)
{
if (!((Iterator)localObject3).hasNext()) {
break label423;
}
localObject2 = (Media)((Iterator)localObject3).next();
if (localObject1 != null) {
break;
}
label131:
localObject1 = localObject2;
}
}
}
else {
return null;
}
return null;
label142:
if (!(localObject3 instanceof Collection))
{
localObject2 = new ArrayList();
localObject3 = ((Iterable)localObject3).iterator();
for (;;)
{
localObject1 = localObject2;
if (!((Iterator)localObject3).hasNext()) {
break;
}
((List)localObject2).add((Media)((Iterator)localObject3).next());
}
}
localObject1 = new ArrayList((Collection)localObject3);
Collections.sort((List)localObject1, paramMediaComparator);
if (paramInt1 <= 0)
{
paramMediaComparator = (MediaComparator)localObject1;
label230:
localMediaListImpl.addMedia(paramMediaComparator, true);
}
for (;;)
{
long l2 = SystemClock.elapsedRealtime();
Log.v(this.TAG, "[", new Object[] { getId(), "] openMediaList() - Take ", Long.valueOf(l2 - l1), " ms to select ", Integer.valueOf(localMediaListImpl.size()), " media" });
return localMediaListImpl;
paramMediaComparator = (MediaComparator)localObject1;
if (((List)localObject1).size() <= paramInt1) {
break label230;
}
if (((List)localObject1).size() < paramInt1 * 2)
{
paramInt2 = ((List)localObject1).size();
for (;;)
{
paramInt2 -= 1;
paramMediaComparator = (MediaComparator)localObject1;
if (paramInt2 < paramInt1) {
break;
}
((List)localObject1).remove(paramInt2);
}
}
paramMediaComparator = new ArrayList(paramInt1);
paramInt2 = 0;
while (paramInt2 < paramInt1)
{
paramMediaComparator.add((Media)((List)localObject1).get(paramInt2));
paramInt2 += 1;
}
break label230;
if (paramMediaComparator.compare(localObject2, localObject1) < 0) {
break label131;
}
break;
label423:
localMediaListImpl.addMedia((Media)localObject1);
}
}
public <T> void putExtra(ExtraKey<T> paramExtraKey, T paramT)
{
if (paramT == null)
{
if (this.m_Extra != null) {}
}
else
{
if (this.m_Extra != null) {}
for (;;)
{
this.m_Extra.put(paramExtraKey.getId(), paramT);
return;
this.m_Extra = new LongSparseArray();
}
}
this.m_Extra.delete(paramExtraKey.getId());
}
protected boolean removeMedia(Media paramMedia, boolean paramBoolean)
{
if (paramMedia != null)
{
if (this.m_PendingAddingMedia.remove(paramMedia)) {
break label51;
}
if (!this.m_Media.contains(paramMedia)) {
break label53;
}
if (!this.m_PendingRemovingMedia.add(paramMedia)) {
break label55;
}
if (paramBoolean) {
break label57;
}
}
label51:
label53:
label55:
label57:
while (((Boolean)get(PROP_IS_DELETING)).booleanValue())
{
return true;
return false;
return true;
return false;
return false;
}
commitMediaSync();
return true;
}
protected void removeMediaFromMediaLists(Media paramMedia)
{
int i = this.m_OpenedMediaLists.size() - 1;
if (i >= 0)
{
MediaListImpl localMediaListImpl = (MediaListImpl)this.m_OpenedMediaLists.get(i);
if (!localMediaListImpl.removeMedia(paramMedia)) {}
for (;;)
{
i -= 1;
break;
if ((localMediaListImpl.getMaxMediaCount() > 0) && (localMediaListImpl.size() < localMediaListImpl.getMaxMediaCount()) && (localMediaListImpl.size() < this.m_Media.size())) {
localMediaListImpl.addMedia(this.m_Media);
}
}
}
}
protected void removeMediaFromMediaLists(Collection<Media> paramCollection)
{
if (paramCollection == null) {}
while ((paramCollection.isEmpty()) || (this.m_OpenedMediaLists.isEmpty())) {
return;
}
int i;
MediaListImpl localMediaListImpl;
if (!(paramCollection instanceof List))
{
i = this.m_OpenedMediaLists.size() - 1;
if (i >= 0)
{
localMediaListImpl = (MediaListImpl)this.m_OpenedMediaLists.get(i);
Iterator localIterator = paramCollection.iterator();
for (boolean bool1 = false; localIterator.hasNext(); bool1 = localMediaListImpl.removeMedia((Media)localIterator.next()) | bool1) {}
}
}
else
{
paramCollection = (List)paramCollection;
int k = paramCollection.size();
i = this.m_OpenedMediaLists.size() - 1;
if (i >= 0)
{
localMediaListImpl = (MediaListImpl)this.m_OpenedMediaLists.get(i);
int j = k - 1;
boolean bool2 = false;
while (j >= 0)
{
bool2 |= localMediaListImpl.removeMedia((Media)paramCollection.get(j));
j -= 1;
}
if (!bool2) {}
for (;;)
{
i -= 1;
break;
if ((localMediaListImpl.getMaxMediaCount() > 0) && (localMediaListImpl.size() < localMediaListImpl.getMaxMediaCount()) && (localMediaListImpl.size() < this.m_Media.size())) {
localMediaListImpl.addMedia(this.m_Media);
}
}
if (j == 0) {}
for (;;)
{
i -= 1;
break;
if ((localMediaListImpl.getMaxMediaCount() > 0) && (localMediaListImpl.size() < localMediaListImpl.getMaxMediaCount()) && (localMediaListImpl.size() < this.m_Media.size())) {
localMediaListImpl.addMedia(this.m_Media);
}
}
}
}
}
public <TValue> boolean set(PropertyKey<TValue> paramPropertyKey, TValue paramTValue)
{
if (paramPropertyKey != PROP_CONTAINS_HIDDEN_MEDIA) {
return super.set(paramPropertyKey, paramTValue);
}
return setContainsHiddenMediaProp(((Boolean)paramTValue).booleanValue());
}
protected abstract boolean shouldContainsMedia(Media paramMedia, int paramInt);
protected abstract void startDeletion(Handle paramHandle, int paramInt);
public String toString()
{
return getId();
}
protected void updateCoverHashCode()
{
StringBuilder localStringBuilder;
int i;
Object localObject;
if (!((Boolean)get(PROP_IS_DELETING)).booleanValue())
{
localStringBuilder = new StringBuilder();
localStringBuilder.append('[');
localStringBuilder.append(getId());
localStringBuilder.append(']');
int j = this.m_CoverMediaList.size();
i = 0;
if (i >= j) {
break label166;
}
localObject = (Media)this.m_CoverMediaList.get(i);
if ((localObject instanceof GroupedMedia)) {
break label133;
}
label89:
if (i > 0) {
break label155;
}
}
for (;;)
{
localStringBuilder.append(((Media)localObject).getId());
localStringBuilder.append(':');
localStringBuilder.append(((Media)localObject).getLastModifiedTime());
i += 1;
break;
return;
label133:
Media localMedia = ((GroupedMedia)localObject).getCover();
if (localMedia == null) {
break label89;
}
localObject = localMedia;
break label89;
label155:
localStringBuilder.append(',');
}
label166:
setReadOnly(PROP_COVER_HASH_CODE, localStringBuilder.toString());
}
private final class CommitMediaSyncRunnable
implements Runnable
{
private CommitMediaSyncRunnable() {}
public void run()
{
BaseMediaSet.this.m_IsDelayedMediaSyncCommitScheduled = false;
BaseMediaSet.this.commitMediaSync();
}
}
private final class MediaListImpl
extends BaseMediaList
{
public MediaListImpl(MediaComparator paramMediaComparator, int paramInt)
{
super(paramInt);
}
public void release()
{
verifyAccess();
BaseMediaSet.this.onMediaListReleased(this);
super.release();
}
}
}
/* Location: /Users/joshua/Desktop/system_framework/classes-dex2jar.jar!/com/oneplus/gallery2/media/BaseMediaSet.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 33,532 | java | BaseMediaSet.java | Java | [
{
"context": ");\n }\n }\n}\n\n\n/* Location: /Users/joshua/Desktop/system_framework/classes-dex2jar.jar!/com",
"end": 33369,
"score": 0.7974069118499756,
"start": 33363,
"tag": "USERNAME",
"value": "joshua"
}
] | null | [] | package com.oneplus.gallery2.media;
import android.content.Intent;
import android.os.Handler;
import android.os.SystemClock;
import android.util.LongSparseArray;
import com.oneplus.base.BaseApplication;
import com.oneplus.base.BasicBaseObject;
import com.oneplus.base.CallbackHandle;
import com.oneplus.base.EventArgs;
import com.oneplus.base.Handle;
import com.oneplus.base.HandlerUtils;
import com.oneplus.base.Log;
import com.oneplus.base.PropertyChangeEventArgs;
import com.oneplus.base.PropertyChangedCallback;
import com.oneplus.base.PropertyKey;
import com.oneplus.base.PropertySource;
import com.oneplus.gallery2.ExtraKey;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
public abstract class BaseMediaSet
extends BasicBaseObject
implements MediaSet
{
private static final int COVER_MEDIA_UPDATE_FLAGS_MASK = Media.FLAG_LAST_MODIFIED_TIME_CHANGED | GroupedMedia.FLAG_COVER_CHANGED;
private static final long DURATION_COMMIT_MEDIA_SYNC_DELAY = 500L;
private static final boolean PRINT_MEDIA_DEBUG_LOG = false;
private boolean m_ContainsHiddenMedia;
private final List<Media> m_CoverMediaList = new ArrayList();
private LongSparseArray<Object> m_Extra;
private final Set<Media> m_HiddenMedia = new HashSet();
private boolean m_IsDelayedMediaSyncCommitScheduled;
private PropertyChangedCallback<Locale> m_LocaleChangedCallback;
private final Set<Media> m_Media = new HashSet();
private Handle m_MediaChangeCBHandle;
private Handle m_MediaIterationClientHandle;
private long m_MediaIterationStartTime;
private final PropertyChangedCallback<Boolean> m_MediaTableStateChangedCB = new PropertyChangedCallback()
{
public void onPropertyChanged(PropertySource paramAnonymousPropertySource, PropertyKey<Boolean> paramAnonymousPropertyKey, PropertyChangeEventArgs<Boolean> paramAnonymousPropertyChangeEventArgs)
{
if (!((Boolean)paramAnonymousPropertyChangeEventArgs.getNewValue()).booleanValue()) {
return;
}
paramAnonymousPropertySource.removeCallback(paramAnonymousPropertyKey, this);
BaseMediaSet.this.onMediaTableReady();
}
};
private final List<MediaListImpl> m_OpenedMediaLists = new ArrayList();
private final Set<Media> m_PendingAddingMedia = new HashSet();
private final Set<Media> m_PendingRemovingMedia = new HashSet();
private int m_PhotoCount;
private final MediaSource m_Source;
private final MediaType m_TargetMediaType;
private int m_VideoCount;
protected BaseMediaSet(MediaSource paramMediaSource, MediaType paramMediaType)
{
label140:
label147:
int i;
if (paramMediaSource != null)
{
if (paramMediaType == MediaType.UNKNOWN) {
break label175;
}
this.m_Source = paramMediaSource;
this.m_TargetMediaType = paramMediaType;
this.m_LocaleChangedCallback = onPrepareLocaleChangedCallback();
if (this.m_LocaleChangedCallback != null) {
break label185;
}
if (!((Boolean)paramMediaSource.get(MediaSource.PROP_IS_MEDIA_TABLE_READY)).booleanValue()) {
break label201;
}
onMediaTableReady();
if (canSyncMediaBeforeMediaTableReady()) {
break label217;
}
i = getNameResourceId();
if (i != 0) {
break label224;
}
}
for (;;)
{
enablePropertyLogs(PROP_COVER_HASH_CODE, 1);
return;
throw new IllegalArgumentException("No media source");
label175:
throw new IllegalArgumentException("No target media type");
label185:
BaseApplication.current().addCallback(BaseApplication.PROP_LOCALE, this.m_LocaleChangedCallback);
break;
label201:
paramMediaSource.addCallback(MediaSource.PROP_IS_MEDIA_TABLE_READY, this.m_MediaTableStateChangedCB);
break label140;
label217:
setupMedia();
break label147;
label224:
setReadOnly(PROP_NAME, BaseApplication.current().getString(i));
}
}
private boolean addHiddenMedia(Media paramMedia)
{
if (paramMedia == null) {}
while (paramMedia.isVisible()) {
return false;
}
boolean bool = this.m_HiddenMedia.add(paramMedia);
if (!bool) {
return bool;
}
setReadOnly(MediaSet.PROP_HIDDEN_MEDIA_COUNT, Integer.valueOf(this.m_HiddenMedia.size()));
return bool;
}
private void onMediaListReleased(MediaListImpl paramMediaListImpl)
{
if (this.m_OpenedMediaLists.remove(paramMediaListImpl))
{
Log.v(this.TAG, "[", getId(), "] onMediaListReleased() - Opened media list count : ", Integer.valueOf(this.m_OpenedMediaLists.size()));
return;
}
}
private boolean removeHiddenMedia(Media paramMedia)
{
boolean bool;
if (paramMedia != null)
{
bool = this.m_HiddenMedia.remove(paramMedia);
if (!bool) {
return bool;
}
}
else
{
return false;
}
setReadOnly(MediaSet.PROP_HIDDEN_MEDIA_COUNT, Integer.valueOf(this.m_HiddenMedia.size()));
return bool;
}
private void scheduleCommitMediaSync()
{
if (this.m_IsDelayedMediaSyncCommitScheduled) {
return;
}
this.m_IsDelayedMediaSyncCommitScheduled = HandlerUtils.post(this, new CommitMediaSyncRunnable(null), 500L);
}
private boolean setContainsHiddenMediaProp(boolean paramBoolean)
{
boolean bool = this.m_ContainsHiddenMedia;
if (bool != paramBoolean)
{
this.m_ContainsHiddenMedia = paramBoolean;
if (!paramBoolean)
{
localIterator = this.m_HiddenMedia.iterator();
while (localIterator.hasNext()) {
removeMedia((Media)localIterator.next(), false);
}
}
}
else
{
return false;
}
Iterator localIterator = this.m_HiddenMedia.iterator();
while (localIterator.hasNext()) {
addMedia((Media)localIterator.next(), false);
}
commitMediaSync();
return notifyPropertyChanged(PROP_CONTAINS_HIDDEN_MEDIA, Boolean.valueOf(bool), Boolean.valueOf(paramBoolean));
}
private void setupMedia()
{
if (Handle.isValid(this.m_MediaChangeCBHandle)) {
if (!Handle.isValid(this.m_MediaIterationClientHandle)) {
break label42;
}
}
for (;;)
{
if (Handle.isValid(this.m_MediaIterationClientHandle)) {
break label53;
}
return;
this.m_MediaChangeCBHandle = onPrepareMediaChangeCallback();
break;
label42:
this.m_MediaIterationClientHandle = onPrepareMediaIterationClient();
}
label53:
this.m_Source.scheduleMediaIteration(0);
}
private boolean shouldContainsMediaInternal(Media paramMedia, int paramInt)
{
if (this.m_TargetMediaType == null) {}
while (paramMedia.getType() == this.m_TargetMediaType) {
return shouldContainsMedia(paramMedia, paramInt);
}
return false;
}
private void updateCoverMediaList()
{
this.m_CoverMediaList.clear();
if (this.m_Media.size() <= 12)
{
this.m_CoverMediaList.addAll(this.m_Media);
Collections.sort(this.m_CoverMediaList, COVER_MEDIA_COMPARATOR);
}
for (;;)
{
updateCoverHashCode();
return;
Iterator localIterator = this.m_Media.iterator();
while (localIterator.hasNext())
{
Media localMedia = (Media)localIterator.next();
int i = Collections.binarySearch(this.m_CoverMediaList, localMedia, COVER_MEDIA_COMPARATOR) ^ 0xFFFFFFFF;
if ((i >= 0) && (i < 12)) {
this.m_CoverMediaList.add(i, localMedia);
}
}
}
}
protected boolean addMedia(Media paramMedia, boolean paramBoolean)
{
if (paramMedia != null)
{
if (!paramMedia.isVisible()) {
break label47;
}
if (this.m_Media.contains(paramMedia)) {
break label62;
}
if (!this.m_PendingRemovingMedia.remove(paramMedia)) {
break label64;
}
label39:
if (paramBoolean) {
break label79;
}
}
for (;;)
{
return true;
return false;
label47:
addHiddenMedia(paramMedia);
if (this.m_ContainsHiddenMedia) {
break;
}
return false;
label62:
return false;
label64:
if (this.m_PendingAddingMedia.add(paramMedia)) {
break label39;
}
return false;
label79:
commitMediaSync();
}
}
protected void addMediaToMediaLists(Media paramMedia)
{
int i = this.m_OpenedMediaLists.size() - 1;
while (i >= 0)
{
((MediaListImpl)this.m_OpenedMediaLists.get(i)).addMedia(paramMedia);
i -= 1;
}
}
protected void addMediaToMediaLists(Collection<Media> paramCollection)
{
MediaListImpl localMediaListImpl = null;
if (paramCollection == null) {}
while (this.m_OpenedMediaLists.isEmpty()) {
return;
}
ArrayList localArrayList = new ArrayList(paramCollection);
int i = this.m_OpenedMediaLists.size() - 1;
paramCollection = localMediaListImpl;
if (i >= 0)
{
localMediaListImpl = (MediaListImpl)this.m_OpenedMediaLists.get(i);
if (localMediaListImpl.getComparator() == paramCollection) {}
for (;;)
{
localMediaListImpl.addMedia(localArrayList, true);
i -= 1;
break;
paramCollection = localMediaListImpl.getComparator();
Collections.sort(localArrayList, paramCollection);
}
}
}
protected boolean canSyncMediaBeforeMediaTableReady()
{
return true;
}
protected void checkMediaPositionInMediaLists(Media paramMedia, int paramInt)
{
int i = this.m_OpenedMediaLists.size() - 1;
if (i >= 0)
{
MediaListImpl localMediaListImpl = (MediaListImpl)this.m_OpenedMediaLists.get(i);
if ((localMediaListImpl.getComparator().getEffectiveMediaUpdateFlags() & paramInt) == 0) {}
for (;;)
{
i -= 1;
break;
localMediaListImpl.checkMediaIndex(paramMedia);
}
}
}
protected void clearExtras()
{
this.m_Extra = null;
}
protected void clearMedia()
{
verifyAccess();
if (!this.m_Media.isEmpty())
{
int i = this.m_PhotoCount;
int j = this.m_VideoCount;
this.m_PendingAddingMedia.clear();
this.m_PendingRemovingMedia.clear();
this.m_Media.clear();
this.m_CoverMediaList.clear();
this.m_PhotoCount = 0;
this.m_VideoCount = 0;
notifyPropertyChanged(PROP_PHOTO_COUNT, Integer.valueOf(i), Integer.valueOf(this.m_PhotoCount));
notifyPropertyChanged(PROP_VIDEO_COUNT, Integer.valueOf(j), Integer.valueOf(this.m_VideoCount));
setReadOnly(PROP_MEDIA_COUNT, null);
updateCoverHashCode();
return;
}
}
protected void commitMediaSync()
{
int i1 = 0;
int i2 = 0;
verifyAccess();
int n;
int i;
int j;
label53:
label57:
label61:
Media localMedia;
if (this.m_PendingRemovingMedia.isEmpty())
{
n = 0;
i = 0;
j = 0;
if (this.m_PendingAddingMedia.isEmpty())
{
k = i2;
if (n != 0) {
break label486;
}
if (k != 0) {
break label493;
}
if (j != 0) {
break label500;
}
if (i != 0) {
break label537;
}
setReadOnly(PROP_MEDIA_COUNT, Integer.valueOf(this.m_Media.size()));
}
}
else
{
localIterator = this.m_PendingRemovingMedia.iterator();
i = 0;
k = 0;
m = 0;
j = 0;
while (localIterator.hasNext())
{
localMedia = (Media)localIterator.next();
if (this.m_Media.remove(localMedia)) {
switch ($SWITCH_TABLE$com$oneplus$gallery2$media$MediaType()[localMedia.getType().ordinal()])
{
default:
break;
case 2:
j -= 1;
case 3:
for (;;)
{
if (k == 0) {
break label201;
}
i = 1;
break;
m -= 1;
}
label201:
if (Collections.binarySearch(this.m_CoverMediaList, localMedia, COVER_MEDIA_COMPARATOR) < 0)
{
i = 1;
}
else
{
i = 1;
k = 1;
}
break;
}
}
}
if (i == 0) {}
for (;;)
{
this.m_PendingRemovingMedia.clear();
i = m;
n = k;
break;
removeMediaFromMediaLists(this.m_PendingRemovingMedia);
}
}
Iterator localIterator = this.m_PendingAddingMedia.iterator();
int m = 0;
int k = i1;
for (;;)
{
if (localIterator.hasNext())
{
localMedia = (Media)localIterator.next();
if (this.m_Media.add(localMedia)) {
switch ($SWITCH_TABLE$com$oneplus$gallery2$media$MediaType()[localMedia.getType().ordinal()])
{
default:
break;
case 2:
j += 1;
case 3:
for (;;)
{
if (n == 0) {
break label376;
}
k = 1;
break;
i += 1;
}
label376:
k = Collections.binarySearch(this.m_CoverMediaList, localMedia, COVER_MEDIA_COMPARATOR) ^ 0xFFFFFFFF;
if (k < 0) {}
while (k >= 12)
{
k = 1;
break;
}
this.m_CoverMediaList.add(k, localMedia);
while (this.m_CoverMediaList.size() > 12) {
this.m_CoverMediaList.remove(this.m_CoverMediaList.size() - 1);
}
}
}
}
else
{
if (k == 0) {}
for (;;)
{
this.m_PendingAddingMedia.clear();
k = m;
break;
addMediaToMediaLists(this.m_PendingAddingMedia);
}
label486:
updateCoverMediaList();
break label53;
label493:
updateCoverHashCode();
break label53;
label500:
this.m_PhotoCount += j;
notifyPropertyChanged(PROP_PHOTO_COUNT, Integer.valueOf(this.m_PhotoCount - j), Integer.valueOf(this.m_PhotoCount));
break label57;
label537:
this.m_VideoCount += i;
notifyPropertyChanged(PROP_VIDEO_COUNT, Integer.valueOf(this.m_VideoCount - i), Integer.valueOf(this.m_VideoCount));
break label61;
k = 1;
m = 1;
}
}
}
protected void completeDeletion(Handle paramHandle, boolean paramBoolean, int paramInt)
{
verifyAccess();
if (paramHandle == null) {}
while (!(paramHandle instanceof CallbackHandle)) {
return;
}
if (((Boolean)get(PROP_IS_DELETING)).booleanValue())
{
paramHandle = (CallbackHandle)paramHandle;
if (paramHandle.getCallback() != null) {
break label88;
}
setReadOnly(PROP_IS_DELETING, Boolean.valueOf(false));
if (paramBoolean) {
break label104;
}
}
for (;;)
{
onDeletionCompleted(paramBoolean, paramInt);
if (paramBoolean) {
break label120;
}
if (!((Boolean)get(PROP_IS_RELEASED)).booleanValue()) {
break label165;
}
return;
return;
label88:
((MediaSet.DeletionCallback)paramHandle.getCallback()).onDeletionCompleted(this, paramBoolean, paramInt);
break;
label104:
this.m_CoverMediaList.clear();
updateCoverHashCode();
}
label120:
clearMedia();
raise(EVENT_DELETED, EventArgs.EMPTY);
paramHandle = new Intent("com.oneplus.gallery2.media.action.MEDIA_SET_DELETED");
paramHandle.putExtra("MediaSetId", getId());
BaseApplication.current().sendBroadcast(paramHandle);
return;
label165:
commitMediaSync();
}
public boolean contains(Media paramMedia)
{
if (paramMedia == null) {}
while (!this.m_Media.contains(paramMedia)) {
return false;
}
return true;
}
public Handle delete(MediaSet.DeletionCallback paramDeletionCallback, int paramInt)
{
verifyAccess();
if (((Boolean)get(PROP_IS_RELEASED)).booleanValue()) {}
while (((Boolean)get(PROP_IS_DELETING)).booleanValue()) {
return null;
}
setReadOnly(PROP_IS_DELETING, Boolean.valueOf(true));
CallbackHandle local2 = new CallbackHandle("DeleteMediaSet", paramDeletionCallback, null)
{
protected void onClose(int paramAnonymousInt) {}
};
if (paramDeletionCallback == null) {}
for (;;)
{
startDeletion(local2, paramInt);
return local2;
paramDeletionCallback.onDeletionStarted(this, paramInt);
}
}
public <TValue> TValue get(PropertyKey<TValue> paramPropertyKey)
{
if (paramPropertyKey != PROP_CONTAINS_HIDDEN_MEDIA)
{
if (paramPropertyKey != PROP_PHOTO_COUNT)
{
if (paramPropertyKey == PROP_VIDEO_COUNT) {
break label43;
}
return (TValue)super.get(paramPropertyKey);
}
}
else {
return Boolean.valueOf(this.m_ContainsHiddenMedia);
}
return Integer.valueOf(this.m_PhotoCount);
label43:
return Integer.valueOf(this.m_VideoCount);
}
public <T> T getExtra(ExtraKey<T> paramExtraKey, T paramT)
{
if (this.m_Extra == null) {}
do
{
return paramT;
paramExtraKey = this.m_Extra.get(paramExtraKey.getId());
} while (paramExtraKey == null);
return paramExtraKey;
}
public final Handler getHandler()
{
return this.m_Source.getHandler();
}
protected final Iterable<Media> getMedia()
{
return this.m_Media;
}
protected int getNameResourceId()
{
return 0;
}
public <T extends MediaSource> T getSource()
{
return this.m_Source;
}
public MediaType getTargetMediaType()
{
return this.m_TargetMediaType;
}
public boolean isVisibilityChangeSupported()
{
return false;
}
protected void onDeletionCompleted(boolean paramBoolean, int paramInt) {}
protected void onIterateMedia(Media paramMedia)
{
if (!shouldContainsMediaInternal(paramMedia, 0)) {
return;
}
addMedia(paramMedia, false);
}
protected void onLocaleChanged(Locale paramLocale1, Locale paramLocale2)
{
int i = getNameResourceId();
if (i == 0) {
return;
}
setReadOnly(PROP_NAME, BaseApplication.current().getString(i));
}
protected void onMediaCreated(Media paramMedia, int paramInt)
{
if (!shouldContainsMediaInternal(paramMedia, paramInt)) {
return;
}
if (!((Boolean)paramMedia.getSource().get(MediaSource.PROP_IS_MEDIA_TABLE_READY)).booleanValue())
{
addMedia(paramMedia, false);
scheduleCommitMediaSync();
return;
}
addMedia(paramMedia, true);
}
protected void onMediaDeleted(Media paramMedia, int paramInt)
{
removeHiddenMedia(paramMedia);
if (!((Boolean)paramMedia.getSource().get(MediaSource.PROP_IS_MEDIA_TABLE_READY)).booleanValue())
{
removeMedia(paramMedia, false);
scheduleCommitMediaSync();
return;
}
removeMedia(paramMedia, true);
}
protected void onMediaIterationEnded()
{
long l1 = SystemClock.elapsedRealtime();
long l2 = this.m_MediaIterationStartTime;
Log.d(this.TAG, "onMediaIterationEnded() - Take ", Long.valueOf(l1 - l2), " ms to iterate media");
commitMediaSync();
}
protected void onMediaIterationStarted()
{
this.m_MediaIterationStartTime = SystemClock.elapsedRealtime();
}
protected void onMediaTableReady()
{
if (!canSyncMediaBeforeMediaTableReady())
{
setupMedia();
return;
}
commitMediaSync();
}
protected void onMediaUpdated(Media paramMedia, int paramInt)
{
boolean bool2 = true;
boolean bool1 = true;
if (!paramMedia.getSource().isRecycledMedia(paramMedia))
{
if (!shouldContainsMediaInternal(paramMedia, paramInt))
{
removeHiddenMedia(paramMedia);
removeMedia(paramMedia, true);
}
}
else {
return;
}
int i;
if ((Media.FLAG_VISIBILITY_CHANGED & paramInt) == 0)
{
i = 0;
label55:
if (i != 0) {
break label132;
}
label59:
if (!paramMedia.isVisible()) {
break label159;
}
}
for (;;)
{
if (i == 0)
{
label72:
if (addMedia(paramMedia, bool1)) {
break label203;
}
if (!this.m_Media.contains(paramMedia)) {
break;
}
checkMediaPositionInMediaLists(paramMedia, paramInt);
if ((!this.m_CoverMediaList.contains(paramMedia)) || ((COVER_MEDIA_UPDATE_FLAGS_MASK & paramInt) == 0)) {
break;
}
updateCoverHashCode();
return;
i = 1;
break label55;
label132:
if (!paramMedia.isVisible())
{
addHiddenMedia(paramMedia);
break label59;
}
removeHiddenMedia(paramMedia);
break label59;
label159:
if (!this.m_ContainsHiddenMedia)
{
addHiddenMedia(paramMedia);
if (i != 0) {
break label213;
}
}
}
}
label203:
label213:
for (bool1 = bool2;; bool1 = false)
{
removeMedia(paramMedia, bool1);
if (i == 0) {
break;
}
scheduleCommitMediaSync();
return;
bool1 = false;
break label72;
if (i == 0) {
return;
}
scheduleCommitMediaSync();
return;
}
}
protected PropertyChangedCallback<Locale> onPrepareLocaleChangedCallback()
{
new PropertyChangedCallback()
{
public void onPropertyChanged(PropertySource paramAnonymousPropertySource, PropertyKey<Locale> paramAnonymousPropertyKey, PropertyChangeEventArgs<Locale> paramAnonymousPropertyChangeEventArgs)
{
BaseMediaSet.this.onLocaleChanged((Locale)paramAnonymousPropertyChangeEventArgs.getOldValue(), (Locale)paramAnonymousPropertyChangeEventArgs.getNewValue());
}
};
}
protected Handle onPrepareMediaChangeCallback()
{
this.m_Source.addMediaChangedCallback(new MediaChangeCallback()
{
public void onMediaCreated(MediaSource paramAnonymousMediaSource, Media paramAnonymousMedia, int paramAnonymousInt)
{
BaseMediaSet.this.onMediaCreated(paramAnonymousMedia, paramAnonymousInt);
}
public void onMediaDeleted(MediaSource paramAnonymousMediaSource, Media paramAnonymousMedia, int paramAnonymousInt)
{
BaseMediaSet.this.onMediaDeleted(paramAnonymousMedia, paramAnonymousInt);
}
public void onMediaUpdated(MediaSource paramAnonymousMediaSource, Media paramAnonymousMedia, int paramAnonymousInt)
{
BaseMediaSet.this.onMediaUpdated(paramAnonymousMedia, paramAnonymousInt);
}
});
}
protected Iterable<Media> onPrepareMediaForMediaList()
{
return this.m_Media;
}
protected Handle onPrepareMediaIterationClient()
{
this.m_Source.addMediaIterationClient(new MediaIterationClient()
{
public void onIterate(Media paramAnonymousMedia)
{
BaseMediaSet.this.onIterateMedia(paramAnonymousMedia);
}
public void onIterationEnded()
{
BaseMediaSet.this.onMediaIterationEnded();
}
public void onIterationStarted()
{
BaseMediaSet.this.onMediaIterationStarted();
}
}, this.m_TargetMediaType);
}
protected void onRelease()
{
this.m_Source.removeCallback(MediaSource.PROP_IS_MEDIA_TABLE_READY, this.m_MediaTableStateChangedCB);
if (this.m_LocaleChangedCallback == null) {}
for (;;)
{
this.m_MediaChangeCBHandle = Handle.close(this.m_MediaChangeCBHandle);
this.m_MediaIterationClientHandle = Handle.close(this.m_MediaIterationClientHandle);
clearMedia();
super.onRelease();
return;
BaseApplication.current().removeCallback(BaseApplication.PROP_LOCALE, this.m_LocaleChangedCallback);
}
}
public MediaList openMediaList(MediaComparator paramMediaComparator, int paramInt1, int paramInt2)
{
Object localObject1 = null;
verifyAccess();
MediaListImpl localMediaListImpl;
long l1;
Object localObject3;
Object localObject2;
if (!((Boolean)get(PROP_IS_RELEASED)).booleanValue())
{
if (paramInt1 != 0)
{
localMediaListImpl = new MediaListImpl(paramMediaComparator, paramInt1);
this.m_OpenedMediaLists.add(localMediaListImpl);
Log.v(this.TAG, "[", getId(), "] openMediaList() - Opened media list count : ", Integer.valueOf(this.m_OpenedMediaLists.size()));
l1 = SystemClock.elapsedRealtime();
localObject3 = onPrepareMediaForMediaList();
if (paramInt1 != 1) {
break label142;
}
localObject3 = ((Iterable)localObject3).iterator();
for (;;)
{
if (!((Iterator)localObject3).hasNext()) {
break label423;
}
localObject2 = (Media)((Iterator)localObject3).next();
if (localObject1 != null) {
break;
}
label131:
localObject1 = localObject2;
}
}
}
else {
return null;
}
return null;
label142:
if (!(localObject3 instanceof Collection))
{
localObject2 = new ArrayList();
localObject3 = ((Iterable)localObject3).iterator();
for (;;)
{
localObject1 = localObject2;
if (!((Iterator)localObject3).hasNext()) {
break;
}
((List)localObject2).add((Media)((Iterator)localObject3).next());
}
}
localObject1 = new ArrayList((Collection)localObject3);
Collections.sort((List)localObject1, paramMediaComparator);
if (paramInt1 <= 0)
{
paramMediaComparator = (MediaComparator)localObject1;
label230:
localMediaListImpl.addMedia(paramMediaComparator, true);
}
for (;;)
{
long l2 = SystemClock.elapsedRealtime();
Log.v(this.TAG, "[", new Object[] { getId(), "] openMediaList() - Take ", Long.valueOf(l2 - l1), " ms to select ", Integer.valueOf(localMediaListImpl.size()), " media" });
return localMediaListImpl;
paramMediaComparator = (MediaComparator)localObject1;
if (((List)localObject1).size() <= paramInt1) {
break label230;
}
if (((List)localObject1).size() < paramInt1 * 2)
{
paramInt2 = ((List)localObject1).size();
for (;;)
{
paramInt2 -= 1;
paramMediaComparator = (MediaComparator)localObject1;
if (paramInt2 < paramInt1) {
break;
}
((List)localObject1).remove(paramInt2);
}
}
paramMediaComparator = new ArrayList(paramInt1);
paramInt2 = 0;
while (paramInt2 < paramInt1)
{
paramMediaComparator.add((Media)((List)localObject1).get(paramInt2));
paramInt2 += 1;
}
break label230;
if (paramMediaComparator.compare(localObject2, localObject1) < 0) {
break label131;
}
break;
label423:
localMediaListImpl.addMedia((Media)localObject1);
}
}
public <T> void putExtra(ExtraKey<T> paramExtraKey, T paramT)
{
if (paramT == null)
{
if (this.m_Extra != null) {}
}
else
{
if (this.m_Extra != null) {}
for (;;)
{
this.m_Extra.put(paramExtraKey.getId(), paramT);
return;
this.m_Extra = new LongSparseArray();
}
}
this.m_Extra.delete(paramExtraKey.getId());
}
protected boolean removeMedia(Media paramMedia, boolean paramBoolean)
{
if (paramMedia != null)
{
if (this.m_PendingAddingMedia.remove(paramMedia)) {
break label51;
}
if (!this.m_Media.contains(paramMedia)) {
break label53;
}
if (!this.m_PendingRemovingMedia.add(paramMedia)) {
break label55;
}
if (paramBoolean) {
break label57;
}
}
label51:
label53:
label55:
label57:
while (((Boolean)get(PROP_IS_DELETING)).booleanValue())
{
return true;
return false;
return true;
return false;
return false;
}
commitMediaSync();
return true;
}
protected void removeMediaFromMediaLists(Media paramMedia)
{
int i = this.m_OpenedMediaLists.size() - 1;
if (i >= 0)
{
MediaListImpl localMediaListImpl = (MediaListImpl)this.m_OpenedMediaLists.get(i);
if (!localMediaListImpl.removeMedia(paramMedia)) {}
for (;;)
{
i -= 1;
break;
if ((localMediaListImpl.getMaxMediaCount() > 0) && (localMediaListImpl.size() < localMediaListImpl.getMaxMediaCount()) && (localMediaListImpl.size() < this.m_Media.size())) {
localMediaListImpl.addMedia(this.m_Media);
}
}
}
}
protected void removeMediaFromMediaLists(Collection<Media> paramCollection)
{
if (paramCollection == null) {}
while ((paramCollection.isEmpty()) || (this.m_OpenedMediaLists.isEmpty())) {
return;
}
int i;
MediaListImpl localMediaListImpl;
if (!(paramCollection instanceof List))
{
i = this.m_OpenedMediaLists.size() - 1;
if (i >= 0)
{
localMediaListImpl = (MediaListImpl)this.m_OpenedMediaLists.get(i);
Iterator localIterator = paramCollection.iterator();
for (boolean bool1 = false; localIterator.hasNext(); bool1 = localMediaListImpl.removeMedia((Media)localIterator.next()) | bool1) {}
}
}
else
{
paramCollection = (List)paramCollection;
int k = paramCollection.size();
i = this.m_OpenedMediaLists.size() - 1;
if (i >= 0)
{
localMediaListImpl = (MediaListImpl)this.m_OpenedMediaLists.get(i);
int j = k - 1;
boolean bool2 = false;
while (j >= 0)
{
bool2 |= localMediaListImpl.removeMedia((Media)paramCollection.get(j));
j -= 1;
}
if (!bool2) {}
for (;;)
{
i -= 1;
break;
if ((localMediaListImpl.getMaxMediaCount() > 0) && (localMediaListImpl.size() < localMediaListImpl.getMaxMediaCount()) && (localMediaListImpl.size() < this.m_Media.size())) {
localMediaListImpl.addMedia(this.m_Media);
}
}
if (j == 0) {}
for (;;)
{
i -= 1;
break;
if ((localMediaListImpl.getMaxMediaCount() > 0) && (localMediaListImpl.size() < localMediaListImpl.getMaxMediaCount()) && (localMediaListImpl.size() < this.m_Media.size())) {
localMediaListImpl.addMedia(this.m_Media);
}
}
}
}
}
public <TValue> boolean set(PropertyKey<TValue> paramPropertyKey, TValue paramTValue)
{
if (paramPropertyKey != PROP_CONTAINS_HIDDEN_MEDIA) {
return super.set(paramPropertyKey, paramTValue);
}
return setContainsHiddenMediaProp(((Boolean)paramTValue).booleanValue());
}
protected abstract boolean shouldContainsMedia(Media paramMedia, int paramInt);
protected abstract void startDeletion(Handle paramHandle, int paramInt);
public String toString()
{
return getId();
}
protected void updateCoverHashCode()
{
StringBuilder localStringBuilder;
int i;
Object localObject;
if (!((Boolean)get(PROP_IS_DELETING)).booleanValue())
{
localStringBuilder = new StringBuilder();
localStringBuilder.append('[');
localStringBuilder.append(getId());
localStringBuilder.append(']');
int j = this.m_CoverMediaList.size();
i = 0;
if (i >= j) {
break label166;
}
localObject = (Media)this.m_CoverMediaList.get(i);
if ((localObject instanceof GroupedMedia)) {
break label133;
}
label89:
if (i > 0) {
break label155;
}
}
for (;;)
{
localStringBuilder.append(((Media)localObject).getId());
localStringBuilder.append(':');
localStringBuilder.append(((Media)localObject).getLastModifiedTime());
i += 1;
break;
return;
label133:
Media localMedia = ((GroupedMedia)localObject).getCover();
if (localMedia == null) {
break label89;
}
localObject = localMedia;
break label89;
label155:
localStringBuilder.append(',');
}
label166:
setReadOnly(PROP_COVER_HASH_CODE, localStringBuilder.toString());
}
private final class CommitMediaSyncRunnable
implements Runnable
{
private CommitMediaSyncRunnable() {}
public void run()
{
BaseMediaSet.this.m_IsDelayedMediaSyncCommitScheduled = false;
BaseMediaSet.this.commitMediaSync();
}
}
private final class MediaListImpl
extends BaseMediaList
{
public MediaListImpl(MediaComparator paramMediaComparator, int paramInt)
{
super(paramInt);
}
public void release()
{
verifyAccess();
BaseMediaSet.this.onMediaListReleased(this);
super.release();
}
}
}
/* Location: /Users/joshua/Desktop/system_framework/classes-dex2jar.jar!/com/oneplus/gallery2/media/BaseMediaSet.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 33,532 | 0.615442 | 0.601754 | 1,207 | 26.782104 | 28.091455 | 198 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.540182 | false | false | 12 |
1325eab13a4486a8ec5f48ff28e8fd49db5c9c71 | 14,405,320,334,868 | ef538292d8ee1ea4e8792b6ec72efba15214cbf6 | /Spring_Board/GivEngel/src/main/java/com/project/givengel/controller/MainController.java | 0d33f513e96a0b59b7c7482ebf0225a4673255c0 | [] | no_license | GIVENGEL/GivEngel-Project | https://github.com/GIVENGEL/GivEngel-Project | 8cccd61b710445b75af6c168ba61caba202341d6 | d65fd072aa4281c2d3cc70d076bafe76fb5d4b12 | refs/heads/main | 2023-07-04T05:30:25.115000 | 2021-08-11T10:41:13 | 2021-08-11T10:41:13 | 384,379,741 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.project.givengel.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.project.givengel.service.CampaignServiceImpl;
import com.project.givengel.service.FleaService;
import com.project.givengel.service.GoodListService;
import com.project.givengel.service.MypageServiceImpl;
import com.project.givengel.service.SponServiceImpl;
import com.project.givengel.vo.GoodVO;
import com.project.givengel.vo.SponVO;
import com.project.givengel.vo.Spon_comVO;
import com.project.givengel.vo.UserVO;
@Controller
public class MainController {
@Autowired
private CampaignServiceImpl campaignService;
@Autowired
private GoodListService goodListService;
@Autowired
private FleaService fleaService;
@Autowired
private MypageServiceImpl mypageService;
@Autowired
private SponServiceImpl sponService;
/*******************************************************
* 김민주
* 함수명 : index
*
* 함수 기능 : 상품리스트 페이지 전체 상품 리스트(카테고리별 분류)
* 사용된 서비스 : goodList (Service, dao)
* 마지막 수정 : 2021-07-26
*/
// 카테고리별 인기상품 출력?
@RequestMapping("/index.giv")
public void index(Model m,String categories, String color) {
List<GoodVO> list = goodListService.rankingGood();
List<GoodVO> listTOP = new ArrayList<GoodVO>();
List<GoodVO> listBOTTOM = new ArrayList<GoodVO>();
List<GoodVO> listBAG = new ArrayList<GoodVO>();
List<GoodVO> listACC = new ArrayList<GoodVO>();
for(int i=0; i<list.size(); i++) {
if(list.get(i).getGood_tag().contains("TOP")) {
String[] tp = list.get(i).getGood_tag().split("#");
list.get(i).setGood_tag(tp[0]);
listTOP.add(list.get(i));
}else if(list.get(i).getGood_tag().contains("BOTTOM")) {
String[] tp = list.get(i).getGood_tag().split("#");
list.get(i).setGood_tag(tp[0]);
listBOTTOM.add(list.get(i));
}else if(list.get(i).getGood_tag().contains("BAG")) {
String[] tp = list.get(i).getGood_tag().split("#");
list.get(i).setGood_tag(tp[0]);
listBAG.add(list.get(i));
}else if(list.get(i).getGood_tag().contains("ACC")) {
String[] tp = list.get(i).getGood_tag().split("#");
list.get(i).setGood_tag(tp[0]);
listACC.add(list.get(i));
}
}
m.addAttribute("listTOP", listTOP);
m.addAttribute("listBOTTOM",listBOTTOM);
m.addAttribute("listBAG", listBAG);
m.addAttribute("listACC", listACC);
m.addAttribute("latestGood1", goodListService.getlatestGood1());
m.addAttribute("rankingGood", goodListService.rankingGood());
m.addAttribute("goodComRanking", goodListService.goodComRanking());
}
/*****************************************************
* 함수명 : campaignList
* 함수 기능 : 1. 캠페인 리스트(스폰넘버만) 받아온 후 배열로 리스트불러옴 2.현재시간 불러와서 비교하고 안보이게
* 사용된 함수 : -
* 사용된 서비스 : campaignList (Service, dao)
* 마지막 수정 : 2021-08-01
*****************************************************/
@RequestMapping("/campaign.giv")
public Map<String,Object> campaignList(SponVO vo, Model m, Spon_comVO comvo) {
/*
* List<Integer> listString = new ArrayList<Integer>(); for(int
* i=0;i<sponService.getSponList(vo).size();i++) { int temp_sponNum =
* sponService.getSponList(vo).get(i).getSpon_no(); Spon_comVO com = new
* Spon_comVO(); com.setSpon_no(temp_sponNum);
*/
/*
* int result = sponService.countSponCom(com); listString.add(result);]
*/
List<SponVO> spon_list = new ArrayList<SponVO>();
spon_list = campaignService.campaignList();
List<Integer> com_list = new ArrayList<Integer>();
for(int i=0;i<spon_list.size();i++) {
Spon_comVO comvos = new Spon_comVO();
comvos.setSpon_no(spon_list.get(i).getSpon_no());
com_list.add(campaignService.countReview(comvos));
}
Map<String,Object> map = new HashMap<String,Object>();
List<SponVO> spon_list2 = new ArrayList<SponVO>();
spon_list2 = campaignService.campaignSpon();
String nowSysdate = campaignService.nowSysdate();
map.put("CountReview", com_list);
map.put("nowSysdate", nowSysdate);
map.put("spon_list", spon_list);
map.put("non_campaign", spon_list2);
return map;
}
@RequestMapping("/cartForm.giv")
public void cartForm() {
}
@RequestMapping("/contact.giv")
public void contact() {
}
@RequestMapping("/loginForm.giv")
public void loginForm() {
}
@RequestMapping("/myPage.giv")
public String myPage(UserVO vo, HttpServletRequest req, Model m) {
HttpSession session = req.getSession();
UserVO sessionvo = (UserVO)session.getAttribute("user");
if(sessionvo==null) {
return "/index";
}
else {
vo.setUser_no(sessionvo.getUser_no());
UserVO myvo = mypageService.userInfoView(vo);
m.addAttribute("myvo", myvo);
return "/myPage";
}
}
@RequestMapping("/adminLogin.giv")
public void adminLogin() {
}
}
| UTF-8 | Java | 5,508 | java | MainController.java | Java | [] | null | [] | package com.project.givengel.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.project.givengel.service.CampaignServiceImpl;
import com.project.givengel.service.FleaService;
import com.project.givengel.service.GoodListService;
import com.project.givengel.service.MypageServiceImpl;
import com.project.givengel.service.SponServiceImpl;
import com.project.givengel.vo.GoodVO;
import com.project.givengel.vo.SponVO;
import com.project.givengel.vo.Spon_comVO;
import com.project.givengel.vo.UserVO;
@Controller
public class MainController {
@Autowired
private CampaignServiceImpl campaignService;
@Autowired
private GoodListService goodListService;
@Autowired
private FleaService fleaService;
@Autowired
private MypageServiceImpl mypageService;
@Autowired
private SponServiceImpl sponService;
/*******************************************************
* 김민주
* 함수명 : index
*
* 함수 기능 : 상품리스트 페이지 전체 상품 리스트(카테고리별 분류)
* 사용된 서비스 : goodList (Service, dao)
* 마지막 수정 : 2021-07-26
*/
// 카테고리별 인기상품 출력?
@RequestMapping("/index.giv")
public void index(Model m,String categories, String color) {
List<GoodVO> list = goodListService.rankingGood();
List<GoodVO> listTOP = new ArrayList<GoodVO>();
List<GoodVO> listBOTTOM = new ArrayList<GoodVO>();
List<GoodVO> listBAG = new ArrayList<GoodVO>();
List<GoodVO> listACC = new ArrayList<GoodVO>();
for(int i=0; i<list.size(); i++) {
if(list.get(i).getGood_tag().contains("TOP")) {
String[] tp = list.get(i).getGood_tag().split("#");
list.get(i).setGood_tag(tp[0]);
listTOP.add(list.get(i));
}else if(list.get(i).getGood_tag().contains("BOTTOM")) {
String[] tp = list.get(i).getGood_tag().split("#");
list.get(i).setGood_tag(tp[0]);
listBOTTOM.add(list.get(i));
}else if(list.get(i).getGood_tag().contains("BAG")) {
String[] tp = list.get(i).getGood_tag().split("#");
list.get(i).setGood_tag(tp[0]);
listBAG.add(list.get(i));
}else if(list.get(i).getGood_tag().contains("ACC")) {
String[] tp = list.get(i).getGood_tag().split("#");
list.get(i).setGood_tag(tp[0]);
listACC.add(list.get(i));
}
}
m.addAttribute("listTOP", listTOP);
m.addAttribute("listBOTTOM",listBOTTOM);
m.addAttribute("listBAG", listBAG);
m.addAttribute("listACC", listACC);
m.addAttribute("latestGood1", goodListService.getlatestGood1());
m.addAttribute("rankingGood", goodListService.rankingGood());
m.addAttribute("goodComRanking", goodListService.goodComRanking());
}
/*****************************************************
* 함수명 : campaignList
* 함수 기능 : 1. 캠페인 리스트(스폰넘버만) 받아온 후 배열로 리스트불러옴 2.현재시간 불러와서 비교하고 안보이게
* 사용된 함수 : -
* 사용된 서비스 : campaignList (Service, dao)
* 마지막 수정 : 2021-08-01
*****************************************************/
@RequestMapping("/campaign.giv")
public Map<String,Object> campaignList(SponVO vo, Model m, Spon_comVO comvo) {
/*
* List<Integer> listString = new ArrayList<Integer>(); for(int
* i=0;i<sponService.getSponList(vo).size();i++) { int temp_sponNum =
* sponService.getSponList(vo).get(i).getSpon_no(); Spon_comVO com = new
* Spon_comVO(); com.setSpon_no(temp_sponNum);
*/
/*
* int result = sponService.countSponCom(com); listString.add(result);]
*/
List<SponVO> spon_list = new ArrayList<SponVO>();
spon_list = campaignService.campaignList();
List<Integer> com_list = new ArrayList<Integer>();
for(int i=0;i<spon_list.size();i++) {
Spon_comVO comvos = new Spon_comVO();
comvos.setSpon_no(spon_list.get(i).getSpon_no());
com_list.add(campaignService.countReview(comvos));
}
Map<String,Object> map = new HashMap<String,Object>();
List<SponVO> spon_list2 = new ArrayList<SponVO>();
spon_list2 = campaignService.campaignSpon();
String nowSysdate = campaignService.nowSysdate();
map.put("CountReview", com_list);
map.put("nowSysdate", nowSysdate);
map.put("spon_list", spon_list);
map.put("non_campaign", spon_list2);
return map;
}
@RequestMapping("/cartForm.giv")
public void cartForm() {
}
@RequestMapping("/contact.giv")
public void contact() {
}
@RequestMapping("/loginForm.giv")
public void loginForm() {
}
@RequestMapping("/myPage.giv")
public String myPage(UserVO vo, HttpServletRequest req, Model m) {
HttpSession session = req.getSession();
UserVO sessionvo = (UserVO)session.getAttribute("user");
if(sessionvo==null) {
return "/index";
}
else {
vo.setUser_no(sessionvo.getUser_no());
UserVO myvo = mypageService.userInfoView(vo);
m.addAttribute("myvo", myvo);
return "/myPage";
}
}
@RequestMapping("/adminLogin.giv")
public void adminLogin() {
}
}
| 5,508 | 0.648085 | 0.642397 | 168 | 30.392857 | 22.447037 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.035714 | false | false | 12 |
d9a5d4af5d07650652c68e4dd435e798de38ef0e | 910,533,104,055 | 9068c0c806919a8f017baf7ccd307d3d361facc4 | /ALSession/ClientSession.java | c37d3d07b59490abe5b6edc4af01b9426d63397c | [] | no_license | mikecl24/RMI_Kerberos | https://github.com/mikecl24/RMI_Kerberos | 55b0cf842ba04aa1562c1a031c93713a6b347947 | 7235eef908dbd9c46b0b69ac71645bc93473bf59 | refs/heads/master | 2021-09-07T20:12:33.643000 | 2018-02-28T12:58:50 | 2018-02-28T12:58:50 | 72,854,894 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ALSession;
/**
* Created by 0x18 on 12/10/2016.
*/
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.security.Key;
import java.util.Calendar;
import java.util.Date;
public class ClientSession {
public static void main(String[] args) throws RemoteException, NotBoundException, MalformedURLException {
PrintServiceSession PrintService = (PrintServiceSession) Naming.lookup("rmi://localhost:5099/print");
AuthenticationServiceSession AuthService = (AuthenticationServiceSession) Naming.lookup("rmi://localhost:5100/auth");
TGSServiceSession TGSService = (TGSServiceSession) Naming.lookup("rmi://localhost:5101/tgs");
//setup time
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
/* REQUEST AUTHENTICATION */
String auth = AuthService.authenticate("User1", "Password1",
cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
if (auth.equals("")){
System.out.println("Authentication Failed");
System.exit(0);
}
//split return (Key(client, tgs), {|username, Key(client, tgs), time|}K(AS,TGS))
//get key from first element
String[] val = auth.split(":");
String TGSkey = val[0];
//get encrypted bytes from the rest (ASTGS encryption)
auth = auth.substring(TGSkey.length()+1);
TGSkey = TGSkey.substring(0,16);
byte[] encr = String2ByteArray(auth);
//use gotten key between client and tgs to encrypt time to send TGS
cal.setTime(date);
String st = Integer.toString(cal.get(Calendar.YEAR)) + Integer.toString(cal.get(Calendar.MONTH))+ Integer.toString(cal.get(Calendar.DATE))+Integer.toString(cal.get(Calendar.HOUR_OF_DAY))+Integer.toString(cal.get(Calendar.MINUTE));
byte[] encrypted = encryptfucntion(st, TGSkey);
/* REQUEST A TICKET */
String[] TGS = TGSService.getTicket(encrypted,encr).split("W");
if (TGS.length != 2){
System.out.println("Ticket Retreival Failed");
System.exit(0);
}
String[] TGSClientBytes = TGS[0].split(":");
encr = new byte[TGSClientBytes.length];
for (int i = 0; i<TGSClientBytes.length; i++){
encr[i] = (byte) Integer.parseInt(TGSClientBytes[i]);
}
//decrypt 1st part of the message
String decrypted ="";
decrypted = decryptfunction(TGS[0],TGSkey);
//remove service, since there is only print service currently
decrypted = decrypted.split(":")[1];
//Part 2 still encrypted! TGS[1] K(TGS,Service) It is the ticket
//encrypt time using new key received
cal.setTime(date);
st = Integer.toString(cal.get(Calendar.YEAR)) + Integer.toString(cal.get(Calendar.MONTH))+ Integer.toString(cal.get(Calendar.DATE))+Integer.toString(cal.get(Calendar.HOUR_OF_DAY))+Integer.toString(cal.get(Calendar.MINUTE));
encr = encryptfucntion(st, decrypted);
String ticket = TGS[1];
/* CONFIRM THE SESSION WITH SERVICE */
String SessionConfirmation = PrintService.startSession(encr, ticket);
//verify server answer!
String add = st.charAt(st.length()-1)+"";
st = st.substring(0,st.length()-2);
st = st + (Integer.parseInt(add)+1);
if (!decryptfunction(SessionConfirmation, decrypted).equals(st)){
System.out.println("Server verification failed");
System.exit(0);
}
/* DO ANY ACTIONS IN PRINT SERVICE HERE */
System.out.println("---- " + PrintService.start(ticket));
System.out.println("---- " + PrintService.print("file1.txt", "printer1", ticket));
System.out.println("---- " + PrintService.setConfig("Page", "A4", ticket));
System.out.println("---- " + PrintService.readConfig("Page", ticket));
System.out.println("---- " + PrintService.status(ticket));
System.out.println("---- " + PrintService.stop(ticket));
System.out.println("---- " + PrintService.status(ticket));
System.out.println("---- " + PrintService.print("file2.txt", "printer1", ticket));
System.out.println("---- " + PrintService.start(ticket));
System.out.println("---- " + PrintService.print("file2.txt", "printer1", ticket));
System.out.println("---- " + PrintService.print("file3.txt", "printer1", ticket));
System.out.println("---- " + PrintService.print("file4.txt", "printer1", ticket));
System.out.println("---- " + PrintService.queue(ticket));
System.out.println("---- " + PrintService.topQueue(10, ticket));
System.out.println("---- " + PrintService.topQueue(3, ticket));
System.out.println("---- " + PrintService.queue(ticket));
System.out.println("---- " + PrintService.restart(ticket));
System.out.println("---- " + PrintService.queue(ticket));
}
private static String decryptfunction(String st, String key){
//Transform string to byte array
String[] IndByte = st.split(":");
byte[] encr = new byte[IndByte.length];
for (int i = 0; i<IndByte.length; i++){
encr[i] = (byte) Integer.parseInt(IndByte[i]);
}
String decrypted ="";
try {
Key aesKey = new SecretKeySpec(key.substring(0,16).getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
// decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
decrypted = new String(cipher.doFinal(encr));
//System.out.println(decrypted);
}catch (Exception e){
e.printStackTrace();
}
return decrypted;
}
private static byte[] encryptfucntion(String st, String key){
byte[] encrypted;
String TGSkey = key.substring(0,16);
try {
Key aesKey = new SecretKeySpec(TGSkey.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
encrypted = cipher.doFinal(st.getBytes());
}catch (Exception e){
e.printStackTrace();
encrypted = null;
}
return encrypted;
}
private static byte[] String2ByteArray(String st){
String[] subST = st.split(":");
byte[] encr = new byte[subST.length];
for (int i = 0; i<subST.length; i++){
encr[i] = (byte) Integer.parseInt(subST[i]);
}
return encr;
}
}
| UTF-8 | Java | 6,805 | java | ClientSession.java | Java | [
{
"context": "package ALSession;\n\n/**\n * Created by 0x18 on 12/10/2016.\n */\n\nimport javax.crypto.Cipher;\ni",
"end": 42,
"score": 0.999086856842041,
"start": 38,
"tag": "USERNAME",
"value": "0x18"
},
{
"context": " String auth = AuthService.authenticate(\"User1\", \"Password1\",\n cal.get(Calendar.YEAR), cal.get",
"end": 1050,
"score": 0.9930086731910706,
"start": 1041,
"tag": "PASSWORD",
"value": "Password1"
}
] | null | [] | package ALSession;
/**
* Created by 0x18 on 12/10/2016.
*/
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.security.Key;
import java.util.Calendar;
import java.util.Date;
public class ClientSession {
public static void main(String[] args) throws RemoteException, NotBoundException, MalformedURLException {
PrintServiceSession PrintService = (PrintServiceSession) Naming.lookup("rmi://localhost:5099/print");
AuthenticationServiceSession AuthService = (AuthenticationServiceSession) Naming.lookup("rmi://localhost:5100/auth");
TGSServiceSession TGSService = (TGSServiceSession) Naming.lookup("rmi://localhost:5101/tgs");
//setup time
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
/* REQUEST AUTHENTICATION */
String auth = AuthService.authenticate("User1", "<PASSWORD>",
cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
if (auth.equals("")){
System.out.println("Authentication Failed");
System.exit(0);
}
//split return (Key(client, tgs), {|username, Key(client, tgs), time|}K(AS,TGS))
//get key from first element
String[] val = auth.split(":");
String TGSkey = val[0];
//get encrypted bytes from the rest (ASTGS encryption)
auth = auth.substring(TGSkey.length()+1);
TGSkey = TGSkey.substring(0,16);
byte[] encr = String2ByteArray(auth);
//use gotten key between client and tgs to encrypt time to send TGS
cal.setTime(date);
String st = Integer.toString(cal.get(Calendar.YEAR)) + Integer.toString(cal.get(Calendar.MONTH))+ Integer.toString(cal.get(Calendar.DATE))+Integer.toString(cal.get(Calendar.HOUR_OF_DAY))+Integer.toString(cal.get(Calendar.MINUTE));
byte[] encrypted = encryptfucntion(st, TGSkey);
/* REQUEST A TICKET */
String[] TGS = TGSService.getTicket(encrypted,encr).split("W");
if (TGS.length != 2){
System.out.println("Ticket Retreival Failed");
System.exit(0);
}
String[] TGSClientBytes = TGS[0].split(":");
encr = new byte[TGSClientBytes.length];
for (int i = 0; i<TGSClientBytes.length; i++){
encr[i] = (byte) Integer.parseInt(TGSClientBytes[i]);
}
//decrypt 1st part of the message
String decrypted ="";
decrypted = decryptfunction(TGS[0],TGSkey);
//remove service, since there is only print service currently
decrypted = decrypted.split(":")[1];
//Part 2 still encrypted! TGS[1] K(TGS,Service) It is the ticket
//encrypt time using new key received
cal.setTime(date);
st = Integer.toString(cal.get(Calendar.YEAR)) + Integer.toString(cal.get(Calendar.MONTH))+ Integer.toString(cal.get(Calendar.DATE))+Integer.toString(cal.get(Calendar.HOUR_OF_DAY))+Integer.toString(cal.get(Calendar.MINUTE));
encr = encryptfucntion(st, decrypted);
String ticket = TGS[1];
/* CONFIRM THE SESSION WITH SERVICE */
String SessionConfirmation = PrintService.startSession(encr, ticket);
//verify server answer!
String add = st.charAt(st.length()-1)+"";
st = st.substring(0,st.length()-2);
st = st + (Integer.parseInt(add)+1);
if (!decryptfunction(SessionConfirmation, decrypted).equals(st)){
System.out.println("Server verification failed");
System.exit(0);
}
/* DO ANY ACTIONS IN PRINT SERVICE HERE */
System.out.println("---- " + PrintService.start(ticket));
System.out.println("---- " + PrintService.print("file1.txt", "printer1", ticket));
System.out.println("---- " + PrintService.setConfig("Page", "A4", ticket));
System.out.println("---- " + PrintService.readConfig("Page", ticket));
System.out.println("---- " + PrintService.status(ticket));
System.out.println("---- " + PrintService.stop(ticket));
System.out.println("---- " + PrintService.status(ticket));
System.out.println("---- " + PrintService.print("file2.txt", "printer1", ticket));
System.out.println("---- " + PrintService.start(ticket));
System.out.println("---- " + PrintService.print("file2.txt", "printer1", ticket));
System.out.println("---- " + PrintService.print("file3.txt", "printer1", ticket));
System.out.println("---- " + PrintService.print("file4.txt", "printer1", ticket));
System.out.println("---- " + PrintService.queue(ticket));
System.out.println("---- " + PrintService.topQueue(10, ticket));
System.out.println("---- " + PrintService.topQueue(3, ticket));
System.out.println("---- " + PrintService.queue(ticket));
System.out.println("---- " + PrintService.restart(ticket));
System.out.println("---- " + PrintService.queue(ticket));
}
private static String decryptfunction(String st, String key){
//Transform string to byte array
String[] IndByte = st.split(":");
byte[] encr = new byte[IndByte.length];
for (int i = 0; i<IndByte.length; i++){
encr[i] = (byte) Integer.parseInt(IndByte[i]);
}
String decrypted ="";
try {
Key aesKey = new SecretKeySpec(key.substring(0,16).getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
// decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
decrypted = new String(cipher.doFinal(encr));
//System.out.println(decrypted);
}catch (Exception e){
e.printStackTrace();
}
return decrypted;
}
private static byte[] encryptfucntion(String st, String key){
byte[] encrypted;
String TGSkey = key.substring(0,16);
try {
Key aesKey = new SecretKeySpec(TGSkey.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
encrypted = cipher.doFinal(st.getBytes());
}catch (Exception e){
e.printStackTrace();
encrypted = null;
}
return encrypted;
}
private static byte[] String2ByteArray(String st){
String[] subST = st.split(":");
byte[] encr = new byte[subST.length];
for (int i = 0; i<subST.length; i++){
encr[i] = (byte) Integer.parseInt(subST[i]);
}
return encr;
}
}
| 6,806 | 0.612491 | 0.602204 | 158 | 42.069622 | 36.21999 | 238 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.905063 | false | false | 12 |
dd4a9387e89ff491b2002e2c7210798b1e6962e9 | 910,533,104,126 | 61094b6f2545a9f4d7b41ac51c2aa01d1a6fb30b | /undertow-scenario/src/main/java/org/apache/skywalking/testcase/undertow/controller/CaseForwardController.java | ff5c0e1cdbba3296ecd2d3b0d94f47f19d26144e | [
"Apache-2.0"
] | permissive | cloudgc/skywalking-agent-testcases | https://github.com/cloudgc/skywalking-agent-testcases | c07ce509e55ca13a919eb7b883cfac96ac2474fe | d66d499ee6a880d319ad05dd520e4fc7b477f612 | refs/heads/master | 2020-03-26T01:15:22.428000 | 2018-08-14T06:33:59 | 2018-08-14T06:33:59 | 144,359,243 | 0 | 0 | Apache-2.0 | true | 2018-08-11T05:48:58 | 2018-08-11T05:48:58 | 2018-08-04T14:03:59 | 2018-08-06T12:16:44 | 17,279 | 0 | 0 | 0 | null | false | null | package org.apache.skywalking.testcase.undertow.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Copyright @ 2018/8/11
*
* @author cloudgc
*/
@RestController
@RequestMapping("/case/backup")
public class CaseForwardController {
private final static Logger log = LoggerFactory.getLogger(CaseForwardController.class);
@RequestMapping("/forwardone")
public void startForwardOne(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log.info("request:{},response:{}", request, response);
request.getRequestDispatcher("/case/forwardtwo").forward(request, response);
}
@RequestMapping("/forwardtwo")
public void startForwardTwo(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log.info("request:{},response:{}", request, response);
request.getRequestDispatcher("/case/forwardend").forward(request, response);
}
@RequestMapping("/forwardend")
public String forardEnd() {
return "success";
}
}
| UTF-8 | Java | 1,454 | java | CaseForwardController.java | Java | [
{
"context": "ption;\n\n/**\n * Copyright @ 2018/8/11\n *\n * @author cloudgc\n */\n@RestController\n@RequestMapping(\"/case/backup",
"end": 506,
"score": 0.9995903968811035,
"start": 499,
"tag": "USERNAME",
"value": "cloudgc"
}
] | null | [] | package org.apache.skywalking.testcase.undertow.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Copyright @ 2018/8/11
*
* @author cloudgc
*/
@RestController
@RequestMapping("/case/backup")
public class CaseForwardController {
private final static Logger log = LoggerFactory.getLogger(CaseForwardController.class);
@RequestMapping("/forwardone")
public void startForwardOne(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log.info("request:{},response:{}", request, response);
request.getRequestDispatcher("/case/forwardtwo").forward(request, response);
}
@RequestMapping("/forwardtwo")
public void startForwardTwo(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log.info("request:{},response:{}", request, response);
request.getRequestDispatcher("/case/forwardend").forward(request, response);
}
@RequestMapping("/forwardend")
public String forardEnd() {
return "success";
}
}
| 1,454 | 0.750344 | 0.744154 | 44 | 32.045456 | 28.482016 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false | 12 |
0daaa02c4ab9394aa817c695e2f3243d502839cc | 31,233,002,176,767 | ad3a17dc66efb6946e498f68a1a34746f22b7ba0 | /modules/integration/tests-ui-integration/tests-ui/src/test/java/org/wso2/ds/ui/integration/test/dashboard/OptionalLandingPageTest.java | 79a555bc3ee6b09f4bd7f69249849dba637b0d1f | [
"Apache-2.0"
] | permissive | janithRS/product-ds | https://github.com/janithRS/product-ds | d71b306639bc07a6107c450e4db39e86a810fec7 | 549730d3c4d4592b8c7d9b8966a1866dd5d4af4d | refs/heads/master | 2020-04-28T15:37:25.466000 | 2017-10-03T09:48:57 | 2017-10-03T09:48:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.ds.ui.integration.test.dashboard;
import org.openqa.selenium.By;
import org.testng.annotations.*;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.integration.common.utils.exceptions.AutomationUtilException;
import org.wso2.ds.ui.integration.util.DSUIIntegrationTest;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.net.MalformedURLException;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
/**
* To test the functionality when landing page is made as an optional one
*/
public class OptionalLandingPageTest extends DSUIIntegrationTest {
private static final String DASHBOARD_TITLE = "optionallandingdashboard";
private static final String ROLE1 = "optionalrole1";
private static final String ROLE2 = "optionalrole2";
private static final String USERNAME_EDITOR = "optional_editor";
private static final String PASSWORD_EDITOR = "optional_editor";
private static final String USERNAME_VIEWER = "optional_viewer";
private static final String PASSWORD_VIEWER = "optional_viewer";
/**
* Initializes the class.
*
* @param userMode user mode
*/
@Factory(dataProvider = "userMode")
public OptionalLandingPageTest(TestUserMode userMode) {
super(userMode);
}
/**
* Provides user modes.
*
* @return user modes
*/
@DataProvider(name = "userMode")
public static Object[][] userModeProvider() {
return new Object[][]{{TestUserMode.SUPER_TENANT_ADMIN}};
}
/**
* Setup the testing environment.
*
* @throws XPathExpressionException
* @throws IOException
* @throws AutomationUtilException
*/
@BeforeClass(alwaysRun = true)
public void setUp() throws AutomationUtilException, XPathExpressionException, IOException, InterruptedException {
String[] userListForRole1 = {getCurrentUsername(), USERNAME_EDITOR};
String[] userListForRole2 = {getCurrentUsername(), USERNAME_VIEWER};
login(getCurrentUsername(), getCurrentPassword());
deleteDashboards();
addDashBoardWithoutLandingPage(DASHBOARD_TITLE, "This is a test dashboard");
loginToAdminConsole(getCurrentUsername(), getCurrentPassword());
addUser(USERNAME_EDITOR, PASSWORD_EDITOR, PASSWORD_EDITOR);
addUser(USERNAME_VIEWER, PASSWORD_VIEWER, PASSWORD_VIEWER);
addRole(ROLE1);
assignRoleToUser(userListForRole1);
addRole(ROLE2);
assignRoleToUser(userListForRole2);
assignInternalRoleToUser(DASHBOARD_TITLE + "-viewer", new String[]{USERNAME_VIEWER});
assignInternalRoleToUser(DASHBOARD_TITLE + "-editor", new String[]{USERNAME_EDITOR});
addLoginRole(USERNAME_EDITOR);
addLoginRole(USERNAME_VIEWER);
}
/**
* Clean up after running tests.
*
* @throws XPathExpressionException
* @throws MalformedURLException
*/
@AfterClass(alwaysRun = true)
public void tearDown() throws XPathExpressionException, MalformedURLException {
logout();
getDriver().quit();
}
/**
* To test the creation of dashboard without landing page and checking the basic flow without landing page
*
* @throws XPathExpressionException
* @throws MalformedURLException
*/
@Test(groups = "wso2.ds.dashboard", description = "Checking the basic flow of dashboard page creation when landing "
+ "page is optional")
public void testCreateDashboard() throws XPathExpressionException, MalformedURLException, InterruptedException {
redirectToLocation(DS_HOME_CONTEXT, DS_DASHBOARDS_CONTEXT);
getDriver().findElement(By.cssSelector("#" + DASHBOARD_TITLE + " .ues-edit")).click();
addARoleToView("default", ROLE1);
getDriver().findElement(By.cssSelector("div[data-role=\"Internal/everyone\"] .remove-button")).click();
clickOnView("default");
// Check the page creation when there is no internal/everyone role in first page
addPageToDashboard("default-grid");
assertFalse(getDriver().isElementPresent(By.cssSelector("div.modal-body")), "Adding a new page is not allowed "
+ "when landing page doesn`t contain internal/everyone role even though landing page is optional");
assertTrue(getDriver().isElementPresent(By.id("default")),
"When creating new page default view is not created");
}
/**
* Checks whether anon view is allowed in second page, when first page does not contain anonymous view
*
* @throws XPathExpressionException
* @throws MalformedURLException
*/
@Test(groups = "wso2.ds.dashboard", description = "Checking whether the creation of anonymous view allowed in second page",
dependsOnMethods = "testCreateDashboard")
public void testAnonViewCreation() throws XPathExpressionException, MalformedURLException, InterruptedException {
addARoleToView("default", ROLE2);
if (!getDriver().isElementPresent(By.cssSelector("div[data-role=\"Internal/everyone\"]"))) {
clickOnViewSettings("default");
}
getDriver().findElement(By.cssSelector("div[data-role=\"Internal/everyone\"] .remove-button")).click();
createNewView("single-column");
addARoleToView("view0", "anonymous");
getDriver().findElement(By.id("ues-modal-confirm-yes")).click();
assertTrue(getDriver().isElementPresent(By.cssSelector("div[data-role=\"anonymous\"]")),
"Addition of anonymous " + "role not allowed even the landing page is optional");
}
@Test(groups = "wso2.ds.dashboard", description = "Checking whether the required conditions checked before "
+ "making a page as a landing page", dependsOnMethods = "testAnonViewCreation")
public void testMakingLandingPage() throws XPathExpressionException, MalformedURLException, InterruptedException {
// Try to set the first page as a landing page, when the second page contains view with anonymous role
getDriver().findElement(By.className("ues-switch-page-prev")).click();
getDriver().findElement(By.className("fw-pages")).click();
getDriver().findElement(By.cssSelector("input[name='landing']")).click();
Thread.sleep(2000);
String expected = "Cannot Select This Page As Landing";
String message = getDriver().findElement(By.cssSelector(".modal-title")).getText().trim();
assertTrue(expected.equalsIgnoreCase(message),
"Creating of landing page allowed without checking for required conditions");
getDriver().findElement(By.id("ues-modal-info-ok")).click();
createNewView("single-column");
getDriver().findElement(By.className("fw-pages")).click();
Thread.sleep(2000);
getDriver().findElement(By.cssSelector("input[name='landing']")).click();
message = getDriver().findElement(By.cssSelector(".modal-title")).getText().trim();
assertTrue(expected.equalsIgnoreCase(message),
"Creating of landing page allowed without checking for required conditions");
getDriver().findElement(By.id("ues-modal-info-ok")).click();
createNewView("single-column");
addARoleToView("view1", "anonymous");
getDriver().findElement(By.id("ues-modal-confirm-yes")).click();
getDriver().findElement(By.className("fw-pages")).click();
Thread.sleep(2000);
getDriver().findElement(By.cssSelector("input[name='landing']")).click();
assertFalse(getDriver().isElementPresent(By.cssSelector("modal-title")),
"Creating a landing page is not " + "allowed even the necessary conditions satisfied");
getDriver().findElement(By.cssSelector("input[name='landing']")).click();
}
/**
* To test the view mode of the dashboard based on the role of the user
*
* @throws XPathExpressionException
* @throws MalformedURLException
* @throws InterruptedException
*/
@Test(groups = "wso2.ds.dashboard", description = "Checking the view mode and the pages that are shown for each user",
dependsOnMethods = "testMakingLandingPage")
public void testViewMode() throws XPathExpressionException, MalformedURLException, InterruptedException {
deleteView("view0");
deleteView("view1");
clickOnView("default");
Thread.sleep(2000);
String[][] gadgetMappings = {{"publisher", "b"}, {"usa-map", "c"}};
String script = generateAddGadgetScript(gadgetMappings);
getDriver().findElement(By.cssSelector("#btn-sidebar-gadgets i.fw.fw-gadget")).click();
Thread.sleep(2000);
waitTillElementToBeClickable(By.id("publisher"));
getDriver().executeScript(script);
assertTrue(getDriver().findElement(By.id("publisher-0")).isDisplayed(), "Publisher gadget is not added");
getDriver().findElement(By.className("ues-switch-page-next")).click();
deleteView("view0");
logout();
login(USERNAME_EDITOR, PASSWORD_EDITOR);
getDriver().findElement(By.cssSelector("#" + DASHBOARD_TITLE + " .ues-actions .ues-view")).click();
pushWindow();
assertTrue(getDriver().isElementPresent(By.cssSelector("a[href=\"page0\"]")),
"The page that has the view for " + "the particular user is not visible in view mode");
assertTrue(getDriver().isElementPresent(By.id("publisher-0")),
"The correct gadgets are not displayed in view mode");
assertTrue(getDriver().isElementPresent(By.id("usa-map-0")),
"The correct gadgets are not displayed in view mode");
assertFalse(getDriver().isElementPresent(By.cssSelector("a[href=\"page1\"]")),
"The page that does not has the view for " + "the particular user is visible in view mode");
getDriver().close();
popWindow();
logout();
login(USERNAME_VIEWER, PASSWORD_VIEWER);
getDriver().findElement(By.cssSelector("#" + DASHBOARD_TITLE + " .ues-actions .ues-view")).click();
pushWindow();
assertTrue(getDriver().isElementPresent(By.cssSelector("a[href=\"page1\"]")),
"The page that has the view for " + "the particular user is not visible in view mode");
assertFalse(getDriver().isElementPresent(By.cssSelector("a[href=\"page0\"]")),
"The page that does not has the view for " + "the particular user is visible in view mode");
getDriver().close();
popWindow();
}
}
| UTF-8 | Java | 11,310 | java | OptionalLandingPageTest.java | Java | [
{
"context": "te static final String PASSWORD_VIEWER = \"optional_viewer\";\n\n /**\n * Initializes the class.\n ",
"end": 1776,
"score": 0.5060094594955444,
"start": 1776,
"tag": "PASSWORD",
"value": ""
},
{
"context": "sername(), getCurrentPassword());\n addUser(USERNAME_EDITOR, PASSWORD_EDITOR, PASSWORD_EDITOR);\n addUs",
"end": 2992,
"score": 0.6749179363250732,
"start": 2977,
"tag": "USERNAME",
"value": "USERNAME_EDITOR"
},
{
"context": "ASSWORD_EDITOR, PASSWORD_EDITOR);\n addUser(USERNAME_VIEWER, PASSWORD_VIEWER, PASSWORD_VIEWER);\n addRo",
"end": 3060,
"score": 0.8089685440063477,
"start": 3045,
"tag": "USERNAME",
"value": "USERNAME_VIEWER"
},
{
"context": "eToUser(DASHBOARD_TITLE + \"-editor\", new String[]{USERNAME_EDITOR});\n addLoginRole(USERNAME_EDITOR);\n ",
"end": 3417,
"score": 0.6802508234977722,
"start": 3402,
"tag": "USERNAME",
"value": "USERNAME_EDITOR"
},
{
"context": " String[]{USERNAME_EDITOR});\n addLoginRole(USERNAME_EDITOR);\n addLoginRole(USERNAME_VIEWER);\n ",
"end": 3450,
"score": 0.5738062262535095,
"start": 3442,
"tag": "USERNAME",
"value": "USERNAME"
},
{
"context": "{USERNAME_EDITOR});\n addLoginRole(USERNAME_EDITOR);\n addLoginRole(USERNAME_VIEWER);\n }\n\n ",
"end": 3457,
"score": 0.6040340065956116,
"start": 3451,
"tag": "USERNAME",
"value": "EDITOR"
},
{
"context": "eteView(\"view0\");\n logout();\n login(USERNAME_EDITOR, PASSWORD_EDITOR);\n getDriver().findElemen",
"end": 9801,
"score": 0.9994654655456543,
"start": 9786,
"tag": "USERNAME",
"value": "USERNAME_EDITOR"
},
{
"context": "logout();\n login(USERNAME_EDITOR, PASSWORD_EDITOR);\n getDriver().findElement(By.cssSelector(",
"end": 9818,
"score": 0.3019934892654419,
"start": 9812,
"tag": "USERNAME",
"value": "EDITOR"
},
{
"context": " popWindow();\n logout();\n login(USERNAME_VIEWER, PASSWORD_VIEWER);\n getDriver().findElemen",
"end": 10716,
"score": 0.9994825720787048,
"start": 10701,
"tag": "USERNAME",
"value": "USERNAME_VIEWER"
},
{
"context": "logout();\n login(USERNAME_VIEWER, PASSWORD_VIEWER);\n getDriver().findElement(By.cssSelector(",
"end": 10733,
"score": 0.9854352474212646,
"start": 10727,
"tag": "USERNAME",
"value": "VIEWER"
}
] | null | [] | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.ds.ui.integration.test.dashboard;
import org.openqa.selenium.By;
import org.testng.annotations.*;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.integration.common.utils.exceptions.AutomationUtilException;
import org.wso2.ds.ui.integration.util.DSUIIntegrationTest;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.net.MalformedURLException;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
/**
* To test the functionality when landing page is made as an optional one
*/
public class OptionalLandingPageTest extends DSUIIntegrationTest {
private static final String DASHBOARD_TITLE = "optionallandingdashboard";
private static final String ROLE1 = "optionalrole1";
private static final String ROLE2 = "optionalrole2";
private static final String USERNAME_EDITOR = "optional_editor";
private static final String PASSWORD_EDITOR = "optional_editor";
private static final String USERNAME_VIEWER = "optional_viewer";
private static final String PASSWORD_VIEWER = "optional_viewer";
/**
* Initializes the class.
*
* @param userMode user mode
*/
@Factory(dataProvider = "userMode")
public OptionalLandingPageTest(TestUserMode userMode) {
super(userMode);
}
/**
* Provides user modes.
*
* @return user modes
*/
@DataProvider(name = "userMode")
public static Object[][] userModeProvider() {
return new Object[][]{{TestUserMode.SUPER_TENANT_ADMIN}};
}
/**
* Setup the testing environment.
*
* @throws XPathExpressionException
* @throws IOException
* @throws AutomationUtilException
*/
@BeforeClass(alwaysRun = true)
public void setUp() throws AutomationUtilException, XPathExpressionException, IOException, InterruptedException {
String[] userListForRole1 = {getCurrentUsername(), USERNAME_EDITOR};
String[] userListForRole2 = {getCurrentUsername(), USERNAME_VIEWER};
login(getCurrentUsername(), getCurrentPassword());
deleteDashboards();
addDashBoardWithoutLandingPage(DASHBOARD_TITLE, "This is a test dashboard");
loginToAdminConsole(getCurrentUsername(), getCurrentPassword());
addUser(USERNAME_EDITOR, PASSWORD_EDITOR, PASSWORD_EDITOR);
addUser(USERNAME_VIEWER, PASSWORD_VIEWER, PASSWORD_VIEWER);
addRole(ROLE1);
assignRoleToUser(userListForRole1);
addRole(ROLE2);
assignRoleToUser(userListForRole2);
assignInternalRoleToUser(DASHBOARD_TITLE + "-viewer", new String[]{USERNAME_VIEWER});
assignInternalRoleToUser(DASHBOARD_TITLE + "-editor", new String[]{USERNAME_EDITOR});
addLoginRole(USERNAME_EDITOR);
addLoginRole(USERNAME_VIEWER);
}
/**
* Clean up after running tests.
*
* @throws XPathExpressionException
* @throws MalformedURLException
*/
@AfterClass(alwaysRun = true)
public void tearDown() throws XPathExpressionException, MalformedURLException {
logout();
getDriver().quit();
}
/**
* To test the creation of dashboard without landing page and checking the basic flow without landing page
*
* @throws XPathExpressionException
* @throws MalformedURLException
*/
@Test(groups = "wso2.ds.dashboard", description = "Checking the basic flow of dashboard page creation when landing "
+ "page is optional")
public void testCreateDashboard() throws XPathExpressionException, MalformedURLException, InterruptedException {
redirectToLocation(DS_HOME_CONTEXT, DS_DASHBOARDS_CONTEXT);
getDriver().findElement(By.cssSelector("#" + DASHBOARD_TITLE + " .ues-edit")).click();
addARoleToView("default", ROLE1);
getDriver().findElement(By.cssSelector("div[data-role=\"Internal/everyone\"] .remove-button")).click();
clickOnView("default");
// Check the page creation when there is no internal/everyone role in first page
addPageToDashboard("default-grid");
assertFalse(getDriver().isElementPresent(By.cssSelector("div.modal-body")), "Adding a new page is not allowed "
+ "when landing page doesn`t contain internal/everyone role even though landing page is optional");
assertTrue(getDriver().isElementPresent(By.id("default")),
"When creating new page default view is not created");
}
/**
* Checks whether anon view is allowed in second page, when first page does not contain anonymous view
*
* @throws XPathExpressionException
* @throws MalformedURLException
*/
@Test(groups = "wso2.ds.dashboard", description = "Checking whether the creation of anonymous view allowed in second page",
dependsOnMethods = "testCreateDashboard")
public void testAnonViewCreation() throws XPathExpressionException, MalformedURLException, InterruptedException {
addARoleToView("default", ROLE2);
if (!getDriver().isElementPresent(By.cssSelector("div[data-role=\"Internal/everyone\"]"))) {
clickOnViewSettings("default");
}
getDriver().findElement(By.cssSelector("div[data-role=\"Internal/everyone\"] .remove-button")).click();
createNewView("single-column");
addARoleToView("view0", "anonymous");
getDriver().findElement(By.id("ues-modal-confirm-yes")).click();
assertTrue(getDriver().isElementPresent(By.cssSelector("div[data-role=\"anonymous\"]")),
"Addition of anonymous " + "role not allowed even the landing page is optional");
}
@Test(groups = "wso2.ds.dashboard", description = "Checking whether the required conditions checked before "
+ "making a page as a landing page", dependsOnMethods = "testAnonViewCreation")
public void testMakingLandingPage() throws XPathExpressionException, MalformedURLException, InterruptedException {
// Try to set the first page as a landing page, when the second page contains view with anonymous role
getDriver().findElement(By.className("ues-switch-page-prev")).click();
getDriver().findElement(By.className("fw-pages")).click();
getDriver().findElement(By.cssSelector("input[name='landing']")).click();
Thread.sleep(2000);
String expected = "Cannot Select This Page As Landing";
String message = getDriver().findElement(By.cssSelector(".modal-title")).getText().trim();
assertTrue(expected.equalsIgnoreCase(message),
"Creating of landing page allowed without checking for required conditions");
getDriver().findElement(By.id("ues-modal-info-ok")).click();
createNewView("single-column");
getDriver().findElement(By.className("fw-pages")).click();
Thread.sleep(2000);
getDriver().findElement(By.cssSelector("input[name='landing']")).click();
message = getDriver().findElement(By.cssSelector(".modal-title")).getText().trim();
assertTrue(expected.equalsIgnoreCase(message),
"Creating of landing page allowed without checking for required conditions");
getDriver().findElement(By.id("ues-modal-info-ok")).click();
createNewView("single-column");
addARoleToView("view1", "anonymous");
getDriver().findElement(By.id("ues-modal-confirm-yes")).click();
getDriver().findElement(By.className("fw-pages")).click();
Thread.sleep(2000);
getDriver().findElement(By.cssSelector("input[name='landing']")).click();
assertFalse(getDriver().isElementPresent(By.cssSelector("modal-title")),
"Creating a landing page is not " + "allowed even the necessary conditions satisfied");
getDriver().findElement(By.cssSelector("input[name='landing']")).click();
}
/**
* To test the view mode of the dashboard based on the role of the user
*
* @throws XPathExpressionException
* @throws MalformedURLException
* @throws InterruptedException
*/
@Test(groups = "wso2.ds.dashboard", description = "Checking the view mode and the pages that are shown for each user",
dependsOnMethods = "testMakingLandingPage")
public void testViewMode() throws XPathExpressionException, MalformedURLException, InterruptedException {
deleteView("view0");
deleteView("view1");
clickOnView("default");
Thread.sleep(2000);
String[][] gadgetMappings = {{"publisher", "b"}, {"usa-map", "c"}};
String script = generateAddGadgetScript(gadgetMappings);
getDriver().findElement(By.cssSelector("#btn-sidebar-gadgets i.fw.fw-gadget")).click();
Thread.sleep(2000);
waitTillElementToBeClickable(By.id("publisher"));
getDriver().executeScript(script);
assertTrue(getDriver().findElement(By.id("publisher-0")).isDisplayed(), "Publisher gadget is not added");
getDriver().findElement(By.className("ues-switch-page-next")).click();
deleteView("view0");
logout();
login(USERNAME_EDITOR, PASSWORD_EDITOR);
getDriver().findElement(By.cssSelector("#" + DASHBOARD_TITLE + " .ues-actions .ues-view")).click();
pushWindow();
assertTrue(getDriver().isElementPresent(By.cssSelector("a[href=\"page0\"]")),
"The page that has the view for " + "the particular user is not visible in view mode");
assertTrue(getDriver().isElementPresent(By.id("publisher-0")),
"The correct gadgets are not displayed in view mode");
assertTrue(getDriver().isElementPresent(By.id("usa-map-0")),
"The correct gadgets are not displayed in view mode");
assertFalse(getDriver().isElementPresent(By.cssSelector("a[href=\"page1\"]")),
"The page that does not has the view for " + "the particular user is visible in view mode");
getDriver().close();
popWindow();
logout();
login(USERNAME_VIEWER, PASSWORD_VIEWER);
getDriver().findElement(By.cssSelector("#" + DASHBOARD_TITLE + " .ues-actions .ues-view")).click();
pushWindow();
assertTrue(getDriver().isElementPresent(By.cssSelector("a[href=\"page1\"]")),
"The page that has the view for " + "the particular user is not visible in view mode");
assertFalse(getDriver().isElementPresent(By.cssSelector("a[href=\"page0\"]")),
"The page that does not has the view for " + "the particular user is visible in view mode");
getDriver().close();
popWindow();
}
}
| 11,310 | 0.679929 | 0.674447 | 227 | 48.823788 | 35.358265 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.740088 | false | false | 12 |
b9178361bc3e04222e61b2df301286d9d03193ef | 13,176,959,691,847 | f2895ecbeac8e7f39019fc445cb4dcf71d7e854d | /src/de/itter/graphs/algorithms/FlowComparator.java | 5c7aa6faaab43dfc24ae808ac18704ce276bc79c | [] | no_license | itteerde/graphs | https://github.com/itteerde/graphs | b2a1dc7e26a204ba7b054ae4af1190ed33807401 | e442271bab9138477dd01e2675d1ef6d6ba180cf | refs/heads/master | 2021-01-22T06:18:34.486000 | 2017-10-29T19:50:59 | 2017-10-29T19:50:59 | 92,535,768 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package de.itter.graphs.algorithms;
import java.util.Comparator;
import de.itter.graphs.api.Graph;
/**
* @author Erik Itter
*
*/
public class FlowComparator implements Comparator<Graph> {
/*
* (non-Javadoc)
*
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Graph arg0, Graph arg1) {
// TODO Auto-generated method stub
return 0;
}
}
| UTF-8 | Java | 425 | java | FlowComparator.java | Java | [
{
"context": "\nimport de.itter.graphs.api.Graph;\n\n/**\n * @author Erik Itter\n *\n */\npublic class FlowComparator implements Com",
"end": 139,
"score": 0.9998794794082642,
"start": 129,
"tag": "NAME",
"value": "Erik Itter"
}
] | null | [] | /**
*
*/
package de.itter.graphs.algorithms;
import java.util.Comparator;
import de.itter.graphs.api.Graph;
/**
* @author <NAME>
*
*/
public class FlowComparator implements Comparator<Graph> {
/*
* (non-Javadoc)
*
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Graph arg0, Graph arg1) {
// TODO Auto-generated method stub
return 0;
}
}
| 421 | 0.677647 | 0.670588 | 27 | 14.740741 | 19.523191 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 12 |
f216fb04af40eb2bbf56d03faf030b59926bb9ad | 29,532,195,154,652 | 00beef356e6d3a9ee7cfce473b32c20a26b21c31 | /src/test/java/com/kero/security/core/agent/KeroAccessAgentFactoryImplTest.java | e60f6329b96dcaa350cffd77cf36b3684ce7fee8 | [
"Apache-2.0"
] | permissive | Rednoll/kero-security | https://github.com/Rednoll/kero-security | a97f99429f6e4f7588ab4ebe79746d75d0341b93 | 7998406840e9b375c940106aec5d4805f074b3d2 | refs/heads/master | 2023-01-19T17:33:40.538000 | 2020-11-12T13:10:01 | 2020-11-12T13:10:01 | 287,011,542 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kero.security.core.agent;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import com.kero.security.core.agent.configurator.KeroAccessAgentConfigurator;
public class KeroAccessAgentFactoryImplTest {
@Test
public void test() {
KeroAccessAgentConfigurator configurator = Mockito.mock(KeroAccessAgentConfigurator.class);
KeroAccessAgentFactoryImpl factory = new KeroAccessAgentFactoryImpl();
factory.addConfigurator(configurator);
factory.create();
Mockito.verify(configurator, Mockito.times(1)).configure(Mockito.any());
}
}
| UTF-8 | Java | 579 | java | KeroAccessAgentFactoryImplTest.java | Java | [] | null | [] | package com.kero.security.core.agent;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import com.kero.security.core.agent.configurator.KeroAccessAgentConfigurator;
public class KeroAccessAgentFactoryImplTest {
@Test
public void test() {
KeroAccessAgentConfigurator configurator = Mockito.mock(KeroAccessAgentConfigurator.class);
KeroAccessAgentFactoryImpl factory = new KeroAccessAgentFactoryImpl();
factory.addConfigurator(configurator);
factory.create();
Mockito.verify(configurator, Mockito.times(1)).configure(Mockito.any());
}
}
| 579 | 0.791019 | 0.789292 | 22 | 25.318182 | 29.354242 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.454545 | false | false | 12 |
e64585975d16019b45cf4cd321d87f10d43686d6 | 30,408,368,458,201 | f01d6a9cf1b119b3aa2e0ddfffc8a2f5d1cdd747 | /src/com/sonic/HelloStrings.java | 94db46d6e835f3638a2df5b254ad08143d2faccd | [] | no_license | sf7293gv/Java | https://github.com/sf7293gv/Java | f3ac6a7d3d9b6d7998498049dadd125dfe733ab9 | d68149736806ee708a6a30d1bb80b0afd1d0e9f4 | refs/heads/master | 2022-12-13T10:07:35.672000 | 2020-09-01T16:28:56 | 2020-09-01T16:28:56 | 292,050,785 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sonic;
public class HelloStrings {
public static void main(String[] args) {
String name = "Sonic";
String nameinuppercase = name.toUpperCase();
System.out.println(nameinuppercase);
String nameinlowercase = name.toLowerCase();
System.out.println(nameinlowercase);
int charactersinname = name.length();
System.out.println("There are " + charactersinname + " characters in my name");
}
}
| UTF-8 | Java | 462 | java | HelloStrings.java | Java | [
{
"context": "void main(String[] args) {\n String name = \"Sonic\";\n String nameinuppercase = name.toUpperCa",
"end": 121,
"score": 0.9895225763320923,
"start": 116,
"tag": "NAME",
"value": "Sonic"
}
] | null | [] | package com.sonic;
public class HelloStrings {
public static void main(String[] args) {
String name = "Sonic";
String nameinuppercase = name.toUpperCase();
System.out.println(nameinuppercase);
String nameinlowercase = name.toLowerCase();
System.out.println(nameinlowercase);
int charactersinname = name.length();
System.out.println("There are " + charactersinname + " characters in my name");
}
}
| 462 | 0.658009 | 0.658009 | 13 | 34.53846 | 23.666319 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615385 | false | false | 12 |
212383c67f921f99b0b52b6ac312725a658a3c9b | 25,357,486,971,413 | 0c171c7eb2aee1c3d234e231752f14372b53c716 | /src/main/java/com/alojea/insurances/InsurancesApplication.java | 056d829dff2fc3bf5f76db5698de96d9cfd2bb13 | [] | no_license | alojea/AojeaInsurances | https://github.com/alojea/AojeaInsurances | ae1f86cceb8bc908fa490cef32fd93da9b3404b6 | 639dcbc94341867e8e4a8453dbecc2b724d254ae | refs/heads/master | 2020-11-27T20:41:21.750000 | 2020-01-09T11:05:15 | 2020-01-09T11:05:15 | 229,594,305 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.alojea.insurances;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
@SpringBootApplication
@EnableMongoRepositories("com.alojea.insurances.repositories")
public class InsurancesApplication {
public static void main(String[] args) {
SpringApplication.run(InsurancesApplication.class, args);
}
}
| UTF-8 | Java | 468 | java | InsurancesApplication.java | Java | [] | null | [] | package com.alojea.insurances;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
@SpringBootApplication
@EnableMongoRepositories("com.alojea.insurances.repositories")
public class InsurancesApplication {
public static void main(String[] args) {
SpringApplication.run(InsurancesApplication.class, args);
}
}
| 468 | 0.84188 | 0.84188 | 15 | 30.200001 | 28.116899 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 12 |
68ca76f964079cc1a279ab035d0b9f097f2885ea | 695,784,713,257 | 61928b1e7be5c96eb954d60729df5f634f38cc17 | /Homework 1/Die.java | 7a1db6b95a3e18c850e6ccde17f1e457ec26783a | [] | no_license | paulof-dev/CSIT-112-Spring-2018 | https://github.com/paulof-dev/CSIT-112-Spring-2018 | c56bb476416099c87dc60fa408c0b4a7250c0213 | 25c10fb9653c46f020643190f89280c5d20f60e7 | refs/heads/master | 2020-04-29T19:39:59.907000 | 2019-04-01T22:28:33 | 2019-04-01T22:28:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Programming Project 1 - Die.java
* Joao Paulo D. S. Ferreira
* CSIT 112 - Fundamentals of Programming II
* Dr. Dajin Wang
* Febuary 1, 2018
*/
/*
* The program bellow was given by the professor and
* is used to create a single die that can be rolled
*/
//********************************************************************
// Die.java Author: Lewis/Loftus
//
// Solution to Programming Project 5.10 and 5.17 and 6.5
//
// Represents one die (singular of dice) with faces showing values
// between 1 and the number of faces on the die.
//********************************************************************
public class Die
{
private final int MAX = 6; // maximum face value
private int faceValue; // current value showing on the die
//-----------------------------------------------------------------
// Constructor: sets the initial face value.
//-----------------------------------------------------------------
public Die()
{
faceValue = 1;
}
//-----------------------------------------------------------------
// Rolls the die and returns the result.
//-----------------------------------------------------------------
public int roll()
{
faceValue = (int) (Math.random() * MAX) + 1;
return faceValue;
}
//-----------------------------------------------------------------
// Face value mutator.
//-----------------------------------------------------------------
public void setFaceValue (int value)
{
faceValue = value;
}
//-----------------------------------------------------------------
// Face value accessor.
//-----------------------------------------------------------------
public int getFaceValue()
{
return faceValue;
}
//-----------------------------------------------------------------
// Returns a string representation of this die.
//-----------------------------------------------------------------
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
| UTF-8 | Java | 2,165 | java | Die.java | Java | [
{
"context": "/*\r\n * Programming Project 1 - Die.java\r\n * Joao Paulo D. S. Ferreira\r\n * CSIT 112 - Fundamentals of Programming II\r\n *",
"end": 69,
"score": 0.9998296499252319,
"start": 44,
"tag": "NAME",
"value": "Joao Paulo D. S. Ferreira"
},
{
"context": " CSIT 112 - Fundamentals of Programming II\r\n * Dr. Dajin Wang\r\n * Febuary 1, 2018\r\n */\r\n\r\n/* \r\n * The program b",
"end": 134,
"score": 0.9998034834861755,
"start": 124,
"tag": "NAME",
"value": "Dajin Wang"
},
{
"context": "**********************\r\n// Die.java Author: Lewis/Loftus\r\n//\r\n// Solution to Programming Proje",
"end": 384,
"score": 0.8491562008857727,
"start": 383,
"tag": "USERNAME",
"value": "L"
},
{
"context": "********************\r\n// Die.java Author: Lewis/Loftus\r\n//\r\n// Solution to Programming Project",
"end": 386,
"score": 0.6967476606369019,
"start": 384,
"tag": "NAME",
"value": "ew"
},
{
"context": "******************\r\n// Die.java Author: Lewis/Loftus\r\n//\r\n// Solution to Programming Project 5.",
"end": 388,
"score": 0.769611120223999,
"start": 386,
"tag": "USERNAME",
"value": "is"
},
{
"context": "***************\r\n// Die.java Author: Lewis/Loftus\r\n//\r\n// Solution to Programming Project 5.10 and",
"end": 395,
"score": 0.849407970905304,
"start": 389,
"tag": "USERNAME",
"value": "Loftus"
}
] | null | [] | /*
* Programming Project 1 - Die.java
* <NAME>
* CSIT 112 - Fundamentals of Programming II
* Dr. <NAME>
* Febuary 1, 2018
*/
/*
* The program bellow was given by the professor and
* is used to create a single die that can be rolled
*/
//********************************************************************
// Die.java Author: Lewis/Loftus
//
// Solution to Programming Project 5.10 and 5.17 and 6.5
//
// Represents one die (singular of dice) with faces showing values
// between 1 and the number of faces on the die.
//********************************************************************
public class Die
{
private final int MAX = 6; // maximum face value
private int faceValue; // current value showing on the die
//-----------------------------------------------------------------
// Constructor: sets the initial face value.
//-----------------------------------------------------------------
public Die()
{
faceValue = 1;
}
//-----------------------------------------------------------------
// Rolls the die and returns the result.
//-----------------------------------------------------------------
public int roll()
{
faceValue = (int) (Math.random() * MAX) + 1;
return faceValue;
}
//-----------------------------------------------------------------
// Face value mutator.
//-----------------------------------------------------------------
public void setFaceValue (int value)
{
faceValue = value;
}
//-----------------------------------------------------------------
// Face value accessor.
//-----------------------------------------------------------------
public int getFaceValue()
{
return faceValue;
}
//-----------------------------------------------------------------
// Returns a string representation of this die.
//-----------------------------------------------------------------
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
| 2,142 | 0.362587 | 0.352887 | 72 | 28.069445 | 26.390932 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.138889 | false | false | 12 |
a93e8058f4d7f14716b1a04afb8ee139f1db7bbf | 26,843,545,607,869 | d288779e2ff8d0ac8c4368c7cae61403773eb6ad | /app/src/main/java/com/example/khaled/takequiz/QuizQuestionAnswerDoctor.java | c86c5a37d96a57a088d4076deebc55f57d0b75eb | [] | no_license | ebadawy/sw-project | https://github.com/ebadawy/sw-project | 93f87c92e7ed6a51f0995ffe0b133a554f6ac127 | 9c70b3db4f6b2ed7d26aa5fc1409b491e11863c5 | refs/heads/master | 2020-12-28T00:01:14.198000 | 2015-02-15T14:00:14 | 2015-02-15T14:00:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.khaled.takequiz;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.rest.model.Choice;
import com.rest.model.Question;
import com.rest.model.Quiz;
import com.rest.model.QuizWrapper;
import com.squareup.okhttp.Response;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import retrofit.Callback;
import retrofit.RetrofitError;
public class QuizQuestionAnswerDoctor extends FragmentActivity implements View.OnClickListener , OnPageChangeListener {
Button addQuestion;
private PagerAdapter mPagerAdapter;
public List<Fragment> fragments;
public List<Fragment1> createdFragments = new ArrayList<Fragment1>();
Button nextPage;
Button previousPage;
Button save;
ViewPager pager;
int currentPage;
EditText pageNumber;
TextView quizName;
Button go;
TextView viewSubject;
String deadline;
String timelimit;
String quizmark;
String j;
TextView saveplzwait;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_question_answer_doctor);
viewSubject = (TextView) findViewById(R.id.viewSubject);
addQuestion = (Button) findViewById(R.id.addQuestion);
nextPage = (Button) findViewById(R.id.nextPage);
previousPage = (Button) findViewById(R.id.previousPage);
go = (Button) findViewById(R.id.go);
pageNumber = (EditText) findViewById(R.id.pageNumber);
saveplzwait=(TextView)findViewById(R.id.savepleasewait);
save = (Button) findViewById(R.id.save);
addQuestion.setOnClickListener(this);
save.setOnClickListener(this);
initialisePaging();
nextPage.setOnClickListener(this);
previousPage.setOnClickListener(this);
go.setOnClickListener(this);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if (extras == null) {
j = null;
deadline = null;
timelimit = null;
quizmark = null;
} else {
j = extras.getString("subject");
viewSubject.setText(j);
deadline = extras.getString("deadline");
timelimit = extras.getString("timelimit");
quizmark = extras.getString("quizmark");
}
} else {
j = (String) savedInstanceState.getSerializable("subject");
deadline = (String) savedInstanceState.getSerializable("deadline");
timelimit = (String) savedInstanceState.getSerializable("timelimit");
quizmark = (String) savedInstanceState.getSerializable("quizmark");
}
}
private void initialisePaging() {
fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);
pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(mPagerAdapter);
pager.setOnPageChangeListener(this);
}
private void addQuestionClick() {
fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
mPagerAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Question Added Swipe", Toast.LENGTH_SHORT).show();
}
private void goClick() {
String pageNumber_ = pageNumber.getText().toString();
int pageNumberx = Integer.parseInt(pageNumber_);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setCurrentItem(pageNumberx - 1, true);
}
public void saveClick() {
List<String> questions_ = new ArrayList<String>();
List<Question> questions = new ArrayList<Question>();
for (int i = 0; i < fragments.size(); i++) {
Fragment1 f = (Fragment1) fragments.get(i);
createdFragments.add(f);
}
for (int i = 0; i < createdFragments.size(); i++) {
List<String> Choices_ = new ArrayList<String>();
Choices_ = createdFragments.get(i).getChoiceList();
questions_.add(createdFragments.get(i).getQuestion());
System.out.println(questions_.get(i));
List<Choice> choices = new ArrayList<Choice>();
for (int j = 0; j < Choices_.size(); j++) {
Choice c1 = new Choice(Choices_.get(j));
choices.add(c1);
System.out.println(Choices_.get(j));
}
Question q1 = new Question(questions_.get(i),
createdFragments.get(i).getRightChoice(), choices);
questions.add(q1);
}
Quiz quiz = new Quiz(j, deadline, timelimit, Integer.parseInt(quizmark), questions);
QuizWrapper quizWrapper = new QuizWrapper(quiz);
saveplzwait.setText("Please Wait...");
MainActivity.api.createQuize(quizWrapper, MainActivity.current_user.getId(), new Callback<Response>() {
@Override
public void success(Response response, retrofit.client.Response response2) {
saveplzwait.setText("");
Toast.makeText(getApplicationContext(), "Saved Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizQuestionAnswerDoctor.this,ListofQuiz.class);
startActivity(intent);
}
@Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(getApplicationContext(), "Saving Failed", Toast.LENGTH_SHORT).show();
}
});
questions_.clear();
createdFragments.clear();
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.addQuestion:
addQuestionClick();
break;
case R.id.nextPage:
nextPage();
break;
case R.id.previousPage:
previousPage();
break;
case R.id.go:
goClick();
break;
case R.id.save:
try{
saveClick();
}
catch(NumberFormatException e){
Toast.makeText(getApplicationContext(), "Missing Field Recheck", Toast.LENGTH_SHORT).show();
}
break;
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Toast.makeText(getApplicationContext(), "Question " + (position + 1), Toast.LENGTH_SHORT).show();
currentPage = position;
}
@Override
public void onPageScrollStateChanged(int state) {
}
private void nextPage() {
int totalPages = mPagerAdapter.getCount();
int nextPage = currentPage + 1;
if (nextPage >= totalPages) {
// We can't go forward anymore.
// Loop to the first page. If you don't want looping just
// return here.
nextPage = 0;
}
pager = (ViewPager) findViewById(R.id.viewpager);
pager.setCurrentItem(nextPage, true);
}
private void previousPage() {
int totalPages = mPagerAdapter.getCount();
int previousPage = currentPage - 1;
if (previousPage < 0) {
// We can't go back anymore.
// Loop to the last page. If you don't want looping just
// return here.
previousPage = totalPages - 1;
}
pager = (ViewPager) findViewById(R.id.viewpager);
pager.setCurrentItem(previousPage, true);
}
}
| UTF-8 | Java | 8,191 | java | QuizQuestionAnswerDoctor.java | Java | [
{
"context": "package com.example.khaled.takequiz;\n\n\nimport android.content.Intent;\nimport",
"end": 26,
"score": 0.9342769980430603,
"start": 20,
"tag": "USERNAME",
"value": "khaled"
}
] | null | [] | package com.example.khaled.takequiz;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.rest.model.Choice;
import com.rest.model.Question;
import com.rest.model.Quiz;
import com.rest.model.QuizWrapper;
import com.squareup.okhttp.Response;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import retrofit.Callback;
import retrofit.RetrofitError;
public class QuizQuestionAnswerDoctor extends FragmentActivity implements View.OnClickListener , OnPageChangeListener {
Button addQuestion;
private PagerAdapter mPagerAdapter;
public List<Fragment> fragments;
public List<Fragment1> createdFragments = new ArrayList<Fragment1>();
Button nextPage;
Button previousPage;
Button save;
ViewPager pager;
int currentPage;
EditText pageNumber;
TextView quizName;
Button go;
TextView viewSubject;
String deadline;
String timelimit;
String quizmark;
String j;
TextView saveplzwait;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_question_answer_doctor);
viewSubject = (TextView) findViewById(R.id.viewSubject);
addQuestion = (Button) findViewById(R.id.addQuestion);
nextPage = (Button) findViewById(R.id.nextPage);
previousPage = (Button) findViewById(R.id.previousPage);
go = (Button) findViewById(R.id.go);
pageNumber = (EditText) findViewById(R.id.pageNumber);
saveplzwait=(TextView)findViewById(R.id.savepleasewait);
save = (Button) findViewById(R.id.save);
addQuestion.setOnClickListener(this);
save.setOnClickListener(this);
initialisePaging();
nextPage.setOnClickListener(this);
previousPage.setOnClickListener(this);
go.setOnClickListener(this);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if (extras == null) {
j = null;
deadline = null;
timelimit = null;
quizmark = null;
} else {
j = extras.getString("subject");
viewSubject.setText(j);
deadline = extras.getString("deadline");
timelimit = extras.getString("timelimit");
quizmark = extras.getString("quizmark");
}
} else {
j = (String) savedInstanceState.getSerializable("subject");
deadline = (String) savedInstanceState.getSerializable("deadline");
timelimit = (String) savedInstanceState.getSerializable("timelimit");
quizmark = (String) savedInstanceState.getSerializable("quizmark");
}
}
private void initialisePaging() {
fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);
pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(mPagerAdapter);
pager.setOnPageChangeListener(this);
}
private void addQuestionClick() {
fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
mPagerAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Question Added Swipe", Toast.LENGTH_SHORT).show();
}
private void goClick() {
String pageNumber_ = pageNumber.getText().toString();
int pageNumberx = Integer.parseInt(pageNumber_);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setCurrentItem(pageNumberx - 1, true);
}
public void saveClick() {
List<String> questions_ = new ArrayList<String>();
List<Question> questions = new ArrayList<Question>();
for (int i = 0; i < fragments.size(); i++) {
Fragment1 f = (Fragment1) fragments.get(i);
createdFragments.add(f);
}
for (int i = 0; i < createdFragments.size(); i++) {
List<String> Choices_ = new ArrayList<String>();
Choices_ = createdFragments.get(i).getChoiceList();
questions_.add(createdFragments.get(i).getQuestion());
System.out.println(questions_.get(i));
List<Choice> choices = new ArrayList<Choice>();
for (int j = 0; j < Choices_.size(); j++) {
Choice c1 = new Choice(Choices_.get(j));
choices.add(c1);
System.out.println(Choices_.get(j));
}
Question q1 = new Question(questions_.get(i),
createdFragments.get(i).getRightChoice(), choices);
questions.add(q1);
}
Quiz quiz = new Quiz(j, deadline, timelimit, Integer.parseInt(quizmark), questions);
QuizWrapper quizWrapper = new QuizWrapper(quiz);
saveplzwait.setText("Please Wait...");
MainActivity.api.createQuize(quizWrapper, MainActivity.current_user.getId(), new Callback<Response>() {
@Override
public void success(Response response, retrofit.client.Response response2) {
saveplzwait.setText("");
Toast.makeText(getApplicationContext(), "Saved Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(QuizQuestionAnswerDoctor.this,ListofQuiz.class);
startActivity(intent);
}
@Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(getApplicationContext(), "Saving Failed", Toast.LENGTH_SHORT).show();
}
});
questions_.clear();
createdFragments.clear();
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.addQuestion:
addQuestionClick();
break;
case R.id.nextPage:
nextPage();
break;
case R.id.previousPage:
previousPage();
break;
case R.id.go:
goClick();
break;
case R.id.save:
try{
saveClick();
}
catch(NumberFormatException e){
Toast.makeText(getApplicationContext(), "Missing Field Recheck", Toast.LENGTH_SHORT).show();
}
break;
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Toast.makeText(getApplicationContext(), "Question " + (position + 1), Toast.LENGTH_SHORT).show();
currentPage = position;
}
@Override
public void onPageScrollStateChanged(int state) {
}
private void nextPage() {
int totalPages = mPagerAdapter.getCount();
int nextPage = currentPage + 1;
if (nextPage >= totalPages) {
// We can't go forward anymore.
// Loop to the first page. If you don't want looping just
// return here.
nextPage = 0;
}
pager = (ViewPager) findViewById(R.id.viewpager);
pager.setCurrentItem(nextPage, true);
}
private void previousPage() {
int totalPages = mPagerAdapter.getCount();
int previousPage = currentPage - 1;
if (previousPage < 0) {
// We can't go back anymore.
// Loop to the last page. If you don't want looping just
// return here.
previousPage = totalPages - 1;
}
pager = (ViewPager) findViewById(R.id.viewpager);
pager.setCurrentItem(previousPage, true);
}
}
| 8,191 | 0.612502 | 0.609449 | 248 | 32.028225 | 26.643616 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.669355 | false | false | 12 |
5ef5526e8c02ebf3778243f3ab677e6f4b933be0 | 28,097,676,056,836 | 470d0fa6c69778d214bb23daddba004332e54eaa | /service-spring/src/test/java/com/emmisolutions/emmimanager/service/spring/ClientProviderServiceIntegrationTest.java | dc2d8fd5cfb14302752247f22d5481f4ad246a7e | [] | no_license | pohualin/EM_server | https://github.com/pohualin/EM_server | 3fb35b0bac60a34ab3a6b6090859d35f0e719552 | e6c9877fde6c20e160418e7e7868ca699b720217 | refs/heads/master | 2021-01-10T04:37:29.295000 | 2015-10-15T20:23:49 | 2015-10-15T20:23:49 | 44,392,080 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.emmisolutions.emmimanager.service.spring;
import com.emmisolutions.emmimanager.model.*;
import com.emmisolutions.emmimanager.model.user.admin.UserAdmin;
import com.emmisolutions.emmimanager.persistence.ProviderPersistence;
import com.emmisolutions.emmimanager.service.BaseIntegrationTest;
import com.emmisolutions.emmimanager.service.ClientProviderService;
import com.emmisolutions.emmimanager.service.ClientService;
import com.emmisolutions.emmimanager.service.ProviderService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDate;
import org.junit.Test;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.domain.Page;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
/**
* Integration test for the ClientProviderService API
*/
public class ClientProviderServiceIntegrationTest extends BaseIntegrationTest {
@Resource
ClientService clientService;
@Resource
ProviderService providerService;
@Resource
ClientProviderService clientProviderService;
/**
* This test is the lifecycle of a ClientProvider. It creates one, finds it, then deletes it.
*/
@Test
public void createFindDelete() {
final Provider provider = makeProvider();
Client client = makeClient();
Set<ClientProvider> savedProviders = clientProviderService.create(client, new HashSet<Provider>() {{
add(provider);
}});
assertThat("client has one provider", savedProviders.size(), is(1));
assertThat("provider is the one we added", savedProviders.iterator().next().getProvider(), is(provider));
ClientProvider clientProvider = clientProviderService.reload(savedProviders.iterator().next());
assertThat("client provider was loaded", clientProvider, is(notNullValue()));
clientProviderService.remove(clientProvider);
assertThat("client has zero providers after delete", 0l, is(clientProviderService.findByClient(client, null).getTotalElements()));
}
/**
* Ensure that finding possible providers works.. including making sure
* existing providers function properly.
*/
@Test
public void findPossibleProviders(){
// make a bunch of providers
final Provider provider = makeProvider();
for (int i = 0; i < 10; i++) {
makeProvider();
}
// associate a client to one of those providers
Client client = makeClient();
Set<ClientProvider> savedProviders = clientProviderService.create(client, new HashSet<Provider>() {{
add(provider);
}});
ClientProvider savedRelationship = savedProviders.iterator().next();
// find a page of possible ClientProviders using the same name that we used during create
Page<ClientProvider> possibleProviders =
clientProviderService.findPossibleProvidersToAdd(client, new ProviderSearchFilter("ClientProviderServiceIntegrationTest Provider"), null);
assertThat("there should be 11 providers found", possibleProviders.getTotalElements(), is(11l));
assertThat("one of the ClientProvider objects should be the one we saved", possibleProviders, hasItem(savedRelationship));
}
/**
* This test creates a provider on a client as well as updates it
*/
@Test
public void createProviderOnClient(){
Client client = makeClient();
Provider provider = new Provider();
provider.setFirstName("Client Provider Association");
provider.setLastName(RandomStringUtils.randomAlphabetic(255));
ProviderSpecialty specialty = new ProviderSpecialty();
specialty.setName(RandomStringUtils.randomAlphanumeric(18));
provider.setSpecialty(providerService.saveSpecialty(specialty));
provider.setEmail("whatever@whatever.com");
ClientProvider clientProvider = clientProviderService.create(new ClientProvider(client, provider));
assertThat("ClientProvider is not null", clientProvider, is(notNullValue()));
Page<ClientProvider> clientProviderPage = clientProviderService.findByClient(client, null);
assertThat("finding client providers should include the newly created one", clientProviderPage, hasItem(clientProvider));
// update the clientProvider
clientProvider.setExternalId("mateo");
provider.setActive(true);
ClientProvider updated = clientProviderService.update(clientProvider);
assertThat("provider was updated", updated.getProvider().isActive(), is(true));
assertThat("client provider was updated", updated.getExternalId(), is(clientProvider.getExternalId()));
assertThat("client provider version should be different", updated.getVersion(), is(not(clientProvider.getVersion())));
}
@Test
public void findByProvider(){
Client clientA = makeClient();
Client clientB = makeClient();
Provider provider = makeProvider("findByProvider");
Set<Provider> providers = new HashSet<Provider>();
providers.add(provider);
clientProviderService.create(clientA, providers);
clientProviderService.create(clientB, providers);
Page<ClientProvider> list = clientProviderService.findByProvider(provider, null);
assertThat("There shoule be 2 clients found for the provider.", list.getTotalElements(), is(2l));
}
@Test(expected = InvalidDataAccessApiUsageException.class)
public void invalidCreateCall(){
clientProviderService.create(null);
}
/**
* Can't find with a null client
*/
@Test(expected = InvalidDataAccessApiUsageException.class)
public void invalidFindCall(){
clientProviderService.findByClient(null, null);
}
/**
* Can't delete with a non persistent client provider
*/
@Test(expected = InvalidDataAccessApiUsageException.class)
public void invalidDeleteCall(){
clientProviderService.remove(new ClientProvider());
}
/**
* Can't reload a null client provider
*/
@Test(expected = InvalidDataAccessApiUsageException.class)
public void invalidReloadCall(){
clientProviderService.reload(null);
}
/**
* Can't find possible providers for a null client
*/
@Test(expected = InvalidDataAccessApiUsageException.class)
public void invalidFindPossibleCall(){
clientProviderService.findPossibleProvidersToAdd(null, null, null);
}
/**
* Test invalid api access for create
*/
@Test(expected = InvalidDataAccessApiUsageException.class)
public void invalidCreate(){
clientProviderService.create(null, null);
}
private Client makeClient() {
Client client = new Client();
client.setTier(new ClientTier(3l));
client.setContractEnd(LocalDate.now().plusYears(1));
client.setContractStart(LocalDate.now());
client.setRegion(new ClientRegion(1l));
client.setName(RandomStringUtils.randomAlphabetic(255));
client.setType(new ClientType(1l));
client.setActive(true);
client.setContractOwner(new UserAdmin(1l, 0));
client.setSalesForceAccount(new SalesForce(RandomStringUtils.randomAlphanumeric(18)));
return clientService.create(client);
}
private Provider makeProvider(String firstName) {
Provider provider = new Provider();
if(StringUtils.isBlank(firstName)){
firstName = "ClientProviderServiceIntegrationTest Provider";
}
provider.setFirstName(firstName);
provider.setLastName(RandomStringUtils.randomAlphabetic(255));
ProviderSpecialty specialty = new ProviderSpecialty();
specialty.setName(RandomStringUtils.randomAlphanumeric(18));
ProviderSpecialty savedSpecialty = providerService.saveSpecialty(specialty);
provider.setSpecialty(savedSpecialty);
provider.setEmail("whatever@whatever.com");
return providerService.create(provider);
}
private Provider makeProvider(){
return makeProvider("");
}
}
| UTF-8 | Java | 8,258 | java | ClientProviderServiceIntegrationTest.java | Java | [
{
"context": "Specialty(specialty));\n provider.setEmail(\"whatever@whatever.com\");\n\n ClientProvider clientProvider = clien",
"end": 4040,
"score": 0.9998517632484436,
"start": 4019,
"tag": "EMAIL",
"value": "whatever@whatever.com"
},
{
"context": "entProvider\n clientProvider.setExternalId(\"mateo\");\n provider.setActive(true);\n Clie",
"end": 4551,
"score": 0.983037531375885,
"start": 4546,
"tag": "USERNAME",
"value": "mateo"
},
{
"context": "ialty(savedSpecialty);\n provider.setEmail(\"whatever@whatever.com\");\n return providerService.create(provider",
"end": 8123,
"score": 0.9999065399169922,
"start": 8102,
"tag": "EMAIL",
"value": "whatever@whatever.com"
}
] | null | [] | package com.emmisolutions.emmimanager.service.spring;
import com.emmisolutions.emmimanager.model.*;
import com.emmisolutions.emmimanager.model.user.admin.UserAdmin;
import com.emmisolutions.emmimanager.persistence.ProviderPersistence;
import com.emmisolutions.emmimanager.service.BaseIntegrationTest;
import com.emmisolutions.emmimanager.service.ClientProviderService;
import com.emmisolutions.emmimanager.service.ClientService;
import com.emmisolutions.emmimanager.service.ProviderService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDate;
import org.junit.Test;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.domain.Page;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
/**
* Integration test for the ClientProviderService API
*/
public class ClientProviderServiceIntegrationTest extends BaseIntegrationTest {
@Resource
ClientService clientService;
@Resource
ProviderService providerService;
@Resource
ClientProviderService clientProviderService;
/**
* This test is the lifecycle of a ClientProvider. It creates one, finds it, then deletes it.
*/
@Test
public void createFindDelete() {
final Provider provider = makeProvider();
Client client = makeClient();
Set<ClientProvider> savedProviders = clientProviderService.create(client, new HashSet<Provider>() {{
add(provider);
}});
assertThat("client has one provider", savedProviders.size(), is(1));
assertThat("provider is the one we added", savedProviders.iterator().next().getProvider(), is(provider));
ClientProvider clientProvider = clientProviderService.reload(savedProviders.iterator().next());
assertThat("client provider was loaded", clientProvider, is(notNullValue()));
clientProviderService.remove(clientProvider);
assertThat("client has zero providers after delete", 0l, is(clientProviderService.findByClient(client, null).getTotalElements()));
}
/**
* Ensure that finding possible providers works.. including making sure
* existing providers function properly.
*/
@Test
public void findPossibleProviders(){
// make a bunch of providers
final Provider provider = makeProvider();
for (int i = 0; i < 10; i++) {
makeProvider();
}
// associate a client to one of those providers
Client client = makeClient();
Set<ClientProvider> savedProviders = clientProviderService.create(client, new HashSet<Provider>() {{
add(provider);
}});
ClientProvider savedRelationship = savedProviders.iterator().next();
// find a page of possible ClientProviders using the same name that we used during create
Page<ClientProvider> possibleProviders =
clientProviderService.findPossibleProvidersToAdd(client, new ProviderSearchFilter("ClientProviderServiceIntegrationTest Provider"), null);
assertThat("there should be 11 providers found", possibleProviders.getTotalElements(), is(11l));
assertThat("one of the ClientProvider objects should be the one we saved", possibleProviders, hasItem(savedRelationship));
}
/**
* This test creates a provider on a client as well as updates it
*/
@Test
public void createProviderOnClient(){
Client client = makeClient();
Provider provider = new Provider();
provider.setFirstName("Client Provider Association");
provider.setLastName(RandomStringUtils.randomAlphabetic(255));
ProviderSpecialty specialty = new ProviderSpecialty();
specialty.setName(RandomStringUtils.randomAlphanumeric(18));
provider.setSpecialty(providerService.saveSpecialty(specialty));
provider.setEmail("<EMAIL>");
ClientProvider clientProvider = clientProviderService.create(new ClientProvider(client, provider));
assertThat("ClientProvider is not null", clientProvider, is(notNullValue()));
Page<ClientProvider> clientProviderPage = clientProviderService.findByClient(client, null);
assertThat("finding client providers should include the newly created one", clientProviderPage, hasItem(clientProvider));
// update the clientProvider
clientProvider.setExternalId("mateo");
provider.setActive(true);
ClientProvider updated = clientProviderService.update(clientProvider);
assertThat("provider was updated", updated.getProvider().isActive(), is(true));
assertThat("client provider was updated", updated.getExternalId(), is(clientProvider.getExternalId()));
assertThat("client provider version should be different", updated.getVersion(), is(not(clientProvider.getVersion())));
}
@Test
public void findByProvider(){
Client clientA = makeClient();
Client clientB = makeClient();
Provider provider = makeProvider("findByProvider");
Set<Provider> providers = new HashSet<Provider>();
providers.add(provider);
clientProviderService.create(clientA, providers);
clientProviderService.create(clientB, providers);
Page<ClientProvider> list = clientProviderService.findByProvider(provider, null);
assertThat("There shoule be 2 clients found for the provider.", list.getTotalElements(), is(2l));
}
@Test(expected = InvalidDataAccessApiUsageException.class)
public void invalidCreateCall(){
clientProviderService.create(null);
}
/**
* Can't find with a null client
*/
@Test(expected = InvalidDataAccessApiUsageException.class)
public void invalidFindCall(){
clientProviderService.findByClient(null, null);
}
/**
* Can't delete with a non persistent client provider
*/
@Test(expected = InvalidDataAccessApiUsageException.class)
public void invalidDeleteCall(){
clientProviderService.remove(new ClientProvider());
}
/**
* Can't reload a null client provider
*/
@Test(expected = InvalidDataAccessApiUsageException.class)
public void invalidReloadCall(){
clientProviderService.reload(null);
}
/**
* Can't find possible providers for a null client
*/
@Test(expected = InvalidDataAccessApiUsageException.class)
public void invalidFindPossibleCall(){
clientProviderService.findPossibleProvidersToAdd(null, null, null);
}
/**
* Test invalid api access for create
*/
@Test(expected = InvalidDataAccessApiUsageException.class)
public void invalidCreate(){
clientProviderService.create(null, null);
}
private Client makeClient() {
Client client = new Client();
client.setTier(new ClientTier(3l));
client.setContractEnd(LocalDate.now().plusYears(1));
client.setContractStart(LocalDate.now());
client.setRegion(new ClientRegion(1l));
client.setName(RandomStringUtils.randomAlphabetic(255));
client.setType(new ClientType(1l));
client.setActive(true);
client.setContractOwner(new UserAdmin(1l, 0));
client.setSalesForceAccount(new SalesForce(RandomStringUtils.randomAlphanumeric(18)));
return clientService.create(client);
}
private Provider makeProvider(String firstName) {
Provider provider = new Provider();
if(StringUtils.isBlank(firstName)){
firstName = "ClientProviderServiceIntegrationTest Provider";
}
provider.setFirstName(firstName);
provider.setLastName(RandomStringUtils.randomAlphabetic(255));
ProviderSpecialty specialty = new ProviderSpecialty();
specialty.setName(RandomStringUtils.randomAlphanumeric(18));
ProviderSpecialty savedSpecialty = providerService.saveSpecialty(specialty);
provider.setSpecialty(savedSpecialty);
provider.setEmail("<EMAIL>");
return providerService.create(provider);
}
private Provider makeProvider(){
return makeProvider("");
}
}
| 8,230 | 0.714459 | 0.710342 | 206 | 39.087379 | 33.450039 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.728155 | false | false | 12 |
1a12b4178d626b8eb41faaa9aec8c62098cb9f6e | 28,346,784,163,513 | 0f0f83b7a23944f511d2e66410cf50bccb32aeaa | /ModelRocketSim/src/ModelEngine.java | 4cbe51f6efe3be0d664ffb35d5be0bbf16ce82eb | [] | no_license | luke738/HighSchoolProjects | https://github.com/luke738/HighSchoolProjects | 2075b59ad97c91a31dcb895ca0480cd526b6c31b | d89fc25942db91ed7a5d8e41df9e81470ff6d3fd | refs/heads/master | 2020-09-23T06:42:38.277000 | 2016-10-13T06:47:12 | 2016-10-13T06:47:12 | 66,590,533 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Name: Luke St. Regis
* Period: 3
* Date: 5/12/2015
* Assignment: Rocket
* Phone Number: 1-310-560-0942
* Email: luke7380@gmail.com
*/
public class ModelEngine
{
public double mass;
public double fuelMass;
public final double isp;
public final VarCurve thrust;
public ModelEngine(double m, double fuelM, double specImp, VarCurve F_t)
{
mass = m;
fuelMass = fuelM;
isp = specImp;
thrust = F_t;
}
public ModelEngine copy()
{
return new ModelEngine(mass, fuelMass, isp, thrust);
}
}
| UTF-8 | Java | 574 | java | ModelEngine.java | Java | [
{
"context": "/**\n * Name: Luke St. Regis\n * Period: 3\n * Date: 5/12/2015\n * Assignment: Ro",
"end": 27,
"score": 0.9998798966407776,
"start": 13,
"tag": "NAME",
"value": "Luke St. Regis"
},
{
"context": ": Rocket\n * Phone Number: 1-310-560-0942\n * Email: luke7380@gmail.com\n */\npublic class ModelEngine\n{\n public double ",
"end": 142,
"score": 0.9999233484268188,
"start": 124,
"tag": "EMAIL",
"value": "luke7380@gmail.com"
}
] | null | [] | /**
* Name: <NAME>
* Period: 3
* Date: 5/12/2015
* Assignment: Rocket
* Phone Number: 1-310-560-0942
* Email: <EMAIL>
*/
public class ModelEngine
{
public double mass;
public double fuelMass;
public final double isp;
public final VarCurve thrust;
public ModelEngine(double m, double fuelM, double specImp, VarCurve F_t)
{
mass = m;
fuelMass = fuelM;
isp = specImp;
thrust = F_t;
}
public ModelEngine copy()
{
return new ModelEngine(mass, fuelMass, isp, thrust);
}
}
| 555 | 0.611498 | 0.571429 | 28 | 19.5 | 17.340086 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.535714 | false | false | 12 |
faed8d86b4d81a0a25946fb6437c059e2b566393 | 7,035,156,444,635 | 9ec050b65c1dbe51828c6586e7195ce7a310d0de | /network-chat/server/src/main/java/ru/geekbrains/ClientHandler.java | cf506f0fff1d096d26ed3267d71c0c0ef15da256 | [] | no_license | VicNA/geek-university-java-2 | https://github.com/VicNA/geek-university-java-2 | 6ed14e88485fab06650258b73982df939b5f589a | e1dd0d8171d3b0f3f1b1cd1eadd1a941f7a59ebc | refs/heads/main | 2023-08-02T09:29:17.574000 | 2021-09-20T11:38:34 | 2021-09-20T11:38:34 | 384,936,762 | 0 | 0 | null | false | 2021-10-03T20:31:09 | 2021-07-11T11:59:24 | 2021-09-20T11:49:38 | 2021-10-03T20:28:28 | 143 | 0 | 0 | 12 | Java | false | false | package ru.geekbrains;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ClientHandler {
private static final Logger LOGGER = LogManager.getLogger(ClientHandler.class);
private Server server;
private Socket socket;
private String login;
private String name;
private DataInputStream in;
private DataOutputStream out;
// Получение сокета от сервера, создание потоков in/out,
// запуск в отдельном потоке чтения данных получаемых от пользователя
public ClientHandler(Server server, Socket socket) {
try {
this.server = server;
this.socket = socket;
this.in = new DataInputStream(socket.getInputStream());
this.out = new DataOutputStream(socket.getOutputStream());
server.getExecutor().execute(() -> readMessages());
} catch (IOException e) {
e.printStackTrace();
}
}
// Обработка входящих данных получаемых от пользователя
private void readMessages() {
try {
authentication();
readMessage();
} catch (IOException e) {
e.printStackTrace();
} finally {
LOGGER.info("Клиент " + name + " отключился");
server.unsubscribe(this);
closeConnection();
}
}
// Обработка сообщений пользователя на наличие внутренних комманд
// и рассылка сообщения другим пользователям
private void readMessage() throws IOException {
while (true) {
String message = in.readUTF();
if (message.startsWith("/")) {
if (message.equals("/exit")) {
sendMessage("/exit");
break;
}
if (message.startsWith("/w ")) {
String[] tokens = message.split("\\s+", 3);
server.sendPersonalMessage(this, tokens[1], tokens[2]);
continue;
}
if (message.startsWith("/change_nick ")) {
String[] tokens = message.split("\\s+");
if (tokens.length == 1) {
sendMessage("SERVER: Введите имя пользователя");
continue;
}
if (tokens.length > 2) {
sendMessage("SERVER: Имя пользователя не должен содержать пробелы");
continue;
}
if (name.equalsIgnoreCase(tokens[1])) {
sendMessage("SERVER: Данное имя пользователя является текущим");
continue;
}
if (server.getAuthService().isNameBusy(tokens[1])) {
sendMessage("SERVER: Данное имя пользователя уже занято");
continue;
}
server.getAuthService().changeNickname(login, tokens[1]);
String oldName = name;
name = tokens[1];
sendMessage("/changeok " + name);
sendMessage("SERVER: " + oldName + " сменил имя на " + name);
server.broadcastClientList();
continue;
}
}
server.broadcastMessage(name + ": " + message);
}
}
// Обработка сообщения об авторизации
private void authentication() throws IOException {
while (true) {
String message = in.readUTF();
if (!message.startsWith("/auth ")) {
sendMessage("SERVER: Вам необходимо авторизоваться");
continue;
}
String[] tokens = message.split("\\s+");
if (tokens.length == 1) {
sendMessage("SERVER: Вы не указали логин или пароль");
continue;
}
if (tokens.length > 3) {
sendMessage("SERVER: Логин и пароль не должны содержать пробелы");
continue;
}
String[] auth = server.getAuthService().loggedIn(tokens[1], tokens[2]);
if (auth == null) {
sendMessage("SERVER: Такой логин отстутствует");
continue;
}
if (server.isNameBusy(auth[1])) {
sendMessage("SERVER: Данный пользователь уже авторизовался");
continue;
}
login = auth[0];
name = auth[1];
// System.out.println("sendMessage: /authok " + name);
sendMessage("/authok " + name);
server.subscribe(this);
return;
}
}
// Полуение имя пользователя
public String getName() {
return name;
}
// Отправка сообщения пользователю
public void sendMessage(String message) {
try {
out.writeUTF(message);
} catch (IOException e) {
e.printStackTrace();
}
}
// Закрытие подключения сокета и потоков данных
private void closeConnection() {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 6,520 | java | ClientHandler.java | Java | [] | null | [] | package ru.geekbrains;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ClientHandler {
private static final Logger LOGGER = LogManager.getLogger(ClientHandler.class);
private Server server;
private Socket socket;
private String login;
private String name;
private DataInputStream in;
private DataOutputStream out;
// Получение сокета от сервера, создание потоков in/out,
// запуск в отдельном потоке чтения данных получаемых от пользователя
public ClientHandler(Server server, Socket socket) {
try {
this.server = server;
this.socket = socket;
this.in = new DataInputStream(socket.getInputStream());
this.out = new DataOutputStream(socket.getOutputStream());
server.getExecutor().execute(() -> readMessages());
} catch (IOException e) {
e.printStackTrace();
}
}
// Обработка входящих данных получаемых от пользователя
private void readMessages() {
try {
authentication();
readMessage();
} catch (IOException e) {
e.printStackTrace();
} finally {
LOGGER.info("Клиент " + name + " отключился");
server.unsubscribe(this);
closeConnection();
}
}
// Обработка сообщений пользователя на наличие внутренних комманд
// и рассылка сообщения другим пользователям
private void readMessage() throws IOException {
while (true) {
String message = in.readUTF();
if (message.startsWith("/")) {
if (message.equals("/exit")) {
sendMessage("/exit");
break;
}
if (message.startsWith("/w ")) {
String[] tokens = message.split("\\s+", 3);
server.sendPersonalMessage(this, tokens[1], tokens[2]);
continue;
}
if (message.startsWith("/change_nick ")) {
String[] tokens = message.split("\\s+");
if (tokens.length == 1) {
sendMessage("SERVER: Введите имя пользователя");
continue;
}
if (tokens.length > 2) {
sendMessage("SERVER: Имя пользователя не должен содержать пробелы");
continue;
}
if (name.equalsIgnoreCase(tokens[1])) {
sendMessage("SERVER: Данное имя пользователя является текущим");
continue;
}
if (server.getAuthService().isNameBusy(tokens[1])) {
sendMessage("SERVER: Данное имя пользователя уже занято");
continue;
}
server.getAuthService().changeNickname(login, tokens[1]);
String oldName = name;
name = tokens[1];
sendMessage("/changeok " + name);
sendMessage("SERVER: " + oldName + " сменил имя на " + name);
server.broadcastClientList();
continue;
}
}
server.broadcastMessage(name + ": " + message);
}
}
// Обработка сообщения об авторизации
private void authentication() throws IOException {
while (true) {
String message = in.readUTF();
if (!message.startsWith("/auth ")) {
sendMessage("SERVER: Вам необходимо авторизоваться");
continue;
}
String[] tokens = message.split("\\s+");
if (tokens.length == 1) {
sendMessage("SERVER: Вы не указали логин или пароль");
continue;
}
if (tokens.length > 3) {
sendMessage("SERVER: Логин и пароль не должны содержать пробелы");
continue;
}
String[] auth = server.getAuthService().loggedIn(tokens[1], tokens[2]);
if (auth == null) {
sendMessage("SERVER: Такой логин отстутствует");
continue;
}
if (server.isNameBusy(auth[1])) {
sendMessage("SERVER: Данный пользователь уже авторизовался");
continue;
}
login = auth[0];
name = auth[1];
// System.out.println("sendMessage: /authok " + name);
sendMessage("/authok " + name);
server.subscribe(this);
return;
}
}
// Полуение имя пользователя
public String getName() {
return name;
}
// Отправка сообщения пользователю
public void sendMessage(String message) {
try {
out.writeUTF(message);
} catch (IOException e) {
e.printStackTrace();
}
}
// Закрытие подключения сокета и потоков данных
private void closeConnection() {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 6,520 | 0.508613 | 0.505543 | 189 | 30.021164 | 22.882021 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.465608 | false | false | 12 |
ef83e822a2155367fbdc46bd9e566e6f5cb617c5 | 7,035,156,444,407 | 0727603263b267f87d9a606bae6799b25a525631 | /app/src/main/java/com/toposdeus/memorama/Ajustes.java | 4b13ad8ecb70e61beb2e3afa933ecf6969ca95df | [] | no_license | po0oncho0o9208/Memorama | https://github.com/po0oncho0o9208/Memorama | 5888f2c45d00838797f20220363b79abc02e425a | 875402e89f7c346dbfc7a6d39427c678c0b49d30 | refs/heads/master | 2020-03-31T07:26:05.273000 | 2019-07-02T02:54:16 | 2019-07-02T02:54:16 | 152,021,445 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.toposdeus.memorama;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Vibrator;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class Ajustes extends AppCompatActivity implements View.OnClickListener {
CheckBox sonido, vibrar;
Button btnatras, reestablecer, botoncomparte, botoncalifica, botoncreditos;
SharedPreferences sharedPref;
TextView txtest;
static MediaPlayer mediaPlayer, click;
private AdView mAdView;
private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.opciones);
MobileAds.initialize(this, "ca-app-pub-1984616735532779~3068362417");
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
btnatras = findViewById(R.id.atras);
btnatras.setOnClickListener(this);
reestablecer = findViewById(R.id.botonreestablecer);
reestablecer.setOnClickListener(this);
txtest = findViewById(R.id.txtestrella);
botoncreditos = findViewById(R.id.botoncreditos);
botoncreditos.setOnClickListener(this);
botoncomparte = findViewById(R.id.botoncomparte);
botoncomparte.setOnClickListener(this);
botoncalifica = findViewById(R.id.botoncalifica);
botoncalifica.setOnClickListener(this);
sonido = findViewById(R.id.checkboxsonido);
vibrar = findViewById(R.id.checkboxvibrar);
sonido.setChecked(Cargarboolean(this, "sonido"));
vibrar.setChecked(Cargarboolean(this, "vibrar"));
sonido.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
vibrar(Ajustes.this, 50);
if (isChecked) {
Ajustes.Guardarboolean(Ajustes.this, true, "sonido");
sonidoplay(Ajustes.this, click, R.raw.click);
} else {
Ajustes.Guardarboolean(Ajustes.this, false, "sonido");
}
}
});
vibrar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
sonidoplay(Ajustes.this, click, R.raw.click);
if (isChecked) {
Ajustes.Guardarboolean(Ajustes.this, true, "vibrar");
vibrar(Ajustes.this, 50);
} else {
Ajustes.Guardarboolean(Ajustes.this, false, "vibrar");
}
}
});
sharedPref = getSharedPreferences("record", Context.MODE_PRIVATE);
int contador = 0;
for (int n = 0; n < 4; n++) {
for (int i = 0; i < 27; i++) {
contador += sharedPref.getInt(n + "record" + i, 0);
}
}
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/birdyame.ttf");
txtest.setText(contador + " X ");
txtest.setTypeface(font);
}
@Override
public void onClick(View v) {
sonidoplay(this, click, R.raw.click);
vibrar(this, 50);
switch (v.getId()) {
case R.id.botoncomparte:
if (ContextCompat.checkSelfPermission(Ajustes.this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(Ajustes.this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions(Ajustes.this,
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
}
Intent intento = new Intent(Intent.ACTION_SEND);
intento.setType("*/*");
String paramString1 = Integer.toString(R.drawable.atras4);
Bitmap topo2 = BitmapFactory.decodeResource(getResources(), R.drawable.atras4);
String fileName = paramString1 + "" + ".png";
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
topo2.compress(Bitmap.CompressFormat.PNG, 40, bytes);
File ExternalStorageDirectory = Environment.getExternalStorageDirectory();
File file = new File(ExternalStorageDirectory + File.separator + fileName);
FileOutputStream fileOutputStream = null;
try {
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(bytes.toByteArray());
} catch (IOException e) {
} finally {
if (fileOutputStream != null) {
Uri bmpUri = Uri.parse(file.getPath());
intento.putExtra(Intent.EXTRA_TEXT, "Descubre que tan buena memoria tienes y ejercitala con esta aplicacion "
+ Html.fromHtml("<br />") + "https://play.google.com/store/apps/details?id=com.toposdeus.memorama");
intento.putExtra(
Intent.EXTRA_STREAM,
bmpUri);
startActivity(Intent.createChooser(intento,
"Siguenos en nuestra pagina "));
}
}
break;
case R.id.botoncalifica:
Intent intentae4 = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.toposdeus.memorama"));
startActivity(intentae4);
break;
case R.id.botonreestablecer:
final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
final LayoutInflater inflater = getLayoutInflater();
View vi = inflater.inflate(R.layout.dialogoconfirm2, null);
builder.setView(vi);
final android.app.AlertDialog dialog = builder.create();
//decidir despues si sera cancelable o no
dialog.setCancelable(false);
Button botonsi = vi.findViewById(R.id.botonsi1);
botonsi.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
vibrar(Ajustes.this, 50);
sonidoplay(Ajustes.this, click, R.raw.click);
//sharedPref = getSharedPreferences("record", 0);
//sharedPref.edit().remove("record").commit();
sharedPref.edit().clear().commit();
txtest.setText(0 + " X ");
Toast.makeText(Ajustes.this, "Se han restablecido sus datos ", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
}
);
Button botonno = vi.findViewById(R.id.botonno1);
botonno.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
vibrar(Ajustes.this, 50);
sonidoplay(Ajustes.this, click, R.raw.click);
dialog.cancel();
}
}
);
dialog.show();
//Metodos.dialogo( this, getLayoutInflater(), "¿seguro deseas salir de la aplicacion?", 0 );
break;
case R.id.atras:
Intent intent = new Intent(Ajustes.this, Principal.class);
startActivity(intent);
finish();
break;
case R.id.botoncreditos:
ColorDrawable dialogColor = new ColorDrawable(Color.GRAY);
dialogColor.setAlpha(0);
final AlertDialog.Builder builderd = new AlertDialog.Builder(Ajustes.this);
final LayoutInflater inflaterd = getLayoutInflater();
View vid = inflaterd.inflate(R.layout.dialogocalifica, null);
builderd.setView(vid);
final AlertDialog dialogd = builderd.create();
dialogd.setCancelable(true);
dialogd.getWindow().setBackgroundDrawable(dialogColor);
Button botonsid = vid.findViewById(R.id.botonsi);
botonsid.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialogd.cancel();
}
});
dialogd.show();
break;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
vibrar(Ajustes.this, 50);
sonidoplay(Ajustes.this, click, R.raw.click);
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
Intent intent = new Intent(Ajustes.this, Principal.class);
startActivity(intent);
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
public static boolean Cargarboolean(Context context, String nombre) {
SharedPreferences sharedPref;
boolean activado;
sharedPref = context.getSharedPreferences("record", Context.MODE_PRIVATE);
activado = sharedPref.getBoolean(nombre, true);
return activado;
}
public static void Guardarboolean(Context contexto, boolean activado, String nombre) {
SharedPreferences sharedPref;
sharedPref = contexto.getSharedPreferences(
"record", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(nombre, activado);
editor.commit();
}
public static void vibrar(Context contexto, int tim) {
if (Ajustes.Cargarboolean(contexto, "vibrar") == true) {
Vibrator vib = (Vibrator) contexto.getSystemService(VIBRATOR_SERVICE);
vib.vibrate(tim);
}
}
public static void sonidostop(Context context, MediaPlayer mediaPlayer) {
if (Ajustes.Cargarboolean(context, "sonido"))
{
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
}
}
public static void sonidoplay(Context context, MediaPlayer mediaPlay, int name) {
if (Ajustes.Cargarboolean(context, "sonido")) {
mediaPlay = MediaPlayer.create(context, name);
mediaPlay.start();
}
}
public static MediaPlayer preferenciasonido(Context contexto, int sound, boolean reproducir) {
SoundManager soundm;
soundm = new SoundManager(contexto);
mediaPlayer = MediaPlayer.create(contexto, sound);
if (reproducir) {
// mediaPlayer.start();
if (!reproducir) {
// mediaPlayer.stop();
// mediaPlayer = null;
}
}
return mediaPlayer;
}
}
| UTF-8 | Java | 12,983 | java | Ajustes.java | Java | [] | null | [] | package com.toposdeus.memorama;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Vibrator;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class Ajustes extends AppCompatActivity implements View.OnClickListener {
CheckBox sonido, vibrar;
Button btnatras, reestablecer, botoncomparte, botoncalifica, botoncreditos;
SharedPreferences sharedPref;
TextView txtest;
static MediaPlayer mediaPlayer, click;
private AdView mAdView;
private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.opciones);
MobileAds.initialize(this, "ca-app-pub-1984616735532779~3068362417");
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
btnatras = findViewById(R.id.atras);
btnatras.setOnClickListener(this);
reestablecer = findViewById(R.id.botonreestablecer);
reestablecer.setOnClickListener(this);
txtest = findViewById(R.id.txtestrella);
botoncreditos = findViewById(R.id.botoncreditos);
botoncreditos.setOnClickListener(this);
botoncomparte = findViewById(R.id.botoncomparte);
botoncomparte.setOnClickListener(this);
botoncalifica = findViewById(R.id.botoncalifica);
botoncalifica.setOnClickListener(this);
sonido = findViewById(R.id.checkboxsonido);
vibrar = findViewById(R.id.checkboxvibrar);
sonido.setChecked(Cargarboolean(this, "sonido"));
vibrar.setChecked(Cargarboolean(this, "vibrar"));
sonido.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
vibrar(Ajustes.this, 50);
if (isChecked) {
Ajustes.Guardarboolean(Ajustes.this, true, "sonido");
sonidoplay(Ajustes.this, click, R.raw.click);
} else {
Ajustes.Guardarboolean(Ajustes.this, false, "sonido");
}
}
});
vibrar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
sonidoplay(Ajustes.this, click, R.raw.click);
if (isChecked) {
Ajustes.Guardarboolean(Ajustes.this, true, "vibrar");
vibrar(Ajustes.this, 50);
} else {
Ajustes.Guardarboolean(Ajustes.this, false, "vibrar");
}
}
});
sharedPref = getSharedPreferences("record", Context.MODE_PRIVATE);
int contador = 0;
for (int n = 0; n < 4; n++) {
for (int i = 0; i < 27; i++) {
contador += sharedPref.getInt(n + "record" + i, 0);
}
}
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/birdyame.ttf");
txtest.setText(contador + " X ");
txtest.setTypeface(font);
}
@Override
public void onClick(View v) {
sonidoplay(this, click, R.raw.click);
vibrar(this, 50);
switch (v.getId()) {
case R.id.botoncomparte:
if (ContextCompat.checkSelfPermission(Ajustes.this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(Ajustes.this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions(Ajustes.this,
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
}
Intent intento = new Intent(Intent.ACTION_SEND);
intento.setType("*/*");
String paramString1 = Integer.toString(R.drawable.atras4);
Bitmap topo2 = BitmapFactory.decodeResource(getResources(), R.drawable.atras4);
String fileName = paramString1 + "" + ".png";
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
topo2.compress(Bitmap.CompressFormat.PNG, 40, bytes);
File ExternalStorageDirectory = Environment.getExternalStorageDirectory();
File file = new File(ExternalStorageDirectory + File.separator + fileName);
FileOutputStream fileOutputStream = null;
try {
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(bytes.toByteArray());
} catch (IOException e) {
} finally {
if (fileOutputStream != null) {
Uri bmpUri = Uri.parse(file.getPath());
intento.putExtra(Intent.EXTRA_TEXT, "Descubre que tan buena memoria tienes y ejercitala con esta aplicacion "
+ Html.fromHtml("<br />") + "https://play.google.com/store/apps/details?id=com.toposdeus.memorama");
intento.putExtra(
Intent.EXTRA_STREAM,
bmpUri);
startActivity(Intent.createChooser(intento,
"Siguenos en nuestra pagina "));
}
}
break;
case R.id.botoncalifica:
Intent intentae4 = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.toposdeus.memorama"));
startActivity(intentae4);
break;
case R.id.botonreestablecer:
final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
final LayoutInflater inflater = getLayoutInflater();
View vi = inflater.inflate(R.layout.dialogoconfirm2, null);
builder.setView(vi);
final android.app.AlertDialog dialog = builder.create();
//decidir despues si sera cancelable o no
dialog.setCancelable(false);
Button botonsi = vi.findViewById(R.id.botonsi1);
botonsi.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
vibrar(Ajustes.this, 50);
sonidoplay(Ajustes.this, click, R.raw.click);
//sharedPref = getSharedPreferences("record", 0);
//sharedPref.edit().remove("record").commit();
sharedPref.edit().clear().commit();
txtest.setText(0 + " X ");
Toast.makeText(Ajustes.this, "Se han restablecido sus datos ", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
}
);
Button botonno = vi.findViewById(R.id.botonno1);
botonno.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
vibrar(Ajustes.this, 50);
sonidoplay(Ajustes.this, click, R.raw.click);
dialog.cancel();
}
}
);
dialog.show();
//Metodos.dialogo( this, getLayoutInflater(), "¿seguro deseas salir de la aplicacion?", 0 );
break;
case R.id.atras:
Intent intent = new Intent(Ajustes.this, Principal.class);
startActivity(intent);
finish();
break;
case R.id.botoncreditos:
ColorDrawable dialogColor = new ColorDrawable(Color.GRAY);
dialogColor.setAlpha(0);
final AlertDialog.Builder builderd = new AlertDialog.Builder(Ajustes.this);
final LayoutInflater inflaterd = getLayoutInflater();
View vid = inflaterd.inflate(R.layout.dialogocalifica, null);
builderd.setView(vid);
final AlertDialog dialogd = builderd.create();
dialogd.setCancelable(true);
dialogd.getWindow().setBackgroundDrawable(dialogColor);
Button botonsid = vid.findViewById(R.id.botonsi);
botonsid.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialogd.cancel();
}
});
dialogd.show();
break;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
vibrar(Ajustes.this, 50);
sonidoplay(Ajustes.this, click, R.raw.click);
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
Intent intent = new Intent(Ajustes.this, Principal.class);
startActivity(intent);
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
public static boolean Cargarboolean(Context context, String nombre) {
SharedPreferences sharedPref;
boolean activado;
sharedPref = context.getSharedPreferences("record", Context.MODE_PRIVATE);
activado = sharedPref.getBoolean(nombre, true);
return activado;
}
public static void Guardarboolean(Context contexto, boolean activado, String nombre) {
SharedPreferences sharedPref;
sharedPref = contexto.getSharedPreferences(
"record", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(nombre, activado);
editor.commit();
}
public static void vibrar(Context contexto, int tim) {
if (Ajustes.Cargarboolean(contexto, "vibrar") == true) {
Vibrator vib = (Vibrator) contexto.getSystemService(VIBRATOR_SERVICE);
vib.vibrate(tim);
}
}
public static void sonidostop(Context context, MediaPlayer mediaPlayer) {
if (Ajustes.Cargarboolean(context, "sonido"))
{
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
}
}
public static void sonidoplay(Context context, MediaPlayer mediaPlay, int name) {
if (Ajustes.Cargarboolean(context, "sonido")) {
mediaPlay = MediaPlayer.create(context, name);
mediaPlay.start();
}
}
public static MediaPlayer preferenciasonido(Context contexto, int sound, boolean reproducir) {
SoundManager soundm;
soundm = new SoundManager(contexto);
mediaPlayer = MediaPlayer.create(contexto, sound);
if (reproducir) {
// mediaPlayer.start();
if (!reproducir) {
// mediaPlayer.stop();
// mediaPlayer = null;
}
}
return mediaPlayer;
}
}
| 12,983 | 0.580188 | 0.575027 | 328 | 38.579269 | 28.639791 | 149 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.795732 | false | false | 12 |
842e630938337f7721351ce6e05d473e95381ab1 | 24,850,680,791,089 | e3094f6101987f9372c3222fbfdc352528d49fca | /src/com/taskCodeInside/Task1/Task1.java | dc021b0deebad987219dbb2a983afd0c75fbbe84 | [] | no_license | PetrYako/task_CodeInside | https://github.com/PetrYako/task_CodeInside | c54dba4fc1d8de7642a2d6a62d79d714a02c9377 | 9b5f72e29b6a78d870db37792368a8725d70faab | refs/heads/master | 2020-12-23T15:40:33.441000 | 2020-01-30T14:06:08 | 2020-01-30T14:06:08 | 237,193,122 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.taskCodeInside.Task1;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
public class Task1 {
public static String extension = "txt";
public static void main(String[] args) {
WalkFiles walkFiles = new WalkFiles(Paths.get(args[0]), "text");
ForkJoinPool fp = new ForkJoinPool();
fp.invoke(walkFiles);
}
private static class WalkFiles extends RecursiveAction {
private final Path dir;
private final String text;
public WalkFiles(Path dir, String text) {
this.dir = dir;
this.text = text;
}
@Override
protected void compute() {
List<WalkFiles> walkFiles = new ArrayList<>();
try {
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (!dir.equals(WalkFiles.this.dir)) {
WalkFiles w = new WalkFiles(dir, text);
w.fork();
walkFiles.add(w);
return FileVisitResult.SKIP_SUBTREE;
} else {
return FileVisitResult.CONTINUE;
}
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (Files.isReadable(file) && getExtension(file).equals(extension)) {
boolean match = Files.lines(file, StandardCharsets.ISO_8859_1).parallel().anyMatch(l -> l.contentEquals(text));
if (match) {
System.out.println(file.toString());
}
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
if (exc instanceof AccessDeniedException) {
return FileVisitResult.SKIP_SUBTREE;
}
return super.visitFileFailed(file, exc);
}
});
} catch (IOException e) {
e.printStackTrace();
}
for (WalkFiles w: walkFiles) {
w.join();
}
}
}
public static String getExtension(Path file) {
String fileName = file.toFile().getName();
Optional<String> optionalS = Optional.of(fileName)
.filter(f -> f.contains("."))
.map(f -> f.substring(fileName.lastIndexOf(".") + 1));
return optionalS.orElse("");
}
}
| UTF-8 | Java | 3,176 | java | Task1.java | Java | [] | null | [] | package com.taskCodeInside.Task1;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
public class Task1 {
public static String extension = "txt";
public static void main(String[] args) {
WalkFiles walkFiles = new WalkFiles(Paths.get(args[0]), "text");
ForkJoinPool fp = new ForkJoinPool();
fp.invoke(walkFiles);
}
private static class WalkFiles extends RecursiveAction {
private final Path dir;
private final String text;
public WalkFiles(Path dir, String text) {
this.dir = dir;
this.text = text;
}
@Override
protected void compute() {
List<WalkFiles> walkFiles = new ArrayList<>();
try {
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (!dir.equals(WalkFiles.this.dir)) {
WalkFiles w = new WalkFiles(dir, text);
w.fork();
walkFiles.add(w);
return FileVisitResult.SKIP_SUBTREE;
} else {
return FileVisitResult.CONTINUE;
}
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (Files.isReadable(file) && getExtension(file).equals(extension)) {
boolean match = Files.lines(file, StandardCharsets.ISO_8859_1).parallel().anyMatch(l -> l.contentEquals(text));
if (match) {
System.out.println(file.toString());
}
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
if (exc instanceof AccessDeniedException) {
return FileVisitResult.SKIP_SUBTREE;
}
return super.visitFileFailed(file, exc);
}
});
} catch (IOException e) {
e.printStackTrace();
}
for (WalkFiles w: walkFiles) {
w.join();
}
}
}
public static String getExtension(Path file) {
String fileName = file.toFile().getName();
Optional<String> optionalS = Optional.of(fileName)
.filter(f -> f.contains("."))
.map(f -> f.substring(fileName.lastIndexOf(".") + 1));
return optionalS.orElse("");
}
}
| 3,176 | 0.521411 | 0.518577 | 86 | 35.930233 | 28.601427 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.511628 | false | false | 12 |
d7386787c5b65fb140a19165455ab96c715b4c81 | 12,060,268,185,137 | 1fae1b95ae87ae81fcae69009c606ec6b57be83d | /src/main/java/com/example/molveno/importedVanProject/menuitems/Category.java | a36c54d622a85ed13154636d3b4f4f66196933d5 | [] | no_license | hackoor83/molveno-Web | https://github.com/hackoor83/molveno-Web | eb85c5b592e8f7e87a88da6129f45260c43fc502 | 1953e09efe04d12db3651372d4f799b8faf8d298 | refs/heads/master | 2021-01-04T22:11:02.008000 | 2020-02-15T20:01:38 | 2020-02-15T20:01:38 | 240,779,682 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.molveno.importedVanProject.menuitems;
public class Category {
private String categoryName;
public Category(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String printData() {
String data;
data = categoryName;
return data;
}
}
| UTF-8 | Java | 500 | java | Category.java | Java | [] | null | [] | package com.example.molveno.importedVanProject.menuitems;
public class Category {
private String categoryName;
public Category(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String printData() {
String data;
data = categoryName;
return data;
}
}
| 500 | 0.656 | 0.656 | 25 | 19 | 18.566637 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.32 | false | false | 12 |
72b15ed3011fa9e2141aff3343669e53c46e5204 | 17,944,373,376,411 | 6aaa50b8fd33420cb32be861065ffe2f5cea717a | /parchis/src/parchis/AnadirExcepcion.java | e452e65f2042e1450b21b681a3942cf4dc26bc18 | [] | no_license | adricu/university | https://github.com/adricu/university | 709447c4e3e8d403dac6aadba81088ac6ccf2d96 | 92107d54e499c31f8c7613152bf8e9d751a019ea | refs/heads/master | 2020-07-27T09:37:21.538000 | 2016-11-11T14:51:53 | 2016-11-11T14:51:53 | 73,433,415 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package parchis;
public class AnadirExcepcion extends Exception {
public AnadirExcepcion() {
}
}
| UTF-8 | Java | 104 | java | AnadirExcepcion.java | Java | [] | null | [] | package parchis;
public class AnadirExcepcion extends Exception {
public AnadirExcepcion() {
}
}
| 104 | 0.740385 | 0.740385 | 9 | 10.555555 | 15.959052 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 12 |
a1c50b8825c7f760d62a85268b81f83c7ae51525 | 19,774,029,463,424 | a13cf737f5b11d1f99e0bad69d806635d10597ff | /InflearnJavaTheoryLecture/src/lec04/OOP01/createEntity/HouseTest.java | b76b2c00fc1e5765fdcdc60b4ef8e544a86244b0 | [] | no_license | thJeongGab/Study | https://github.com/thJeongGab/Study | 9de5d932bb98436717e91360761f0b112821137d | 0ea35bdd949448b6f09157d3748d8c32d9f84a4a | refs/heads/master | 2021-06-14T07:17:17.985000 | 2021-06-05T07:19:06 | 2021-06-05T07:19:06 | 156,300,625 | 0 | 0 | null | false | 2020-08-17T01:27:19 | 2018-11-06T00:08:06 | 2020-08-16T10:04:45 | 2020-08-17T01:27:19 | 28,539 | 0 | 0 | 0 | CSS | false | false | package lec04.OOP01.createEntity;
public class HouseTest {
public static void main(String[] args) {
House house = new House();
System.out.println("에어컨 : " + house.airconStat);
house.airconOn();
System.out.println("에어컨 : " + house.airconStat);
house.airconOff();
System.out.println("에어컨 : " + house.airconStat);
}
}
| UTF-8 | Java | 396 | java | HouseTest.java | Java | [] | null | [] | package lec04.OOP01.createEntity;
public class HouseTest {
public static void main(String[] args) {
House house = new House();
System.out.println("에어컨 : " + house.airconStat);
house.airconOn();
System.out.println("에어컨 : " + house.airconStat);
house.airconOff();
System.out.println("에어컨 : " + house.airconStat);
}
}
| 396 | 0.597884 | 0.587302 | 18 | 20 | 21.463146 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false | 12 |
cc196fd4176ebaee0f4fa4b5425601487040c992 | 18,150,531,849,283 | 082e26b011e30dc62a62fae95f375e4f87d9e99c | /docs/weixin_7.0.4_source/反编译源码/反混淆后/src/main/java/com/tencent/p177mm/plugin/sns/model/C34957aq.java | 5b84d460a1be926ec5745b1f25cfa4d4f652168b | [] | no_license | xsren/AndroidReverseNotes | https://github.com/xsren/AndroidReverseNotes | 9631a5aabc031006e795a112b7ac756a8edd4385 | 9202c276fe9f04a978e4e08b08e42645d97ca94b | refs/heads/master | 2021-04-07T22:50:51.072000 | 2019-07-16T02:24:43 | 2019-07-16T02:24:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tencent.p177mm.plugin.sns.model;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.p177mm.modelvideo.C26493s;
import com.tencent.p177mm.modelvideo.C26494u;
import com.tencent.p177mm.modelvideo.C37961o;
import com.tencent.p177mm.p187al.C37458c;
import com.tencent.p177mm.plugin.sns.data.C29036i;
import com.tencent.p177mm.protocal.protobuf.bau;
import com.tencent.p177mm.sdk.platformtools.C4990ab;
import com.tencent.p177mm.sdk.platformtools.C5046bo;
import com.tencent.p177mm.vfs.C5730e;
/* renamed from: com.tencent.mm.plugin.sns.model.aq */
public final class C34957aq {
/* renamed from: be */
public static String m57416be(int i, String str) {
AppMethodBeat.m2504i(36634);
String a = C37458c.m63162a("snsvideo", (long) i, "sns", str);
if (C5046bo.isNullOrNil(a)) {
AppMethodBeat.m2505o(36634);
return null;
}
AppMethodBeat.m2505o(36634);
return a;
}
/* renamed from: ug */
public static String m57420ug(String str) {
AppMethodBeat.m2504i(36635);
if (C5046bo.isNullOrNil(str)) {
String str2 = "";
AppMethodBeat.m2505o(36635);
return str2;
}
C4990ab.m7411d("MicroMsg.SnsVideoLogic", "gen sns[%s] video file name [%s]", str, "SNS_".concat(String.valueOf(str)));
AppMethodBeat.m2505o(36635);
return "SNS_".concat(String.valueOf(str));
}
/* renamed from: Yf */
public static String m57412Yf(String str) {
AppMethodBeat.m2504i(36636);
String str2;
if (C5046bo.isNullOrNil(str)) {
str2 = "";
AppMethodBeat.m2505o(36636);
return str2;
}
int indexOf = str.indexOf("SNS_");
if (indexOf < 0) {
str2 = "";
AppMethodBeat.m2505o(36636);
return str2;
}
str2 = "";
try {
str2 = str.substring(indexOf + 4);
} catch (Exception e) {
}
AppMethodBeat.m2505o(36636);
return str2;
}
/* renamed from: Yg */
public static String m57413Yg(String str) {
AppMethodBeat.m2504i(36637);
if (C5046bo.isNullOrNil(str)) {
AppMethodBeat.m2505o(36637);
return null;
}
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "get sns video dir %s mediaId %s", C3892an.m6198fZ(C13373af.getAccSnsPath(), str), str);
AppMethodBeat.m2505o(36637);
return C3892an.m6198fZ(C13373af.getAccSnsPath(), str);
}
/* renamed from: D */
public static String m57411D(bau bau) {
AppMethodBeat.m2504i(36638);
if (bau == null) {
AppMethodBeat.m2505o(36638);
return null;
}
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "get sns video path %s", C3892an.m6198fZ(C13373af.getAccSnsPath(), bau.f17915Id) + C29036i.m46116j(bau));
AppMethodBeat.m2505o(36638);
return C3892an.m6198fZ(C13373af.getAccSnsPath(), bau.f17915Id) + C29036i.m46116j(bau);
}
/* renamed from: dd */
public static boolean m57418dd(String str, int i) {
AppMethodBeat.m2504i(36640);
if (C5046bo.isNullOrNil(str)) {
C4990ab.m7420w("MicroMsg.SnsVideoLogic", "init sns record, but snsLocalId is null");
AppMethodBeat.m2505o(36640);
return false;
}
String ug = C34957aq.m57420ug(str);
C26493s c26493s = new C26493s();
c26493s.fileName = ug;
c26493s.createTime = C5046bo.anT();
c26493s.status = 130;
c26493s.egF = i;
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "init sns Record filename %s, insert %b", ug, Boolean.valueOf(C37961o.all().mo21059b(c26493s)));
AppMethodBeat.m2505o(36640);
return C37961o.all().mo21059b(c26493s);
}
/* renamed from: gb */
public static boolean m57419gb(String str, String str2) {
int i;
boolean b;
AppMethodBeat.m2504i(36642);
C26493s Yh = C34957aq.m57414Yh(str);
if (Yh == null) {
Yh = new C26493s();
Yh.fileName = C34957aq.m57420ug(str);
i = 1;
} else {
i = 0;
}
Yh.createTime = C5046bo.anT();
Yh.cMW = str2;
Yh.status = 199;
if (i != 0) {
b = C37961o.all().mo21059b(Yh);
} else {
Yh.bJt = 33555200;
b = C37961o.all().mo21060c(Yh);
}
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "post sns video snsLocalId %s, md5 %s ret %b", str, str2, Boolean.valueOf(b));
AppMethodBeat.m2505o(36642);
return b;
}
/* renamed from: Yh */
public static C26493s m57414Yh(String str) {
AppMethodBeat.m2504i(36643);
if (C5046bo.isNullOrNil(str)) {
AppMethodBeat.m2505o(36643);
return null;
}
C26493s ut = C26494u.m42268ut(C34957aq.m57420ug(str));
AppMethodBeat.m2505o(36643);
return ut;
}
/* renamed from: a */
public static String m57415a(String str, bau bau) {
String str2;
AppMethodBeat.m2504i(36639);
if (bau == null) {
str2 = null;
} else {
str2 = C3892an.m6198fZ(C13373af.getAccSnsPath(), bau.f17915Id) + C29036i.m46126p(bau);
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "get sns video tmp path %s", str2);
}
if (C5730e.m8628ct(str2)) {
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "it needn't download video[%s] because of the video is self. %s", str, str2);
AppMethodBeat.m2505o(36639);
return str2;
}
str2 = C34957aq.m57411D(bau);
boolean ct = C5730e.m8628ct(str2);
C26493s Yh = C34957aq.m57414Yh(str);
if (Yh == null) {
if (ct) {
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "it old version already download video[%s]. path :%s", str, str2);
AppMethodBeat.m2505o(36639);
return str2;
}
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "video info is null and file is no exists, return null.[%s]", str);
AppMethodBeat.m2505o(36639);
return null;
} else if (ct && Yh.alz()) {
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "it had download sns video[%s] finish. %s", str, str2);
AppMethodBeat.m2505o(36639);
return str2;
} else {
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "it don't download video[%s] finish. file[%b] status[%d], return null.", str, Boolean.valueOf(ct), Integer.valueOf(Yh.status));
AppMethodBeat.m2505o(36639);
return null;
}
}
/* renamed from: c */
public static boolean m57417c(C26493s c26493s, int i) {
AppMethodBeat.m2504i(36641);
c26493s.status = 130;
c26493s.egF = i;
c26493s.bJt = 268435712;
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "update sns Record filename %s, update %b", c26493s.getFileName(), Boolean.valueOf(C37961o.all().mo21060c(c26493s)));
AppMethodBeat.m2505o(36641);
return C37961o.all().mo21060c(c26493s);
}
}
| UTF-8 | Java | 7,210 | java | C34957aq.java | Java | [] | null | [] | package com.tencent.p177mm.plugin.sns.model;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.p177mm.modelvideo.C26493s;
import com.tencent.p177mm.modelvideo.C26494u;
import com.tencent.p177mm.modelvideo.C37961o;
import com.tencent.p177mm.p187al.C37458c;
import com.tencent.p177mm.plugin.sns.data.C29036i;
import com.tencent.p177mm.protocal.protobuf.bau;
import com.tencent.p177mm.sdk.platformtools.C4990ab;
import com.tencent.p177mm.sdk.platformtools.C5046bo;
import com.tencent.p177mm.vfs.C5730e;
/* renamed from: com.tencent.mm.plugin.sns.model.aq */
public final class C34957aq {
/* renamed from: be */
public static String m57416be(int i, String str) {
AppMethodBeat.m2504i(36634);
String a = C37458c.m63162a("snsvideo", (long) i, "sns", str);
if (C5046bo.isNullOrNil(a)) {
AppMethodBeat.m2505o(36634);
return null;
}
AppMethodBeat.m2505o(36634);
return a;
}
/* renamed from: ug */
public static String m57420ug(String str) {
AppMethodBeat.m2504i(36635);
if (C5046bo.isNullOrNil(str)) {
String str2 = "";
AppMethodBeat.m2505o(36635);
return str2;
}
C4990ab.m7411d("MicroMsg.SnsVideoLogic", "gen sns[%s] video file name [%s]", str, "SNS_".concat(String.valueOf(str)));
AppMethodBeat.m2505o(36635);
return "SNS_".concat(String.valueOf(str));
}
/* renamed from: Yf */
public static String m57412Yf(String str) {
AppMethodBeat.m2504i(36636);
String str2;
if (C5046bo.isNullOrNil(str)) {
str2 = "";
AppMethodBeat.m2505o(36636);
return str2;
}
int indexOf = str.indexOf("SNS_");
if (indexOf < 0) {
str2 = "";
AppMethodBeat.m2505o(36636);
return str2;
}
str2 = "";
try {
str2 = str.substring(indexOf + 4);
} catch (Exception e) {
}
AppMethodBeat.m2505o(36636);
return str2;
}
/* renamed from: Yg */
public static String m57413Yg(String str) {
AppMethodBeat.m2504i(36637);
if (C5046bo.isNullOrNil(str)) {
AppMethodBeat.m2505o(36637);
return null;
}
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "get sns video dir %s mediaId %s", C3892an.m6198fZ(C13373af.getAccSnsPath(), str), str);
AppMethodBeat.m2505o(36637);
return C3892an.m6198fZ(C13373af.getAccSnsPath(), str);
}
/* renamed from: D */
public static String m57411D(bau bau) {
AppMethodBeat.m2504i(36638);
if (bau == null) {
AppMethodBeat.m2505o(36638);
return null;
}
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "get sns video path %s", C3892an.m6198fZ(C13373af.getAccSnsPath(), bau.f17915Id) + C29036i.m46116j(bau));
AppMethodBeat.m2505o(36638);
return C3892an.m6198fZ(C13373af.getAccSnsPath(), bau.f17915Id) + C29036i.m46116j(bau);
}
/* renamed from: dd */
public static boolean m57418dd(String str, int i) {
AppMethodBeat.m2504i(36640);
if (C5046bo.isNullOrNil(str)) {
C4990ab.m7420w("MicroMsg.SnsVideoLogic", "init sns record, but snsLocalId is null");
AppMethodBeat.m2505o(36640);
return false;
}
String ug = C34957aq.m57420ug(str);
C26493s c26493s = new C26493s();
c26493s.fileName = ug;
c26493s.createTime = C5046bo.anT();
c26493s.status = 130;
c26493s.egF = i;
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "init sns Record filename %s, insert %b", ug, Boolean.valueOf(C37961o.all().mo21059b(c26493s)));
AppMethodBeat.m2505o(36640);
return C37961o.all().mo21059b(c26493s);
}
/* renamed from: gb */
public static boolean m57419gb(String str, String str2) {
int i;
boolean b;
AppMethodBeat.m2504i(36642);
C26493s Yh = C34957aq.m57414Yh(str);
if (Yh == null) {
Yh = new C26493s();
Yh.fileName = C34957aq.m57420ug(str);
i = 1;
} else {
i = 0;
}
Yh.createTime = C5046bo.anT();
Yh.cMW = str2;
Yh.status = 199;
if (i != 0) {
b = C37961o.all().mo21059b(Yh);
} else {
Yh.bJt = 33555200;
b = C37961o.all().mo21060c(Yh);
}
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "post sns video snsLocalId %s, md5 %s ret %b", str, str2, Boolean.valueOf(b));
AppMethodBeat.m2505o(36642);
return b;
}
/* renamed from: Yh */
public static C26493s m57414Yh(String str) {
AppMethodBeat.m2504i(36643);
if (C5046bo.isNullOrNil(str)) {
AppMethodBeat.m2505o(36643);
return null;
}
C26493s ut = C26494u.m42268ut(C34957aq.m57420ug(str));
AppMethodBeat.m2505o(36643);
return ut;
}
/* renamed from: a */
public static String m57415a(String str, bau bau) {
String str2;
AppMethodBeat.m2504i(36639);
if (bau == null) {
str2 = null;
} else {
str2 = C3892an.m6198fZ(C13373af.getAccSnsPath(), bau.f17915Id) + C29036i.m46126p(bau);
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "get sns video tmp path %s", str2);
}
if (C5730e.m8628ct(str2)) {
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "it needn't download video[%s] because of the video is self. %s", str, str2);
AppMethodBeat.m2505o(36639);
return str2;
}
str2 = C34957aq.m57411D(bau);
boolean ct = C5730e.m8628ct(str2);
C26493s Yh = C34957aq.m57414Yh(str);
if (Yh == null) {
if (ct) {
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "it old version already download video[%s]. path :%s", str, str2);
AppMethodBeat.m2505o(36639);
return str2;
}
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "video info is null and file is no exists, return null.[%s]", str);
AppMethodBeat.m2505o(36639);
return null;
} else if (ct && Yh.alz()) {
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "it had download sns video[%s] finish. %s", str, str2);
AppMethodBeat.m2505o(36639);
return str2;
} else {
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "it don't download video[%s] finish. file[%b] status[%d], return null.", str, Boolean.valueOf(ct), Integer.valueOf(Yh.status));
AppMethodBeat.m2505o(36639);
return null;
}
}
/* renamed from: c */
public static boolean m57417c(C26493s c26493s, int i) {
AppMethodBeat.m2504i(36641);
c26493s.status = 130;
c26493s.egF = i;
c26493s.bJt = 268435712;
C4990ab.m7417i("MicroMsg.SnsVideoLogic", "update sns Record filename %s, update %b", c26493s.getFileName(), Boolean.valueOf(C37961o.all().mo21060c(c26493s)));
AppMethodBeat.m2505o(36641);
return C37961o.all().mo21060c(c26493s);
}
}
| 7,210 | 0.588211 | 0.451872 | 195 | 35.974358 | 31.001148 | 180 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.871795 | false | false | 12 |
60d4637d80b6111e79b9c1cafc754e1147200a13 | 18,150,531,847,333 | 0c5450438e2fedb39f6fe9ce5c92f3febace6c5a | /src/array/ArrayListLearnings.java | 4ad312fa00dc4617f281f6e801bf62b0f30bda7e | [] | no_license | saurabhgargit/JavaProblemSolvings | https://github.com/saurabhgargit/JavaProblemSolvings | 053507f7d78156c5c7b9393920889a5e369c3e0c | deaabb49d190c2632ed388740f67b88412cb60a2 | refs/heads/master | 2023-08-08T01:44:33.841000 | 2021-09-12T17:23:46 | 2021-09-12T17:23:46 | 278,595,642 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package array;
import java.util.ArrayList;
public class ArrayListLearnings {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("apple");
al.add("apple");
al.add("apple");
al.add("apple");
al.add("apple");
al.add("apple");
al.add("apple");
al.add("apple");
al.add("apple");
al.add("Banana");
al.add("Cat");
al.add("Dog");
System.out.println(al.size());
}
}
| UTF-8 | Java | 529 | java | ArrayListLearnings.java | Java | [] | null | [] | package array;
import java.util.ArrayList;
public class ArrayListLearnings {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("apple");
al.add("apple");
al.add("apple");
al.add("apple");
al.add("apple");
al.add("apple");
al.add("apple");
al.add("apple");
al.add("apple");
al.add("Banana");
al.add("Cat");
al.add("Dog");
System.out.println(al.size());
}
}
| 529 | 0.506616 | 0.506616 | 27 | 18.592592 | 14.767982 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.592593 | false | false | 12 |
9d132410e5850f57155a2f3510b98279e00d2980 | 15,144,054,745,667 | f59eda58ed990e6c64d9ae004fa3162e7e70a796 | /src/main/java/com/mxp/erp/security/MyRbacService.java | 0ecf8ca5c0475e4724f403ab2ce8f8ddd4992f44 | [] | no_license | tianlangguya/ERP | https://github.com/tianlangguya/ERP | 4f0f8defa8ba8875e43c33a7836bf4f5f6034fb9 | b8ebb15b2c0ed9f5d8fbb68beb98cddfac3571a3 | refs/heads/master | 2022-06-24T01:09:45.383000 | 2019-09-25T09:52:23 | 2019-09-25T09:52:23 | 201,559,071 | 1 | 1 | null | false | 2022-06-17T02:24:05 | 2019-08-10T00:39:52 | 2019-09-25T09:52:05 | 2022-06-17T02:24:04 | 9,558 | 1 | 1 | 5 | Java | false | false | package com.mxp.erp.security;
import com.mxp.erp.api.IPermissionService;
import com.mxp.erp.api.IUserService;
import com.mxp.erp.entity.PermissionEntity;
import com.mxp.erp.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Component("myRbacService")
public class MyRbacService implements IMyRbacService {
private AntPathMatcher antPathMatcher = new AntPathMatcher();
@Autowired
IPermissionService permissionService;
@Autowired
IUserService userService;
@Override
public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
Object principal = authentication.getPrincipal();
boolean hasPermission = false;
String userName = null;
if (principal instanceof UserDetails) {
userName = ((UserDetails) principal).getUsername();
} else if (principal instanceof String) {
userName = String.valueOf(principal);
}
UserEntity user = userService.getByName(userName);
if (user != null) {
List<PermissionEntity> permissionEntities = permissionService.getByUserId(user.getId());
for (PermissionEntity entity : permissionEntities) {
if (antPathMatcher.match(entity.getPermissionName(), request.getRequestURI())) {
hasPermission = true;
break;
}
}
}
return hasPermission;
}
}
| UTF-8 | Java | 1,761 | java | MyRbacService.java | Java | [] | null | [] | package com.mxp.erp.security;
import com.mxp.erp.api.IPermissionService;
import com.mxp.erp.api.IUserService;
import com.mxp.erp.entity.PermissionEntity;
import com.mxp.erp.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Component("myRbacService")
public class MyRbacService implements IMyRbacService {
private AntPathMatcher antPathMatcher = new AntPathMatcher();
@Autowired
IPermissionService permissionService;
@Autowired
IUserService userService;
@Override
public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
Object principal = authentication.getPrincipal();
boolean hasPermission = false;
String userName = null;
if (principal instanceof UserDetails) {
userName = ((UserDetails) principal).getUsername();
} else if (principal instanceof String) {
userName = String.valueOf(principal);
}
UserEntity user = userService.getByName(userName);
if (user != null) {
List<PermissionEntity> permissionEntities = permissionService.getByUserId(user.getId());
for (PermissionEntity entity : permissionEntities) {
if (antPathMatcher.match(entity.getPermissionName(), request.getRequestURI())) {
hasPermission = true;
break;
}
}
}
return hasPermission;
}
}
| 1,761 | 0.704145 | 0.704145 | 50 | 34.220001 | 26.184187 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.54 | false | false | 12 |
06ac2ae7047f5381cd646af2ea7df0da182b7a12 | 28,527,172,836,910 | d484199484645a5be56394723ece8257b29b3b67 | /src/main/java/com/easervices/config/aop/LoggingAspect.java | 8a95810a19dab8595cf76ecf8350124b0f285599 | [] | no_license | 007Gladiator/ea-services-my_local | https://github.com/007Gladiator/ea-services-my_local | b0218dba0a71a5bf74a921c3f240d14fbd01266e | b7d8be49ce48755c45b6e8cf94b448f3290991d9 | refs/heads/master | 2021-01-17T07:12:32.237000 | 2016-05-25T07:25:59 | 2016-05-25T07:25:59 | 51,001,818 | 0 | 0 | null | false | 2016-02-09T07:18:28 | 2016-02-03T13:36:13 | 2016-02-08T14:19:57 | 2016-02-09T07:18:28 | 4,170 | 0 | 0 | 0 | JavaScript | null | null | package com.easervices.config.aop;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggingAspect {
private static Logger logger;
//@Before("execution(* getImages())")
@Before("execution(* getAbrSummary(*))")
public void logBefore(JoinPoint joinPoint)
{
logger=Logger.getLogger(""+joinPoint.getTarget().getClass().getName()+"."+joinPoint.getSignature().getName());
logger.info("***************************************");
logger.info("service called");
logger.info("Arguments - "+getStringForArgs(joinPoint.getArgs()));
}
@After("execution(* getAbrSummary(*))")
public void logAfter(JoinPoint joinPoint)
{
logger=Logger.getLogger(""+joinPoint.getTarget().getClass().getName()+"."+joinPoint.getSignature().getName());
logger.info("reterived successfully.");
logger.info("***************************************");
}
String getStringForArgs(Object[] args)
{
String output="";
for (int i = 0; i < args.length; i++) {
output+=args[i].toString()+",";
}
return output;
}
}
| UTF-8 | Java | 1,239 | java | LoggingAspect.java | Java | [] | null | [] | package com.easervices.config.aop;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggingAspect {
private static Logger logger;
//@Before("execution(* getImages())")
@Before("execution(* getAbrSummary(*))")
public void logBefore(JoinPoint joinPoint)
{
logger=Logger.getLogger(""+joinPoint.getTarget().getClass().getName()+"."+joinPoint.getSignature().getName());
logger.info("***************************************");
logger.info("service called");
logger.info("Arguments - "+getStringForArgs(joinPoint.getArgs()));
}
@After("execution(* getAbrSummary(*))")
public void logAfter(JoinPoint joinPoint)
{
logger=Logger.getLogger(""+joinPoint.getTarget().getClass().getName()+"."+joinPoint.getSignature().getName());
logger.info("reterived successfully.");
logger.info("***************************************");
}
String getStringForArgs(Object[] args)
{
String output="";
for (int i = 0; i < args.length; i++) {
output+=args[i].toString()+",";
}
return output;
}
}
| 1,239 | 0.673123 | 0.671509 | 42 | 28.5 | 27.066277 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.452381 | false | false | 12 |
d423a9690503a2b3155534cd3ccf583128b665fd | 39,642,548,168,064 | 462c70b7f7a33f9cfcb97e56d7b348473a83e247 | /src/main/java/holiday/controller/ObserverController.java | d555223134f72805a12b85597e533fd5b2cf2325 | [] | no_license | lihengshuai/sunday | https://github.com/lihengshuai/sunday | c45cef63b1f9388a68829a0d36b74b60997caddb | 89d97e5cce53c9df7bf334de0bfc8f8bca241921 | refs/heads/master | 2020-03-27T06:11:26.928000 | 2018-08-25T10:32:38 | 2018-08-25T10:32:38 | 146,086,397 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package holiday.controller;
import holiday.obersver.ObserverHandler;
import holiday.obersver.Subject;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author by Loki on 17/7/17.
*/
@RestController
public class ObserverController {
@Autowired
private List<ObserverHandler> observers;
@GetMapping("/obs")
public void execute() {
Subject subject = new Subject();
observers.forEach(subject::addObserver);
subject.notifyObservers();
}
}
| UTF-8 | Java | 628 | java | ObserverController.java | Java | [
{
"context": "ind.annotation.RestController;\n\n/**\n * @author by Loki on 17/7/17.\n */\n@RestController\npublic class O",
"end": 332,
"score": 0.5415443181991577,
"start": 331,
"tag": "NAME",
"value": "L"
},
{
"context": "d.annotation.RestController;\n\n/**\n * @author by Loki on 17/7/17.\n */\n@RestController\npublic class Obse",
"end": 335,
"score": 0.6026955842971802,
"start": 332,
"tag": "USERNAME",
"value": "oki"
}
] | null | [] | package holiday.controller;
import holiday.obersver.ObserverHandler;
import holiday.obersver.Subject;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author by Loki on 17/7/17.
*/
@RestController
public class ObserverController {
@Autowired
private List<ObserverHandler> observers;
@GetMapping("/obs")
public void execute() {
Subject subject = new Subject();
observers.forEach(subject::addObserver);
subject.notifyObservers();
}
}
| 628 | 0.769108 | 0.761146 | 26 | 23.153847 | 19.960909 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.423077 | false | false | 12 |
ef0172fe895c5f73739d66175314771356734118 | 37,873,021,651,292 | ba2d3e20a85a00da6fb3993ee72263fa5cd52a70 | /src/test/java/manager/ProductManagerTest.java | c54cc84be6da24cab0b4481be6036191d8a56898 | [] | no_license | pldenn/Exception | https://github.com/pldenn/Exception | 155992e7d4ee4cfb965c827bbd6f781be6545c6f | 4449c5b256f6c35ba45809aae19e179030ad6e5a | refs/heads/master | 2022-11-19T23:23:53.794000 | 2020-07-23T15:17:12 | 2020-07-23T15:17:12 | 281,999,824 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package manager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import repository.ProductRepository;
import ru.netology.domain.Book;
import ru.netology.domain.Product;
import ru.netology.domain.Smartphone;
import ru.netology.domain.TShirt;
import static org.junit.jupiter.api.Assertions.*;
class ProductManagerTest {
ProductRepository repository = new ProductRepository();
ProductManager manager = new ProductManager(repository);
Product book = new Book(1, "Вино из одуванчиков", 3, "Рэй Брэдбери");
Product book1 = new Book(2, "Kolobok", 450, "Ushinskiy");
Product smartphone = new Smartphone(3, "One Plus 6", 30_000, "BBK Electronics");
Product book3 = new Book(3, "Putin", 0, "Constitution of RF");
Product TShirt = new TShirt(5, "polo", 582, "XXXL");
@BeforeEach
public void SetUp() {
manager.add(book);
manager.add(book1);
manager.add(smartphone);
manager.add(book3);
manager.add(TShirt);
}
@Test
public void shouldFindAuthor() {
Product[] expected = {book};
Product[] actual = manager.searchBy("рэй брэдбери");
assertArrayEquals(expected, actual);
}
@Test
public void shouldFindNameBook() {
Product[] expected = {book1};
Product[] actual = manager.searchBy("kolobok");
assertArrayEquals(expected, actual);
}
@Test
public void shouldFindPhoneName() {
Product[] expected = {smartphone};
Product[] actual = manager.searchBy("one plus 6");
assertArrayEquals(expected, actual);
}
@Test
public void shouldFindPhoneManufacturer() {
Product[] expected = {smartphone};
Product[] actual = manager.searchBy("BBK Electronics");
assertArrayEquals(expected, actual);
}
@Test
public void shouldNotFindAuthor() {
Product[] expected = {};
Product[] actual = manager.searchBy("рей бредбери");
assertArrayEquals(expected, actual);
}
@Test
public void shouldNotFindNull() {
Product[] expected = {};
Product[] actual = manager.searchBy(null);
assertArrayEquals(expected, actual);
}
}
| UTF-8 | Java | 2,255 | java | ProductManagerTest.java | Java | [
{
"context": "uct book = new Book(1, \"Вино из одуванчиков\", 3, \"Рэй Брэдбери\");\n Product book1 = new Book(2, \"Kolobok\", 450",
"end": 540,
"score": 0.9995223879814148,
"start": 528,
"tag": "NAME",
"value": "Рэй Брэдбери"
},
{
"context": "\"Рэй Брэдбери\");\n Product book1 = new Book(2, \"Kolobok\", 450, \"Ushinskiy\");\n Product smartphone = new",
"end": 584,
"score": 0.6017704010009766,
"start": 577,
"tag": "NAME",
"value": "Kolobok"
},
{
"context": "K Electronics\");\n Product book3 = new Book(3, \"Putin\", 0, \"Constitution of RF\");\n Product TShirt ",
"end": 727,
"score": 0.560484766960144,
"start": 724,
"tag": "NAME",
"value": "Put"
},
{
"context": "ok};\n Product[] actual = manager.searchBy(\"рэй брэдбери\");\n assertArrayEquals(expected, actual);\n ",
"end": 1151,
"score": 0.9994989633560181,
"start": 1139,
"tag": "NAME",
"value": "рэй брэдбери"
},
{
"context": " {};\n Product[] actual = manager.searchBy(\"рей бредбери\");\n assertArrayEquals(expected, actual);\n ",
"end": 1963,
"score": 0.999805748462677,
"start": 1951,
"tag": "NAME",
"value": "рей бредбери"
}
] | null | [] | package manager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import repository.ProductRepository;
import ru.netology.domain.Book;
import ru.netology.domain.Product;
import ru.netology.domain.Smartphone;
import ru.netology.domain.TShirt;
import static org.junit.jupiter.api.Assertions.*;
class ProductManagerTest {
ProductRepository repository = new ProductRepository();
ProductManager manager = new ProductManager(repository);
Product book = new Book(1, "Вино из одуванчиков", 3, "<NAME>");
Product book1 = new Book(2, "Kolobok", 450, "Ushinskiy");
Product smartphone = new Smartphone(3, "One Plus 6", 30_000, "BBK Electronics");
Product book3 = new Book(3, "Putin", 0, "Constitution of RF");
Product TShirt = new TShirt(5, "polo", 582, "XXXL");
@BeforeEach
public void SetUp() {
manager.add(book);
manager.add(book1);
manager.add(smartphone);
manager.add(book3);
manager.add(TShirt);
}
@Test
public void shouldFindAuthor() {
Product[] expected = {book};
Product[] actual = manager.searchBy("<NAME>");
assertArrayEquals(expected, actual);
}
@Test
public void shouldFindNameBook() {
Product[] expected = {book1};
Product[] actual = manager.searchBy("kolobok");
assertArrayEquals(expected, actual);
}
@Test
public void shouldFindPhoneName() {
Product[] expected = {smartphone};
Product[] actual = manager.searchBy("one plus 6");
assertArrayEquals(expected, actual);
}
@Test
public void shouldFindPhoneManufacturer() {
Product[] expected = {smartphone};
Product[] actual = manager.searchBy("BBK Electronics");
assertArrayEquals(expected, actual);
}
@Test
public void shouldNotFindAuthor() {
Product[] expected = {};
Product[] actual = manager.searchBy("<NAME>");
assertArrayEquals(expected, actual);
}
@Test
public void shouldNotFindNull() {
Product[] expected = {};
Product[] actual = manager.searchBy(null);
assertArrayEquals(expected, actual);
}
}
| 2,204 | 0.651247 | 0.639909 | 73 | 29.205479 | 21.928251 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.821918 | false | false | 12 |
5d51e92a2cfabbc5cb3cb47ff9ebae070c9609aa | 36,507,222,059,990 | f54fadde9ce4150f0c36056dbed8c86cadd652ac | /frontend/webadmin/modules/uicommon/src/main/java/org/ovirt/engine/ui/uicommon/models/userportal/IUserPortalListModel.java | 8344f4cb3d349de102aa103c67bede55f6fd94e5 | [
"Apache-2.0"
] | permissive | Dhandapani/gluster-ovirt | https://github.com/Dhandapani/gluster-ovirt | fd45107937cf97e08a922b6dab73b2c1daec245d | be1f413eacf6694c567a778e262d3a6620c2a8ca | refs/heads/master | 2020-06-03T22:50:34.220000 | 2012-03-22T19:31:09 | 2012-03-22T19:31:09 | 3,726,799 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.ovirt.engine.ui.uicommon.models.userportal;
import java.util.Collections;
import org.ovirt.engine.core.compat.*;
import org.ovirt.engine.ui.uicompat.*;
import org.ovirt.engine.core.common.businessentities.*;
import org.ovirt.engine.core.common.vdscommands.*;
import org.ovirt.engine.core.common.queries.*;
import org.ovirt.engine.core.common.action.*;
import org.ovirt.engine.ui.frontend.*;
import org.ovirt.engine.ui.uicommon.*;
import org.ovirt.engine.ui.uicommon.models.*;
import org.ovirt.engine.core.common.*;
import org.ovirt.engine.ui.uicommon.models.*;
import org.ovirt.engine.ui.uicommon.models.userportal.*;
import org.ovirt.engine.core.common.businessentities.*;
import org.ovirt.engine.ui.uicommon.*;
@SuppressWarnings("unused")
public abstract class IUserPortalListModel extends ListWithDetailsModel
{
private boolean canConnectAutomatically;
public boolean getCanConnectAutomatically()
{
return canConnectAutomatically;
}
public void setCanConnectAutomatically(boolean value)
{
if (canConnectAutomatically != value)
{
canConnectAutomatically = value;
OnPropertyChanged(new PropertyChangedEventArgs("CanConnectAutomatically"));
}
}
public abstract void OnVmAndPoolLoad();
protected java.util.HashMap<Guid, vm_pools> poolMap;
public vm_pools ResolveVmPoolById(Guid id)
{
return poolMap.get(id);
}
// Return a list of VMs with status 'UP'
public java.util.ArrayList<UserPortalItemModel> GetStatusUpVms(Iterable items)
{
return GetUpVms(items, true);
}
// Return a list of up VMs
public java.util.ArrayList<UserPortalItemModel> GetUpVms(Iterable items)
{
return GetUpVms(items, false);
}
private java.util.ArrayList<UserPortalItemModel> GetUpVms(Iterable items, boolean onlyVmStatusUp)
{
java.util.ArrayList<UserPortalItemModel> upVms = new java.util.ArrayList<UserPortalItemModel>();
if (items != null)
{
for (Object item : items)
{
UserPortalItemModel userPortalItemModel = (UserPortalItemModel)item;
Object tempVar = userPortalItemModel.getEntity();
VM vm = (VM)((tempVar instanceof VM) ? tempVar : null);
if (vm == null)
{
continue;
}
if ((onlyVmStatusUp && vm.getstatus() == VMStatus.Up) || (!onlyVmStatusUp && userPortalItemModel.getDefaultConsole().IsVmUp()))
{
upVms.add(userPortalItemModel);
}
}
}
return upVms;
}
} | UTF-8 | Java | 2,364 | java | IUserPortalListModel.java | Java | [] | null | [] | package org.ovirt.engine.ui.uicommon.models.userportal;
import java.util.Collections;
import org.ovirt.engine.core.compat.*;
import org.ovirt.engine.ui.uicompat.*;
import org.ovirt.engine.core.common.businessentities.*;
import org.ovirt.engine.core.common.vdscommands.*;
import org.ovirt.engine.core.common.queries.*;
import org.ovirt.engine.core.common.action.*;
import org.ovirt.engine.ui.frontend.*;
import org.ovirt.engine.ui.uicommon.*;
import org.ovirt.engine.ui.uicommon.models.*;
import org.ovirt.engine.core.common.*;
import org.ovirt.engine.ui.uicommon.models.*;
import org.ovirt.engine.ui.uicommon.models.userportal.*;
import org.ovirt.engine.core.common.businessentities.*;
import org.ovirt.engine.ui.uicommon.*;
@SuppressWarnings("unused")
public abstract class IUserPortalListModel extends ListWithDetailsModel
{
private boolean canConnectAutomatically;
public boolean getCanConnectAutomatically()
{
return canConnectAutomatically;
}
public void setCanConnectAutomatically(boolean value)
{
if (canConnectAutomatically != value)
{
canConnectAutomatically = value;
OnPropertyChanged(new PropertyChangedEventArgs("CanConnectAutomatically"));
}
}
public abstract void OnVmAndPoolLoad();
protected java.util.HashMap<Guid, vm_pools> poolMap;
public vm_pools ResolveVmPoolById(Guid id)
{
return poolMap.get(id);
}
// Return a list of VMs with status 'UP'
public java.util.ArrayList<UserPortalItemModel> GetStatusUpVms(Iterable items)
{
return GetUpVms(items, true);
}
// Return a list of up VMs
public java.util.ArrayList<UserPortalItemModel> GetUpVms(Iterable items)
{
return GetUpVms(items, false);
}
private java.util.ArrayList<UserPortalItemModel> GetUpVms(Iterable items, boolean onlyVmStatusUp)
{
java.util.ArrayList<UserPortalItemModel> upVms = new java.util.ArrayList<UserPortalItemModel>();
if (items != null)
{
for (Object item : items)
{
UserPortalItemModel userPortalItemModel = (UserPortalItemModel)item;
Object tempVar = userPortalItemModel.getEntity();
VM vm = (VM)((tempVar instanceof VM) ? tempVar : null);
if (vm == null)
{
continue;
}
if ((onlyVmStatusUp && vm.getstatus() == VMStatus.Up) || (!onlyVmStatusUp && userPortalItemModel.getDefaultConsole().IsVmUp()))
{
upVms.add(userPortalItemModel);
}
}
}
return upVms;
}
} | 2,364 | 0.750846 | 0.750846 | 81 | 28.197531 | 28.196148 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.802469 | false | false | 12 |
94f2595710a5ff21c7c311aeb1e569fe51fac800 | 15,229,954,078,061 | 9656868c60809f8b8f7964155d528b9a5c8c6000 | /src/main/java/com/elsevier/musicdb/service/AlbumService.java | d6f7bf0187d929715df088351b7a57b6a406f033 | [] | no_license | penta-vinod-kumar/musicdb | https://github.com/penta-vinod-kumar/musicdb | 4e0408f2f4544c4a317f8800a94a0d5513e5c1d8 | b4bb2ff9aada0117290941e2a0f80a477c3143cf | refs/heads/master | 2021-05-21T09:54:30.915000 | 2020-04-03T05:59:05 | 2020-04-03T05:59:05 | 252,642,709 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.elsevier.musicdb.service;
import com.elsevier.musicdb.client.DiscogsClient;
import com.elsevier.musicdb.entity.Album;
import com.elsevier.musicdb.entity.Genre;
import com.elsevier.musicdb.repository.AlbumRepository;
import com.elsevier.musicdb.repository.ArtistRepository;
import com.elsevier.musicdb.repository.GenreRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* service class for album controller
*/
@Service
public class AlbumService {
private final AlbumRepository albumRepository;
private final ArtistRepository artistRepository;
private final GenreRepository genreRepository;
private final DiscogsClient discogsClient;
public AlbumService(AlbumRepository albumRepository, ArtistRepository artistRepository, GenreRepository genreRepository, DiscogsClient discogsClient) {
this.albumRepository = albumRepository;
this.artistRepository = artistRepository;
this.genreRepository = genreRepository;
this.discogsClient = discogsClient;
}
/**
* saves album under existing artist. If artist doesn't exit returns empty album object
*
* @param newAlbum album which needs to save
* @param artistId arist id
* @return saved album details.
*/
public Album saveAlbum(Album newAlbum, Long artistId) {
return artistRepository.findById(artistId).map(artist -> {
List<Genre> genreList = newAlbum.getGenres().stream().map(genreRepository::save).collect(Collectors.toList());
newAlbum.setGenres(genreList);
newAlbum.setArtist(artist);
Album album = albumRepository.save(newAlbum);
artist.getAlbums().add(album);
artistRepository.save(artist);
return album;
}).orElse(new Album());
}
/**
* updates existing album details
*
* @param newAlbum new album details
* @param albumId album id which needs to be updated
* @return updated album details
*/
public Album saveOrUpdate(Album newAlbum, Long albumId) {
return albumRepository.findById(albumId).map(album -> {
album.setYearOfRelease(newAlbum.getYearOfRelease());
album.setTitle(newAlbum.getTitle());
album.setGenres(newAlbum.getGenres().stream().map(genreRepository::save).collect(Collectors.toList()));
return albumRepository.save(album);
}).orElseGet(() -> {
newAlbum.setId(albumId);
newAlbum.setGenres(newAlbum.getGenres().stream().map(genreRepository::save).collect(Collectors.toList()));
return albumRepository.save(newAlbum);
});
}
/**
* retrieves all album list for given artist
*
* @param genre
* @param sortDir sorting order eg: asc/dsc
* @param sort on which field sorting needs
* @param artistId artist id
* @return list of albums with given sorting order
*/
public List<Album> findAll(String genre, String sortDir, String sort, Long artistId) {
List<Album> albumList = new ArrayList<>();
return artistRepository.findById(artistId).map(artist -> {
Sort order = "asc".equalsIgnoreCase(sortDir) ? Sort.by(sort).ascending() : Sort.by(sort).descending();
for (Album album : albumRepository.findByArtist(order, artist)) {
if (StringUtils.isBlank(genre) || album.getGenres().stream().map(Genre::getValue).collect(Collectors.toList()).contains(genre)) {
albumList.add(album);
}
}
return albumList;
}).orElse(albumList);
}
/**
* retrieves album details for given id
*
* @param albumId album id
* @return album details with resourceUrl
*/
public Album findById(Long albumId) {
return albumRepository.findById(albumId).map(album -> {
album.setResourceUrl(discogsClient.retriveResourceUrl(album));
return album;
}).orElse(new Album());
}
}
| UTF-8 | Java | 4,199 | java | AlbumService.java | Java | [] | null | [] | package com.elsevier.musicdb.service;
import com.elsevier.musicdb.client.DiscogsClient;
import com.elsevier.musicdb.entity.Album;
import com.elsevier.musicdb.entity.Genre;
import com.elsevier.musicdb.repository.AlbumRepository;
import com.elsevier.musicdb.repository.ArtistRepository;
import com.elsevier.musicdb.repository.GenreRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* service class for album controller
*/
@Service
public class AlbumService {
private final AlbumRepository albumRepository;
private final ArtistRepository artistRepository;
private final GenreRepository genreRepository;
private final DiscogsClient discogsClient;
public AlbumService(AlbumRepository albumRepository, ArtistRepository artistRepository, GenreRepository genreRepository, DiscogsClient discogsClient) {
this.albumRepository = albumRepository;
this.artistRepository = artistRepository;
this.genreRepository = genreRepository;
this.discogsClient = discogsClient;
}
/**
* saves album under existing artist. If artist doesn't exit returns empty album object
*
* @param newAlbum album which needs to save
* @param artistId arist id
* @return saved album details.
*/
public Album saveAlbum(Album newAlbum, Long artistId) {
return artistRepository.findById(artistId).map(artist -> {
List<Genre> genreList = newAlbum.getGenres().stream().map(genreRepository::save).collect(Collectors.toList());
newAlbum.setGenres(genreList);
newAlbum.setArtist(artist);
Album album = albumRepository.save(newAlbum);
artist.getAlbums().add(album);
artistRepository.save(artist);
return album;
}).orElse(new Album());
}
/**
* updates existing album details
*
* @param newAlbum new album details
* @param albumId album id which needs to be updated
* @return updated album details
*/
public Album saveOrUpdate(Album newAlbum, Long albumId) {
return albumRepository.findById(albumId).map(album -> {
album.setYearOfRelease(newAlbum.getYearOfRelease());
album.setTitle(newAlbum.getTitle());
album.setGenres(newAlbum.getGenres().stream().map(genreRepository::save).collect(Collectors.toList()));
return albumRepository.save(album);
}).orElseGet(() -> {
newAlbum.setId(albumId);
newAlbum.setGenres(newAlbum.getGenres().stream().map(genreRepository::save).collect(Collectors.toList()));
return albumRepository.save(newAlbum);
});
}
/**
* retrieves all album list for given artist
*
* @param genre
* @param sortDir sorting order eg: asc/dsc
* @param sort on which field sorting needs
* @param artistId artist id
* @return list of albums with given sorting order
*/
public List<Album> findAll(String genre, String sortDir, String sort, Long artistId) {
List<Album> albumList = new ArrayList<>();
return artistRepository.findById(artistId).map(artist -> {
Sort order = "asc".equalsIgnoreCase(sortDir) ? Sort.by(sort).ascending() : Sort.by(sort).descending();
for (Album album : albumRepository.findByArtist(order, artist)) {
if (StringUtils.isBlank(genre) || album.getGenres().stream().map(Genre::getValue).collect(Collectors.toList()).contains(genre)) {
albumList.add(album);
}
}
return albumList;
}).orElse(albumList);
}
/**
* retrieves album details for given id
*
* @param albumId album id
* @return album details with resourceUrl
*/
public Album findById(Long albumId) {
return albumRepository.findById(albumId).map(album -> {
album.setResourceUrl(discogsClient.retriveResourceUrl(album));
return album;
}).orElse(new Album());
}
}
| 4,199 | 0.673256 | 0.673017 | 107 | 38.242992 | 31.211021 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.523364 | false | false | 12 |
f41b238ed1116778f6b58e9b5a12335ceb0458f6 | 37,486,474,562,098 | 8838fd1f5f57e969f26ce311761a1b0dbadf8729 | /legao/src/main/java/com/zxq/legao/util/DateUtil.java | acbddfaf7a7597286220e98aa9e3a218af939e2c | [] | no_license | dzx181/legao_20181112 | https://github.com/dzx181/legao_20181112 | d927fc71590f9ff93afd7345fb0d2293fbf25401 | 6b3e47124f87a2d9a29777d0959defa97aea0e65 | refs/heads/master | 2022-08-09T21:44:26.345000 | 2020-05-03T13:51:40 | 2020-05-03T13:51:40 | 239,098,597 | 2 | 0 | null | false | 2022-06-29T17:56:45 | 2020-02-08T09:12:17 | 2021-11-22T02:26:51 | 2022-06-29T17:56:42 | 3,125 | 1 | 0 | 3 | HTML | false | false | package com.zxq.legao.util;
import com.zxq.legao.entity.vo.ScheduleVO;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* Description:
* <p>
* 日期工具类
* </p>
*
* @author dengzhenxiang
* @Date 2018/11/11 17:41
*/
public class DateUtil {
/**
* 根据日期计算年龄
*
* @param date
* @return
*/
public static String getAge(Date date) {
Long currentTime = System.currentTimeMillis();
if ((currentTime - date.getTime()) <= 0 || date == null) {
return "0岁0个月";
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(new Date());
int ageyear = calendar1.get(Calendar.YEAR) - calendar.get(Calendar.YEAR);
int agemonth = calendar1.get(Calendar.MONTH) - calendar.get(Calendar.MONTH);
if (agemonth <= 0) {
agemonth = 0;
}
String age = ageyear + "岁" + agemonth + "个月";
return age;
}
/**
* 计算星期,周数
* @param date
* @return 集合中第一个元素为课程时间在星期几,第二个元素为在一年里的第几周
*/
public static List<Integer> getWeek(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.setFirstDayOfWeek(Calendar.MONDAY);
Integer week = calendar.get(Calendar.DAY_OF_WEEK);
Integer weekYear = calendar.get(Calendar.WEEK_OF_YEAR);
List<Integer> dateList = new ArrayList<>(2);
dateList.add(week);
dateList.add(weekYear);
return dateList;
}
/**
* 计算当前时间所在的周
* @param date
* @return
*/
public static List<String> getStartAndEndWeekDate(Date date){
List<String> dateList = new ArrayList<>(2);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM月dd日");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
// 判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了
int dayWeek = calendar.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
if (1 == dayWeek) {
calendar.add(Calendar.DAY_OF_MONTH, -1);
}
// 获得当前日期是一个星期的第几天
int day = calendar.get(Calendar.DAY_OF_WEEK);
// 获取该周第一天
calendar.add(Calendar.DATE, calendar.getFirstDayOfWeek() - day);
dateList.add(simpleDateFormat.format(calendar.getTime()));
// 获取该周最后一天
calendar.add(Calendar.DATE, 6);
dateList.add(simpleDateFormat.format(calendar.getTime()));
return dateList;
}
/**
* 根据某年的周数获取日期范围
* @param scheduleVO
*/
public static List<ScheduleVO> getDatebyWeekOfYear(List<ScheduleVO> scheduleVO){
if (scheduleVO.isEmpty()){
return null;
}
int size = scheduleVO.size();
int year = Calendar.getInstance().get((Calendar.YEAR));
int week = 0;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM月dd日");
for (int i = 0; i <size ; i++) {
week = Integer.valueOf(scheduleVO.get(i).getWeekOfYear());
Calendar calendar = Calendar.getInstance();
calendar.set(year, 0, 1);
//算出第一周还剩几天 +1是因为1号是1天
int dayOfWeek = 7- calendar.get(Calendar.DAY_OF_WEEK)+2;
//周数减去第一周再减去要得到的周
week -=2;
calendar.add(Calendar.DAY_OF_YEAR, week*7+dayOfWeek);
scheduleVO.get(i).setWeekStartTime(simpleDateFormat.format(calendar.getTime()));
calendar.add(Calendar.DAY_OF_YEAR, 6);
scheduleVO.get(i).setWeekEndTime(simpleDateFormat.format(calendar.getTime()));
}
return scheduleVO;
}
}
| UTF-8 | Java | 4,266 | java | DateUtil.java | Java | [
{
"context": "Description:\n * <p>\n * 日期工具类\n * </p>\n *\n * @author dengzhenxiang\n * @Date 2018/11/11 17:41\n */\npublic class DateUt",
"end": 281,
"score": 0.9890716075897217,
"start": 268,
"tag": "USERNAME",
"value": "dengzhenxiang"
}
] | null | [] | package com.zxq.legao.util;
import com.zxq.legao.entity.vo.ScheduleVO;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* Description:
* <p>
* 日期工具类
* </p>
*
* @author dengzhenxiang
* @Date 2018/11/11 17:41
*/
public class DateUtil {
/**
* 根据日期计算年龄
*
* @param date
* @return
*/
public static String getAge(Date date) {
Long currentTime = System.currentTimeMillis();
if ((currentTime - date.getTime()) <= 0 || date == null) {
return "0岁0个月";
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(new Date());
int ageyear = calendar1.get(Calendar.YEAR) - calendar.get(Calendar.YEAR);
int agemonth = calendar1.get(Calendar.MONTH) - calendar.get(Calendar.MONTH);
if (agemonth <= 0) {
agemonth = 0;
}
String age = ageyear + "岁" + agemonth + "个月";
return age;
}
/**
* 计算星期,周数
* @param date
* @return 集合中第一个元素为课程时间在星期几,第二个元素为在一年里的第几周
*/
public static List<Integer> getWeek(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.setFirstDayOfWeek(Calendar.MONDAY);
Integer week = calendar.get(Calendar.DAY_OF_WEEK);
Integer weekYear = calendar.get(Calendar.WEEK_OF_YEAR);
List<Integer> dateList = new ArrayList<>(2);
dateList.add(week);
dateList.add(weekYear);
return dateList;
}
/**
* 计算当前时间所在的周
* @param date
* @return
*/
public static List<String> getStartAndEndWeekDate(Date date){
List<String> dateList = new ArrayList<>(2);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM月dd日");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
// 判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了
int dayWeek = calendar.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
if (1 == dayWeek) {
calendar.add(Calendar.DAY_OF_MONTH, -1);
}
// 获得当前日期是一个星期的第几天
int day = calendar.get(Calendar.DAY_OF_WEEK);
// 获取该周第一天
calendar.add(Calendar.DATE, calendar.getFirstDayOfWeek() - day);
dateList.add(simpleDateFormat.format(calendar.getTime()));
// 获取该周最后一天
calendar.add(Calendar.DATE, 6);
dateList.add(simpleDateFormat.format(calendar.getTime()));
return dateList;
}
/**
* 根据某年的周数获取日期范围
* @param scheduleVO
*/
public static List<ScheduleVO> getDatebyWeekOfYear(List<ScheduleVO> scheduleVO){
if (scheduleVO.isEmpty()){
return null;
}
int size = scheduleVO.size();
int year = Calendar.getInstance().get((Calendar.YEAR));
int week = 0;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM月dd日");
for (int i = 0; i <size ; i++) {
week = Integer.valueOf(scheduleVO.get(i).getWeekOfYear());
Calendar calendar = Calendar.getInstance();
calendar.set(year, 0, 1);
//算出第一周还剩几天 +1是因为1号是1天
int dayOfWeek = 7- calendar.get(Calendar.DAY_OF_WEEK)+2;
//周数减去第一周再减去要得到的周
week -=2;
calendar.add(Calendar.DAY_OF_YEAR, week*7+dayOfWeek);
scheduleVO.get(i).setWeekStartTime(simpleDateFormat.format(calendar.getTime()));
calendar.add(Calendar.DAY_OF_YEAR, 6);
scheduleVO.get(i).setWeekEndTime(simpleDateFormat.format(calendar.getTime()));
}
return scheduleVO;
}
}
| 4,266 | 0.608954 | 0.59912 | 121 | 30.933884 | 24.407604 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.570248 | false | false | 12 |
332615fcbffac4308bdd3e63bed46ea5a1d9eecb | 35,476,429,886,367 | 38288a18b53fa3bb467758297d8ee957281c16a5 | /src/main/java/org/giiwa/core/dfile/FileServer.java | 6234454a6093de374befea70af0d20e9882929f2 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | chenguangwei/giiwa | https://github.com/chenguangwei/giiwa | db85f158374acb121faa4e12a188474ddbf255ee | 8de4f432aca378fe89d861c85a0dbf41c80ae221 | refs/heads/master | 2020-06-05T04:02:32.039000 | 2019-06-08T22:29:21 | 2019-06-08T22:29:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.giiwa.core.dfile;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.giiwa.core.bean.X;
import org.giiwa.core.conf.Config;
import org.giiwa.core.dfile.command.DELETE;
import org.giiwa.core.dfile.command.GET;
import org.giiwa.core.dfile.command.HTTP;
import org.giiwa.core.dfile.command.INFO;
import org.giiwa.core.dfile.command.LIST;
import org.giiwa.core.dfile.command.MKDIRS;
import org.giiwa.core.dfile.command.PUT;
import org.giiwa.core.dfile.command.MOVE;
import org.giiwa.core.nio.IoProtocol;
import org.giiwa.core.nio.Server;
import org.giiwa.core.task.Task;
import org.giiwa.framework.bean.Disk;
import org.giiwa.mq.IStub;
import org.giiwa.mq.MQ;
public class FileServer implements IRequestHandler {
private static Log log = LogFactory.getLog(FileServer.class);
public static FileServer inst = new FileServer();
public static String URL = "tcp://127.0.0.1:9091";
private static Map<Byte, ICommand> commands = new HashMap<Byte, ICommand>();
private Server serv;
public void stop() {
X.close(serv);
}
public void start() {
if (serv == null) {
try {
commands.put(ICommand.CMD_DELETE, new DELETE());
commands.put(ICommand.CMD_INFO, new INFO());
commands.put(ICommand.CMD_GET, new GET());
commands.put(ICommand.CMD_PUT, new PUT());
commands.put(ICommand.CMD_LIST, new LIST());
commands.put(ICommand.CMD_MKDIRS, new MKDIRS());
commands.put(ICommand.CMD_MOVE, new MOVE());
commands.put(ICommand.CMD_HTTP, new HTTP());
URL = Config.getConf().getString("dfile.url", "tcp://127.0.0.1:9091");
serv = Server.bind(URL, new RequestHandler(URL, this));
} catch (Exception e) {
log.error(URL, e);
Task.schedule(() -> {
start();
}, 3000);
}
_bind();
}
}
private void _bind() {
try {
// listen the reset
new IStub("disk.reset") {
@Override
public void onRequest(long seq, org.giiwa.mq.MQ.Request req) {
Disk.reset();
}
}.bind(MQ.Mode.TOPIC);
} catch (Exception e) {
log.error(e.getMessage(), e);
Task.schedule(() -> {
_bind();
}, 3000);
}
}
public static void reset() {
// listen the reset
try {
MQ.topic("disk.reset", MQ.Request.create().put("reset"));
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
public void process(Request in, IResponseHandler handler) {
Task.schedule(() -> {
byte cmd = in.readByte();
// System.out.println("cmd=" + cmd);
ICommand c = commands.get(cmd);
if (c != null) {
// ICommand.log.debug("cmd=" + cmd + ", processor=" + c);
c.process(in, handler);
} else {
Response out = Response.create(in.seq, Request.SMALL);
out.writeString("unknown cmd");
handler.send(out);
}
});
}
@Override
public void closed(String name) {
// do nothing
}
public void shutdown() {
if (serv != null) {
X.close(serv);
serv = null;
}
}
static class RequestHandler extends IoProtocol {
private String name;
private IRequestHandler handler;
public RequestHandler(String name, IRequestHandler handler) {
this.name = name;
this.handler = handler;
}
/**
* {@inheritDoc}
*/
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
session.closeNow();
log.error(session.getRemoteAddress(), cause);
}
/**
* {@inheritDoc}
*/
@Override
public void messageReceived(IoSession session, IoBuffer message) throws Exception {
IoBuffer b = message;
IoBuffer bb = (IoBuffer) session.getAttribute("bb");
if (bb == null) {
bb = IoBuffer.allocate(Request.BIG);
bb.setAutoExpand(true);
session.setAttribute("bb", bb);
}
bb.put(b.buf());
bb.flip();
Request r = Request.read(bb);
while (r != null) {
handler.process(r, new IResponseHandler() {
@Override
public void send(Response resp) {
resp.out.flip();
IoBuffer b = IoBuffer.allocate(resp.out.remaining() + 4);
b.putInt(resp.out.remaining());
b.put(resp.out);
b.flip();
session.write(b);
b.free();
resp.out.free();
}
});
r = Request.read(bb);
}
bb.compact();
}
/**
* {@inheritDoc}
*/
@Override
public void sessionClosed(IoSession session) throws Exception {
session.closeNow();
log.info("closed, session=" + session.getRemoteAddress());
handler.closed(name);
}
@Override
public void sessionOpened(IoSession session) throws Exception {
session.getConfig().setBothIdleTime(180);
super.sessionOpened(session);
}
/**
* {@inheritDoc}
*/
@Override
public void sessionCreated(IoSession session) throws Exception {
log.info("created, session=" + session.getRemoteAddress());
}
/**
* {@inheritDoc}
*/
@Override
public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
log.info("idle, session=" + session.getRemoteAddress());
}
}
}
| UTF-8 | Java | 5,147 | java | FileServer.java | Java | [
{
"context": "FileServer();\n\n\tpublic static String URL = \"tcp://127.0.0.1:9091\";\n\n\tprivate static Map<Byte, ICommand> comma",
"end": 1118,
"score": 0.9997340440750122,
"start": 1109,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " = Config.getConf().getString(\"dfile.url\", \"tcp://127.0.0.1:9091\");\n\n\t\t\t\tserv = Server.bind(URL, new RequestH",
"end": 1790,
"score": 0.9996984004974365,
"start": 1781,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | null | [] |
package org.giiwa.core.dfile;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.giiwa.core.bean.X;
import org.giiwa.core.conf.Config;
import org.giiwa.core.dfile.command.DELETE;
import org.giiwa.core.dfile.command.GET;
import org.giiwa.core.dfile.command.HTTP;
import org.giiwa.core.dfile.command.INFO;
import org.giiwa.core.dfile.command.LIST;
import org.giiwa.core.dfile.command.MKDIRS;
import org.giiwa.core.dfile.command.PUT;
import org.giiwa.core.dfile.command.MOVE;
import org.giiwa.core.nio.IoProtocol;
import org.giiwa.core.nio.Server;
import org.giiwa.core.task.Task;
import org.giiwa.framework.bean.Disk;
import org.giiwa.mq.IStub;
import org.giiwa.mq.MQ;
public class FileServer implements IRequestHandler {
private static Log log = LogFactory.getLog(FileServer.class);
public static FileServer inst = new FileServer();
public static String URL = "tcp://127.0.0.1:9091";
private static Map<Byte, ICommand> commands = new HashMap<Byte, ICommand>();
private Server serv;
public void stop() {
X.close(serv);
}
public void start() {
if (serv == null) {
try {
commands.put(ICommand.CMD_DELETE, new DELETE());
commands.put(ICommand.CMD_INFO, new INFO());
commands.put(ICommand.CMD_GET, new GET());
commands.put(ICommand.CMD_PUT, new PUT());
commands.put(ICommand.CMD_LIST, new LIST());
commands.put(ICommand.CMD_MKDIRS, new MKDIRS());
commands.put(ICommand.CMD_MOVE, new MOVE());
commands.put(ICommand.CMD_HTTP, new HTTP());
URL = Config.getConf().getString("dfile.url", "tcp://127.0.0.1:9091");
serv = Server.bind(URL, new RequestHandler(URL, this));
} catch (Exception e) {
log.error(URL, e);
Task.schedule(() -> {
start();
}, 3000);
}
_bind();
}
}
private void _bind() {
try {
// listen the reset
new IStub("disk.reset") {
@Override
public void onRequest(long seq, org.giiwa.mq.MQ.Request req) {
Disk.reset();
}
}.bind(MQ.Mode.TOPIC);
} catch (Exception e) {
log.error(e.getMessage(), e);
Task.schedule(() -> {
_bind();
}, 3000);
}
}
public static void reset() {
// listen the reset
try {
MQ.topic("disk.reset", MQ.Request.create().put("reset"));
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
public void process(Request in, IResponseHandler handler) {
Task.schedule(() -> {
byte cmd = in.readByte();
// System.out.println("cmd=" + cmd);
ICommand c = commands.get(cmd);
if (c != null) {
// ICommand.log.debug("cmd=" + cmd + ", processor=" + c);
c.process(in, handler);
} else {
Response out = Response.create(in.seq, Request.SMALL);
out.writeString("unknown cmd");
handler.send(out);
}
});
}
@Override
public void closed(String name) {
// do nothing
}
public void shutdown() {
if (serv != null) {
X.close(serv);
serv = null;
}
}
static class RequestHandler extends IoProtocol {
private String name;
private IRequestHandler handler;
public RequestHandler(String name, IRequestHandler handler) {
this.name = name;
this.handler = handler;
}
/**
* {@inheritDoc}
*/
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
session.closeNow();
log.error(session.getRemoteAddress(), cause);
}
/**
* {@inheritDoc}
*/
@Override
public void messageReceived(IoSession session, IoBuffer message) throws Exception {
IoBuffer b = message;
IoBuffer bb = (IoBuffer) session.getAttribute("bb");
if (bb == null) {
bb = IoBuffer.allocate(Request.BIG);
bb.setAutoExpand(true);
session.setAttribute("bb", bb);
}
bb.put(b.buf());
bb.flip();
Request r = Request.read(bb);
while (r != null) {
handler.process(r, new IResponseHandler() {
@Override
public void send(Response resp) {
resp.out.flip();
IoBuffer b = IoBuffer.allocate(resp.out.remaining() + 4);
b.putInt(resp.out.remaining());
b.put(resp.out);
b.flip();
session.write(b);
b.free();
resp.out.free();
}
});
r = Request.read(bb);
}
bb.compact();
}
/**
* {@inheritDoc}
*/
@Override
public void sessionClosed(IoSession session) throws Exception {
session.closeNow();
log.info("closed, session=" + session.getRemoteAddress());
handler.closed(name);
}
@Override
public void sessionOpened(IoSession session) throws Exception {
session.getConfig().setBothIdleTime(180);
super.sessionOpened(session);
}
/**
* {@inheritDoc}
*/
@Override
public void sessionCreated(IoSession session) throws Exception {
log.info("created, session=" + session.getRemoteAddress());
}
/**
* {@inheritDoc}
*/
@Override
public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
log.info("idle, session=" + session.getRemoteAddress());
}
}
}
| 5,147 | 0.656693 | 0.650476 | 227 | 21.669603 | 20.917315 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.475771 | false | false | 12 |
a73928b0e0989204ceb4ad7438ba4baa10716049 | 8,512,625,249,541 | 2b40d631500ad65884aaaa8bc95c667d4430f8b9 | /app/src/main/java/cn/slzhong/numberdetector/Processor.java | 2681fd9380b5149248aa06a421fdf5876eb4224f | [] | no_license | sherlock917/NumberDetector | https://github.com/sherlock917/NumberDetector | 31e8ae859445fcb4e84b0425f80ce6ba64747773 | 714ef5a38133e4c94bc814ffd991db370b0225d2 | refs/heads/master | 2020-06-04T23:08:19.315000 | 2015-07-06T06:28:55 | 2015-07-06T06:28:55 | 37,201,493 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.slzhong.numberdetector;
import android.graphics.Bitmap;
import android.graphics.Color;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
/**
* Created by SherlockZhong on 6/11/15.
*/
public class Processor {
public static byte[] bitmapToByteArray(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] bytes = baos.toByteArray();
return bytes;
}
public static int[][] bitmapToMatrix(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[][] matrix = new int[height][width];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int val = Color.red(bitmap.getPixel(i, j));
matrix[j][i] = val == 0 ? 1 : 0;
}
}
return matrix;
}
public static Bitmap grayProcess(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap result = Bitmap.createBitmap(bitmap);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int r = Color.red(bitmap.getPixel(i, j));
int g = Color.green(bitmap.getPixel(i, j));
int b = Color.blue(bitmap.getPixel(i, j));
int val = (int) (r * 0.3 + g * 0.59 + b * 0.11);
result.setPixel(i, j, Color.rgb(val, val, val));
}
}
return result;
}
public static Bitmap equalization(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap result = Bitmap.createBitmap(bitmap);
int[] count = new int[256];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int val = Color.red(bitmap.getPixel(i, j));
count[val]++;
}
}
int[] lut = new int[256];
int sum;
sum = lut[0] = count[0];
for (int i = 1; i < 256; i++) {
sum += count[i];
lut[i] = 255 * sum / width / height;
}
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int val = Color.red(bitmap.getPixel(i, j));
result.setPixel(i, j, Color.rgb(lut[val], lut[val], lut[val]));
}
}
return result;
}
public static Bitmap binarize(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap result = Bitmap.createBitmap(bitmap);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int val = Color.red(bitmap.getPixel(i, j));
if (val > 20) {
result.setPixel(i, j, Color.rgb(255, 255, 255));
} else {
result.setPixel(i, j, Color.rgb(0, 0, 0));
}
}
}
return result;
}
public static Bitmap clip(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
HashMap<String, int[]> projection = project(bitmap);
int[] x = projection.get("x");
int[] y = projection.get("y");
int left, right;
left = right = -1;
for (int i = 0; i < x.length; i++) {
if (x[i] == 1) {
left = left == -1 ? i : i > left ? left : i;
right = i > right ? i : right;
}
}
int top, bottom;
top = bottom = -1;
for (int i = 0; i < y.length; i++) {
if (y[i] == 1) {
top = top == -1 ? i : i > top ? top : i;
bottom = i > bottom ? i : bottom;
}
}
try {
int w = right - left;
int h = bottom - top;
width = w > 0 ? w : width;
height = h > 0 ? h : height;
return Bitmap.createBitmap(bitmap, left, top, width, height);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Bitmap lighten(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap result = Bitmap.createBitmap(bitmap);
boolean black = false;
int span = 0;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int val = Color.red(bitmap.getPixel(j, i));
if (val == 0) {
black = true;
span++;
} else if (val == 255 && black && span > 5) {
black = false;
span = 0;
for (int k = 0; k < 3; k++) {
if (j - k >= 0) {
result.setPixel(j - k, i, Color.rgb(255, 255, 255));
}
}
}
}
}
return result;
}
public static List<Bitmap> split(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
HashMap<String, int[]> projection = Processor.project(bitmap);
int[] x = projection.get("x");
List<int[]> list = new LinkedList<>();
int start, end;
start = end = 0;
while (start < x.length && end < x.length) {
if (x[start] == 0) {
start++;
} else {
end = start + 1;
while (end < x.length && x[end] == 1) {
end++;
}
if (end - start > 3) {
int[] point = new int[2];
point[0] = start;
point[1] = end;
list.add(point);
}
start = end = end + 1;
}
}
List<Bitmap> result = new LinkedList<>();
for (int i = 0; i < list.size(); i++) {
int[] point = list.get(i);
Bitmap digit = Bitmap.createBitmap(bitmap, point[0], 0, point[1] - point[0], height);
digit = clip(digit);
if (digit != null) {
result.add(digit);
}
}
return result;
}
public static HashMap<String, int[]> project(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int x[] = new int[width];
int y[] = new int[height];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int val = Color.red(bitmap.getPixel(i, j));
if (val == 0) {
x[i] = 1;
y[j] = 1;
}
}
}
HashMap<String, int[]> hashMap = new HashMap<>();
hashMap.put("x", x);
hashMap.put("y", y);
return hashMap;
}
}
| UTF-8 | Java | 7,099 | java | Processor.java | Java | [
{
"context": "kedList;\nimport java.util.List;\n\n/**\n * Created by SherlockZhong on 6/11/15.\n */\npublic class Processor {\n\n pub",
"end": 248,
"score": 0.9994627833366394,
"start": 235,
"tag": "NAME",
"value": "SherlockZhong"
}
] | null | [] | package cn.slzhong.numberdetector;
import android.graphics.Bitmap;
import android.graphics.Color;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
/**
* Created by SherlockZhong on 6/11/15.
*/
public class Processor {
public static byte[] bitmapToByteArray(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] bytes = baos.toByteArray();
return bytes;
}
public static int[][] bitmapToMatrix(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[][] matrix = new int[height][width];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int val = Color.red(bitmap.getPixel(i, j));
matrix[j][i] = val == 0 ? 1 : 0;
}
}
return matrix;
}
public static Bitmap grayProcess(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap result = Bitmap.createBitmap(bitmap);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int r = Color.red(bitmap.getPixel(i, j));
int g = Color.green(bitmap.getPixel(i, j));
int b = Color.blue(bitmap.getPixel(i, j));
int val = (int) (r * 0.3 + g * 0.59 + b * 0.11);
result.setPixel(i, j, Color.rgb(val, val, val));
}
}
return result;
}
public static Bitmap equalization(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap result = Bitmap.createBitmap(bitmap);
int[] count = new int[256];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int val = Color.red(bitmap.getPixel(i, j));
count[val]++;
}
}
int[] lut = new int[256];
int sum;
sum = lut[0] = count[0];
for (int i = 1; i < 256; i++) {
sum += count[i];
lut[i] = 255 * sum / width / height;
}
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int val = Color.red(bitmap.getPixel(i, j));
result.setPixel(i, j, Color.rgb(lut[val], lut[val], lut[val]));
}
}
return result;
}
public static Bitmap binarize(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap result = Bitmap.createBitmap(bitmap);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int val = Color.red(bitmap.getPixel(i, j));
if (val > 20) {
result.setPixel(i, j, Color.rgb(255, 255, 255));
} else {
result.setPixel(i, j, Color.rgb(0, 0, 0));
}
}
}
return result;
}
public static Bitmap clip(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
HashMap<String, int[]> projection = project(bitmap);
int[] x = projection.get("x");
int[] y = projection.get("y");
int left, right;
left = right = -1;
for (int i = 0; i < x.length; i++) {
if (x[i] == 1) {
left = left == -1 ? i : i > left ? left : i;
right = i > right ? i : right;
}
}
int top, bottom;
top = bottom = -1;
for (int i = 0; i < y.length; i++) {
if (y[i] == 1) {
top = top == -1 ? i : i > top ? top : i;
bottom = i > bottom ? i : bottom;
}
}
try {
int w = right - left;
int h = bottom - top;
width = w > 0 ? w : width;
height = h > 0 ? h : height;
return Bitmap.createBitmap(bitmap, left, top, width, height);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Bitmap lighten(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap result = Bitmap.createBitmap(bitmap);
boolean black = false;
int span = 0;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int val = Color.red(bitmap.getPixel(j, i));
if (val == 0) {
black = true;
span++;
} else if (val == 255 && black && span > 5) {
black = false;
span = 0;
for (int k = 0; k < 3; k++) {
if (j - k >= 0) {
result.setPixel(j - k, i, Color.rgb(255, 255, 255));
}
}
}
}
}
return result;
}
public static List<Bitmap> split(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
HashMap<String, int[]> projection = Processor.project(bitmap);
int[] x = projection.get("x");
List<int[]> list = new LinkedList<>();
int start, end;
start = end = 0;
while (start < x.length && end < x.length) {
if (x[start] == 0) {
start++;
} else {
end = start + 1;
while (end < x.length && x[end] == 1) {
end++;
}
if (end - start > 3) {
int[] point = new int[2];
point[0] = start;
point[1] = end;
list.add(point);
}
start = end = end + 1;
}
}
List<Bitmap> result = new LinkedList<>();
for (int i = 0; i < list.size(); i++) {
int[] point = list.get(i);
Bitmap digit = Bitmap.createBitmap(bitmap, point[0], 0, point[1] - point[0], height);
digit = clip(digit);
if (digit != null) {
result.add(digit);
}
}
return result;
}
public static HashMap<String, int[]> project(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int x[] = new int[width];
int y[] = new int[height];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int val = Color.red(bitmap.getPixel(i, j));
if (val == 0) {
x[i] = 1;
y[j] = 1;
}
}
}
HashMap<String, int[]> hashMap = new HashMap<>();
hashMap.put("x", x);
hashMap.put("y", y);
return hashMap;
}
}
| 7,099 | 0.442598 | 0.427384 | 224 | 30.691965 | 20.004211 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.879464 | false | false | 12 |
3e426e8ec0774c439787a0f766861b6c04f31cba | 2,018,634,650,389 | 8b2dc7787bb572567982c92332451e6cc523bfc4 | /03_objectifiy_operator/src/com/triple_operator/control/Controller.java | b33c8f0ab106f8dcde6813ce57e5f57a53e6b547 | [] | no_license | newkayak12/newkayak_lecture | https://github.com/newkayak12/newkayak_lecture | e9dc2427517b3eb78164b9cdb64bf7dcc69eaebd | 066c5de9114ca318acfdea570355eebae6258e5f | refs/heads/master | 2023-03-07T15:36:26.565000 | 2021-02-16T09:02:28 | 2021-02-16T09:02:28 | 318,845,621 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.triple_operator.control;
import java.util.Scanner;
public class Controller {
// 이전에 대소비교나 논리 연산을 한 것이 조건으로 들어가기 시작하는 그림이 나온다!
Scanner scn = new Scanner(System.in);
// 필드 (위)
public Controller() {
}
// 생성자(위)
// 메소드 (아래)
public void tripleOp() {
System.out.println("삼항 연산자 ");
System.out.println("-----------");
// 삼항 연산자는 조건식에 의해 실행 된 구문을 결정하는 연산
// 조건문 ? true일 때 실행 될 구문 : false일 떄 실행 될 구문;
//
int su = 12;
// 'su 가 10이면 10이다.'를 출력, 'su 가 10이 아니면 10이 아니다.'를 출력
String result =((su == 10)? "10이다." : "10이 아니다.");
System.out.println(result);
System.out.println();
// 조건에 따라서 다른 로직을 실행할 수 있게 만드는 것을 쓰고 있음
}
// 숫자를 입력받아 100보다 큰 수면 "우와 크다" 출력 아니면 "에이 작다" 출력
public void ooah( ) {
System.out.print(" input number : ");
int num = scn.nextInt();
String result = ((num >100)? "우와! 크다" : "에이 작다");
System.out.println(result);
}
// 미성년이면 "공부나하세요!" 아니면 "취업 좀 하세요"
public void whatThe( ) {
System.out.print("몇 살이에요?");
int age = scn.nextInt();
String result = ((age>0&&age<=19)? "공부나 하세요!" : "취업 좀 하세요 ");
System.out.println( result );
}
// 나이가 19 이하인 사람 > 나이를 입력 받았을 때 그 입력값이 19이하이면
// > 나이를 저장할 저장소가 필요하겠네!
// kh학생이면 코딩하세요 아니면 취업하세요
// 학생 여부를 입력받아 처리
public void go() {
System.out.println("kh학생입니까 y/n");
// kh학생인지 어떻게 알까? _ 흔히 '요구 사항'이라고 하지...
// 이렇게 명세해서 알려주지 않아.
// 뭉뚱그려서 말한 것을 우리가 해체해서 하나씩 천천히 구상하고
// 만들어야지
// 그러기 위해서는 우리의 사고의 흐름을 정리할 필요가 있어
// 마인드 맵도 좋고 주석으로 하나씩 정리해 나가면서 하면 좋지
// 1. String으로 받는 방법
// String input = scn.next();
// String result = ( ( input.equals("y") )? "코딩하세요" : "취업하세요" );
// 2. char로 받는 방법
char choice = scn.next().charAt(0);
String result = ( ( choice == 'y' )? "코딩하세요" : "취업하세요" );
System.out.println( result );
}
// 미성년인지 확인하고 미성년이 아니고 남자면 왼쪽으로 가세요, 아니면 오른쪽으로 가세요
// 미성년이면 나이 더 먹고 오세요~
public void nestedtriple( ) {
int age;
char gen;
System.out.print("몇 살이세요?");
age = scn.nextInt();
System.out.println("성별이 어떻게 되세요? (M/W) ");
gen = scn.next().charAt(0);
String result = ( (age>19)? ( (gen == 'M')? "왼쪽으로 가세요" : "오른쪽으로 가세요" ) : "나이 더 먹고 오세요." );
System.out.println(result);
// 더 복합으로 구성해볼까?
String result2 = ( (age>19)? ( (gen == 'M')? "왼쪽으로 가세요" : "오른쪽으로 가세요" ) : ( (17<=age&& age<=19)? "고딩? 수능 공부해라 " : "요구르트 한 잔 해!") );
System.out.println(result2);
// 실전에서는 삼항 연산자는 이렇게 복잡하게 쓰지는 않아
// javaScript에서 설정값을 주거나 하는 때 간단하게 쓰지!
}
// 비트 연산에 대해서
public void bitOp() {
// 비트 연산 실행하기
// 저장소에 있는 비트끼리의 연산을 의미함.
// 연산에는 & : (A&B) : 각 비트가 모두 1일 때 ‘0’ 다르면 ‘1’
// |: (A|B) : 각 비트 중 하나라도 1일 때 1 아니면 0
// ^(XOR): (A^B) : 두 비트가 다른 값을 가질 때 1 같으면 0
// ~: (A~B) : 1일 때 0, 0일 때 1
int a = 10, b = 22;
String basic = " ";
for ( int i = 0; i<32; i++ ) {
basic += "0";
}
String bit = basic+Integer.toBinaryString( a );
bit = bit.substring( bit.length() - 32 );
System.out.println( bit + " > a의 비트값" );
bit = basic+Integer.toBinaryString( b );
bit = bit.substring( bit.length() - 32 );
System.out.println( bit + " > b의 비트값 " );
System.out.println("-------------------------------------------");
bit = basic+Integer.toBinaryString( a&b );
bit = bit.substring( bit.length() - 32 );
System.out.println( bit + " > a&b의 비트값 " );
System.out.println();
bit = basic+Integer.toBinaryString( a|b );
bit = bit.substring( bit.length() - 32 );
System.out.println( bit + " > a|b의 비트값 " );
System.out.println();
bit = basic+Integer.toBinaryString( a^b );
bit = bit.substring( bit.length() - 32 );
System.out.println( bit + " > a^b의 비트값 " );
System.out.println();
bit = basic+Integer.toBinaryString( ~a );
bit = bit.substring( bit.length() - 32 );
System.out.println( bit + " > ~a의 비트값 " );
// 객체의 substring 다시 한 번
}
}
| UTF-8 | Java | 5,272 | java | Controller.java | Java | [] | null | [] | package com.triple_operator.control;
import java.util.Scanner;
public class Controller {
// 이전에 대소비교나 논리 연산을 한 것이 조건으로 들어가기 시작하는 그림이 나온다!
Scanner scn = new Scanner(System.in);
// 필드 (위)
public Controller() {
}
// 생성자(위)
// 메소드 (아래)
public void tripleOp() {
System.out.println("삼항 연산자 ");
System.out.println("-----------");
// 삼항 연산자는 조건식에 의해 실행 된 구문을 결정하는 연산
// 조건문 ? true일 때 실행 될 구문 : false일 떄 실행 될 구문;
//
int su = 12;
// 'su 가 10이면 10이다.'를 출력, 'su 가 10이 아니면 10이 아니다.'를 출력
String result =((su == 10)? "10이다." : "10이 아니다.");
System.out.println(result);
System.out.println();
// 조건에 따라서 다른 로직을 실행할 수 있게 만드는 것을 쓰고 있음
}
// 숫자를 입력받아 100보다 큰 수면 "우와 크다" 출력 아니면 "에이 작다" 출력
public void ooah( ) {
System.out.print(" input number : ");
int num = scn.nextInt();
String result = ((num >100)? "우와! 크다" : "에이 작다");
System.out.println(result);
}
// 미성년이면 "공부나하세요!" 아니면 "취업 좀 하세요"
public void whatThe( ) {
System.out.print("몇 살이에요?");
int age = scn.nextInt();
String result = ((age>0&&age<=19)? "공부나 하세요!" : "취업 좀 하세요 ");
System.out.println( result );
}
// 나이가 19 이하인 사람 > 나이를 입력 받았을 때 그 입력값이 19이하이면
// > 나이를 저장할 저장소가 필요하겠네!
// kh학생이면 코딩하세요 아니면 취업하세요
// 학생 여부를 입력받아 처리
public void go() {
System.out.println("kh학생입니까 y/n");
// kh학생인지 어떻게 알까? _ 흔히 '요구 사항'이라고 하지...
// 이렇게 명세해서 알려주지 않아.
// 뭉뚱그려서 말한 것을 우리가 해체해서 하나씩 천천히 구상하고
// 만들어야지
// 그러기 위해서는 우리의 사고의 흐름을 정리할 필요가 있어
// 마인드 맵도 좋고 주석으로 하나씩 정리해 나가면서 하면 좋지
// 1. String으로 받는 방법
// String input = scn.next();
// String result = ( ( input.equals("y") )? "코딩하세요" : "취업하세요" );
// 2. char로 받는 방법
char choice = scn.next().charAt(0);
String result = ( ( choice == 'y' )? "코딩하세요" : "취업하세요" );
System.out.println( result );
}
// 미성년인지 확인하고 미성년이 아니고 남자면 왼쪽으로 가세요, 아니면 오른쪽으로 가세요
// 미성년이면 나이 더 먹고 오세요~
public void nestedtriple( ) {
int age;
char gen;
System.out.print("몇 살이세요?");
age = scn.nextInt();
System.out.println("성별이 어떻게 되세요? (M/W) ");
gen = scn.next().charAt(0);
String result = ( (age>19)? ( (gen == 'M')? "왼쪽으로 가세요" : "오른쪽으로 가세요" ) : "나이 더 먹고 오세요." );
System.out.println(result);
// 더 복합으로 구성해볼까?
String result2 = ( (age>19)? ( (gen == 'M')? "왼쪽으로 가세요" : "오른쪽으로 가세요" ) : ( (17<=age&& age<=19)? "고딩? 수능 공부해라 " : "요구르트 한 잔 해!") );
System.out.println(result2);
// 실전에서는 삼항 연산자는 이렇게 복잡하게 쓰지는 않아
// javaScript에서 설정값을 주거나 하는 때 간단하게 쓰지!
}
// 비트 연산에 대해서
public void bitOp() {
// 비트 연산 실행하기
// 저장소에 있는 비트끼리의 연산을 의미함.
// 연산에는 & : (A&B) : 각 비트가 모두 1일 때 ‘0’ 다르면 ‘1’
// |: (A|B) : 각 비트 중 하나라도 1일 때 1 아니면 0
// ^(XOR): (A^B) : 두 비트가 다른 값을 가질 때 1 같으면 0
// ~: (A~B) : 1일 때 0, 0일 때 1
int a = 10, b = 22;
String basic = " ";
for ( int i = 0; i<32; i++ ) {
basic += "0";
}
String bit = basic+Integer.toBinaryString( a );
bit = bit.substring( bit.length() - 32 );
System.out.println( bit + " > a의 비트값" );
bit = basic+Integer.toBinaryString( b );
bit = bit.substring( bit.length() - 32 );
System.out.println( bit + " > b의 비트값 " );
System.out.println("-------------------------------------------");
bit = basic+Integer.toBinaryString( a&b );
bit = bit.substring( bit.length() - 32 );
System.out.println( bit + " > a&b의 비트값 " );
System.out.println();
bit = basic+Integer.toBinaryString( a|b );
bit = bit.substring( bit.length() - 32 );
System.out.println( bit + " > a|b의 비트값 " );
System.out.println();
bit = basic+Integer.toBinaryString( a^b );
bit = bit.substring( bit.length() - 32 );
System.out.println( bit + " > a^b의 비트값 " );
System.out.println();
bit = basic+Integer.toBinaryString( ~a );
bit = bit.substring( bit.length() - 32 );
System.out.println( bit + " > ~a의 비트값 " );
// 객체의 substring 다시 한 번
}
}
| 5,272 | 0.555729 | 0.536198 | 163 | 22.558283 | 21.071045 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.282209 | false | false | 12 |
ec73f06344a8a5c28d4d3bcce06e4be7f7ecf45e | 26,637,387,174,969 | b2b67c94ea1e1a5df4148965e4b9d86f476de297 | /repo/repo-common/src/main/java/com/evolveum/midpoint/repo/common/task/AbstractSearchIterativeActivityExecution.java | 381135f04aa07dd10116a0fe1f8bc864fcefabc2 | [
"EUPL-1.2",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license",
"CDDL-1.0",
"GPL-1.0-or-later",
"MPL-2.0",
"EPL-1.0",
"MIT",
"Apache-2.0"
] | permissive | martin-lizner/midpoint | https://github.com/martin-lizner/midpoint | 475af71fd307fcd8ec17faed0bd65f02ba13ce49 | db111337b0b62dd0bd3de21839d7e316b4527bff | refs/heads/master | 2021-12-04T17:29:58.082000 | 2021-07-23T05:00:53 | 2021-07-23T05:00:53 | 161,333,785 | 0 | 0 | Apache-2.0 | true | 2018-12-11T12:55:59 | 2018-12-11T12:55:59 | 2018-12-11T12:44:22 | 2018-12-11T12:44:20 | 152,572 | 0 | 0 | 0 | null | false | null | /*
* Copyright (c) 2020 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.repo.common.task;
import com.evolveum.midpoint.prism.ItemDefinition;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.query.ObjectFilter;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.repo.common.activity.ActivityExecutionException;
import com.evolveum.midpoint.repo.common.activity.definition.WorkDefinition;
import com.evolveum.midpoint.repo.common.activity.execution.ExecutionInstantiationContext;
import com.evolveum.midpoint.repo.common.activity.handlers.ActivityHandler;
import com.evolveum.midpoint.repo.common.activity.state.ActivityBucketManagementStatistics;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.ResultHandler;
import com.evolveum.midpoint.schema.SchemaService;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.expression.ExpressionProfile;
import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.MiscSchemaUtil;
import com.evolveum.midpoint.schema.util.ObjectQueryUtil;
import com.evolveum.midpoint.schema.util.task.BucketingUtil;
import com.evolveum.midpoint.task.api.RunningTask;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.task.api.TaskManager;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.exception.*;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import static com.evolveum.midpoint.schema.result.OperationResultStatus.FATAL_ERROR;
import static com.evolveum.midpoint.task.api.TaskRunResult.TaskRunResultStatus.PERMANENT_ERROR;
import static com.evolveum.midpoint.util.MiscUtil.stateCheck;
import static java.util.Objects.requireNonNull;
/**
* Single execution of a given search-iterative task part.
*
* Takes care of preparing and issuing the search query.
*
* *TODO finish cleanup*
*/
public abstract class AbstractSearchIterativeActivityExecution<
O extends ObjectType,
WD extends WorkDefinition,
AH extends ActivityHandler<WD, AH>,
AE extends AbstractSearchIterativeActivityExecution<O, WD, AH, AE, BS>,
BS extends AbstractActivityWorkStateType>
extends AbstractIterativeActivityExecution<PrismObject<O>, WD, AH, BS> {
private static final Trace LOGGER = TraceManager.getTrace(AbstractSearchIterativeActivityExecution.class);
private static final long FREE_BUCKET_WAIT_TIME = -1; // indefinitely
/**
* Specification of the search that is to be executed: object type, query, options, and "use repository" flag.
*/
protected SearchSpecification<O> searchSpecification;
/**
* Additional filter to be applied to each object received (if not null).
* Currently used to filter failed objects when `FILTER_AFTER_RETRIEVAL` mode is selected.
*
* See {@link AbstractSearchIterativeItemProcessor#process(ItemProcessingRequest, RunningTask, OperationResult)}.
*/
ObjectFilter additionalFilter;
/**
* Pre-processes object received before it is passed to the task handler specific processing.
* (Only for non-failed objects.) Currently used to fetch failed objects when `FETCH_FAILED_OBJECTS` mode is selected.
*
* See {@link AbstractSearchIterativeItemProcessor#process(ItemProcessingRequest, RunningTask, OperationResult)}.
*/
ObjectPreprocessor<O> preprocessor;
/**
* In some situations (e.g. because provisioning service does not allow searches without specifying resource
* or objectclass/kind) we need to use repository directly for some specific tasks or task parts.
*/
private boolean requiresDirectRepositoryAccess;
/**
* OIDs of objects submitted to processing in current part execution (i.e. in the current bucket).
*/
private final Set<String> oidsSeen = ConcurrentHashMap.newKeySet();
/**
* Current bucket that is being processed.
* It is used to narrow the search query.
*/
protected WorkBucketType bucket;
public AbstractSearchIterativeActivityExecution(@NotNull ExecutionInstantiationContext<WD, AH> context,
@NotNull String shortNameCapitalized) {
super(context, shortNameCapitalized);
}
/**
* Bucketed version of the execution.
*/
@Override
protected void executeInitialized(OperationResult opResult)
throws ActivityExecutionException, CommonException {
RunningTask task = taskExecution.getRunningTask();
boolean initialExecution = true;
// resetWorkStateAndStatisticsIfWorkComplete(result);
// startCollectingStatistics(task, handler);
for (; task.canRun(); initialExecution = false) {
bucket = getWorkBucket(initialExecution, opResult);
if (!task.canRun()) {
break;
}
if (bucket == null) {
LOGGER.trace("No (next) work bucket within {}, exiting", task);
// updateStructuredProgressOnNoMoreBuckets();
break;
}
executeSingleBucket(opResult);
if (!task.canRun() || errorState.wasStoppingExceptionEncountered()) {
break;
}
completeWorkBucketAndUpdateStructuredProgress(opResult);
}
// task.updateAndStoreStatisticsIntoRepository(true, opResult);
}
private WorkBucketType getWorkBucket(boolean initialExecution, OperationResult result) {
RunningTask task = taskExecution.getRunningTask();
WorkBucketType bucket;
try {
bucket = beans.bucketingManager.getWorkBucket(task, activity.getPath(),
activity.getDefinition().getDistributionDefinition(), FREE_BUCKET_WAIT_TIME, initialExecution,
getLiveBucketManagementStatistics(), result);
task.refresh(result); // We want to have the most current state of the running task.
} catch (InterruptedException e) {
LOGGER.trace("InterruptedExecution in getWorkBucket for {}", task);
if (!task.canRun()) {
return null;
} else {
LoggingUtils.logUnexpectedException(LOGGER, "Unexpected InterruptedException in {}", e, task);
throw new SystemException("Unexpected InterruptedException: " + e.getMessage(), e);
}
} catch (Throwable t) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't allocate a work bucket for task {}", t, task);
throw new SystemException("Couldn't allocate a work bucket for task: " + t.getMessage(), t);
}
return bucket;
}
private void completeWorkBucketAndUpdateStructuredProgress(OperationResult result) {
RunningTask task = taskExecution.getRunningTask();
try {
beans.bucketingManager.completeWorkBucket(task, getActivityPath(), bucket,
getLiveBucketManagementStatistics(), result);
activityState.getLiveProgress().onCommitPoint();
// TODO update in repository
// task.changeStructuredProgressOnWorkBucketCompletion();
// updateAndStoreStatisticsIntoRepository(task, result);
} catch (ObjectAlreadyExistsException | ObjectNotFoundException | SchemaException | RuntimeException e) {
throw new SystemException("Couldn't complete work bucket for task: " + e.getMessage(), e);
}
}
@Override
protected void prepareItemSource(OperationResult opResult) throws ActivityExecutionException, CommonException {
prepareSearchSpecification(opResult);
}
private void prepareSearchSpecification(OperationResult opResult) throws CommonException, ActivityExecutionException {
searchSpecification = createSearchSpecification(opResult);
customizeSearchSpecification(searchSpecification, opResult);
narrowQueryForBucketingAndErrorHandling();
searchSpecification.setQuery(
evaluateQueryExpressions(searchSpecification.getQuery(), opResult));
applyDefinitionsToQuery(opResult);
LOGGER.trace("{}: will do the following search:\n{}",
activityShortNameCapitalized, DebugUtil.debugDumpLazily(searchSpecification));
}
/**
* Creates the search specification (type, query, options, use repo). Normally it is created from the configuration
* embodied in work definition, but it can be fully overridden for the least configurable activities.
*
* Note that at repo-common level we do not support {@link ResourceObjectSetSpecificationImpl}.
*
* TODO Clean this up a little bit. It is quite awkward.
*/
protected @NotNull SearchSpecification<O> createSearchSpecification(OperationResult opResult) throws SchemaException, ActivityExecutionException {
ObjectSetSpecification objectSetSpecification = ObjectSetSpecification.fromWorkDefinition(activity.getWorkDefinition());
if (objectSetSpecification instanceof RepositoryObjectSetSpecificationImpl) {
return SearchSpecification.fromRepositoryObjectSetSpecification(
(RepositoryObjectSetSpecificationImpl) objectSetSpecification);
} else {
throw new UnsupportedOperationException("Non-repository object set specification is not supported: " +
objectSetSpecification);
}
}
/**
* Customizes the configured search specification. Almost fully delegated to the subclasses;
* except for the "use repository" flag, which has some default behavior here.
*
* *BEWARE* Be careful when overriding this, because of killing use repository flag check - FIXME
*/
@SuppressWarnings("WeakerAccess") // To allow overriding in subclasses.
protected void customizeSearchSpecification(@NotNull SearchSpecification<O> searchSpecification, OperationResult opResult)
throws CommonException, ActivityExecutionException {
searchSpecification.setQuery(customizeQuery(searchSpecification.getQuery(), opResult));
searchSpecification.setSearchOptions(customizeSearchOptions(searchSpecification.getSearchOptions(), opResult));
searchSpecification.setUseRepository(customizeUseRepository(searchSpecification.getUseRepository(), opResult));
}
protected ObjectQuery customizeQuery(ObjectQuery configuredQuery, OperationResult opResult) throws CommonException {
return configuredQuery;
}
protected Collection<SelectorOptions<GetOperationOptions>> customizeSearchOptions(
Collection<SelectorOptions<GetOperationOptions>> configuredOptions, OperationResult opResult)
throws CommonException {
return configuredOptions;
}
/**
* Customizes the direct use of repository. The default implementation makes use
* of requiresDirectRepositoryAccess and also checks the authorization of direct access.
*
* FIXME this implementation is not good, as it allows unintentional overriding of the autz check
*/
@SuppressWarnings("WeakerAccess") // To allow overriding in subclasses.
protected Boolean customizeUseRepository(Boolean configuredValue, OperationResult opResult)
throws CommonException {
if (configuredValue != null) {
// if we requested this mode explicitly we need to have appropriate authorization
if (configuredValue) {
checkRawAuthorization(getRunningTask(), opResult);
}
return configuredValue;
} else {
return requiresDirectRepositoryAccess;
}
}
protected void checkRawAuthorization(Task task, OperationResult result)
throws CommunicationException, ObjectNotFoundException, SchemaException, SecurityViolationException,
ConfigurationException, ExpressionEvaluationException {
// nothing to do here as we are in repo-common
}
private void narrowQueryForBucketingAndErrorHandling() throws ActivityExecutionException {
checkSearchSpecificationPresent();
try {
ObjectQuery queryFromHandler = searchSpecification.getQuery(); // TODO better name
LOGGER.trace("{}: query as defined by activity:\n{}", activityShortNameCapitalized,
DebugUtil.debugDumpLazily(queryFromHandler));
ObjectQuery failureNarrowedQuery = narrowQueryToProcessFailedObjectsOnly(queryFromHandler); // logging is inside
ObjectQuery bucketNarrowedQuery = beans.bucketingManager.narrowQueryForWorkBucket(
getObjectType(),
failureNarrowedQuery,
activity.getDefinition().getDistributionDefinition(),
createItemDefinitionProvider(),
bucket);
LOGGER.trace("{}: using a query (after applying work bucket, before evaluating expressions):\n{}",
activityShortNameCapitalized, DebugUtil.debugDumpLazily(bucketNarrowedQuery));
searchSpecification.setQuery(bucketNarrowedQuery);
} catch (Throwable t) {
// This is most probably a permanent error. (The real communication with a resource is carried out when the
// query is issued. With an exception of untested resource. But it is generally advised to do the connection test
// before running any tasks.)
throw new ActivityExecutionException("Couldn't create object query", FATAL_ERROR, PERMANENT_ERROR, t);
}
}
/**
* Besides updating the query this method influences the search process:
*
* In case of FETCH_FAILED_OBJECTS it
*
* - sets up a pre-processor that implements fetching individual shadows (that are to be re-tried) from a resource,
* - turns on the "no fetch" option.
*
* In case of FILTER_AFTER_RETRIEVAL it
*
* - installs additional filter that passes through only selected objects (the ones that were failed).
*/
@Nullable
private ObjectQuery narrowQueryToProcessFailedObjectsOnly(ObjectQuery query) {
FailedObjectsSelectorType selector = getRunningTask().getExtensionContainerRealValueOrClone(SchemaConstants.MODEL_EXTENSION_FAILED_OBJECTS_SELECTOR);
if (selector == null) {
return query;
} else {
ObjectFilter failedObjectsFilter =
new FailedObjectsFilterCreator(selector, getRunningTask(), getPrismContext())
.createFilter();
FailedObjectsSelectionMethodType selectionMethod = getFailedObjectsSelectionMethod(selector);
switch (selectionMethod) {
case FETCH_FAILED_OBJECTS:
// We will use the narrowed query. The noFetch option ensures that search in provisioning will work.
// It would be nice to check if the query does not refer to attributes that are not cached.
// But it should be done in the provisioning module.
searchSpecification.setNoFetchOption();
preprocessor = createShadowFetchingPreprocessor();
LOGGER.trace("{}: shadow-fetching preprocessor was set up", activityShortNameCapitalized);
case NARROW_QUERY:
ObjectQuery failureNarrowedQuery = ObjectQueryUtil.addConjunctions(query, getPrismContext(), failedObjectsFilter);
LOGGER.trace("{}: query narrowed to select failed objects only:\n{}", activityShortNameCapitalized,
DebugUtil.debugDumpLazily(failureNarrowedQuery));
return failureNarrowedQuery;
case FILTER_AFTER_RETRIEVAL:
additionalFilter = failedObjectsFilter;
LOGGER.trace("{}: will use additional filter to select failed objects only (but executes "
+ "the search with original query):\n{}", activityShortNameCapitalized,
DebugUtil.debugDumpLazily(failedObjectsFilter));
return query;
default:
throw new AssertionError(selectionMethod);
}
}
}
private @NotNull FailedObjectsSelectionMethodType getFailedObjectsSelectionMethod(FailedObjectsSelectorType selector) {
FailedObjectsSelectionMethodType method = selector.getSelectionMethod();
if (method != null && method != FailedObjectsSelectionMethodType.DEFAULT) {
return method;
} else if (searchesResourceObjects()) {
return FailedObjectsSelectionMethodType.FETCH_FAILED_OBJECTS;
} else {
return FailedObjectsSelectionMethodType.NARROW_QUERY;
}
}
private boolean searchesResourceObjects() {
return searchSpecification.concernsShadows() &&
!isUseRepository() && modelProcessingAvailable() &&
!searchSpecification.isNoFetch() && !searchSpecification.isRaw();
}
@NotNull
protected ObjectPreprocessor<O> createShadowFetchingPreprocessor() {
throw new UnsupportedOperationException("FETCH_FAILED_OBJECTS is not available in this type of tasks. "
+ "Model processing is required.");
}
/**
* Returns a provider of definitions for runtime items (e.g. attributes) that are needed in bucket filters.
* To be implemented in subclasses that work with resource objects.
*/
protected Function<ItemPath, ItemDefinition<?>> createItemDefinitionProvider() {
return null;
}
protected final Function<ItemPath, ItemDefinition<?>> createItemDefinitionProviderForAttributes(
ObjectClassComplexTypeDefinition objectClass) {
return itemPath -> {
if (itemPath.startsWithName(ShadowType.F_ATTRIBUTES)) {
return objectClass.findAttributeDefinition(itemPath.rest().asSingleName());
} else {
return null;
}
};
}
/**
* Evaluates expressions in query. Currently implemented only in model-impl. TODO why?
*/
protected ObjectQuery evaluateQueryExpressions(ObjectQuery query, OperationResult opResult)
throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException,
ConfigurationException, SecurityViolationException {
return query;
}
/**
* Applies definitions to query. Currently related only to provisioning-level definitions.
* Therefore not available in repo-common.
*/
protected void applyDefinitionsToQuery(OperationResult opResult) throws CommonException {
}
/**
* TODO reconsider
*/
@Override
protected void setExpectedTotal(OperationResult opResult) throws CommonException {
Long expectedTotal = computeExpectedTotal(opResult);
getRunningTask().setExpectedTotal(expectedTotal);
getRunningTask().flushPendingModifications(opResult);
}
@Nullable
private Long computeExpectedTotal(OperationResult opResult) throws SchemaException, ObjectNotFoundException,
CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
if (!getReportingOptions().isDetermineExpectedTotal()) {
return null;
} else if (BucketingUtil.hasLimitations(bucket)) {
// We avoid computing expected total if we are processing a bucket: actually we could do it,
// but we should not display the result as 'task expected total'.
return null;
} else {
Integer expectedTotal = countObjects(opResult);
if (expectedTotal != null) {
return (long) expectedTotal;
} else {
return null;
}
}
}
/**
* Used to count objects using model or any similar higher-level interface. Defaults to repository count.
*/
protected Integer countObjects(OperationResult opResult) throws SchemaException, ObjectNotFoundException,
CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
return countObjectsInRepository(opResult);
}
protected final int countObjectsInRepository(OperationResult opResult) throws SchemaException {
return beans.repositoryService.countObjects(
getObjectType(),
getQuery(),
getSearchOptions(),
opResult);
}
@Override
protected void processItems(OperationResult opResult) throws CommonException {
searchIterative(opResult);
}
/**
* Used to search using model or any similar higher-level interface. Defaults to search using repository.
*/
protected void searchIterative(OperationResult opResult) throws CommonException {
searchIterativeInRepository(opResult);
}
protected final void searchIterativeInRepository(OperationResult opResult) throws SchemaException {
beans.repositoryService.searchObjectsIterative(
getObjectType(),
getQuery(),
createSearchResultHandler(),
getSearchOptions(),
true,
opResult);
}
protected boolean modelProcessingAvailable() {
return false;
}
protected void setRequiresDirectRepositoryAccess() {
this.requiresDirectRepositoryAccess = true;
}
protected ExpressionProfile getExpressionProfile() {
// TODO Determine from task object archetype
return MiscSchemaUtil.getExpressionProfile();
}
public SchemaService getSchemaService() {
return beans.schemaService;
}
protected TaskManager getTaskManager() {
return beans.taskManager;
}
/**
* Passes all objects found into the processing coordinator.
* (Which processes them directly or queues them for the worker threads.)
*/
protected final ResultHandler<O> createSearchResultHandler() {
return (object, parentResult) -> {
ObjectProcessingRequest<O> request = new ObjectProcessingRequest<>(object, this);
return coordinator.submit(request, parentResult);
};
}
@Override
public boolean providesTracingAndDynamicProfiling() {
// This is a temporary solution
return !isNonScavengingWorker();
}
private boolean isNonScavengingWorker() {
return activityState.isWorker() && !activityState.isScavenger();
}
@Override
protected @NotNull ErrorHandlingStrategyExecutor.FollowUpAction getDefaultErrorAction() {
// This is the default for search-iterative tasks. It is a legacy behavior, and also the most logical:
// we do not need to stop on error, because there's always possible to re-run the whole task.
return ErrorHandlingStrategyExecutor.FollowUpAction.CONTINUE;
}
boolean checkAndRegisterOid(String oid) {
return oidsSeen.add(oid);
}
@FunctionalInterface
public interface SimpleItemProcessor<O extends ObjectType> {
boolean processObject(PrismObject<O> object, ItemProcessingRequest<PrismObject<O>> request,
RunningTask workerTask, OperationResult result) throws CommonException, ActivityExecutionException;
}
protected final ItemProcessor<PrismObject<O>> createDefaultItemProcessor(SimpleItemProcessor<O> simpleItemProcessor) {
//noinspection unchecked
return new AbstractSearchIterativeItemProcessor<>((AE) this) {
@Override
protected boolean processObject(PrismObject<O> object, ItemProcessingRequest<PrismObject<O>> request,
RunningTask workerTask, OperationResult result) throws CommonException, ActivityExecutionException {
return simpleItemProcessor.processObject(object, request, workerTask, result);
}
};
}
@Override
protected boolean hasProgressCommitPoints() {
return true;
}
private ActivityBucketManagementStatistics getLiveBucketManagementStatistics() {
return activityState.getLiveStatistics().getLiveBucketManagement();
}
public @NotNull SearchSpecification<O> getSearchSpecificationRequired() {
return requireNonNull(searchSpecification, "no search specification");
}
private void checkSearchSpecificationPresent() {
stateCheck(searchSpecification != null, "no search specification");
}
public final Class<O> getObjectType() {
return getSearchSpecificationRequired().getObjectType();
}
public final ObjectQuery getQuery() {
return getSearchSpecificationRequired().getQuery();
}
public final Collection<SelectorOptions<GetOperationOptions>> getSearchOptions() {
return getSearchSpecificationRequired().getSearchOptions();
}
public final boolean isUseRepository() {
return Boolean.TRUE.equals(searchSpecification.getUseRepository());
}
}
| UTF-8 | Java | 25,940 | java | AbstractSearchIterativeActivityExecution.java | Java | [
{
"context": "/*\n * Copyright (c) 2020 Evolveum and contributors\n *\n * This work is dual-licensed",
"end": 33,
"score": 0.8195104002952576,
"start": 25,
"tag": "NAME",
"value": "Evolveum"
}
] | null | [] | /*
* Copyright (c) 2020 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.repo.common.task;
import com.evolveum.midpoint.prism.ItemDefinition;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.query.ObjectFilter;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.repo.common.activity.ActivityExecutionException;
import com.evolveum.midpoint.repo.common.activity.definition.WorkDefinition;
import com.evolveum.midpoint.repo.common.activity.execution.ExecutionInstantiationContext;
import com.evolveum.midpoint.repo.common.activity.handlers.ActivityHandler;
import com.evolveum.midpoint.repo.common.activity.state.ActivityBucketManagementStatistics;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.ResultHandler;
import com.evolveum.midpoint.schema.SchemaService;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.expression.ExpressionProfile;
import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.MiscSchemaUtil;
import com.evolveum.midpoint.schema.util.ObjectQueryUtil;
import com.evolveum.midpoint.schema.util.task.BucketingUtil;
import com.evolveum.midpoint.task.api.RunningTask;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.task.api.TaskManager;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.exception.*;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import static com.evolveum.midpoint.schema.result.OperationResultStatus.FATAL_ERROR;
import static com.evolveum.midpoint.task.api.TaskRunResult.TaskRunResultStatus.PERMANENT_ERROR;
import static com.evolveum.midpoint.util.MiscUtil.stateCheck;
import static java.util.Objects.requireNonNull;
/**
* Single execution of a given search-iterative task part.
*
* Takes care of preparing and issuing the search query.
*
* *TODO finish cleanup*
*/
public abstract class AbstractSearchIterativeActivityExecution<
O extends ObjectType,
WD extends WorkDefinition,
AH extends ActivityHandler<WD, AH>,
AE extends AbstractSearchIterativeActivityExecution<O, WD, AH, AE, BS>,
BS extends AbstractActivityWorkStateType>
extends AbstractIterativeActivityExecution<PrismObject<O>, WD, AH, BS> {
private static final Trace LOGGER = TraceManager.getTrace(AbstractSearchIterativeActivityExecution.class);
private static final long FREE_BUCKET_WAIT_TIME = -1; // indefinitely
/**
* Specification of the search that is to be executed: object type, query, options, and "use repository" flag.
*/
protected SearchSpecification<O> searchSpecification;
/**
* Additional filter to be applied to each object received (if not null).
* Currently used to filter failed objects when `FILTER_AFTER_RETRIEVAL` mode is selected.
*
* See {@link AbstractSearchIterativeItemProcessor#process(ItemProcessingRequest, RunningTask, OperationResult)}.
*/
ObjectFilter additionalFilter;
/**
* Pre-processes object received before it is passed to the task handler specific processing.
* (Only for non-failed objects.) Currently used to fetch failed objects when `FETCH_FAILED_OBJECTS` mode is selected.
*
* See {@link AbstractSearchIterativeItemProcessor#process(ItemProcessingRequest, RunningTask, OperationResult)}.
*/
ObjectPreprocessor<O> preprocessor;
/**
* In some situations (e.g. because provisioning service does not allow searches without specifying resource
* or objectclass/kind) we need to use repository directly for some specific tasks or task parts.
*/
private boolean requiresDirectRepositoryAccess;
/**
* OIDs of objects submitted to processing in current part execution (i.e. in the current bucket).
*/
private final Set<String> oidsSeen = ConcurrentHashMap.newKeySet();
/**
* Current bucket that is being processed.
* It is used to narrow the search query.
*/
protected WorkBucketType bucket;
public AbstractSearchIterativeActivityExecution(@NotNull ExecutionInstantiationContext<WD, AH> context,
@NotNull String shortNameCapitalized) {
super(context, shortNameCapitalized);
}
/**
* Bucketed version of the execution.
*/
@Override
protected void executeInitialized(OperationResult opResult)
throws ActivityExecutionException, CommonException {
RunningTask task = taskExecution.getRunningTask();
boolean initialExecution = true;
// resetWorkStateAndStatisticsIfWorkComplete(result);
// startCollectingStatistics(task, handler);
for (; task.canRun(); initialExecution = false) {
bucket = getWorkBucket(initialExecution, opResult);
if (!task.canRun()) {
break;
}
if (bucket == null) {
LOGGER.trace("No (next) work bucket within {}, exiting", task);
// updateStructuredProgressOnNoMoreBuckets();
break;
}
executeSingleBucket(opResult);
if (!task.canRun() || errorState.wasStoppingExceptionEncountered()) {
break;
}
completeWorkBucketAndUpdateStructuredProgress(opResult);
}
// task.updateAndStoreStatisticsIntoRepository(true, opResult);
}
private WorkBucketType getWorkBucket(boolean initialExecution, OperationResult result) {
RunningTask task = taskExecution.getRunningTask();
WorkBucketType bucket;
try {
bucket = beans.bucketingManager.getWorkBucket(task, activity.getPath(),
activity.getDefinition().getDistributionDefinition(), FREE_BUCKET_WAIT_TIME, initialExecution,
getLiveBucketManagementStatistics(), result);
task.refresh(result); // We want to have the most current state of the running task.
} catch (InterruptedException e) {
LOGGER.trace("InterruptedExecution in getWorkBucket for {}", task);
if (!task.canRun()) {
return null;
} else {
LoggingUtils.logUnexpectedException(LOGGER, "Unexpected InterruptedException in {}", e, task);
throw new SystemException("Unexpected InterruptedException: " + e.getMessage(), e);
}
} catch (Throwable t) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't allocate a work bucket for task {}", t, task);
throw new SystemException("Couldn't allocate a work bucket for task: " + t.getMessage(), t);
}
return bucket;
}
private void completeWorkBucketAndUpdateStructuredProgress(OperationResult result) {
RunningTask task = taskExecution.getRunningTask();
try {
beans.bucketingManager.completeWorkBucket(task, getActivityPath(), bucket,
getLiveBucketManagementStatistics(), result);
activityState.getLiveProgress().onCommitPoint();
// TODO update in repository
// task.changeStructuredProgressOnWorkBucketCompletion();
// updateAndStoreStatisticsIntoRepository(task, result);
} catch (ObjectAlreadyExistsException | ObjectNotFoundException | SchemaException | RuntimeException e) {
throw new SystemException("Couldn't complete work bucket for task: " + e.getMessage(), e);
}
}
@Override
protected void prepareItemSource(OperationResult opResult) throws ActivityExecutionException, CommonException {
prepareSearchSpecification(opResult);
}
private void prepareSearchSpecification(OperationResult opResult) throws CommonException, ActivityExecutionException {
searchSpecification = createSearchSpecification(opResult);
customizeSearchSpecification(searchSpecification, opResult);
narrowQueryForBucketingAndErrorHandling();
searchSpecification.setQuery(
evaluateQueryExpressions(searchSpecification.getQuery(), opResult));
applyDefinitionsToQuery(opResult);
LOGGER.trace("{}: will do the following search:\n{}",
activityShortNameCapitalized, DebugUtil.debugDumpLazily(searchSpecification));
}
/**
* Creates the search specification (type, query, options, use repo). Normally it is created from the configuration
* embodied in work definition, but it can be fully overridden for the least configurable activities.
*
* Note that at repo-common level we do not support {@link ResourceObjectSetSpecificationImpl}.
*
* TODO Clean this up a little bit. It is quite awkward.
*/
protected @NotNull SearchSpecification<O> createSearchSpecification(OperationResult opResult) throws SchemaException, ActivityExecutionException {
ObjectSetSpecification objectSetSpecification = ObjectSetSpecification.fromWorkDefinition(activity.getWorkDefinition());
if (objectSetSpecification instanceof RepositoryObjectSetSpecificationImpl) {
return SearchSpecification.fromRepositoryObjectSetSpecification(
(RepositoryObjectSetSpecificationImpl) objectSetSpecification);
} else {
throw new UnsupportedOperationException("Non-repository object set specification is not supported: " +
objectSetSpecification);
}
}
/**
* Customizes the configured search specification. Almost fully delegated to the subclasses;
* except for the "use repository" flag, which has some default behavior here.
*
* *BEWARE* Be careful when overriding this, because of killing use repository flag check - FIXME
*/
@SuppressWarnings("WeakerAccess") // To allow overriding in subclasses.
protected void customizeSearchSpecification(@NotNull SearchSpecification<O> searchSpecification, OperationResult opResult)
throws CommonException, ActivityExecutionException {
searchSpecification.setQuery(customizeQuery(searchSpecification.getQuery(), opResult));
searchSpecification.setSearchOptions(customizeSearchOptions(searchSpecification.getSearchOptions(), opResult));
searchSpecification.setUseRepository(customizeUseRepository(searchSpecification.getUseRepository(), opResult));
}
protected ObjectQuery customizeQuery(ObjectQuery configuredQuery, OperationResult opResult) throws CommonException {
return configuredQuery;
}
protected Collection<SelectorOptions<GetOperationOptions>> customizeSearchOptions(
Collection<SelectorOptions<GetOperationOptions>> configuredOptions, OperationResult opResult)
throws CommonException {
return configuredOptions;
}
/**
* Customizes the direct use of repository. The default implementation makes use
* of requiresDirectRepositoryAccess and also checks the authorization of direct access.
*
* FIXME this implementation is not good, as it allows unintentional overriding of the autz check
*/
@SuppressWarnings("WeakerAccess") // To allow overriding in subclasses.
protected Boolean customizeUseRepository(Boolean configuredValue, OperationResult opResult)
throws CommonException {
if (configuredValue != null) {
// if we requested this mode explicitly we need to have appropriate authorization
if (configuredValue) {
checkRawAuthorization(getRunningTask(), opResult);
}
return configuredValue;
} else {
return requiresDirectRepositoryAccess;
}
}
protected void checkRawAuthorization(Task task, OperationResult result)
throws CommunicationException, ObjectNotFoundException, SchemaException, SecurityViolationException,
ConfigurationException, ExpressionEvaluationException {
// nothing to do here as we are in repo-common
}
private void narrowQueryForBucketingAndErrorHandling() throws ActivityExecutionException {
checkSearchSpecificationPresent();
try {
ObjectQuery queryFromHandler = searchSpecification.getQuery(); // TODO better name
LOGGER.trace("{}: query as defined by activity:\n{}", activityShortNameCapitalized,
DebugUtil.debugDumpLazily(queryFromHandler));
ObjectQuery failureNarrowedQuery = narrowQueryToProcessFailedObjectsOnly(queryFromHandler); // logging is inside
ObjectQuery bucketNarrowedQuery = beans.bucketingManager.narrowQueryForWorkBucket(
getObjectType(),
failureNarrowedQuery,
activity.getDefinition().getDistributionDefinition(),
createItemDefinitionProvider(),
bucket);
LOGGER.trace("{}: using a query (after applying work bucket, before evaluating expressions):\n{}",
activityShortNameCapitalized, DebugUtil.debugDumpLazily(bucketNarrowedQuery));
searchSpecification.setQuery(bucketNarrowedQuery);
} catch (Throwable t) {
// This is most probably a permanent error. (The real communication with a resource is carried out when the
// query is issued. With an exception of untested resource. But it is generally advised to do the connection test
// before running any tasks.)
throw new ActivityExecutionException("Couldn't create object query", FATAL_ERROR, PERMANENT_ERROR, t);
}
}
/**
* Besides updating the query this method influences the search process:
*
* In case of FETCH_FAILED_OBJECTS it
*
* - sets up a pre-processor that implements fetching individual shadows (that are to be re-tried) from a resource,
* - turns on the "no fetch" option.
*
* In case of FILTER_AFTER_RETRIEVAL it
*
* - installs additional filter that passes through only selected objects (the ones that were failed).
*/
@Nullable
private ObjectQuery narrowQueryToProcessFailedObjectsOnly(ObjectQuery query) {
FailedObjectsSelectorType selector = getRunningTask().getExtensionContainerRealValueOrClone(SchemaConstants.MODEL_EXTENSION_FAILED_OBJECTS_SELECTOR);
if (selector == null) {
return query;
} else {
ObjectFilter failedObjectsFilter =
new FailedObjectsFilterCreator(selector, getRunningTask(), getPrismContext())
.createFilter();
FailedObjectsSelectionMethodType selectionMethod = getFailedObjectsSelectionMethod(selector);
switch (selectionMethod) {
case FETCH_FAILED_OBJECTS:
// We will use the narrowed query. The noFetch option ensures that search in provisioning will work.
// It would be nice to check if the query does not refer to attributes that are not cached.
// But it should be done in the provisioning module.
searchSpecification.setNoFetchOption();
preprocessor = createShadowFetchingPreprocessor();
LOGGER.trace("{}: shadow-fetching preprocessor was set up", activityShortNameCapitalized);
case NARROW_QUERY:
ObjectQuery failureNarrowedQuery = ObjectQueryUtil.addConjunctions(query, getPrismContext(), failedObjectsFilter);
LOGGER.trace("{}: query narrowed to select failed objects only:\n{}", activityShortNameCapitalized,
DebugUtil.debugDumpLazily(failureNarrowedQuery));
return failureNarrowedQuery;
case FILTER_AFTER_RETRIEVAL:
additionalFilter = failedObjectsFilter;
LOGGER.trace("{}: will use additional filter to select failed objects only (but executes "
+ "the search with original query):\n{}", activityShortNameCapitalized,
DebugUtil.debugDumpLazily(failedObjectsFilter));
return query;
default:
throw new AssertionError(selectionMethod);
}
}
}
private @NotNull FailedObjectsSelectionMethodType getFailedObjectsSelectionMethod(FailedObjectsSelectorType selector) {
FailedObjectsSelectionMethodType method = selector.getSelectionMethod();
if (method != null && method != FailedObjectsSelectionMethodType.DEFAULT) {
return method;
} else if (searchesResourceObjects()) {
return FailedObjectsSelectionMethodType.FETCH_FAILED_OBJECTS;
} else {
return FailedObjectsSelectionMethodType.NARROW_QUERY;
}
}
private boolean searchesResourceObjects() {
return searchSpecification.concernsShadows() &&
!isUseRepository() && modelProcessingAvailable() &&
!searchSpecification.isNoFetch() && !searchSpecification.isRaw();
}
@NotNull
protected ObjectPreprocessor<O> createShadowFetchingPreprocessor() {
throw new UnsupportedOperationException("FETCH_FAILED_OBJECTS is not available in this type of tasks. "
+ "Model processing is required.");
}
/**
* Returns a provider of definitions for runtime items (e.g. attributes) that are needed in bucket filters.
* To be implemented in subclasses that work with resource objects.
*/
protected Function<ItemPath, ItemDefinition<?>> createItemDefinitionProvider() {
return null;
}
protected final Function<ItemPath, ItemDefinition<?>> createItemDefinitionProviderForAttributes(
ObjectClassComplexTypeDefinition objectClass) {
return itemPath -> {
if (itemPath.startsWithName(ShadowType.F_ATTRIBUTES)) {
return objectClass.findAttributeDefinition(itemPath.rest().asSingleName());
} else {
return null;
}
};
}
/**
* Evaluates expressions in query. Currently implemented only in model-impl. TODO why?
*/
protected ObjectQuery evaluateQueryExpressions(ObjectQuery query, OperationResult opResult)
throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException,
ConfigurationException, SecurityViolationException {
return query;
}
/**
* Applies definitions to query. Currently related only to provisioning-level definitions.
* Therefore not available in repo-common.
*/
protected void applyDefinitionsToQuery(OperationResult opResult) throws CommonException {
}
/**
* TODO reconsider
*/
@Override
protected void setExpectedTotal(OperationResult opResult) throws CommonException {
Long expectedTotal = computeExpectedTotal(opResult);
getRunningTask().setExpectedTotal(expectedTotal);
getRunningTask().flushPendingModifications(opResult);
}
@Nullable
private Long computeExpectedTotal(OperationResult opResult) throws SchemaException, ObjectNotFoundException,
CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
if (!getReportingOptions().isDetermineExpectedTotal()) {
return null;
} else if (BucketingUtil.hasLimitations(bucket)) {
// We avoid computing expected total if we are processing a bucket: actually we could do it,
// but we should not display the result as 'task expected total'.
return null;
} else {
Integer expectedTotal = countObjects(opResult);
if (expectedTotal != null) {
return (long) expectedTotal;
} else {
return null;
}
}
}
/**
* Used to count objects using model or any similar higher-level interface. Defaults to repository count.
*/
protected Integer countObjects(OperationResult opResult) throws SchemaException, ObjectNotFoundException,
CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
return countObjectsInRepository(opResult);
}
protected final int countObjectsInRepository(OperationResult opResult) throws SchemaException {
return beans.repositoryService.countObjects(
getObjectType(),
getQuery(),
getSearchOptions(),
opResult);
}
@Override
protected void processItems(OperationResult opResult) throws CommonException {
searchIterative(opResult);
}
/**
* Used to search using model or any similar higher-level interface. Defaults to search using repository.
*/
protected void searchIterative(OperationResult opResult) throws CommonException {
searchIterativeInRepository(opResult);
}
protected final void searchIterativeInRepository(OperationResult opResult) throws SchemaException {
beans.repositoryService.searchObjectsIterative(
getObjectType(),
getQuery(),
createSearchResultHandler(),
getSearchOptions(),
true,
opResult);
}
protected boolean modelProcessingAvailable() {
return false;
}
protected void setRequiresDirectRepositoryAccess() {
this.requiresDirectRepositoryAccess = true;
}
protected ExpressionProfile getExpressionProfile() {
// TODO Determine from task object archetype
return MiscSchemaUtil.getExpressionProfile();
}
public SchemaService getSchemaService() {
return beans.schemaService;
}
protected TaskManager getTaskManager() {
return beans.taskManager;
}
/**
* Passes all objects found into the processing coordinator.
* (Which processes them directly or queues them for the worker threads.)
*/
protected final ResultHandler<O> createSearchResultHandler() {
return (object, parentResult) -> {
ObjectProcessingRequest<O> request = new ObjectProcessingRequest<>(object, this);
return coordinator.submit(request, parentResult);
};
}
@Override
public boolean providesTracingAndDynamicProfiling() {
// This is a temporary solution
return !isNonScavengingWorker();
}
private boolean isNonScavengingWorker() {
return activityState.isWorker() && !activityState.isScavenger();
}
@Override
protected @NotNull ErrorHandlingStrategyExecutor.FollowUpAction getDefaultErrorAction() {
// This is the default for search-iterative tasks. It is a legacy behavior, and also the most logical:
// we do not need to stop on error, because there's always possible to re-run the whole task.
return ErrorHandlingStrategyExecutor.FollowUpAction.CONTINUE;
}
boolean checkAndRegisterOid(String oid) {
return oidsSeen.add(oid);
}
@FunctionalInterface
public interface SimpleItemProcessor<O extends ObjectType> {
boolean processObject(PrismObject<O> object, ItemProcessingRequest<PrismObject<O>> request,
RunningTask workerTask, OperationResult result) throws CommonException, ActivityExecutionException;
}
protected final ItemProcessor<PrismObject<O>> createDefaultItemProcessor(SimpleItemProcessor<O> simpleItemProcessor) {
//noinspection unchecked
return new AbstractSearchIterativeItemProcessor<>((AE) this) {
@Override
protected boolean processObject(PrismObject<O> object, ItemProcessingRequest<PrismObject<O>> request,
RunningTask workerTask, OperationResult result) throws CommonException, ActivityExecutionException {
return simpleItemProcessor.processObject(object, request, workerTask, result);
}
};
}
@Override
protected boolean hasProgressCommitPoints() {
return true;
}
private ActivityBucketManagementStatistics getLiveBucketManagementStatistics() {
return activityState.getLiveStatistics().getLiveBucketManagement();
}
public @NotNull SearchSpecification<O> getSearchSpecificationRequired() {
return requireNonNull(searchSpecification, "no search specification");
}
private void checkSearchSpecificationPresent() {
stateCheck(searchSpecification != null, "no search specification");
}
public final Class<O> getObjectType() {
return getSearchSpecificationRequired().getObjectType();
}
public final ObjectQuery getQuery() {
return getSearchSpecificationRequired().getQuery();
}
public final Collection<SelectorOptions<GetOperationOptions>> getSearchOptions() {
return getSearchSpecificationRequired().getSearchOptions();
}
public final boolean isUseRepository() {
return Boolean.TRUE.equals(searchSpecification.getUseRepository());
}
}
| 25,940 | 0.698728 | 0.698419 | 591 | 42.891708 | 38.446636 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.543147 | false | false | 12 |
3593d3856391f7241468ffd34febd45bba035551 | 18,975,165,514,780 | faa92a39e851f425f90096c46a4d0f0313464687 | /Mercadinho/src/Comentarios.java | 652e6b8a5632725be6015199936c224c355c38ab | [] | no_license | fabianaota/mercadinho | https://github.com/fabianaota/mercadinho | 0cb2ce4ff130cf7fbf176fa968ce5246908d21d4 | 7228b14e71b622530f0dc7220131574d3c870edc | refs/heads/master | 2020-04-05T13:58:17.070000 | 2018-11-09T22:03:26 | 2018-11-09T22:03:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*import java.util.ArrayList;
import java.util.List;
public class Comentarios {
}
public static void main(String[] args) {
List<Cliente> listaDeClientes = new ArrayList<>();
Cliente umCliente = new Cliente();
umCliente.preencherDados(); // pegar dados
listaDeClientes.add(umCliente);
umCliente = new Cliente();
umCliente.preencherDados();
listaDeClientes.add(umCliente);
umCliente = new Cliente();
umCliente.preencherDados();
listaDeClientes.add(umCliente);
for (int i = 0 ; i < listaDeClientes.size(); i++) {
System.out.println(" O nome do cliente é :" + listaDeClientes.get(i).getNome()+ " e o cpf é :" + listaDeClientes.get(i).getCpf());
}
*/
/*package com.company;
import java.util.Scanner;
public class Cliente {
private String nome;
private String cpf;
public void preencherDados(){
Scanner sc = new Scanner(System.in);
System.out.println("Digite seu nome:");
this.setNome(sc.next());
System.out.println("Digite seu cpf:");
this.setCpf(sc.next());
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
}*/ | UTF-8 | Java | 1,403 | java | Comentarios.java | Java | [] | null | [] | /*import java.util.ArrayList;
import java.util.List;
public class Comentarios {
}
public static void main(String[] args) {
List<Cliente> listaDeClientes = new ArrayList<>();
Cliente umCliente = new Cliente();
umCliente.preencherDados(); // pegar dados
listaDeClientes.add(umCliente);
umCliente = new Cliente();
umCliente.preencherDados();
listaDeClientes.add(umCliente);
umCliente = new Cliente();
umCliente.preencherDados();
listaDeClientes.add(umCliente);
for (int i = 0 ; i < listaDeClientes.size(); i++) {
System.out.println(" O nome do cliente é :" + listaDeClientes.get(i).getNome()+ " e o cpf é :" + listaDeClientes.get(i).getCpf());
}
*/
/*package com.company;
import java.util.Scanner;
public class Cliente {
private String nome;
private String cpf;
public void preencherDados(){
Scanner sc = new Scanner(System.in);
System.out.println("Digite seu nome:");
this.setNome(sc.next());
System.out.println("Digite seu cpf:");
this.setCpf(sc.next());
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
}*/ | 1,403 | 0.593862 | 0.593148 | 67 | 19.925373 | 23.345116 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.41791 | false | false | 12 |
929926c60c1f19a39f15cf16456e763bb8f7cf61 | 12,094,627,955,366 | ef9302069045260a2bccdbaac5bc713fd4ef6470 | /app/src/main/java/com/ethan/imapp/activities/MainActivity.java | fec5ebc0a6693d03f520d181327aed5381d8c37e | [
"MIT"
] | permissive | Fannibals/IM_Android | https://github.com/Fannibals/IM_Android | c20349c13108e125287931d921b576e5902fd9d8 | c57da7b2d19e79882a71f9830e232d67cadba6e6 | refs/heads/master | 2020-11-24T19:04:43.092000 | 2020-03-22T08:32:10 | 2020-03-22T08:32:10 | 228,303,775 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ethan.imapp.activities;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AnticipateInterpolator;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.ViewTarget;
import com.ethan.common.app.BaseActivity;
import com.ethan.common.app.BaseFragment;
import com.ethan.common.widget.PortraitView;
import com.ethan.imapp.R;
import com.ethan.imapp.activities.AccountActivity;
import com.ethan.imapp.fragments.assist.PermissionFragment;
import com.ethan.imapp.fragments.main.ActiveFragment;
import com.ethan.imapp.fragments.main.ContactFragment;
import com.ethan.imapp.fragments.main.GroupFragment;
import com.ethan.imapp.helper.NavHelper;
import com.ethan.imapp.helper.PermissionHelper;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import net.qiujuer.genius.ui.Ui;
import net.qiujuer.genius.ui.widget.FloatActionButton;
import butterknife.BindView;
import butterknife.OnClick;
public class MainActivity extends BaseActivity implements
BottomNavigationView.OnNavigationItemSelectedListener,
NavHelper.OnTabChangedListener<Integer>{
@BindView(R.id.appBar)
View mLayAppBar;
@BindView(R.id.img_portrait)
PortraitView mPortrait;
@BindView(R.id.txt_title)
TextView mTitle;
@BindView(R.id.lay_container)
FrameLayout mContainer;
@BindView(R.id.btn_action)
FloatActionButton mAction;
@BindView(R.id.navigation)
BottomNavigationView mNavigation;
/**
* Handling fragment
*/
private NavHelper<Integer> mNavHelper;
// Entrance for the Main Activity
public static void show (Context context){
context.startActivity(new Intent(context, MainActivity.class));
}
@Override
protected int getContentLayoutId() {
return R.layout.activity_main;
}
@Override
protected void initWidget() {
super.initWidget();
mNavHelper = new NavHelper(this, R.id.lay_container,
getSupportFragmentManager(),this);
mNavHelper.add(R.id.action_home,new NavHelper.Tab<>(ActiveFragment.class,R.string.title_home))
.add(R.id.action_group, new NavHelper.Tab<>(GroupFragment.class,R.string.title_group))
.add(R.id.action_contact, new NavHelper.Tab<>(ContactFragment.class, R.string.title_contact));
mNavigation.setOnNavigationItemSelectedListener(this);
// ViewTarget is used here for handling the scenario
// that setting image into customized view
// if for normal imageview, just use that ref
Glide.with(this)
.load(R.drawable.bg_src_morning)
.centerCrop()
.into(new ViewTarget<View, GlideDrawable>(mLayAppBar) {
@Override
public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
this.view.setBackground(resource.getCurrent());
}
})
;
PermissionFragment.haveAll(this,getSupportFragmentManager());
}
/**
* 里面进行了menu的default selection
*/
@Override
protected void initData() {
super.initData();
// 从底部导航栏中接管我们的Menu,然后进行手动的触发第一次点击
Menu menu = mNavigation.getMenu();
// default: select home
menu.performIdentifierAction(R.id.action_home,0);
}
@OnClick(R.id.img_search)
void onSearchMenuClick(){
}
@OnClick({R.id.btn_action})
void onActionClick(){
AccountActivity.show(this);
}
/**
* is Triggered when we click the navigation bar
*
* @param menuItem
* @return True for we can hold the action event
*/
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
// 转接事件流到工具类中
return mNavHelper.performClickMenu(menuItem.getItemId());
}
/**
* CallBack methods after NavHelper executed
* @param newTab
* @param oldTab
*/
@Override
public void onTabChanged(NavHelper.Tab<Integer> newTab, NavHelper.Tab<Integer> oldTab) {
// 从额外字段
mTitle.setText(newTab.extra);
// Animation
float transY = 0;
float rotation = 0;
if (newTab.extra.equals(R.string.title_home)){
// hide the btn when at the homepage
transY = Ui.dipToPx(getResources(),76);
}else{
//
if (newTab.extra.equals(R.string.title_group)){
mAction.setImageResource(R.drawable.ic_group_add);
// rotation 如果一样的话,看起来没变
rotation = -360;
}else{
mAction.setImageResource(R.drawable.ic_contact_add);
rotation = 360;
}
}
// start animation
mAction.animate()
.rotation(rotation)
.translationY(transY)
.setInterpolator(new AnticipateOvershootInterpolator(1)) // 弹性效果
.setDuration(480)
.start();
}
}
| UTF-8 | Java | 5,952 | java | MainActivity.java | Java | [] | null | [] | package com.ethan.imapp.activities;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AnticipateInterpolator;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.ViewTarget;
import com.ethan.common.app.BaseActivity;
import com.ethan.common.app.BaseFragment;
import com.ethan.common.widget.PortraitView;
import com.ethan.imapp.R;
import com.ethan.imapp.activities.AccountActivity;
import com.ethan.imapp.fragments.assist.PermissionFragment;
import com.ethan.imapp.fragments.main.ActiveFragment;
import com.ethan.imapp.fragments.main.ContactFragment;
import com.ethan.imapp.fragments.main.GroupFragment;
import com.ethan.imapp.helper.NavHelper;
import com.ethan.imapp.helper.PermissionHelper;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import net.qiujuer.genius.ui.Ui;
import net.qiujuer.genius.ui.widget.FloatActionButton;
import butterknife.BindView;
import butterknife.OnClick;
public class MainActivity extends BaseActivity implements
BottomNavigationView.OnNavigationItemSelectedListener,
NavHelper.OnTabChangedListener<Integer>{
@BindView(R.id.appBar)
View mLayAppBar;
@BindView(R.id.img_portrait)
PortraitView mPortrait;
@BindView(R.id.txt_title)
TextView mTitle;
@BindView(R.id.lay_container)
FrameLayout mContainer;
@BindView(R.id.btn_action)
FloatActionButton mAction;
@BindView(R.id.navigation)
BottomNavigationView mNavigation;
/**
* Handling fragment
*/
private NavHelper<Integer> mNavHelper;
// Entrance for the Main Activity
public static void show (Context context){
context.startActivity(new Intent(context, MainActivity.class));
}
@Override
protected int getContentLayoutId() {
return R.layout.activity_main;
}
@Override
protected void initWidget() {
super.initWidget();
mNavHelper = new NavHelper(this, R.id.lay_container,
getSupportFragmentManager(),this);
mNavHelper.add(R.id.action_home,new NavHelper.Tab<>(ActiveFragment.class,R.string.title_home))
.add(R.id.action_group, new NavHelper.Tab<>(GroupFragment.class,R.string.title_group))
.add(R.id.action_contact, new NavHelper.Tab<>(ContactFragment.class, R.string.title_contact));
mNavigation.setOnNavigationItemSelectedListener(this);
// ViewTarget is used here for handling the scenario
// that setting image into customized view
// if for normal imageview, just use that ref
Glide.with(this)
.load(R.drawable.bg_src_morning)
.centerCrop()
.into(new ViewTarget<View, GlideDrawable>(mLayAppBar) {
@Override
public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
this.view.setBackground(resource.getCurrent());
}
})
;
PermissionFragment.haveAll(this,getSupportFragmentManager());
}
/**
* 里面进行了menu的default selection
*/
@Override
protected void initData() {
super.initData();
// 从底部导航栏中接管我们的Menu,然后进行手动的触发第一次点击
Menu menu = mNavigation.getMenu();
// default: select home
menu.performIdentifierAction(R.id.action_home,0);
}
@OnClick(R.id.img_search)
void onSearchMenuClick(){
}
@OnClick({R.id.btn_action})
void onActionClick(){
AccountActivity.show(this);
}
/**
* is Triggered when we click the navigation bar
*
* @param menuItem
* @return True for we can hold the action event
*/
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
// 转接事件流到工具类中
return mNavHelper.performClickMenu(menuItem.getItemId());
}
/**
* CallBack methods after NavHelper executed
* @param newTab
* @param oldTab
*/
@Override
public void onTabChanged(NavHelper.Tab<Integer> newTab, NavHelper.Tab<Integer> oldTab) {
// 从额外字段
mTitle.setText(newTab.extra);
// Animation
float transY = 0;
float rotation = 0;
if (newTab.extra.equals(R.string.title_home)){
// hide the btn when at the homepage
transY = Ui.dipToPx(getResources(),76);
}else{
//
if (newTab.extra.equals(R.string.title_group)){
mAction.setImageResource(R.drawable.ic_group_add);
// rotation 如果一样的话,看起来没变
rotation = -360;
}else{
mAction.setImageResource(R.drawable.ic_contact_add);
rotation = 360;
}
}
// start animation
mAction.animate()
.rotation(rotation)
.translationY(transY)
.setInterpolator(new AnticipateOvershootInterpolator(1)) // 弹性效果
.setDuration(480)
.start();
}
}
| 5,952 | 0.674279 | 0.671703 | 191 | 29.481676 | 24.784906 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.460733 | false | false | 12 |
40d014175737278089a9ad8a1c39115eda5aa824 | 29,300,266,936,804 | b21fe22ccdb4f0054ccf5a31ea7f087b5c5caa78 | /src/main/java/groceryapp/GroceryAppController.java | bbdfd24720c2476d8acaa1f043ca3d45e2dfa290 | [] | no_license | GeneCPChung/grocery-app | https://github.com/GeneCPChung/grocery-app | 8fcc9479a8a258df0319eb6d662a0dc079dddace | 791c979eb7779f882a5ce5aee34d295d89626cac | refs/heads/master | 2021-08-22T15:53:26.451000 | 2017-11-30T15:25:40 | 2017-11-30T15:25:40 | 112,223,050 | 0 | 0 | null | true | 2017-11-27T16:53:37 | 2017-11-27T16:53:36 | 2017-11-27T16:48:29 | 2017-11-27T16:48:30 | 0 | 0 | 0 | 0 | null | false | null | package groceryapp;
import javax.annotation.Resource;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
public class GroceryAppController {
@Resource
RecipeRepository recipeRepo;
@Resource
IngredientRepository ingredientRepo;
@Resource
StoreItemRepository storeItemRepo;
@Resource
LineItemRepository lineItemRepo;
@RequestMapping("/recipes")
public String getAllRecipes(Model model) {
model.addAttribute("recipes", recipeRepo.findAll());
return "recipes";
}
@RequestMapping("/recipe")
public String getOneRecipe(@RequestParam Long id, Model model) {
model.addAttribute("recipe", recipeRepo.findOne(id));
return "recipe";
}
@RequestMapping("/ingredients")
public String getAllIngredients(Model model) {
model.addAttribute("ingredients", ingredientRepo.findAll());
return "ingredients";
}
}
| UTF-8 | Java | 940 | java | GroceryAppController.java | Java | [] | null | [] | package groceryapp;
import javax.annotation.Resource;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
public class GroceryAppController {
@Resource
RecipeRepository recipeRepo;
@Resource
IngredientRepository ingredientRepo;
@Resource
StoreItemRepository storeItemRepo;
@Resource
LineItemRepository lineItemRepo;
@RequestMapping("/recipes")
public String getAllRecipes(Model model) {
model.addAttribute("recipes", recipeRepo.findAll());
return "recipes";
}
@RequestMapping("/recipe")
public String getOneRecipe(@RequestParam Long id, Model model) {
model.addAttribute("recipe", recipeRepo.findOne(id));
return "recipe";
}
@RequestMapping("/ingredients")
public String getAllIngredients(Model model) {
model.addAttribute("ingredients", ingredientRepo.findAll());
return "ingredients";
}
}
| 940 | 0.782979 | 0.782979 | 41 | 21.926828 | 21.21825 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.170732 | false | false | 12 |
91afceb0f8b06e46ef3ab851ef5fc2af4d08f7ae | 1,254,130,509,965 | f6c60bd73ada72d8916ad378526fdd87096517a7 | /sample-webapp/src/main/java/song/MaoPao.java | aef1dad61531054838eda83a5b6efc3401a5775d | [] | no_license | caige2015/caige | https://github.com/caige2015/caige | 4d5b25e8e267ba3a5830e37b382b58d4a5803c70 | 3700d39d8922a6f7868d9ff8212789148a0428c0 | refs/heads/master | 2021-01-23T09:52:05.849000 | 2016-02-18T07:44:52 | 2016-02-18T07:44:52 | 38,352,586 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package song;
public class MaoPao {
public static void main(String[] args) {
int[] array = {1,3,4,5,2,7,9,8,34,45,23,12,6};
int[] orderList = getListOfOrder(array);
for(int i=0; i < orderList.length; i++) {
System.out.print(orderList[i] + " ");
}
}
public static int[] getListOfOrder(int[] list){
int temp = 0;
for(int i=0; i < list.length-1; i++) {
for(int j=i+1; j < list.length; j++) {
if(list[i] > list[j]){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
return list;
}
}
| UTF-8 | Java | 727 | java | MaoPao.java | Java | [] | null | [] | package song;
public class MaoPao {
public static void main(String[] args) {
int[] array = {1,3,4,5,2,7,9,8,34,45,23,12,6};
int[] orderList = getListOfOrder(array);
for(int i=0; i < orderList.length; i++) {
System.out.print(orderList[i] + " ");
}
}
public static int[] getListOfOrder(int[] list){
int temp = 0;
for(int i=0; i < list.length-1; i++) {
for(int j=i+1; j < list.length; j++) {
if(list[i] > list[j]){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
return list;
}
}
| 727 | 0.411279 | 0.381018 | 26 | 25.961538 | 18.735981 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.038462 | false | false | 12 |
34600c69d1a60bcb441201355d2aa73fd441ad6f | 14,499,809,639,723 | 469e77bcc3df9bed86e0d21b263d7e5ef97acdfc | /src/com/exitium/cloakcapture/enums/Team.java | 335c05ce433dfc98462f07c32c783059eab36427 | [] | no_license | rocketrobot3/CloakCapture | https://github.com/rocketrobot3/CloakCapture | ea083207ba40cc786c2c11522683d59c8fd0a489 | 127639bbc2b5888e944e96e65559818416fbfd32 | refs/heads/master | 2018-01-10T22:12:26.732000 | 2016-02-25T14:04:19 | 2016-02-25T14:04:19 | 52,234,727 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.exitium.cloakcapture.enums;
public enum Team {
RED, BLUE;
} | UTF-8 | Java | 73 | java | Team.java | Java | [] | null | [] | package com.exitium.cloakcapture.enums;
public enum Team {
RED, BLUE;
} | 73 | 0.753425 | 0.753425 | 5 | 13.8 | 14.246403 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 12 |
b0ad1cc32e6f621949eccb56f09ac8dc7c8eb92c | 27,384,711,548,502 | 6907aef6668952bdededdaf45312fb4f388a648e | /Rck&BrsCRecCollection/app/src/main/java/com/example/myapplication/Element.java | ad78c9b0da34a70db93acdad6c4735053f9d6c80 | [] | no_license | Matix02/WatchApp | https://github.com/Matix02/WatchApp | 632bd62fd530aacf7fc21cb565b9b45c1f1673d8 | bf70c42dac73f4b0d5c16eeb1005d3548bba9916 | refs/heads/master | 2021-04-11T03:16:12.367000 | 2020-07-22T14:21:31 | 2020-07-22T14:21:31 | 248,988,132 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.myapplication;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity(tableName = "Element")
public class Element {
@PrimaryKey(autoGenerate = true)
private long id;
//muszą byc public, bo innaczej bedzie przypał
public String recom;
public String title;
public String category;
boolean isWatched;
Element() { }
public Element(String title, String category, boolean isWatched, String recom) {
this.title = title;
this.category = category;
this.isWatched = isWatched;
this.recom = recom;
}
public Element(long id, String title, String category, boolean isWatched, String recom) {
this.id = id;
this.title = title;
this.category = category;
this.isWatched = isWatched;
this.recom = recom;
}
public long getId() { return id; }
public void setId(long id) { this.id = id; }
String getTitle() {
return title;
}
void setTitle(String title) {
this.title = title;
}
String getCategory() {
return category;
}
void setCategory(String category) {
this.category = category;
}
boolean isWatched() {
return isWatched;
}
void setWatched(boolean watched) {
isWatched = watched;
}
String getRecom() { return recom; }
void setRecom(String recom) { this.recom = recom; }
}
@Entity(tableName = "ElementFilter")
class ElementFilter {
@PrimaryKey(autoGenerate = true)
private long id;
@ColumnInfo(defaultValue = "true")
private boolean finished;
@ColumnInfo(defaultValue = "true")
private boolean unFinished;
@ColumnInfo(defaultValue = "true")
private boolean filmCategory;
@ColumnInfo(defaultValue = "true")
private boolean seriesCategory;
@ColumnInfo(defaultValue = "true")
private boolean bookCategory;
@ColumnInfo(defaultValue = "true")
private boolean gamesCategory;
@ColumnInfo(defaultValue = "true")
private boolean rockRecommedation;
@ColumnInfo(defaultValue = "true")
private boolean borysRecommedation;
@ColumnInfo(defaultValue = "true")
private boolean rockBorysRecommedation;
@ColumnInfo(defaultValue = "true")
private boolean otherRecommedation;
ElementFilter(boolean finished, boolean unFinished, boolean filmCategory, boolean seriesCategory,
boolean bookCategory, boolean gamesCategory, boolean rockRecommedation, boolean borysRecommedation,
boolean rockBorysRecommedation, boolean otherRecommedation) {
this.finished = finished;
this.unFinished = unFinished;
this.filmCategory = filmCategory;
this.seriesCategory = seriesCategory;
this.bookCategory = bookCategory;
this.gamesCategory = gamesCategory;
this.rockRecommedation = rockRecommedation;
this.borysRecommedation = borysRecommedation;
this.rockBorysRecommedation = rockBorysRecommedation;
this.otherRecommedation = otherRecommedation;
}
public boolean isFinished() {
return finished;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public boolean isUnFinished() {
return unFinished;
}
public void setUnFinished(boolean unFinished) {
this.unFinished = unFinished;
}
public boolean isFilmCategory() {
return filmCategory;
}
public void setFilmCategory(boolean filmCategory) {
this.filmCategory = filmCategory;
}
public boolean isSeriesCategory() {
return seriesCategory;
}
public void setSeriesCategory(boolean seriesCategory) {
this.seriesCategory = seriesCategory;
}
public boolean isBookCategory() {
return bookCategory;
}
public void setBookCategory(boolean bookCategory) {
this.bookCategory = bookCategory;
}
public boolean isGamesCategory() {
return gamesCategory;
}
public void setGamesCategory(boolean gamesCategory) {
this.gamesCategory = gamesCategory;
}
public boolean isRockRecommedation() {
return rockRecommedation;
}
public void setRockRecommedation(boolean rockRecommedation) {
this.rockRecommedation = rockRecommedation;
}
public boolean isBorysRecommedation() {
return borysRecommedation;
}
public void setBorysRecommedation(boolean borysRecommedation) {
this.borysRecommedation = borysRecommedation;
}
public boolean isRockBorysRecommedation() {
return rockBorysRecommedation;
}
public void setRockBorysRecommedation(boolean rockBorysRecommedation) {
this.rockBorysRecommedation = rockBorysRecommedation;
}
public boolean isOtherRecommedation() {
return otherRecommedation;
}
public void setOtherRecommedation(boolean otherRecommedation) {
this.otherRecommedation = otherRecommedation;
}
}
| UTF-8 | Java | 5,065 | java | Element.java | Java | [] | null | [] | package com.example.myapplication;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity(tableName = "Element")
public class Element {
@PrimaryKey(autoGenerate = true)
private long id;
//muszą byc public, bo innaczej bedzie przypał
public String recom;
public String title;
public String category;
boolean isWatched;
Element() { }
public Element(String title, String category, boolean isWatched, String recom) {
this.title = title;
this.category = category;
this.isWatched = isWatched;
this.recom = recom;
}
public Element(long id, String title, String category, boolean isWatched, String recom) {
this.id = id;
this.title = title;
this.category = category;
this.isWatched = isWatched;
this.recom = recom;
}
public long getId() { return id; }
public void setId(long id) { this.id = id; }
String getTitle() {
return title;
}
void setTitle(String title) {
this.title = title;
}
String getCategory() {
return category;
}
void setCategory(String category) {
this.category = category;
}
boolean isWatched() {
return isWatched;
}
void setWatched(boolean watched) {
isWatched = watched;
}
String getRecom() { return recom; }
void setRecom(String recom) { this.recom = recom; }
}
@Entity(tableName = "ElementFilter")
class ElementFilter {
@PrimaryKey(autoGenerate = true)
private long id;
@ColumnInfo(defaultValue = "true")
private boolean finished;
@ColumnInfo(defaultValue = "true")
private boolean unFinished;
@ColumnInfo(defaultValue = "true")
private boolean filmCategory;
@ColumnInfo(defaultValue = "true")
private boolean seriesCategory;
@ColumnInfo(defaultValue = "true")
private boolean bookCategory;
@ColumnInfo(defaultValue = "true")
private boolean gamesCategory;
@ColumnInfo(defaultValue = "true")
private boolean rockRecommedation;
@ColumnInfo(defaultValue = "true")
private boolean borysRecommedation;
@ColumnInfo(defaultValue = "true")
private boolean rockBorysRecommedation;
@ColumnInfo(defaultValue = "true")
private boolean otherRecommedation;
ElementFilter(boolean finished, boolean unFinished, boolean filmCategory, boolean seriesCategory,
boolean bookCategory, boolean gamesCategory, boolean rockRecommedation, boolean borysRecommedation,
boolean rockBorysRecommedation, boolean otherRecommedation) {
this.finished = finished;
this.unFinished = unFinished;
this.filmCategory = filmCategory;
this.seriesCategory = seriesCategory;
this.bookCategory = bookCategory;
this.gamesCategory = gamesCategory;
this.rockRecommedation = rockRecommedation;
this.borysRecommedation = borysRecommedation;
this.rockBorysRecommedation = rockBorysRecommedation;
this.otherRecommedation = otherRecommedation;
}
public boolean isFinished() {
return finished;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public boolean isUnFinished() {
return unFinished;
}
public void setUnFinished(boolean unFinished) {
this.unFinished = unFinished;
}
public boolean isFilmCategory() {
return filmCategory;
}
public void setFilmCategory(boolean filmCategory) {
this.filmCategory = filmCategory;
}
public boolean isSeriesCategory() {
return seriesCategory;
}
public void setSeriesCategory(boolean seriesCategory) {
this.seriesCategory = seriesCategory;
}
public boolean isBookCategory() {
return bookCategory;
}
public void setBookCategory(boolean bookCategory) {
this.bookCategory = bookCategory;
}
public boolean isGamesCategory() {
return gamesCategory;
}
public void setGamesCategory(boolean gamesCategory) {
this.gamesCategory = gamesCategory;
}
public boolean isRockRecommedation() {
return rockRecommedation;
}
public void setRockRecommedation(boolean rockRecommedation) {
this.rockRecommedation = rockRecommedation;
}
public boolean isBorysRecommedation() {
return borysRecommedation;
}
public void setBorysRecommedation(boolean borysRecommedation) {
this.borysRecommedation = borysRecommedation;
}
public boolean isRockBorysRecommedation() {
return rockBorysRecommedation;
}
public void setRockBorysRecommedation(boolean rockBorysRecommedation) {
this.rockBorysRecommedation = rockBorysRecommedation;
}
public boolean isOtherRecommedation() {
return otherRecommedation;
}
public void setOtherRecommedation(boolean otherRecommedation) {
this.otherRecommedation = otherRecommedation;
}
}
| 5,065 | 0.674699 | 0.674699 | 197 | 24.695431 | 22.575056 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.436548 | false | false | 12 |
ae0329b32c9b9040367a48465a1fd69d05b2686d | 19,164,144,134,476 | 2d355ba0c5a6287d410836ce45ec7cf0e5a6dfc4 | /src/com/example/apkloader/MainActivity.java | effd016ce1cae7436efde65c6774d591ddeff2f5 | [] | no_license | franzejr/APKLoader | https://github.com/franzejr/APKLoader | a5ad2836fe09a9f045510a91b9cb719e60ff33c7 | 138433926c21af28fc675a9612695385bd0998f8 | refs/heads/master | 2016-09-06T06:05:03.531000 | 2015-02-14T15:50:47 | 2015-02-14T15:50:47 | 30,764,776 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.apkloader;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends Activity {
private File appDirectory;
private String className;
private APKLoader staticMathApk;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txtView = (TextView) findViewById(R.id.result);
loadAPKFile();
staticMathApk = (APKLoader) APKLoader.newInstance(appDirectory,
getCacheDir().getAbsolutePath(), getClassLoader());
txtView.setText(appDirectory.toString());
Class sumClass;
String result = "";
try {
sumClass = staticMathApk.loadClass(className);
ClassLoaderWrapper classLoader = new ClassLoaderWrapper(sumClass);
HashMap<String, String> hashMap = loadParameters();
result = (String) classLoader.executeMethod("execute", hashMap);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
txtView.setText(result);
}
private HashMap<String, String> loadParameters() {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("first", "33222333");
hashMap.put("second", "2");
return hashMap;
}
private void loadAPKFile() {
//Classes
className = "com.ufc.methods.Sum";
//Apk
String appName = "StaticMath.apk";
String pathExternalStorage = Environment.getExternalStorageDirectory().toString();
appDirectory = new File(pathExternalStorage +"/" + appName);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| UTF-8 | Java | 2,299 | java | MainActivity.java | Java | [] | null | [] | package com.example.apkloader;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends Activity {
private File appDirectory;
private String className;
private APKLoader staticMathApk;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txtView = (TextView) findViewById(R.id.result);
loadAPKFile();
staticMathApk = (APKLoader) APKLoader.newInstance(appDirectory,
getCacheDir().getAbsolutePath(), getClassLoader());
txtView.setText(appDirectory.toString());
Class sumClass;
String result = "";
try {
sumClass = staticMathApk.loadClass(className);
ClassLoaderWrapper classLoader = new ClassLoaderWrapper(sumClass);
HashMap<String, String> hashMap = loadParameters();
result = (String) classLoader.executeMethod("execute", hashMap);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
txtView.setText(result);
}
private HashMap<String, String> loadParameters() {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("first", "33222333");
hashMap.put("second", "2");
return hashMap;
}
private void loadAPKFile() {
//Classes
className = "com.ufc.methods.Sum";
//Apk
String appName = "StaticMath.apk";
String pathExternalStorage = Environment.getExternalStorageDirectory().toString();
appDirectory = new File(pathExternalStorage +"/" + appName);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 2,299 | 0.738147 | 0.734232 | 90 | 24.544445 | 21.965712 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.855556 | false | false | 12 |
d78e47dd48fb4285010e79bc1fb601e05da7b7bb | 21,157,008,937,579 | f663b7dde74d006c28fff03d100073ff3e254532 | /app/src/main/java/com/example/home/first/Main3Activity.java | ed0f1866f51cbafea04a767778f59bc31b2cdc28 | [] | no_license | gamalat/Product- | https://github.com/gamalat/Product- | 5f48edc7766372ed227c3c39a56e274cf0fdea8f | d70c3f80975052cfb2424e64b2dc78f39b2105b0 | refs/heads/master | 2020-09-24T10:58:02.465000 | 2019-12-04T00:36:52 | 2019-12-04T00:36:52 | 225,744,446 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.home.first;
import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Main3Activity extends AppCompatActivity {
RequestQueue rq;
String id;
public List<pro_detail> arrayList3 = new ArrayList<pro_detail>();
ImageView imageView;
TextView textView;
TextView textView2;
TextView textView3;
@SuppressLint("WrongViewCast")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
id = getIntent().getStringExtra("id");
Toast.makeText(this, "id" + id
, Toast.LENGTH_SHORT).show();
imageView= (ImageView) findViewById(R.id.image3);
textView=(TextView) findViewById(R.id.txt31);
textView2=(TextView) findViewById(R.id.txt32);
textView3=(TextView) findViewById(R.id.txt33);
start();
}
public void start() {
String url = "http://lamsa.pioneers-solutions.org/Api/Helper/GetService?id="+id;
rq = Volley.newRequestQueue(this);
final JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Method.GET, url, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
textView.setText(response.getString("Name"));
textView2.setText(response.getString("price"));
textView3.setText(response.getString("Description"));
Picasso.with(getApplicationContext()).load("http://lamsa.pioneers-solutions.org"+response.getString("Image")).into(imageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main3Activity.this, "error in response", Toast.LENGTH_SHORT).show();
}
}
);
rq.add(jsonObjectRequest);
}
} | UTF-8 | Java | 2,910 | java | Main3Activity.java | Java | [] | null | [] | package com.example.home.first;
import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Main3Activity extends AppCompatActivity {
RequestQueue rq;
String id;
public List<pro_detail> arrayList3 = new ArrayList<pro_detail>();
ImageView imageView;
TextView textView;
TextView textView2;
TextView textView3;
@SuppressLint("WrongViewCast")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
id = getIntent().getStringExtra("id");
Toast.makeText(this, "id" + id
, Toast.LENGTH_SHORT).show();
imageView= (ImageView) findViewById(R.id.image3);
textView=(TextView) findViewById(R.id.txt31);
textView2=(TextView) findViewById(R.id.txt32);
textView3=(TextView) findViewById(R.id.txt33);
start();
}
public void start() {
String url = "http://lamsa.pioneers-solutions.org/Api/Helper/GetService?id="+id;
rq = Volley.newRequestQueue(this);
final JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Method.GET, url, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
textView.setText(response.getString("Name"));
textView2.setText(response.getString("price"));
textView3.setText(response.getString("Description"));
Picasso.with(getApplicationContext()).load("http://lamsa.pioneers-solutions.org"+response.getString("Image")).into(imageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main3Activity.this, "error in response", Toast.LENGTH_SHORT).show();
}
}
);
rq.add(jsonObjectRequest);
}
} | 2,910 | 0.678351 | 0.671134 | 90 | 31.344444 | 27.528637 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.633333 | false | false | 1 |
63f4cee10a98b2aeabf6cd9ad916472ea476ac2f | 21,157,008,935,439 | 6f02d538d3c636b5ce0772c8fb6f66ab3872c156 | /cloud-demo-consumer-feign/src/main/java/cn/org/zhixiang/config/ConnectTimeHealthIndicator.java | 78fd8eb28da2799fc2cc769078fe578b5c4fe884 | [] | no_license | lyc88/spring-cloud-demo | https://github.com/lyc88/spring-cloud-demo | 39f744a3912f4809a12ee84a9374b6be076289a6 | 5b7942df5c8baab2b000162afd7a068ffe98115a | refs/heads/master | 2020-06-18T08:30:45.906000 | 2019-07-10T02:35:39 | 2019-07-10T02:35:39 | 196,233,655 | 0 | 1 | null | true | 2019-07-10T15:46:07 | 2019-07-10T15:46:07 | 2019-07-10T02:35:42 | 2019-07-10T02:35:40 | 55 | 0 | 0 | 0 | null | false | false | package cn.org.zhixiang.config;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class ConnectTimeHealthIndicator implements HealthIndicator {
@Override
public Health health() {
long connectTime=(long)Math.random()*10;//模拟一个连接操作
if(connectTime>3){
//如果连接时间大于3则认为连接失败,返回状态为down
return Health.down().withDetail("code", "504").withDetail("msg","xx应用连接超时").build();
}
return Health.up().build();
}
}
| UTF-8 | Java | 672 | java | ConnectTimeHealthIndicator.java | Java | [] | null | [] | package cn.org.zhixiang.config;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class ConnectTimeHealthIndicator implements HealthIndicator {
@Override
public Health health() {
long connectTime=(long)Math.random()*10;//模拟一个连接操作
if(connectTime>3){
//如果连接时间大于3则认为连接失败,返回状态为down
return Health.down().withDetail("code", "504").withDetail("msg","xx应用连接超时").build();
}
return Health.up().build();
}
}
| 672 | 0.70598 | 0.694352 | 17 | 34.411766 | 26.439852 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.529412 | false | false | 1 |
3a9619c402f88ee54f68cf54185221bfd9f761de | 33,818,572,498,256 | f1dcb21265dd30d6a043528b4d12f58a47b54eba | /src/main/java/com/isikerhan/sparkexamples/ml/kmeans/ClusterMappingPairer.java | 0609c6c3f3991222d83a805319ee62e2f9989a9d | [] | no_license | isikerhan/kmeans-spark | https://github.com/isikerhan/kmeans-spark | ee3dcabd885fb5ee229b76e756357065e952a59f | 540edf5c91e586be46d302ea0355197a6dbec3f1 | refs/heads/master | 2021-05-03T06:48:00.725000 | 2016-10-05T19:07:20 | 2016-10-05T19:07:20 | 58,267,919 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.isikerhan.sparkexamples.ml.kmeans;
import java.io.Serializable;
import java.util.List;
import org.apache.spark.api.java.function.PairFunction;
import com.isikerhan.sparkexamples.ml.kmeans.Cluster;
import com.isikerhan.sparkexamples.ml.math.Vector;
import com.isikerhan.sparkexamples.ml.math.distance.DistanceFunction;
import scala.Tuple2;
public class ClusterMappingPairer implements Serializable, PairFunction<Vector<?>, Vector<?>, Cluster> {
private static final long serialVersionUID = 1L;
private List<Cluster> clusterList;
private DistanceFunction distanceFunction;
public ClusterMappingPairer(List<Cluster> clusterList, DistanceFunction distanceFunction) {
super();
this.clusterList = clusterList;
this.distanceFunction = distanceFunction;
}
@Override
public Tuple2<Vector<?>, Cluster> call(Vector<?> v) throws Exception {
double minDistance = Double.MAX_VALUE;
Cluster c = null;
for (int i = 0; i < clusterList.size(); i++) {
Cluster current = clusterList.get(i);
double dist = distanceFunction.distance(v, current.getCentroid());
if (dist < minDistance) {
minDistance = dist;
c = current;
}
}
return new Tuple2<>(v, c);
}
}
| UTF-8 | Java | 1,200 | java | ClusterMappingPairer.java | Java | [] | null | [] | package com.isikerhan.sparkexamples.ml.kmeans;
import java.io.Serializable;
import java.util.List;
import org.apache.spark.api.java.function.PairFunction;
import com.isikerhan.sparkexamples.ml.kmeans.Cluster;
import com.isikerhan.sparkexamples.ml.math.Vector;
import com.isikerhan.sparkexamples.ml.math.distance.DistanceFunction;
import scala.Tuple2;
public class ClusterMappingPairer implements Serializable, PairFunction<Vector<?>, Vector<?>, Cluster> {
private static final long serialVersionUID = 1L;
private List<Cluster> clusterList;
private DistanceFunction distanceFunction;
public ClusterMappingPairer(List<Cluster> clusterList, DistanceFunction distanceFunction) {
super();
this.clusterList = clusterList;
this.distanceFunction = distanceFunction;
}
@Override
public Tuple2<Vector<?>, Cluster> call(Vector<?> v) throws Exception {
double minDistance = Double.MAX_VALUE;
Cluster c = null;
for (int i = 0; i < clusterList.size(); i++) {
Cluster current = clusterList.get(i);
double dist = distanceFunction.distance(v, current.getCentroid());
if (dist < minDistance) {
minDistance = dist;
c = current;
}
}
return new Tuple2<>(v, c);
}
}
| 1,200 | 0.750833 | 0.746667 | 44 | 26.272728 | 27.15893 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.681818 | false | false | 1 |
896e899bb3365e8b65343af6b56904004987b989 | 7,902,739,887,797 | c0c5db6ca4b1b9799c055698631e4f7bf0fe2c54 | /TextGuns/src/abr/txtguns/cmd/CommandLoader.java | 3b1c7ae6b42d55b07395eb5327fbfc4dcad0b0ca | [
"MIT"
] | permissive | Sonotsugipaa/textguns | https://github.com/Sonotsugipaa/textguns | 1061efd4837c91156e590bb28c2f3ee27e9e4804 | af14304340a6f1c44b5e6d03b15130ad02c1b86d | refs/heads/master | 2020-03-28T16:18:25.996000 | 2018-09-22T15:19:25 | 2018-09-22T15:19:25 | 148,679,924 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package abr.txtguns.cmd;
import java.lang.reflect.Method;
import java.util.HashMap;
public class CommandLoader {
HashMap<String, Command> commands = new HashMap<>();
public CommandLoader() {
}
public void registerCommands(Class<?> containerClass) {
Method[] methods = containerClass.getDeclaredMethods();
for(Method m: methods) {
if(m.isAnnotationPresent(RegisterCommand.class)) {
RegisterCommand annot = m.getAnnotation(RegisterCommand.class);
String name = m.getName().toLowerCase();
commands.put(name, new Command(
name, m,
annot.minArgs(),
annot.maxArgs()
));
}
}
}
public Command getCommand(String name) {
Command got = commands.get(name.toLowerCase());
if(got == null) {
return new Command(null, null, 0, 0);
} /* else */ {
return got;
}
}
}
| UTF-8 | Java | 822 | java | CommandLoader.java | Java | [] | null | [] | package abr.txtguns.cmd;
import java.lang.reflect.Method;
import java.util.HashMap;
public class CommandLoader {
HashMap<String, Command> commands = new HashMap<>();
public CommandLoader() {
}
public void registerCommands(Class<?> containerClass) {
Method[] methods = containerClass.getDeclaredMethods();
for(Method m: methods) {
if(m.isAnnotationPresent(RegisterCommand.class)) {
RegisterCommand annot = m.getAnnotation(RegisterCommand.class);
String name = m.getName().toLowerCase();
commands.put(name, new Command(
name, m,
annot.minArgs(),
annot.maxArgs()
));
}
}
}
public Command getCommand(String name) {
Command got = commands.get(name.toLowerCase());
if(got == null) {
return new Command(null, null, 0, 0);
} /* else */ {
return got;
}
}
}
| 822 | 0.671533 | 0.6691 | 37 | 21.216217 | 20.148281 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.324324 | false | false | 1 |
49d8e0b2618de44493cd05a8d2b67ff7c575342a | 33,758,442,959,966 | 49f4baa13540d2c9ca76288fa58b9338238b1a51 | /sunshower-service/service-core/src/main/java/io/sunshower/service/git/JGitRepositoryService.java | 625ef600756fdce92a0ba3b500c49f45d6363bb3 | [
"MIT"
] | permissive | sunshower-io/sunshower-core | https://github.com/sunshower-io/sunshower-core | 458d22996acc93182c1c3d372e66f562dc14797f | 99c46668dcd4a1c490274c5df5a4deef6e8d8a00 | refs/heads/master | 2021-06-23T21:26:56.264000 | 2019-06-03T06:40:10 | 2019-06-03T06:40:10 | 115,072,241 | 2 | 0 | null | false | 2019-06-03T06:15:25 | 2017-12-22T03:25:21 | 2019-03-21T00:47:18 | 2019-06-03T06:15:24 | 854 | 2 | 0 | 0 | Java | false | false | package io.sunshower.service.git;
import io.sunshower.model.core.auth.User;
import io.sunshower.service.revision.model.Repository;
import io.sunshower.service.security.AuthenticationSession;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/** Created by haswell on 5/24/17. */
public class JGitRepositoryService implements RepositoryService {
@Inject private AuthenticationSession session;
@PersistenceContext private EntityManager entityManager;
@Override
public GitRepository open(Repository repository) {
return new JGitRepository(repository, entityManager.find(User.class, session.getId()));
}
}
| UTF-8 | Java | 683 | java | JGitRepositoryService.java | Java | [
{
"context": "ax.persistence.PersistenceContext;\n\n/** Created by haswell on 5/24/17. */\npublic class JGitRepositoryService",
"end": 328,
"score": 0.998989999294281,
"start": 321,
"tag": "USERNAME",
"value": "haswell"
}
] | null | [] | package io.sunshower.service.git;
import io.sunshower.model.core.auth.User;
import io.sunshower.service.revision.model.Repository;
import io.sunshower.service.security.AuthenticationSession;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/** Created by haswell on 5/24/17. */
public class JGitRepositoryService implements RepositoryService {
@Inject private AuthenticationSession session;
@PersistenceContext private EntityManager entityManager;
@Override
public GitRepository open(Repository repository) {
return new JGitRepository(repository, entityManager.find(User.class, session.getId()));
}
}
| 683 | 0.814056 | 0.806735 | 20 | 33.150002 | 26.222652 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 1 |
17df4f9f2cf34c5925d0c433629ec2e289443931 | 14,645,838,527,032 | 93c53a8d21303885e96497ccab0c587cc2a333c6 | /Supermarket/SuperMarketSystem/src/model/StatisticsVisitor.java | b9d415f3edb7608dbcaebdca42d7823726bee555 | [] | no_license | Mamata2507/Projects | https://github.com/Mamata2507/Projects | f48500a62f2b7252d849a71a69789194c70899e8 | f7d8bcb4c28fb05631fe86dcb146c2d5bf04b393 | refs/heads/master | 2023-03-16T10:52:20.395000 | 2020-03-14T19:00:51 | 2020-03-14T19:00:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package model;
public interface StatisticsVisitor {
public void visit(Manager m) ;
}
| UTF-8 | Java | 90 | java | StatisticsVisitor.java | Java | [] | null | [] | package model;
public interface StatisticsVisitor {
public void visit(Manager m) ;
}
| 90 | 0.744444 | 0.744444 | 7 | 11.857142 | 14.495601 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 1 |
cd3a119858ad0609b0bd45f2d4180806581ff8bd | 27,135,603,441,634 | b7f35ab6170d7899fc0ab4eecd7385228c4abd5a | /src/Odev/Soru17.java | 25a3c84c2a01a90166f09b76059fb81eb35c1905 | [] | no_license | adnan-2/-devler | https://github.com/adnan-2/-devler | 475c0935cb70a65c216071cdf17831fd91ff452b | 1684a4893ada3d2e04efd71a42f67d63e7854831 | refs/heads/master | 2023-04-04T07:36:13.778000 | 2021-04-14T21:43:58 | 2021-04-14T21:43:58 | 358,041,026 | 0 | 0 | null | false | 2021-04-14T21:43:59 | 2021-04-14T21:00:41 | 2021-04-14T21:09:38 | 2021-04-14T21:43:58 | 0 | 0 | 0 | 0 | Java | false | false | package Odev;
import java.util.Scanner;
public class Soru17 {
public static void main(String[] args) {
/*
* Soru 18 ) Interview Question Kullanicidan bir String isteyin. Kullanicinin
* girdigi String'in palindrome olup olmadigini kontrol eden bir program yazin.
* (Palindrome Nedir?)
*/
// String sınıfının nesneleri
Scanner scan = new Scanner(System.in);
System.out.println("Lutfen bir string giriniz");
String str = scan.nextLine().replace(" " ,"").toLowerCase();
String tersi = "";
for (int i = str.length()-1; i >= 0; i--)
tersi+= str.charAt(i);
if (str.equals(tersi))
System.out.println("Palindrom.");
else
System.out.println("Palindrom değil.");
}
}
| ISO-8859-9 | Java | 761 | java | Soru17.java | Java | [] | null | [] | package Odev;
import java.util.Scanner;
public class Soru17 {
public static void main(String[] args) {
/*
* Soru 18 ) Interview Question Kullanicidan bir String isteyin. Kullanicinin
* girdigi String'in palindrome olup olmadigini kontrol eden bir program yazin.
* (Palindrome Nedir?)
*/
// String sınıfının nesneleri
Scanner scan = new Scanner(System.in);
System.out.println("Lutfen bir string giriniz");
String str = scan.nextLine().replace(" " ,"").toLowerCase();
String tersi = "";
for (int i = str.length()-1; i >= 0; i--)
tersi+= str.charAt(i);
if (str.equals(tersi))
System.out.println("Palindrom.");
else
System.out.println("Palindrom değil.");
}
}
| 761 | 0.625661 | 0.617725 | 33 | 21.90909 | 23.510622 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.363636 | false | false | 1 |
7f1ae277ba1174ab3f96d7d39f5f2656d66d813a | 15,659,450,790,551 | 5b614e8a9270de0bb03c8582c34cc97513cabd19 | /src/main/java/com/lh/system/service/impl/SysLogServiceImpl.java | d3263823bf5b7894db9362f2111aa4aa9af4b462 | [] | no_license | Kroos-x/lionherding | https://github.com/Kroos-x/lionherding | e460cfa6b491e7a70b7075ec336bc1a8a1696dbb | 0101596426455effd7701e09bc049d9ced0e0b98 | refs/heads/master | 2020-05-21T07:23:32.732000 | 2019-12-26T11:17:26 | 2019-12-26T11:17:26 | 185,958,054 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lh.system.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lh.common.dao.DaoApi;
import com.lh.common.utils.LocalHostUtil;
import com.lh.common.utils.SpringContextUtils;
import com.lh.system.entity.SysLog;
import com.lh.system.entity.SysUser;
import com.lh.system.mapper.SysLogMapper;
import com.lh.system.service.SysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* 功能描述:
*
* <p>版权所有:</p>
* 未经本人许可,不得以任何方式复制或使用本程序任何部分
*
* @Company: 紫色年华
* @Author xieyc
* @Date 2019-09-21
* @Version: 1.0.0
*
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements SysLogService {
@Autowired
private DaoApi daoApi;
@Override
public void addLog(String LogContent, Integer logType, String requestMethod,String requestParams) {
SysLog sysLog = new SysLog();
sysLog.setLogContent(LogContent);
sysLog.setLogType(logType);
sysLog.setRequestMethod(requestMethod);
sysLog.setRequestParam(requestParams);
try {
HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
sysLog.setIpAdress(LocalHostUtil.getIpAddress(request));
} catch (Exception e) {
sysLog.setIpAdress("异常地址");
}
SysUser currUser = daoApi.getCurrentUser();
sysLog.setCreateUserId(currUser == null ? "" : currUser.getSysUserId());
sysLog.setCreateUserName(currUser == null ? "" : currUser.getUserName());
//保存系统日志
this.baseMapper.insert(sysLog);
}
@Override
public JSONObject logInfo() {
JSONObject jsonObject = new JSONObject();
Map<String,Object> map = new HashMap<String, Object>();
map.put("totalVisitCount", 120);
map.put("todayVisitCount", 19);
map.put("todayIp", "192.168.0.283");
jsonObject.put("logInfo",map);
return jsonObject;
}
}
| UTF-8 | Java | 2,354 | java | SysLogServiceImpl.java | Java | [
{
"context": "可,不得以任何方式复制或使用本程序任何部分\n*\n* @Company: 紫色年华\n* @Author xieyc\n* @Date 2019-09-21\n* @Version: 1.0.0\n*\n*/\n@Servic",
"end": 791,
"score": 0.9997186064720154,
"start": 786,
"tag": "USERNAME",
"value": "xieyc"
},
{
"context": "odayVisitCount\", 19);\n map.put(\"todayIp\", \"192.168.0.283\");\n jsonObject.put(\"logInfo\",map);\n ",
"end": 2175,
"score": 0.9997058510780334,
"start": 2162,
"tag": "IP_ADDRESS",
"value": "192.168.0.283"
}
] | null | [] | package com.lh.system.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lh.common.dao.DaoApi;
import com.lh.common.utils.LocalHostUtil;
import com.lh.common.utils.SpringContextUtils;
import com.lh.system.entity.SysLog;
import com.lh.system.entity.SysUser;
import com.lh.system.mapper.SysLogMapper;
import com.lh.system.service.SysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* 功能描述:
*
* <p>版权所有:</p>
* 未经本人许可,不得以任何方式复制或使用本程序任何部分
*
* @Company: 紫色年华
* @Author xieyc
* @Date 2019-09-21
* @Version: 1.0.0
*
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements SysLogService {
@Autowired
private DaoApi daoApi;
@Override
public void addLog(String LogContent, Integer logType, String requestMethod,String requestParams) {
SysLog sysLog = new SysLog();
sysLog.setLogContent(LogContent);
sysLog.setLogType(logType);
sysLog.setRequestMethod(requestMethod);
sysLog.setRequestParam(requestParams);
try {
HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
sysLog.setIpAdress(LocalHostUtil.getIpAddress(request));
} catch (Exception e) {
sysLog.setIpAdress("异常地址");
}
SysUser currUser = daoApi.getCurrentUser();
sysLog.setCreateUserId(currUser == null ? "" : currUser.getSysUserId());
sysLog.setCreateUserName(currUser == null ? "" : currUser.getUserName());
//保存系统日志
this.baseMapper.insert(sysLog);
}
@Override
public JSONObject logInfo() {
JSONObject jsonObject = new JSONObject();
Map<String,Object> map = new HashMap<String, Object>();
map.put("totalVisitCount", 120);
map.put("todayVisitCount", 19);
map.put("todayIp", "192.168.0.283");
jsonObject.put("logInfo",map);
return jsonObject;
}
}
| 2,354 | 0.708962 | 0.697427 | 70 | 31.200001 | 25.095589 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.657143 | false | false | 1 |
9b642779637765f91fdc0f5cd58db74ddc43330c | 12,592,844,120,074 | cebc136b203eabd194d306fddec082c63d0395df | /app/src/main/java/luyuan/tech/com/chaoke/activity/ShouFangShenPiActivity.java | bd138b64bc4fecda04f4b14c073bbf7b7aadc1c5 | [] | no_license | haikelei/ChaoKe | https://github.com/haikelei/ChaoKe | 7867bd3ab764a7eb7218ce40a2574dbb5e684c14 | 87663cc479f7ab01399b6bba3648ba0cd07ac277 | refs/heads/master | 2020-06-02T10:02:10.831000 | 2019-09-02T00:58:46 | 2019-09-02T00:58:46 | 191,120,855 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package luyuan.tech.com.chaoke.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import luyuan.tech.com.chaoke.MainActivity;
import luyuan.tech.com.chaoke.R;
import luyuan.tech.com.chaoke.adapter.ImageSelectAdapter;
import luyuan.tech.com.chaoke.base.BaseActivity;
import luyuan.tech.com.chaoke.bean.ImageBean;
import luyuan.tech.com.chaoke.bean.StringDataResponse;
import luyuan.tech.com.chaoke.net.HttpManager;
import luyuan.tech.com.chaoke.net.NetParser;
import luyuan.tech.com.chaoke.utils.ImageUploadUtils;
import luyuan.tech.com.chaoke.utils.T;
import luyuan.tech.com.chaoke.utils.UserInfoUtils;
import luyuan.tech.com.chaoke.widget.InputLayout;
import luyuan.tech.com.chaoke.widget.SelectLayout;
/**
* @author: lujialei
* @date: 2019/6/10
* @describe:
*/
public class ShouFangShenPiActivity extends BaseActivity {
@BindView(R.id.iv_back)
ImageView ivBack;
@BindView(R.id.btn_next)
Button btnNext;
@BindView(R.id.input_address)
InputLayout inputAddress;
@BindView(R.id.input_huxing)
InputLayout inputHuxing;
@BindView(R.id.input_chaoxiang)
InputLayout inputChaoxiang;
@BindView(R.id.input_mianji)
InputLayout inputMianji;
@BindView(R.id.input_shoufangjiage)
InputLayout inputShoufangjiage;
@BindView(R.id.sl_fukuanfangshi)
SelectLayout slFukuanfangshi;
@BindView(R.id.rv_woshi)
RecyclerView rvWoshi;
@BindView(R.id.rv_keting)
RecyclerView rvKeting;
@BindView(R.id.rv_chufang)
RecyclerView rvChufang;
@BindView(R.id.rv_weishengjian)
RecyclerView rvWeishengjian;
@BindView(R.id.rv_yangtai)
RecyclerView rvYangtai;
private String id;
private ImageSelectAdapter adapterWoshi;
private ImageSelectAdapter adapterKeting;
private ImageSelectAdapter adapterChufang;
private ImageSelectAdapter adapterWeishengjian;
private ImageSelectAdapter adapterYangtai;
private ArrayList<ImageBean> listWoshi;
private ArrayList<ImageBean> listKeting;
private ArrayList<ImageBean> listChufang;
private ArrayList<ImageBean> listWeishengjian;
private ArrayList<ImageBean> listYangtai;
public static final int CODE_WOSHI = 150;
public static final int CODE_CHUFANG = 151;
public static final int CODE_KETING = 152;
public static final int CODE_WEISHENGJIAN = 153;
public static final int CODE_YANGTAI = 154;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoufang_shenpi);
ButterKnife.bind(this);
if (getIntent() != null) {
id = getIntent().getStringExtra("id");
}
ivBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
loadData();
}
});
// 付款方式 1 为 2为 3为 4为
String[] arr = {"月付","季付","半年付","年付"};
setSelectLListener(slFukuanfangshi,arr,"付款方式");
initView();
initListener();
}
private void initListener() {
adapterWoshi.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
ImageBean imageBean = listWoshi.get(position);
onClick(imageBean,CODE_WOSHI);
}
});
adapterYangtai.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
ImageBean imageBean = listYangtai.get(position);
onClick(imageBean,CODE_YANGTAI);
}
});
adapterWeishengjian.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
ImageBean imageBean = listWeishengjian.get(position);
onClick(imageBean,CODE_WEISHENGJIAN);
}
});
adapterChufang.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
ImageBean imageBean = listChufang.get(position);
onClick(imageBean,CODE_CHUFANG);
}
});
adapterKeting.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
ImageBean imageBean = listKeting.get(position);
onClick(imageBean,CODE_KETING);
}
});
}
private void onClick(ImageBean imageBean, int code) {
if (imageBean.isAddItem()){
PictureSelector.create(getActivity())
.openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
.maxSelectNum(5)// 最大图片选择数量
.minSelectNum(0)// 最小选择数量
.imageSpanCount(4)// 每行显示个数
.selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
.previewImage(false)// 是否可预览图片
.isCamera(true)// 是否显示拍照按钮
.isZoomAnim(true)// 图片列表点击 缩放效果 默认true
.enableCrop(false)// 是否裁剪
.compress(true)// 是否压缩
.synOrAsy(true)//同步true或异步false 压缩 默认同步
.glideOverride(160, 160)// glide 加载宽高,越小图片列表越流畅,但会影响列表图片浏览的清晰度
.freeStyleCropEnabled(false)// 裁剪框是否可拖拽
.showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
// .selectionMedia(selectList)// 是否传入已选图片
.minimumCompressSize(100)// 小于100kb的图片不压缩
.forResult(code);//结果回调onActivityResult code
}
}
private void initView() {
//卧室
listWoshi = new ArrayList<>();
ImageBean bean = new ImageBean();
bean.setAddItem(true);
listWoshi.add(bean);
adapterWoshi = new ImageSelectAdapter(listWoshi);
rvWoshi.setLayoutManager(new LinearLayoutManager(getBaseContext(),LinearLayoutManager.HORIZONTAL,false));
rvWoshi.setAdapter(adapterWoshi);
//客厅
listKeting = new ArrayList<>();
ImageBean bean1 = new ImageBean();
bean1.setAddItem(true);
listKeting.add(bean1);
adapterKeting = new ImageSelectAdapter(listKeting);
rvKeting.setLayoutManager(new LinearLayoutManager(getBaseContext(),LinearLayoutManager.HORIZONTAL,false));
rvKeting.setAdapter(adapterKeting);
//厨房
listChufang = new ArrayList<>();
ImageBean bean2 = new ImageBean();
bean2.setAddItem(true);
listChufang.add(bean2);
adapterChufang = new ImageSelectAdapter(listChufang);
rvChufang.setLayoutManager(new LinearLayoutManager(getBaseContext(),LinearLayoutManager.HORIZONTAL,false));
rvChufang.setAdapter(adapterChufang);
//卫生间
listWeishengjian = new ArrayList<>();
ImageBean bean3 = new ImageBean();
bean3.setAddItem(true);
listWeishengjian.add(bean3);
adapterWeishengjian = new ImageSelectAdapter(listWeishengjian);
rvWeishengjian.setLayoutManager(new LinearLayoutManager(getBaseContext(),LinearLayoutManager.HORIZONTAL,false));
rvWeishengjian.setAdapter(adapterWeishengjian);
//阳台
listYangtai = new ArrayList<>();
ImageBean bean4 = new ImageBean();
bean4.setAddItem(true);
listYangtai.add(bean4);
adapterYangtai = new ImageSelectAdapter(listYangtai);
rvYangtai.setLayoutManager(new LinearLayoutManager(getBaseContext(),LinearLayoutManager.HORIZONTAL,false));
rvYangtai.setAdapter(adapterYangtai);
}
private void loadData() {
if (!checkEmptyInfo()){
return;
}
HttpManager.post(HttpManager.SHOUFANG_SHENPI)
.params("token", UserInfoUtils.getInstance().getToken())
.params("rent_id",id)
.params("room_address",getValue(inputAddress))
.params("apartment_type",getValue(inputHuxing))
.params("orientation",getValue(inputChaoxiang))
.params("area",getValue(inputMianji))
.params("collect_price",getValue(inputShoufangjiage))
.params("pay_type",getValue(slFukuanfangshi))
.params("bedroom", getListJson(listWoshi))
.params("living_room",getListJson(listKeting))
.params("kitchen",getListJson(listChufang))
.params("toilet",getListJson(listWeishengjian))
.params("balcony",getListJson(listYangtai))
.execute(new SimpleCallBack<String>() {
@Override
public void onError(ApiException e) {
T.showShort(getBaseContext(), e.getMessage());
}
@Override
public void onSuccess(String data) {
StringDataResponse stringDataResponse = NetParser.parse(data,StringDataResponse.class);
if (!TextUtils.isEmpty(stringDataResponse.getMsg())){
T.showShort(getActivity(),stringDataResponse.getMsg());
}else {
showSuccess();
startActivity(new Intent(getBaseContext(), MainActivity.class));
}
}
});
}
private String getListJson(List<ImageBean> data){
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < data.size(); i++) {
ImageBean imageBean = data.get(i);
if (!imageBean.isAddItem()){
list.add(imageBean.getPath());
}
}
String s = new Gson().toJson(list);
return s;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CODE_WOSHI:
// 图片选择结果回调
onResult(data,listWoshi,adapterWoshi);
break;
case CODE_KETING:
// 图片选择结果回调
onResult(data,listKeting,adapterKeting);
break;
case CODE_CHUFANG:
// 图片选择结果回调
onResult(data,listChufang,adapterChufang);
break;
case CODE_WEISHENGJIAN:
// 图片选择结果回调
onResult(data,listWeishengjian,adapterWeishengjian);
break;
case CODE_YANGTAI:
// 图片选择结果回调
onResult(data,listYangtai,adapterYangtai);
break;
}
}
}
private void onResult(Intent data, final ArrayList<ImageBean> list, final ImageSelectAdapter adapter) {
List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
for (LocalMedia media : selectList) {
final String path = media.getCompressPath();
File file = new File(path);
ImageUploadUtils.getInstance().uploadImage(file, new UpCompletionHandler() {
@Override
public void complete(String key, ResponseInfo info, JSONObject response) {
//res包含hash、key等信息,具体字段取决于上传策略的设置
if (info.isOK()) {
try {
String name = response.getString("key");
ImageBean bean = new ImageBean();
bean.setPath(name);
list.add(0, bean);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
}
}
| UTF-8 | Java | 14,022 | java | ShouFangShenPiActivity.java | Java | [
{
"context": "h.com.chaoke.widget.SelectLayout;\n\n/**\n * @author: lujialei\n * @date: 2019/6/10\n * @describe:\n */\n\n\npublic cl",
"end": 1680,
"score": 0.9987412691116333,
"start": 1672,
"tag": "USERNAME",
"value": "lujialei"
},
{
"context": "_SHENPI)\n .params(\"token\", UserInfoUtils.getInstance().getToken())\n .params(\"rent_id\",id)\n ",
"end": 9348,
"score": 0.6729236841201782,
"start": 9320,
"tag": "KEY",
"value": "Utils.getInstance().getToken"
}
] | null | [] | package luyuan.tech.com.chaoke.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import luyuan.tech.com.chaoke.MainActivity;
import luyuan.tech.com.chaoke.R;
import luyuan.tech.com.chaoke.adapter.ImageSelectAdapter;
import luyuan.tech.com.chaoke.base.BaseActivity;
import luyuan.tech.com.chaoke.bean.ImageBean;
import luyuan.tech.com.chaoke.bean.StringDataResponse;
import luyuan.tech.com.chaoke.net.HttpManager;
import luyuan.tech.com.chaoke.net.NetParser;
import luyuan.tech.com.chaoke.utils.ImageUploadUtils;
import luyuan.tech.com.chaoke.utils.T;
import luyuan.tech.com.chaoke.utils.UserInfoUtils;
import luyuan.tech.com.chaoke.widget.InputLayout;
import luyuan.tech.com.chaoke.widget.SelectLayout;
/**
* @author: lujialei
* @date: 2019/6/10
* @describe:
*/
public class ShouFangShenPiActivity extends BaseActivity {
@BindView(R.id.iv_back)
ImageView ivBack;
@BindView(R.id.btn_next)
Button btnNext;
@BindView(R.id.input_address)
InputLayout inputAddress;
@BindView(R.id.input_huxing)
InputLayout inputHuxing;
@BindView(R.id.input_chaoxiang)
InputLayout inputChaoxiang;
@BindView(R.id.input_mianji)
InputLayout inputMianji;
@BindView(R.id.input_shoufangjiage)
InputLayout inputShoufangjiage;
@BindView(R.id.sl_fukuanfangshi)
SelectLayout slFukuanfangshi;
@BindView(R.id.rv_woshi)
RecyclerView rvWoshi;
@BindView(R.id.rv_keting)
RecyclerView rvKeting;
@BindView(R.id.rv_chufang)
RecyclerView rvChufang;
@BindView(R.id.rv_weishengjian)
RecyclerView rvWeishengjian;
@BindView(R.id.rv_yangtai)
RecyclerView rvYangtai;
private String id;
private ImageSelectAdapter adapterWoshi;
private ImageSelectAdapter adapterKeting;
private ImageSelectAdapter adapterChufang;
private ImageSelectAdapter adapterWeishengjian;
private ImageSelectAdapter adapterYangtai;
private ArrayList<ImageBean> listWoshi;
private ArrayList<ImageBean> listKeting;
private ArrayList<ImageBean> listChufang;
private ArrayList<ImageBean> listWeishengjian;
private ArrayList<ImageBean> listYangtai;
public static final int CODE_WOSHI = 150;
public static final int CODE_CHUFANG = 151;
public static final int CODE_KETING = 152;
public static final int CODE_WEISHENGJIAN = 153;
public static final int CODE_YANGTAI = 154;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoufang_shenpi);
ButterKnife.bind(this);
if (getIntent() != null) {
id = getIntent().getStringExtra("id");
}
ivBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
loadData();
}
});
// 付款方式 1 为 2为 3为 4为
String[] arr = {"月付","季付","半年付","年付"};
setSelectLListener(slFukuanfangshi,arr,"付款方式");
initView();
initListener();
}
private void initListener() {
adapterWoshi.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
ImageBean imageBean = listWoshi.get(position);
onClick(imageBean,CODE_WOSHI);
}
});
adapterYangtai.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
ImageBean imageBean = listYangtai.get(position);
onClick(imageBean,CODE_YANGTAI);
}
});
adapterWeishengjian.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
ImageBean imageBean = listWeishengjian.get(position);
onClick(imageBean,CODE_WEISHENGJIAN);
}
});
adapterChufang.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
ImageBean imageBean = listChufang.get(position);
onClick(imageBean,CODE_CHUFANG);
}
});
adapterKeting.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
ImageBean imageBean = listKeting.get(position);
onClick(imageBean,CODE_KETING);
}
});
}
private void onClick(ImageBean imageBean, int code) {
if (imageBean.isAddItem()){
PictureSelector.create(getActivity())
.openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
.maxSelectNum(5)// 最大图片选择数量
.minSelectNum(0)// 最小选择数量
.imageSpanCount(4)// 每行显示个数
.selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
.previewImage(false)// 是否可预览图片
.isCamera(true)// 是否显示拍照按钮
.isZoomAnim(true)// 图片列表点击 缩放效果 默认true
.enableCrop(false)// 是否裁剪
.compress(true)// 是否压缩
.synOrAsy(true)//同步true或异步false 压缩 默认同步
.glideOverride(160, 160)// glide 加载宽高,越小图片列表越流畅,但会影响列表图片浏览的清晰度
.freeStyleCropEnabled(false)// 裁剪框是否可拖拽
.showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
// .selectionMedia(selectList)// 是否传入已选图片
.minimumCompressSize(100)// 小于100kb的图片不压缩
.forResult(code);//结果回调onActivityResult code
}
}
private void initView() {
//卧室
listWoshi = new ArrayList<>();
ImageBean bean = new ImageBean();
bean.setAddItem(true);
listWoshi.add(bean);
adapterWoshi = new ImageSelectAdapter(listWoshi);
rvWoshi.setLayoutManager(new LinearLayoutManager(getBaseContext(),LinearLayoutManager.HORIZONTAL,false));
rvWoshi.setAdapter(adapterWoshi);
//客厅
listKeting = new ArrayList<>();
ImageBean bean1 = new ImageBean();
bean1.setAddItem(true);
listKeting.add(bean1);
adapterKeting = new ImageSelectAdapter(listKeting);
rvKeting.setLayoutManager(new LinearLayoutManager(getBaseContext(),LinearLayoutManager.HORIZONTAL,false));
rvKeting.setAdapter(adapterKeting);
//厨房
listChufang = new ArrayList<>();
ImageBean bean2 = new ImageBean();
bean2.setAddItem(true);
listChufang.add(bean2);
adapterChufang = new ImageSelectAdapter(listChufang);
rvChufang.setLayoutManager(new LinearLayoutManager(getBaseContext(),LinearLayoutManager.HORIZONTAL,false));
rvChufang.setAdapter(adapterChufang);
//卫生间
listWeishengjian = new ArrayList<>();
ImageBean bean3 = new ImageBean();
bean3.setAddItem(true);
listWeishengjian.add(bean3);
adapterWeishengjian = new ImageSelectAdapter(listWeishengjian);
rvWeishengjian.setLayoutManager(new LinearLayoutManager(getBaseContext(),LinearLayoutManager.HORIZONTAL,false));
rvWeishengjian.setAdapter(adapterWeishengjian);
//阳台
listYangtai = new ArrayList<>();
ImageBean bean4 = new ImageBean();
bean4.setAddItem(true);
listYangtai.add(bean4);
adapterYangtai = new ImageSelectAdapter(listYangtai);
rvYangtai.setLayoutManager(new LinearLayoutManager(getBaseContext(),LinearLayoutManager.HORIZONTAL,false));
rvYangtai.setAdapter(adapterYangtai);
}
private void loadData() {
if (!checkEmptyInfo()){
return;
}
HttpManager.post(HttpManager.SHOUFANG_SHENPI)
.params("token", UserInfoUtils.getInstance().getToken())
.params("rent_id",id)
.params("room_address",getValue(inputAddress))
.params("apartment_type",getValue(inputHuxing))
.params("orientation",getValue(inputChaoxiang))
.params("area",getValue(inputMianji))
.params("collect_price",getValue(inputShoufangjiage))
.params("pay_type",getValue(slFukuanfangshi))
.params("bedroom", getListJson(listWoshi))
.params("living_room",getListJson(listKeting))
.params("kitchen",getListJson(listChufang))
.params("toilet",getListJson(listWeishengjian))
.params("balcony",getListJson(listYangtai))
.execute(new SimpleCallBack<String>() {
@Override
public void onError(ApiException e) {
T.showShort(getBaseContext(), e.getMessage());
}
@Override
public void onSuccess(String data) {
StringDataResponse stringDataResponse = NetParser.parse(data,StringDataResponse.class);
if (!TextUtils.isEmpty(stringDataResponse.getMsg())){
T.showShort(getActivity(),stringDataResponse.getMsg());
}else {
showSuccess();
startActivity(new Intent(getBaseContext(), MainActivity.class));
}
}
});
}
private String getListJson(List<ImageBean> data){
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < data.size(); i++) {
ImageBean imageBean = data.get(i);
if (!imageBean.isAddItem()){
list.add(imageBean.getPath());
}
}
String s = new Gson().toJson(list);
return s;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CODE_WOSHI:
// 图片选择结果回调
onResult(data,listWoshi,adapterWoshi);
break;
case CODE_KETING:
// 图片选择结果回调
onResult(data,listKeting,adapterKeting);
break;
case CODE_CHUFANG:
// 图片选择结果回调
onResult(data,listChufang,adapterChufang);
break;
case CODE_WEISHENGJIAN:
// 图片选择结果回调
onResult(data,listWeishengjian,adapterWeishengjian);
break;
case CODE_YANGTAI:
// 图片选择结果回调
onResult(data,listYangtai,adapterYangtai);
break;
}
}
}
private void onResult(Intent data, final ArrayList<ImageBean> list, final ImageSelectAdapter adapter) {
List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
for (LocalMedia media : selectList) {
final String path = media.getCompressPath();
File file = new File(path);
ImageUploadUtils.getInstance().uploadImage(file, new UpCompletionHandler() {
@Override
public void complete(String key, ResponseInfo info, JSONObject response) {
//res包含hash、key等信息,具体字段取决于上传策略的设置
if (info.isOK()) {
try {
String name = response.getString("key");
ImageBean bean = new ImageBean();
bean.setPath(name);
list.add(0, bean);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
}
}
| 14,022 | 0.613889 | 0.609673 | 340 | 38.770588 | 25.142073 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.694118 | false | false | 1 |
7b50d5570c429872dd9543c2c85570f0827f10a3 | 38,508,676,790,495 | 2e0e592129b4835690ae74ab48784c213e1fc3c0 | /src/pakg1/automated_Meal_counter/ParameterPass.java | 4d68ba3d6d09c9a48894cfddb5d8119f6551594f | [] | no_license | tammum/Automatic-Meal-Counter | https://github.com/tammum/Automatic-Meal-Counter | 731cc44a40665347e87ca0815b9a792e2fda9cda | 4b43a2ee0740d344120f2e959f62daf75924f7e2 | refs/heads/master | 2020-03-11T20:41:48.817000 | 2018-04-23T03:25:32 | 2018-04-23T03:25:32 | 130,243,525 | 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 pakg1.automated_Meal_counter;
/**
*
* @author Tammum Islam
*/
public class ParameterPass {
ParameterPass(String s,MemberSection ms){
ms.userid = s;
}
}
| UTF-8 | Java | 365 | java | ParameterPass.java | Java | [
{
"context": "e pakg1.automated_Meal_counter;\n\n/**\n *\n * @author Tammum Islam\n */\npublic class ParameterPass {\n ParameterPas",
"end": 254,
"score": 0.9998429417610168,
"start": 242,
"tag": "NAME",
"value": "Tammum Islam"
}
] | 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 pakg1.automated_Meal_counter;
/**
*
* @author <NAME>
*/
public class ParameterPass {
ParameterPass(String s,MemberSection ms){
ms.userid = s;
}
}
| 359 | 0.69589 | 0.693151 | 16 | 21.8125 | 23.251932 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 1 |
8b7dac1109d2ce91a0656b27871b27bc09cfda43 | 38,508,676,790,789 | 22d36ff82cdc1e8af1f2ccdb6d6bdd24ce871926 | /demo/src/main/java/test.java | 183ac1e3bf9fd2ea56797b5630e5f49088a0f54e | [] | no_license | 8636/java-demo | https://github.com/8636/java-demo | 10a6b085d5de0b189f58abbfda67c65184486b80 | b31b599dd949dbe248bd063e0bb37119c03ba0cc | refs/heads/master | 2022-06-30T03:15:28.399000 | 2020-03-24T07:38:43 | 2020-03-24T07:38:43 | 205,535,498 | 0 | 0 | null | false | 2022-06-17T02:44:28 | 2019-08-31T11:26:54 | 2020-03-24T07:39:14 | 2022-06-17T02:44:28 | 467 | 0 | 0 | 5 | JavaScript | false | false | import java.io.File;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
/**
* @author duan
* @version 1.0
* @date 2019/11/21 9:13
*/
public class test {
public static void main(String[] args) throws ParseException {
String pathPrefix = "src/main/resources/static";
String relativePath = pathPrefix + "/" + "2" +"/" + "3";
//存放上传文件的文件夹
File file = new File(relativePath);
if (!file.isDirectory()) {
//递归生成文件夹
file.mkdirs();
}
}
/* HashSet<Object> objects1 = new HashSet<>();
objects1.add("1");
Set<String> set = new TreeSet<String>();
set.add("08:00");
set.add("00:00");
set.add("24:00");
set.add("18:00");
set.add("12:00");
set.add("20:00");
System.out.println(set);
Object[] objects = set.toArray();
String s = "12:00-18:00,22:00-24:00";
for (int i = 0; i < set.size(); i++) {
if (i+1 ==set.size()){
return;
}
String s1 = (String) objects[i] + "-"+ objects[i+1];
if (s.contains(s1)){
System.out.println("-----" + s1);
}
System.out.println(s1);
}
}*/
}
| UTF-8 | Java | 1,438 | java | test.java | Java | [
{
"context": "til.Set;\nimport java.util.TreeSet;\n\n/**\n * @author duan\n * @version 1.0\n * @date 2019/11/21 9:13\n */\npubl",
"end": 237,
"score": 0.9932541847229004,
"start": 233,
"tag": "USERNAME",
"value": "duan"
}
] | null | [] | import java.io.File;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
/**
* @author duan
* @version 1.0
* @date 2019/11/21 9:13
*/
public class test {
public static void main(String[] args) throws ParseException {
String pathPrefix = "src/main/resources/static";
String relativePath = pathPrefix + "/" + "2" +"/" + "3";
//存放上传文件的文件夹
File file = new File(relativePath);
if (!file.isDirectory()) {
//递归生成文件夹
file.mkdirs();
}
}
/* HashSet<Object> objects1 = new HashSet<>();
objects1.add("1");
Set<String> set = new TreeSet<String>();
set.add("08:00");
set.add("00:00");
set.add("24:00");
set.add("18:00");
set.add("12:00");
set.add("20:00");
System.out.println(set);
Object[] objects = set.toArray();
String s = "12:00-18:00,22:00-24:00";
for (int i = 0; i < set.size(); i++) {
if (i+1 ==set.size()){
return;
}
String s1 = (String) objects[i] + "-"+ objects[i+1];
if (s.contains(s1)){
System.out.println("-----" + s1);
}
System.out.println(s1);
}
}*/
}
| 1,438 | 0.516382 | 0.470085 | 51 | 26.529411 | 16.958256 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.607843 | false | false | 1 |
e2d7432fc11c874d4c4daef2b2c21d2c0a3d70fd | 15,522,011,875,164 | 3f434ac5ba8788b00982210f9f7766e37fb36fbb | /src/main/java/enums/TokenType.java | b5613e560ca243105cb02ca5ada713e2bb32f81f | [] | no_license | william-yz/sql-tuning | https://github.com/william-yz/sql-tuning | f09149fa53338f183ddddc6dc0e90db6c5f62b18 | ceaa632af3a67f79cc55d87d6cf411eb3a4db262 | refs/heads/master | 2020-03-18T13:28:49.383000 | 2018-05-25T01:17:07 | 2018-05-25T01:17:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package enums;
public enum TokenType {
STRING, NUMBER, TOKEN, PUNCTUATION, KEYWORD, OPERATOR;
}
| UTF-8 | Java | 101 | java | TokenType.java | Java | [] | null | [] | package enums;
public enum TokenType {
STRING, NUMBER, TOKEN, PUNCTUATION, KEYWORD, OPERATOR;
}
| 101 | 0.732673 | 0.732673 | 5 | 19.200001 | 21.198112 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.4 | false | false | 1 |
c75307b2d56efd3e55ea093e238c6c09b9c40663 | 35,218,731,868,318 | be04ab6c3c73074802f37bb4e5b4f943033312e4 | /Telephone/app/src/main/java/song/telephone/Bluetooth.java | 964d005ef4a9dd562f7877f05364dbe38beeec4d | [] | no_license | es2fq/Telestrations | https://github.com/es2fq/Telestrations | dcd9ffcd2291936f47155d2c1864b942fb63d68a | 6026cfbb6d570211dcf3900ce9eb354b171abd89 | refs/heads/master | 2020-04-10T09:23:23.307000 | 2015-03-14T02:46:49 | 2015-03-14T02:46:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package song.telephone;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import java.util.Set;
public class Bluetooth extends Activity {
private final static int REQUEST_ENABLE_BT = 1;
ArrayAdapter arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
String status = "";
if( bluetooth != null ) {
if( bluetooth.isEnabled() ) {
String deviceAddress = bluetooth.getAddress();
String deviceName = bluetooth.getName();
status = deviceName + " : " + deviceAddress;
Set<BluetoothDevice> pairedDevices = bluetooth.getBondedDevices();
if( pairedDevices.size() > 0 ) {
for( BluetoothDevice device : pairedDevices ) {
arrayAdapter.add( device.getName() + "\n" + device.getAddress() );
}
}
}
else {
Intent enableBluetooth = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE );
startActivityForResult( enableBluetooth , REQUEST_ENABLE_BT );
}
Toast.makeText( this , status , Toast.LENGTH_LONG ).show();
}
else {
// Does not support bluetooth
}
}
@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_bluetooth, 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);
}
}
| UTF-8 | Java | 2,443 | java | Bluetooth.java | Java | [] | null | [] | package song.telephone;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import java.util.Set;
public class Bluetooth extends Activity {
private final static int REQUEST_ENABLE_BT = 1;
ArrayAdapter arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
String status = "";
if( bluetooth != null ) {
if( bluetooth.isEnabled() ) {
String deviceAddress = bluetooth.getAddress();
String deviceName = bluetooth.getName();
status = deviceName + " : " + deviceAddress;
Set<BluetoothDevice> pairedDevices = bluetooth.getBondedDevices();
if( pairedDevices.size() > 0 ) {
for( BluetoothDevice device : pairedDevices ) {
arrayAdapter.add( device.getName() + "\n" + device.getAddress() );
}
}
}
else {
Intent enableBluetooth = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE );
startActivityForResult( enableBluetooth , REQUEST_ENABLE_BT );
}
Toast.makeText( this , status , Toast.LENGTH_LONG ).show();
}
else {
// Does not support bluetooth
}
}
@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_bluetooth, 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);
}
}
| 2,443 | 0.623823 | 0.623004 | 74 | 32.013512 | 26.152615 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.486486 | false | false | 1 |
27c4d9507cf2be4c6a90bde03a0ae4970a130d85 | 34,445,637,759,868 | d3bf33e957f8c290697f92385aa3c342a4126db9 | /Trivia/app/src/main/java/com/example/magnetification/trivia/HighScoreActivity.java | 774b283a8559afeeb739e87ddb30156b05aa5ccd | [] | no_license | marcelvdla/AppStudio | https://github.com/marcelvdla/AppStudio | bdae1b1724dc271fc88ff3e623ae9c8b0487fad8 | a5579934bf73d1faac2e64d9f5fd992effcf70c1 | refs/heads/master | 2022-06-29T02:59:38.337000 | 2018-12-17T22:14:41 | 2018-12-17T22:14:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.magnetification.trivia;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
public class HighScoreActivity extends AppCompatActivity implements HighScoreHelper.Callback {
private HighScoreHelper help;
private HighScoreList highScores;
// Sets highscore layout and onclicklistener for the back button.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_high_score);
help = new HighScoreHelper(this);
help.getScores(this, "https://ide50-magnetification.cs50.io:8080/scores");
Button back = findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(HighScoreActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
// uses the highscoreadapter to show all the highscores when retrieved.
@Override
public void gotHighScores(JSONArray scoreList, HighScoreHelper.Callback ac) {
highScores = new HighScoreList(scoreList, ac);
HighScoreAdapter adapter = new HighScoreAdapter(this, R.layout.score_item, highScores.getHighScorelist());
ListView list = findViewById(R.id.highscoreList);
list.setAdapter(adapter);
}
// Shows error message when something went wrong retrieving the highscores
@Override
public void gotHighScoresError(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
| UTF-8 | Java | 1,830 | java | HighScoreActivity.java | Java | [] | null | [] | package com.example.magnetification.trivia;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
public class HighScoreActivity extends AppCompatActivity implements HighScoreHelper.Callback {
private HighScoreHelper help;
private HighScoreList highScores;
// Sets highscore layout and onclicklistener for the back button.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_high_score);
help = new HighScoreHelper(this);
help.getScores(this, "https://ide50-magnetification.cs50.io:8080/scores");
Button back = findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(HighScoreActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
// uses the highscoreadapter to show all the highscores when retrieved.
@Override
public void gotHighScores(JSONArray scoreList, HighScoreHelper.Callback ac) {
highScores = new HighScoreList(scoreList, ac);
HighScoreAdapter adapter = new HighScoreAdapter(this, R.layout.score_item, highScores.getHighScorelist());
ListView list = findViewById(R.id.highscoreList);
list.setAdapter(adapter);
}
// Shows error message when something went wrong retrieving the highscores
@Override
public void gotHighScoresError(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
| 1,830 | 0.712022 | 0.707104 | 53 | 33.528301 | 29.353798 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.603774 | false | false | 1 |
59b0bc855ac55b62ffba70624c5f230b2e4bafe0 | 35,021,163,369,745 | fa16cb7b448dfea844cf87532d6552073d5d3571 | /src/collidable/behaviors/SeekModule.java | b20750007189686928b176e445c40ff53039a983 | [] | no_license | rdarnold/dronelab | https://github.com/rdarnold/dronelab | 53704d18df5b44d49d80cd01656b03d6100256b6 | 9f7d7e2f6bc03f82d6c2610f78342922c70bc580 | refs/heads/master | 2022-05-16T02:24:27.130000 | 2021-09-20T17:26:38 | 2021-09-20T17:26:38 | 163,692,208 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dronelab.collidable.behaviors;
import java.util.ArrayList;
import javafx.geometry.Point2D;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import dronelab.utils.*;
import dronelab.collidable.*;
public class SeekModule extends BehaviorModule {
public SeekModule() {
super(Constants.STR_SEEK, Constants.STR_SEEK_J);
drawLetter = "S";
}
@Override
public boolean setup() { return true; }
@Override
public boolean reset() { return true; }
@Override
public boolean usesDrawLocation() { return true; }
@Override
public boolean draw(GraphicsContext gc) {
if (drone == null || drone.seekLocation == null)
return false;
return drawLocation(gc, (int)drone.seekLocation.getX(), (int)drone.seekLocation.getY());
}
@Override
public boolean receive(String msg) {
return true;
}
@Override
public boolean react() {
return seek();
}
private boolean seek() {
if (drone == null) {
return false;
}
/*if (drone.isSeekingTarget() == false) {
// If we are calling the seek module but there is no target to seek,
// set our target location to current location.
if (drone.isSeekingTarget() == false) {
drone.setTargetLocation(drone.x(), drone.y());
}
return false;
}*/
if (drone.seekLocation == null) {
//drone.setTargetLocation(Math.round(drone.x() + drone.wid/2), Math.round(drone.y() + drone.hgt/2));
//drone.stopSeekingTarget();
return false;
}
// We can't really seek if we dont know where we are.
if (drone.ls == null) {
return false;
}
// Check to see if we are there, if we are, then delete our location
if (Physics.withinDistance(drone.ls.x(), drone.ls.y(), drone.seekLocation.getX(), drone.seekLocation.getY(), 20) == true) {
drone.seekLocation = null;
//drone.setTargetLocation(Math.round(drone.x() + drone.wid/2), Math.round(drone.y() + drone.hgt/2));
return false;
}
//System.out.println("" + inputLocation.getX());
drone.setTargetLocation(drone.seekLocation.getX(), drone.seekLocation.getY());
return true;
}
} | UTF-8 | Java | 2,386 | java | SeekModule.java | Java | [] | null | [] | package dronelab.collidable.behaviors;
import java.util.ArrayList;
import javafx.geometry.Point2D;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import dronelab.utils.*;
import dronelab.collidable.*;
public class SeekModule extends BehaviorModule {
public SeekModule() {
super(Constants.STR_SEEK, Constants.STR_SEEK_J);
drawLetter = "S";
}
@Override
public boolean setup() { return true; }
@Override
public boolean reset() { return true; }
@Override
public boolean usesDrawLocation() { return true; }
@Override
public boolean draw(GraphicsContext gc) {
if (drone == null || drone.seekLocation == null)
return false;
return drawLocation(gc, (int)drone.seekLocation.getX(), (int)drone.seekLocation.getY());
}
@Override
public boolean receive(String msg) {
return true;
}
@Override
public boolean react() {
return seek();
}
private boolean seek() {
if (drone == null) {
return false;
}
/*if (drone.isSeekingTarget() == false) {
// If we are calling the seek module but there is no target to seek,
// set our target location to current location.
if (drone.isSeekingTarget() == false) {
drone.setTargetLocation(drone.x(), drone.y());
}
return false;
}*/
if (drone.seekLocation == null) {
//drone.setTargetLocation(Math.round(drone.x() + drone.wid/2), Math.round(drone.y() + drone.hgt/2));
//drone.stopSeekingTarget();
return false;
}
// We can't really seek if we dont know where we are.
if (drone.ls == null) {
return false;
}
// Check to see if we are there, if we are, then delete our location
if (Physics.withinDistance(drone.ls.x(), drone.ls.y(), drone.seekLocation.getX(), drone.seekLocation.getY(), 20) == true) {
drone.seekLocation = null;
//drone.setTargetLocation(Math.round(drone.x() + drone.wid/2), Math.round(drone.y() + drone.hgt/2));
return false;
}
//System.out.println("" + inputLocation.getX());
drone.setTargetLocation(drone.seekLocation.getX(), drone.seekLocation.getY());
return true;
}
} | 2,386 | 0.593043 | 0.590109 | 79 | 29.215189 | 28.624001 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.582278 | false | false | 1 |
6760913d138b235738ceef3a80a550abc32ee07f | 5,214,090,316,348 | 39d3aacac482ac40440356e5820c9afb22123b5c | /app/src/main/java/com/example/proiectmaster/Models/Alarma.java | a32591dcd2ee5f84174d175030fdc72f64296e89 | [] | no_license | andraelise/proiect-master | https://github.com/andraelise/proiect-master | ad068d47b8be1c85ecbac525c8a079fa4b50cb94 | 0cd978d09d51c7a7669bdb9f9b59de0e98a1fc29 | refs/heads/master | 2023-05-28T17:08:00.875000 | 2021-06-08T17:45:13 | 2021-06-08T17:45:13 | 359,157,389 | 0 | 0 | null | false | 2021-06-08T17:45:14 | 2021-04-18T13:55:21 | 2021-06-07T19:38:52 | 2021-06-08T17:45:13 | 713 | 0 | 0 | 0 | Java | false | false | package com.example.proiectmaster.Models;
import java.io.Serializable;
import java.util.Date;
public class Alarma implements Serializable {
private String parametru, text;
private Date data = null;
private double valMinima, valMaxima, valActuala;
public Alarma() {
}
public Alarma(String parametru, Date data, double valMinima, double valMaxima, double valActuala, String text) {
this.parametru = parametru;
this.data = data;
this.valMinima = valMinima;
this.valMaxima = valMaxima;
this.valActuala = valActuala;
this.text = text;
}
public void setParametru(String parametru) {
this.parametru = parametru;
}
public String getParametru() {
return parametru;
}
public void setData(Date data) { this.data = data; }
public Date getData() { return data; }
public void setValMinima(double valMinima) {
this.valMinima = valMinima;
}
public double getValMinima() {
return valMinima;
}
public void setValMaxima(double valMaxima) {
this.valMaxima = valMaxima;
}
public double getValMaxima() {
return valMaxima;
}
public void setValActuala(double valActuala) {
this.valActuala = valActuala;
}
public double getValActuala() {
return valActuala;
}
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
} | UTF-8 | Java | 1,493 | java | Alarma.java | Java | [] | null | [] | package com.example.proiectmaster.Models;
import java.io.Serializable;
import java.util.Date;
public class Alarma implements Serializable {
private String parametru, text;
private Date data = null;
private double valMinima, valMaxima, valActuala;
public Alarma() {
}
public Alarma(String parametru, Date data, double valMinima, double valMaxima, double valActuala, String text) {
this.parametru = parametru;
this.data = data;
this.valMinima = valMinima;
this.valMaxima = valMaxima;
this.valActuala = valActuala;
this.text = text;
}
public void setParametru(String parametru) {
this.parametru = parametru;
}
public String getParametru() {
return parametru;
}
public void setData(Date data) { this.data = data; }
public Date getData() { return data; }
public void setValMinima(double valMinima) {
this.valMinima = valMinima;
}
public double getValMinima() {
return valMinima;
}
public void setValMaxima(double valMaxima) {
this.valMaxima = valMaxima;
}
public double getValMaxima() {
return valMaxima;
}
public void setValActuala(double valActuala) {
this.valActuala = valActuala;
}
public double getValActuala() {
return valActuala;
}
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
} | 1,493 | 0.636303 | 0.636303 | 68 | 20.970589 | 21.088728 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.